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.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.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.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 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.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.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.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.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); } }
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; } }
/** * @(#)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.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 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 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 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 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 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 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 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 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 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 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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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 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(); } }
package com.stalary.pf.recruit.data.dto; import com.stalary.pf.recruit.data.vo.HR; import lombok.Data; /** * @model User * @description 用户对象 * @field userId 用户id * @field nickname 昵称 * @field username 用户名 * @field password 密码 * @field companyId 关联的公司Id * @field phone 手机号 * @field email 邮箱 * @field projectId 项目id * @field role 角色,1为hr,2为求职者 * @field firstId 关联Id * @field code 验证码(注册时使用) **/ @Data public class User { private Long id; private String username; private String nickname; private String phone; private String password; private String email; private Long projectId; private Integer role; private Long firstId; private String code; public User(HR hr) { this.username = hr.getUsername(); this.nickname = hr.getNickname(); this.password = hr.getPassword(); this.phone = hr.getPhone(); this.email = hr.getEmail(); this.firstId = hr.getCompanyId(); this.code = hr.getCode(); this.role = 1; } public User() { } }
package com.stalary.pf.user.data.dto; import lombok.Data; /** * @model User * @description 用户对象 * @field userId 用户id * @field nickname 昵称 * @field username 用户名 * @field password 密码 * @field companyId 关联的公司Id * @field phone 手机号 * @field email 邮箱 * @field projectId 项目id * @field role 角色,1为hr,2为求职者 * @field firstId 关联Id * @field code 验证码(注册时使用) **/ @Data public class User { private Long id; private String username; private String nickname; private String phone; private String password; private String email; private Long projectId; private Integer role; private Long firstId; private String code; public User(Applicant applicant) { this.username = applicant.getUsername(); this.password = applicant.getPassword(); this.phone = applicant.getPhone(); this.email = applicant.getEmail(); this.code = applicant.getCode(); this.role = 2; } public User(HR hr) { this.username = hr.getUsername(); this.nickname = hr.getNickname(); this.password = hr.getPassword(); this.phone = hr.getPhone(); this.email = hr.getEmail(); this.firstId = hr.getCompanyId(); this.code = hr.getCode(); this.role = 1; } public User() { } }
package com.simplemall.micro.serv.common.bean.account; import java.util.ArrayList; import java.util.Date; import java.util.List; public class AccAddressCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_address * * @MBG Generated Wed Aug 16 15:54:11 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_address * * @MBG Generated Wed Aug 16 15:54:11 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_address * * @MBG Generated Wed Aug 16 15:54:11 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public AccAddressCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_address * * @MBG Generated Wed Aug 16 15:54:11 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andAccountIdIsNull() { addCriterion("account_id is null"); return (Criteria) this; } public Criteria andAccountIdIsNotNull() { addCriterion("account_id is not null"); return (Criteria) this; } public Criteria andAccountIdEqualTo(String value) { addCriterion("account_id =", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdNotEqualTo(String value) { addCriterion("account_id <>", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdGreaterThan(String value) { addCriterion("account_id >", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdGreaterThanOrEqualTo(String value) { addCriterion("account_id >=", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdLessThan(String value) { addCriterion("account_id <", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdLessThanOrEqualTo(String value) { addCriterion("account_id <=", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdLike(String value) { addCriterion("account_id like", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdNotLike(String value) { addCriterion("account_id not like", value, "accountId"); return (Criteria) this; } public Criteria andAccountIdIn(List<String> values) { addCriterion("account_id in", values, "accountId"); return (Criteria) this; } public Criteria andAccountIdNotIn(List<String> values) { addCriterion("account_id not in", values, "accountId"); return (Criteria) this; } public Criteria andAccountIdBetween(String value1, String value2) { addCriterion("account_id between", value1, value2, "accountId"); return (Criteria) this; } public Criteria andAccountIdNotBetween(String value1, String value2) { addCriterion("account_id not between", value1, value2, "accountId"); return (Criteria) this; } public Criteria andRealNameIsNull() { addCriterion("real_name is null"); return (Criteria) this; } public Criteria andRealNameIsNotNull() { addCriterion("real_name is not null"); return (Criteria) this; } public Criteria andRealNameEqualTo(String value) { addCriterion("real_name =", value, "realName"); return (Criteria) this; } public Criteria andRealNameNotEqualTo(String value) { addCriterion("real_name <>", value, "realName"); return (Criteria) this; } public Criteria andRealNameGreaterThan(String value) { addCriterion("real_name >", value, "realName"); return (Criteria) this; } public Criteria andRealNameGreaterThanOrEqualTo(String value) { addCriterion("real_name >=", value, "realName"); return (Criteria) this; } public Criteria andRealNameLessThan(String value) { addCriterion("real_name <", value, "realName"); return (Criteria) this; } public Criteria andRealNameLessThanOrEqualTo(String value) { addCriterion("real_name <=", value, "realName"); return (Criteria) this; } public Criteria andRealNameLike(String value) { addCriterion("real_name like", value, "realName"); return (Criteria) this; } public Criteria andRealNameNotLike(String value) { addCriterion("real_name not like", value, "realName"); return (Criteria) this; } public Criteria andRealNameIn(List<String> values) { addCriterion("real_name in", values, "realName"); return (Criteria) this; } public Criteria andRealNameNotIn(List<String> values) { addCriterion("real_name not in", values, "realName"); return (Criteria) this; } public Criteria andRealNameBetween(String value1, String value2) { addCriterion("real_name between", value1, value2, "realName"); return (Criteria) this; } public Criteria andRealNameNotBetween(String value1, String value2) { addCriterion("real_name not between", value1, value2, "realName"); return (Criteria) this; } public Criteria andDetailAddressIsNull() { addCriterion("detail_address is null"); return (Criteria) this; } public Criteria andDetailAddressIsNotNull() { addCriterion("detail_address is not null"); return (Criteria) this; } public Criteria andDetailAddressEqualTo(String value) { addCriterion("detail_address =", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressNotEqualTo(String value) { addCriterion("detail_address <>", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressGreaterThan(String value) { addCriterion("detail_address >", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressGreaterThanOrEqualTo(String value) { addCriterion("detail_address >=", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressLessThan(String value) { addCriterion("detail_address <", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressLessThanOrEqualTo(String value) { addCriterion("detail_address <=", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressLike(String value) { addCriterion("detail_address like", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressNotLike(String value) { addCriterion("detail_address not like", value, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressIn(List<String> values) { addCriterion("detail_address in", values, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressNotIn(List<String> values) { addCriterion("detail_address not in", values, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressBetween(String value1, String value2) { addCriterion("detail_address between", value1, value2, "detailAddress"); return (Criteria) this; } public Criteria andDetailAddressNotBetween(String value1, String value2) { addCriterion("detail_address not between", value1, value2, "detailAddress"); return (Criteria) this; } public Criteria andIsFluIsNull() { addCriterion("is_flu is null"); return (Criteria) this; } public Criteria andIsFluIsNotNull() { addCriterion("is_flu is not null"); return (Criteria) this; } public Criteria andIsFluEqualTo(String value) { addCriterion("is_flu =", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluNotEqualTo(String value) { addCriterion("is_flu <>", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluGreaterThan(String value) { addCriterion("is_flu >", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluGreaterThanOrEqualTo(String value) { addCriterion("is_flu >=", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluLessThan(String value) { addCriterion("is_flu <", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluLessThanOrEqualTo(String value) { addCriterion("is_flu <=", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluLike(String value) { addCriterion("is_flu like", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluNotLike(String value) { addCriterion("is_flu not like", value, "isFlu"); return (Criteria) this; } public Criteria andIsFluIn(List<String> values) { addCriterion("is_flu in", values, "isFlu"); return (Criteria) this; } public Criteria andIsFluNotIn(List<String> values) { addCriterion("is_flu not in", values, "isFlu"); return (Criteria) this; } public Criteria andIsFluBetween(String value1, String value2) { addCriterion("is_flu between", value1, value2, "isFlu"); return (Criteria) this; } public Criteria andIsFluNotBetween(String value1, String value2) { addCriterion("is_flu not between", value1, value2, "isFlu"); return (Criteria) this; } public Criteria andCreateByIsNull() { addCriterion("create_by is null"); return (Criteria) this; } public Criteria andCreateByIsNotNull() { addCriterion("create_by is not null"); return (Criteria) this; } public Criteria andCreateByEqualTo(String value) { addCriterion("create_by =", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotEqualTo(String value) { addCriterion("create_by <>", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThan(String value) { addCriterion("create_by >", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThanOrEqualTo(String value) { addCriterion("create_by >=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThan(String value) { addCriterion("create_by <", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThanOrEqualTo(String value) { addCriterion("create_by <=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLike(String value) { addCriterion("create_by like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotLike(String value) { addCriterion("create_by not like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByIn(List<String> values) { addCriterion("create_by in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByNotIn(List<String> values) { addCriterion("create_by not in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByBetween(String value1, String value2) { addCriterion("create_by between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateByNotBetween(String value1, String value2) { addCriterion("create_by not between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_address * * @MBG Generated do_not_delete_during_merge Wed Aug 16 15:54:11 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_address * * @MBG Generated Wed Aug 16 15:54:11 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.account; import java.util.ArrayList; import java.util.Date; import java.util.List; public class AccountCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_account * * @MBG Generated Tue Aug 15 11:57:16 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_account * * @MBG Generated Tue Aug 15 11:57:16 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_acc_account * * @MBG Generated Tue Aug 15 11:57:16 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public AccountCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_account * * @MBG Generated Tue Aug 15 11:57:16 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andPhoneIsNull() { addCriterion("phone is null"); return (Criteria) this; } public Criteria andPhoneIsNotNull() { addCriterion("phone is not null"); return (Criteria) this; } public Criteria andPhoneEqualTo(String value) { addCriterion("phone =", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotEqualTo(String value) { addCriterion("phone <>", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThan(String value) { addCriterion("phone >", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThanOrEqualTo(String value) { addCriterion("phone >=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThan(String value) { addCriterion("phone <", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThanOrEqualTo(String value) { addCriterion("phone <=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLike(String value) { addCriterion("phone like", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotLike(String value) { addCriterion("phone not like", value, "phone"); return (Criteria) this; } public Criteria andPhoneIn(List<String> values) { addCriterion("phone in", values, "phone"); return (Criteria) this; } public Criteria andPhoneNotIn(List<String> values) { addCriterion("phone not in", values, "phone"); return (Criteria) this; } public Criteria andPhoneBetween(String value1, String value2) { addCriterion("phone between", value1, value2, "phone"); return (Criteria) this; } public Criteria andPhoneNotBetween(String value1, String value2) { addCriterion("phone not between", value1, value2, "phone"); return (Criteria) this; } public Criteria andEmailIsNull() { addCriterion("email is null"); return (Criteria) this; } public Criteria andEmailIsNotNull() { addCriterion("email is not null"); return (Criteria) this; } public Criteria andEmailEqualTo(String value) { addCriterion("email =", value, "email"); return (Criteria) this; } public Criteria andEmailNotEqualTo(String value) { addCriterion("email <>", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThan(String value) { addCriterion("email >", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThanOrEqualTo(String value) { addCriterion("email >=", value, "email"); return (Criteria) this; } public Criteria andEmailLessThan(String value) { addCriterion("email <", value, "email"); return (Criteria) this; } public Criteria andEmailLessThanOrEqualTo(String value) { addCriterion("email <=", value, "email"); return (Criteria) this; } public Criteria andEmailLike(String value) { addCriterion("email like", value, "email"); return (Criteria) this; } public Criteria andEmailNotLike(String value) { addCriterion("email not like", value, "email"); return (Criteria) this; } public Criteria andEmailIn(List<String> values) { addCriterion("email in", values, "email"); return (Criteria) this; } public Criteria andEmailNotIn(List<String> values) { addCriterion("email not in", values, "email"); return (Criteria) this; } public Criteria andEmailBetween(String value1, String value2) { addCriterion("email between", value1, value2, "email"); return (Criteria) this; } public Criteria andEmailNotBetween(String value1, String value2) { addCriterion("email not between", value1, value2, "email"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andCreateByIsNull() { addCriterion("create_by is null"); return (Criteria) this; } public Criteria andCreateByIsNotNull() { addCriterion("create_by is not null"); return (Criteria) this; } public Criteria andCreateByEqualTo(String value) { addCriterion("create_by =", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotEqualTo(String value) { addCriterion("create_by <>", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThan(String value) { addCriterion("create_by >", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThanOrEqualTo(String value) { addCriterion("create_by >=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThan(String value) { addCriterion("create_by <", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThanOrEqualTo(String value) { addCriterion("create_by <=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLike(String value) { addCriterion("create_by like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotLike(String value) { addCriterion("create_by not like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByIn(List<String> values) { addCriterion("create_by in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByNotIn(List<String> values) { addCriterion("create_by not in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByBetween(String value1, String value2) { addCriterion("create_by between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateByNotBetween(String value1, String value2) { addCriterion("create_by not between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_account * * @MBG Generated do_not_delete_during_merge Tue Aug 15 11:57:16 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_acc_account * * @MBG Generated Tue Aug 15 11:57:16 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.order; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class OrderInfoCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_inf * * @MBG Generated Wed Aug 16 17:49:42 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_inf * * @MBG Generated Wed Aug 16 17:49:42 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_inf * * @MBG Generated Wed Aug 16 17:49:42 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public OrderInfoCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_inf * * @MBG Generated Wed Aug 16 17:49:42 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSerialNoIsNull() { addCriterion("serial_no is null"); return (Criteria) this; } public Criteria andSerialNoIsNotNull() { addCriterion("serial_no is not null"); return (Criteria) this; } public Criteria andSerialNoEqualTo(String value) { addCriterion("serial_no =", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotEqualTo(String value) { addCriterion("serial_no <>", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThan(String value) { addCriterion("serial_no >", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThanOrEqualTo(String value) { addCriterion("serial_no >=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThan(String value) { addCriterion("serial_no <", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThanOrEqualTo(String value) { addCriterion("serial_no <=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLike(String value) { addCriterion("serial_no like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotLike(String value) { addCriterion("serial_no not like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoIn(List<String> values) { addCriterion("serial_no in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotIn(List<String> values) { addCriterion("serial_no not in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoBetween(String value1, String value2) { addCriterion("serial_no between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotBetween(String value1, String value2) { addCriterion("serial_no not between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("status like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("status not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andPayTypeIsNull() { addCriterion("pay_type is null"); return (Criteria) this; } public Criteria andPayTypeIsNotNull() { addCriterion("pay_type is not null"); return (Criteria) this; } public Criteria andPayTypeEqualTo(String value) { addCriterion("pay_type =", value, "payType"); return (Criteria) this; } public Criteria andPayTypeNotEqualTo(String value) { addCriterion("pay_type <>", value, "payType"); return (Criteria) this; } public Criteria andPayTypeGreaterThan(String value) { addCriterion("pay_type >", value, "payType"); return (Criteria) this; } public Criteria andPayTypeGreaterThanOrEqualTo(String value) { addCriterion("pay_type >=", value, "payType"); return (Criteria) this; } public Criteria andPayTypeLessThan(String value) { addCriterion("pay_type <", value, "payType"); return (Criteria) this; } public Criteria andPayTypeLessThanOrEqualTo(String value) { addCriterion("pay_type <=", value, "payType"); return (Criteria) this; } public Criteria andPayTypeLike(String value) { addCriterion("pay_type like", value, "payType"); return (Criteria) this; } public Criteria andPayTypeNotLike(String value) { addCriterion("pay_type not like", value, "payType"); return (Criteria) this; } public Criteria andPayTypeIn(List<String> values) { addCriterion("pay_type in", values, "payType"); return (Criteria) this; } public Criteria andPayTypeNotIn(List<String> values) { addCriterion("pay_type not in", values, "payType"); return (Criteria) this; } public Criteria andPayTypeBetween(String value1, String value2) { addCriterion("pay_type between", value1, value2, "payType"); return (Criteria) this; } public Criteria andPayTypeNotBetween(String value1, String value2) { addCriterion("pay_type not between", value1, value2, "payType"); return (Criteria) this; } public Criteria andPayStatusIsNull() { addCriterion("pay_status is null"); return (Criteria) this; } public Criteria andPayStatusIsNotNull() { addCriterion("pay_status is not null"); return (Criteria) this; } public Criteria andPayStatusEqualTo(String value) { addCriterion("pay_status =", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotEqualTo(String value) { addCriterion("pay_status <>", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusGreaterThan(String value) { addCriterion("pay_status >", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusGreaterThanOrEqualTo(String value) { addCriterion("pay_status >=", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusLessThan(String value) { addCriterion("pay_status <", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusLessThanOrEqualTo(String value) { addCriterion("pay_status <=", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusLike(String value) { addCriterion("pay_status like", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotLike(String value) { addCriterion("pay_status not like", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusIn(List<String> values) { addCriterion("pay_status in", values, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotIn(List<String> values) { addCriterion("pay_status not in", values, "payStatus"); return (Criteria) this; } public Criteria andPayStatusBetween(String value1, String value2) { addCriterion("pay_status between", value1, value2, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotBetween(String value1, String value2) { addCriterion("pay_status not between", value1, value2, "payStatus"); return (Criteria) this; } public Criteria andShippingAccountIsNull() { addCriterion("shipping_account is null"); return (Criteria) this; } public Criteria andShippingAccountIsNotNull() { addCriterion("shipping_account is not null"); return (Criteria) this; } public Criteria andShippingAccountEqualTo(String value) { addCriterion("shipping_account =", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountNotEqualTo(String value) { addCriterion("shipping_account <>", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountGreaterThan(String value) { addCriterion("shipping_account >", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountGreaterThanOrEqualTo(String value) { addCriterion("shipping_account >=", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountLessThan(String value) { addCriterion("shipping_account <", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountLessThanOrEqualTo(String value) { addCriterion("shipping_account <=", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountLike(String value) { addCriterion("shipping_account like", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountNotLike(String value) { addCriterion("shipping_account not like", value, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountIn(List<String> values) { addCriterion("shipping_account in", values, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountNotIn(List<String> values) { addCriterion("shipping_account not in", values, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountBetween(String value1, String value2) { addCriterion("shipping_account between", value1, value2, "shippingAccount"); return (Criteria) this; } public Criteria andShippingAccountNotBetween(String value1, String value2) { addCriterion("shipping_account not between", value1, value2, "shippingAccount"); return (Criteria) this; } public Criteria andShippingNameIsNull() { addCriterion("shipping_name is null"); return (Criteria) this; } public Criteria andShippingNameIsNotNull() { addCriterion("shipping_name is not null"); return (Criteria) this; } public Criteria andShippingNameEqualTo(String value) { addCriterion("shipping_name =", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameNotEqualTo(String value) { addCriterion("shipping_name <>", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameGreaterThan(String value) { addCriterion("shipping_name >", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameGreaterThanOrEqualTo(String value) { addCriterion("shipping_name >=", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameLessThan(String value) { addCriterion("shipping_name <", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameLessThanOrEqualTo(String value) { addCriterion("shipping_name <=", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameLike(String value) { addCriterion("shipping_name like", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameNotLike(String value) { addCriterion("shipping_name not like", value, "shippingName"); return (Criteria) this; } public Criteria andShippingNameIn(List<String> values) { addCriterion("shipping_name in", values, "shippingName"); return (Criteria) this; } public Criteria andShippingNameNotIn(List<String> values) { addCriterion("shipping_name not in", values, "shippingName"); return (Criteria) this; } public Criteria andShippingNameBetween(String value1, String value2) { addCriterion("shipping_name between", value1, value2, "shippingName"); return (Criteria) this; } public Criteria andShippingNameNotBetween(String value1, String value2) { addCriterion("shipping_name not between", value1, value2, "shippingName"); return (Criteria) this; } public Criteria andShippingAddressIsNull() { addCriterion("shipping_address is null"); return (Criteria) this; } public Criteria andShippingAddressIsNotNull() { addCriterion("shipping_address is not null"); return (Criteria) this; } public Criteria andShippingAddressEqualTo(String value) { addCriterion("shipping_address =", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressNotEqualTo(String value) { addCriterion("shipping_address <>", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressGreaterThan(String value) { addCriterion("shipping_address >", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressGreaterThanOrEqualTo(String value) { addCriterion("shipping_address >=", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressLessThan(String value) { addCriterion("shipping_address <", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressLessThanOrEqualTo(String value) { addCriterion("shipping_address <=", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressLike(String value) { addCriterion("shipping_address like", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressNotLike(String value) { addCriterion("shipping_address not like", value, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressIn(List<String> values) { addCriterion("shipping_address in", values, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressNotIn(List<String> values) { addCriterion("shipping_address not in", values, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressBetween(String value1, String value2) { addCriterion("shipping_address between", value1, value2, "shippingAddress"); return (Criteria) this; } public Criteria andShippingAddressNotBetween(String value1, String value2) { addCriterion("shipping_address not between", value1, value2, "shippingAddress"); return (Criteria) this; } public Criteria andShippingPhoneIsNull() { addCriterion("shipping_phone is null"); return (Criteria) this; } public Criteria andShippingPhoneIsNotNull() { addCriterion("shipping_phone is not null"); return (Criteria) this; } public Criteria andShippingPhoneEqualTo(String value) { addCriterion("shipping_phone =", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneNotEqualTo(String value) { addCriterion("shipping_phone <>", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneGreaterThan(String value) { addCriterion("shipping_phone >", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneGreaterThanOrEqualTo(String value) { addCriterion("shipping_phone >=", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneLessThan(String value) { addCriterion("shipping_phone <", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneLessThanOrEqualTo(String value) { addCriterion("shipping_phone <=", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneLike(String value) { addCriterion("shipping_phone like", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneNotLike(String value) { addCriterion("shipping_phone not like", value, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneIn(List<String> values) { addCriterion("shipping_phone in", values, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneNotIn(List<String> values) { addCriterion("shipping_phone not in", values, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneBetween(String value1, String value2) { addCriterion("shipping_phone between", value1, value2, "shippingPhone"); return (Criteria) this; } public Criteria andShippingPhoneNotBetween(String value1, String value2) { addCriterion("shipping_phone not between", value1, value2, "shippingPhone"); return (Criteria) this; } public Criteria andPostWayIsNull() { addCriterion("post_way is null"); return (Criteria) this; } public Criteria andPostWayIsNotNull() { addCriterion("post_way is not null"); return (Criteria) this; } public Criteria andPostWayEqualTo(String value) { addCriterion("post_way =", value, "postWay"); return (Criteria) this; } public Criteria andPostWayNotEqualTo(String value) { addCriterion("post_way <>", value, "postWay"); return (Criteria) this; } public Criteria andPostWayGreaterThan(String value) { addCriterion("post_way >", value, "postWay"); return (Criteria) this; } public Criteria andPostWayGreaterThanOrEqualTo(String value) { addCriterion("post_way >=", value, "postWay"); return (Criteria) this; } public Criteria andPostWayLessThan(String value) { addCriterion("post_way <", value, "postWay"); return (Criteria) this; } public Criteria andPostWayLessThanOrEqualTo(String value) { addCriterion("post_way <=", value, "postWay"); return (Criteria) this; } public Criteria andPostWayLike(String value) { addCriterion("post_way like", value, "postWay"); return (Criteria) this; } public Criteria andPostWayNotLike(String value) { addCriterion("post_way not like", value, "postWay"); return (Criteria) this; } public Criteria andPostWayIn(List<String> values) { addCriterion("post_way in", values, "postWay"); return (Criteria) this; } public Criteria andPostWayNotIn(List<String> values) { addCriterion("post_way not in", values, "postWay"); return (Criteria) this; } public Criteria andPostWayBetween(String value1, String value2) { addCriterion("post_way between", value1, value2, "postWay"); return (Criteria) this; } public Criteria andPostWayNotBetween(String value1, String value2) { addCriterion("post_way not between", value1, value2, "postWay"); return (Criteria) this; } public Criteria andPostFeeIsNull() { addCriterion("post_fee is null"); return (Criteria) this; } public Criteria andPostFeeIsNotNull() { addCriterion("post_fee is not null"); return (Criteria) this; } public Criteria andPostFeeEqualTo(BigDecimal value) { addCriterion("post_fee =", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeNotEqualTo(BigDecimal value) { addCriterion("post_fee <>", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeGreaterThan(BigDecimal value) { addCriterion("post_fee >", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeGreaterThanOrEqualTo(BigDecimal value) { addCriterion("post_fee >=", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeLessThan(BigDecimal value) { addCriterion("post_fee <", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeLessThanOrEqualTo(BigDecimal value) { addCriterion("post_fee <=", value, "postFee"); return (Criteria) this; } public Criteria andPostFeeIn(List<BigDecimal> values) { addCriterion("post_fee in", values, "postFee"); return (Criteria) this; } public Criteria andPostFeeNotIn(List<BigDecimal> values) { addCriterion("post_fee not in", values, "postFee"); return (Criteria) this; } public Criteria andPostFeeBetween(BigDecimal value1, BigDecimal value2) { addCriterion("post_fee between", value1, value2, "postFee"); return (Criteria) this; } public Criteria andPostFeeNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("post_fee not between", value1, value2, "postFee"); return (Criteria) this; } public Criteria andPriceIsNull() { addCriterion("price is null"); return (Criteria) this; } public Criteria andPriceIsNotNull() { addCriterion("price is not null"); return (Criteria) this; } public Criteria andPriceEqualTo(BigDecimal value) { addCriterion("price =", value, "price"); return (Criteria) this; } public Criteria andPriceNotEqualTo(BigDecimal value) { addCriterion("price <>", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThan(BigDecimal value) { addCriterion("price >", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThanOrEqualTo(BigDecimal value) { addCriterion("price >=", value, "price"); return (Criteria) this; } public Criteria andPriceLessThan(BigDecimal value) { addCriterion("price <", value, "price"); return (Criteria) this; } public Criteria andPriceLessThanOrEqualTo(BigDecimal value) { addCriterion("price <=", value, "price"); return (Criteria) this; } public Criteria andPriceIn(List<BigDecimal> values) { addCriterion("price in", values, "price"); return (Criteria) this; } public Criteria andPriceNotIn(List<BigDecimal> values) { addCriterion("price not in", values, "price"); return (Criteria) this; } public Criteria andPriceBetween(BigDecimal value1, BigDecimal value2) { addCriterion("price between", value1, value2, "price"); return (Criteria) this; } public Criteria andPriceNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("price not between", value1, value2, "price"); return (Criteria) this; } public Criteria andCreateByIsNull() { addCriterion("create_by is null"); return (Criteria) this; } public Criteria andCreateByIsNotNull() { addCriterion("create_by is not null"); return (Criteria) this; } public Criteria andCreateByEqualTo(String value) { addCriterion("create_by =", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotEqualTo(String value) { addCriterion("create_by <>", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThan(String value) { addCriterion("create_by >", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThanOrEqualTo(String value) { addCriterion("create_by >=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThan(String value) { addCriterion("create_by <", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThanOrEqualTo(String value) { addCriterion("create_by <=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLike(String value) { addCriterion("create_by like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotLike(String value) { addCriterion("create_by not like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByIn(List<String> values) { addCriterion("create_by in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByNotIn(List<String> values) { addCriterion("create_by not in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByBetween(String value1, String value2) { addCriterion("create_by between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateByNotBetween(String value1, String value2) { addCriterion("create_by not between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_inf * * @MBG Generated do_not_delete_during_merge Wed Aug 16 17:49:42 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_inf * * @MBG Generated Wed Aug 16 17:49:42 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.order; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class OrderProductCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_produt * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_produt * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_produt * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public OrderProductCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_produt * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSerialNoIsNull() { addCriterion("serial_no is null"); return (Criteria) this; } public Criteria andSerialNoIsNotNull() { addCriterion("serial_no is not null"); return (Criteria) this; } public Criteria andSerialNoEqualTo(String value) { addCriterion("serial_no =", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotEqualTo(String value) { addCriterion("serial_no <>", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThan(String value) { addCriterion("serial_no >", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThanOrEqualTo(String value) { addCriterion("serial_no >=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThan(String value) { addCriterion("serial_no <", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThanOrEqualTo(String value) { addCriterion("serial_no <=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLike(String value) { addCriterion("serial_no like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotLike(String value) { addCriterion("serial_no not like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoIn(List<String> values) { addCriterion("serial_no in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotIn(List<String> values) { addCriterion("serial_no not in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoBetween(String value1, String value2) { addCriterion("serial_no between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotBetween(String value1, String value2) { addCriterion("serial_no not between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andPrdNameIsNull() { addCriterion("prd_name is null"); return (Criteria) this; } public Criteria andPrdNameIsNotNull() { addCriterion("prd_name is not null"); return (Criteria) this; } public Criteria andPrdNameEqualTo(String value) { addCriterion("prd_name =", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameNotEqualTo(String value) { addCriterion("prd_name <>", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameGreaterThan(String value) { addCriterion("prd_name >", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameGreaterThanOrEqualTo(String value) { addCriterion("prd_name >=", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameLessThan(String value) { addCriterion("prd_name <", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameLessThanOrEqualTo(String value) { addCriterion("prd_name <=", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameLike(String value) { addCriterion("prd_name like", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameNotLike(String value) { addCriterion("prd_name not like", value, "prdName"); return (Criteria) this; } public Criteria andPrdNameIn(List<String> values) { addCriterion("prd_name in", values, "prdName"); return (Criteria) this; } public Criteria andPrdNameNotIn(List<String> values) { addCriterion("prd_name not in", values, "prdName"); return (Criteria) this; } public Criteria andPrdNameBetween(String value1, String value2) { addCriterion("prd_name between", value1, value2, "prdName"); return (Criteria) this; } public Criteria andPrdNameNotBetween(String value1, String value2) { addCriterion("prd_name not between", value1, value2, "prdName"); return (Criteria) this; } public Criteria andPrdPriceIsNull() { addCriterion("prd_price is null"); return (Criteria) this; } public Criteria andPrdPriceIsNotNull() { addCriterion("prd_price is not null"); return (Criteria) this; } public Criteria andPrdPriceEqualTo(BigDecimal value) { addCriterion("prd_price =", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceNotEqualTo(BigDecimal value) { addCriterion("prd_price <>", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceGreaterThan(BigDecimal value) { addCriterion("prd_price >", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceGreaterThanOrEqualTo(BigDecimal value) { addCriterion("prd_price >=", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceLessThan(BigDecimal value) { addCriterion("prd_price <", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceLessThanOrEqualTo(BigDecimal value) { addCriterion("prd_price <=", value, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceIn(List<BigDecimal> values) { addCriterion("prd_price in", values, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceNotIn(List<BigDecimal> values) { addCriterion("prd_price not in", values, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceBetween(BigDecimal value1, BigDecimal value2) { addCriterion("prd_price between", value1, value2, "prdPrice"); return (Criteria) this; } public Criteria andPrdPriceNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("prd_price not between", value1, value2, "prdPrice"); return (Criteria) this; } public Criteria andPrdQtyIsNull() { addCriterion("prd_qty is null"); return (Criteria) this; } public Criteria andPrdQtyIsNotNull() { addCriterion("prd_qty is not null"); return (Criteria) this; } public Criteria andPrdQtyEqualTo(Integer value) { addCriterion("prd_qty =", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyNotEqualTo(Integer value) { addCriterion("prd_qty <>", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyGreaterThan(Integer value) { addCriterion("prd_qty >", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyGreaterThanOrEqualTo(Integer value) { addCriterion("prd_qty >=", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyLessThan(Integer value) { addCriterion("prd_qty <", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyLessThanOrEqualTo(Integer value) { addCriterion("prd_qty <=", value, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyIn(List<Integer> values) { addCriterion("prd_qty in", values, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyNotIn(List<Integer> values) { addCriterion("prd_qty not in", values, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyBetween(Integer value1, Integer value2) { addCriterion("prd_qty between", value1, value2, "prdQty"); return (Criteria) this; } public Criteria andPrdQtyNotBetween(Integer value1, Integer value2) { addCriterion("prd_qty not between", value1, value2, "prdQty"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_produt * * @MBG Generated do_not_delete_during_merge Wed Aug 16 06:01:18 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_produt * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.order; import java.util.ArrayList; import java.util.Date; import java.util.List; public class OrderStateCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_state * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_state * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_ord_state * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public OrderStateCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_state * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSerialNoIsNull() { addCriterion("serial_no is null"); return (Criteria) this; } public Criteria andSerialNoIsNotNull() { addCriterion("serial_no is not null"); return (Criteria) this; } public Criteria andSerialNoEqualTo(String value) { addCriterion("serial_no =", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotEqualTo(String value) { addCriterion("serial_no <>", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThan(String value) { addCriterion("serial_no >", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThanOrEqualTo(String value) { addCriterion("serial_no >=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThan(String value) { addCriterion("serial_no <", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThanOrEqualTo(String value) { addCriterion("serial_no <=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLike(String value) { addCriterion("serial_no like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotLike(String value) { addCriterion("serial_no not like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoIn(List<String> values) { addCriterion("serial_no in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotIn(List<String> values) { addCriterion("serial_no not in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoBetween(String value1, String value2) { addCriterion("serial_no between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotBetween(String value1, String value2) { addCriterion("serial_no not between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("status like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("status not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_state * * @MBG Generated do_not_delete_during_merge Wed Aug 16 06:01:18 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_ord_state * * @MBG Generated Wed Aug 16 06:01:18 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.product; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PrdExtendCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_extend * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_extend * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_extend * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public PrdExtendCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_extend * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSupplierNameIsNull() { addCriterion("supplier_name is null"); return (Criteria) this; } public Criteria andSupplierNameIsNotNull() { addCriterion("supplier_name is not null"); return (Criteria) this; } public Criteria andSupplierNameEqualTo(String value) { addCriterion("supplier_name =", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameNotEqualTo(String value) { addCriterion("supplier_name <>", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameGreaterThan(String value) { addCriterion("supplier_name >", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameGreaterThanOrEqualTo(String value) { addCriterion("supplier_name >=", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameLessThan(String value) { addCriterion("supplier_name <", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameLessThanOrEqualTo(String value) { addCriterion("supplier_name <=", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameLike(String value) { addCriterion("supplier_name like", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameNotLike(String value) { addCriterion("supplier_name not like", value, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameIn(List<String> values) { addCriterion("supplier_name in", values, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameNotIn(List<String> values) { addCriterion("supplier_name not in", values, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameBetween(String value1, String value2) { addCriterion("supplier_name between", value1, value2, "supplierName"); return (Criteria) this; } public Criteria andSupplierNameNotBetween(String value1, String value2) { addCriterion("supplier_name not between", value1, value2, "supplierName"); return (Criteria) this; } public Criteria andLongDescIsNull() { addCriterion("long_desc is null"); return (Criteria) this; } public Criteria andLongDescIsNotNull() { addCriterion("long_desc is not null"); return (Criteria) this; } public Criteria andLongDescEqualTo(String value) { addCriterion("long_desc =", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescNotEqualTo(String value) { addCriterion("long_desc <>", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescGreaterThan(String value) { addCriterion("long_desc >", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescGreaterThanOrEqualTo(String value) { addCriterion("long_desc >=", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescLessThan(String value) { addCriterion("long_desc <", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescLessThanOrEqualTo(String value) { addCriterion("long_desc <=", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescLike(String value) { addCriterion("long_desc like", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescNotLike(String value) { addCriterion("long_desc not like", value, "longDesc"); return (Criteria) this; } public Criteria andLongDescIn(List<String> values) { addCriterion("long_desc in", values, "longDesc"); return (Criteria) this; } public Criteria andLongDescNotIn(List<String> values) { addCriterion("long_desc not in", values, "longDesc"); return (Criteria) this; } public Criteria andLongDescBetween(String value1, String value2) { addCriterion("long_desc between", value1, value2, "longDesc"); return (Criteria) this; } public Criteria andLongDescNotBetween(String value1, String value2) { addCriterion("long_desc not between", value1, value2, "longDesc"); return (Criteria) this; } public Criteria andWeightIsNull() { addCriterion("weight is null"); return (Criteria) this; } public Criteria andWeightIsNotNull() { addCriterion("weight is not null"); return (Criteria) this; } public Criteria andWeightEqualTo(String value) { addCriterion("weight =", value, "weight"); return (Criteria) this; } public Criteria andWeightNotEqualTo(String value) { addCriterion("weight <>", value, "weight"); return (Criteria) this; } public Criteria andWeightGreaterThan(String value) { addCriterion("weight >", value, "weight"); return (Criteria) this; } public Criteria andWeightGreaterThanOrEqualTo(String value) { addCriterion("weight >=", value, "weight"); return (Criteria) this; } public Criteria andWeightLessThan(String value) { addCriterion("weight <", value, "weight"); return (Criteria) this; } public Criteria andWeightLessThanOrEqualTo(String value) { addCriterion("weight <=", value, "weight"); return (Criteria) this; } public Criteria andWeightLike(String value) { addCriterion("weight like", value, "weight"); return (Criteria) this; } public Criteria andWeightNotLike(String value) { addCriterion("weight not like", value, "weight"); return (Criteria) this; } public Criteria andWeightIn(List<String> values) { addCriterion("weight in", values, "weight"); return (Criteria) this; } public Criteria andWeightNotIn(List<String> values) { addCriterion("weight not in", values, "weight"); return (Criteria) this; } public Criteria andWeightBetween(String value1, String value2) { addCriterion("weight between", value1, value2, "weight"); return (Criteria) this; } public Criteria andWeightNotBetween(String value1, String value2) { addCriterion("weight not between", value1, value2, "weight"); return (Criteria) this; } public Criteria andOriginIsNull() { addCriterion("origin is null"); return (Criteria) this; } public Criteria andOriginIsNotNull() { addCriterion("origin is not null"); return (Criteria) this; } public Criteria andOriginEqualTo(String value) { addCriterion("origin =", value, "origin"); return (Criteria) this; } public Criteria andOriginNotEqualTo(String value) { addCriterion("origin <>", value, "origin"); return (Criteria) this; } public Criteria andOriginGreaterThan(String value) { addCriterion("origin >", value, "origin"); return (Criteria) this; } public Criteria andOriginGreaterThanOrEqualTo(String value) { addCriterion("origin >=", value, "origin"); return (Criteria) this; } public Criteria andOriginLessThan(String value) { addCriterion("origin <", value, "origin"); return (Criteria) this; } public Criteria andOriginLessThanOrEqualTo(String value) { addCriterion("origin <=", value, "origin"); return (Criteria) this; } public Criteria andOriginLike(String value) { addCriterion("origin like", value, "origin"); return (Criteria) this; } public Criteria andOriginNotLike(String value) { addCriterion("origin not like", value, "origin"); return (Criteria) this; } public Criteria andOriginIn(List<String> values) { addCriterion("origin in", values, "origin"); return (Criteria) this; } public Criteria andOriginNotIn(List<String> values) { addCriterion("origin not in", values, "origin"); return (Criteria) this; } public Criteria andOriginBetween(String value1, String value2) { addCriterion("origin between", value1, value2, "origin"); return (Criteria) this; } public Criteria andOriginNotBetween(String value1, String value2) { addCriterion("origin not between", value1, value2, "origin"); return (Criteria) this; } public Criteria andSaledQtyIsNull() { addCriterion("saled_qty is null"); return (Criteria) this; } public Criteria andSaledQtyIsNotNull() { addCriterion("saled_qty is not null"); return (Criteria) this; } public Criteria andSaledQtyEqualTo(Integer value) { addCriterion("saled_qty =", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyNotEqualTo(Integer value) { addCriterion("saled_qty <>", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyGreaterThan(Integer value) { addCriterion("saled_qty >", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyGreaterThanOrEqualTo(Integer value) { addCriterion("saled_qty >=", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyLessThan(Integer value) { addCriterion("saled_qty <", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyLessThanOrEqualTo(Integer value) { addCriterion("saled_qty <=", value, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyIn(List<Integer> values) { addCriterion("saled_qty in", values, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyNotIn(List<Integer> values) { addCriterion("saled_qty not in", values, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyBetween(Integer value1, Integer value2) { addCriterion("saled_qty between", value1, value2, "saledQty"); return (Criteria) this; } public Criteria andSaledQtyNotBetween(Integer value1, Integer value2) { addCriterion("saled_qty not between", value1, value2, "saledQty"); return (Criteria) this; } public Criteria andCreateByIsNull() { addCriterion("create_by is null"); return (Criteria) this; } public Criteria andCreateByIsNotNull() { addCriterion("create_by is not null"); return (Criteria) this; } public Criteria andCreateByEqualTo(String value) { addCriterion("create_by =", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotEqualTo(String value) { addCriterion("create_by <>", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThan(String value) { addCriterion("create_by >", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThanOrEqualTo(String value) { addCriterion("create_by >=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThan(String value) { addCriterion("create_by <", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThanOrEqualTo(String value) { addCriterion("create_by <=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLike(String value) { addCriterion("create_by like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotLike(String value) { addCriterion("create_by not like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByIn(List<String> values) { addCriterion("create_by in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByNotIn(List<String> values) { addCriterion("create_by not in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByBetween(String value1, String value2) { addCriterion("create_by between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateByNotBetween(String value1, String value2) { addCriterion("create_by not between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_extend * * @MBG Generated do_not_delete_during_merge Wed Aug 16 06:09:46 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_extend * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.common.bean.product; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PrdInfoCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_info * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_info * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_prd_info * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public PrdInfoCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_info * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andLabelNameIsNull() { addCriterion("label_name is null"); return (Criteria) this; } public Criteria andLabelNameIsNotNull() { addCriterion("label_name is not null"); return (Criteria) this; } public Criteria andLabelNameEqualTo(String value) { addCriterion("label_name =", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameNotEqualTo(String value) { addCriterion("label_name <>", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameGreaterThan(String value) { addCriterion("label_name >", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameGreaterThanOrEqualTo(String value) { addCriterion("label_name >=", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameLessThan(String value) { addCriterion("label_name <", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameLessThanOrEqualTo(String value) { addCriterion("label_name <=", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameLike(String value) { addCriterion("label_name like", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameNotLike(String value) { addCriterion("label_name not like", value, "labelName"); return (Criteria) this; } public Criteria andLabelNameIn(List<String> values) { addCriterion("label_name in", values, "labelName"); return (Criteria) this; } public Criteria andLabelNameNotIn(List<String> values) { addCriterion("label_name not in", values, "labelName"); return (Criteria) this; } public Criteria andLabelNameBetween(String value1, String value2) { addCriterion("label_name between", value1, value2, "labelName"); return (Criteria) this; } public Criteria andLabelNameNotBetween(String value1, String value2) { addCriterion("label_name not between", value1, value2, "labelName"); return (Criteria) this; } public Criteria andShortDescIsNull() { addCriterion("short_desc is null"); return (Criteria) this; } public Criteria andShortDescIsNotNull() { addCriterion("short_desc is not null"); return (Criteria) this; } public Criteria andShortDescEqualTo(String value) { addCriterion("short_desc =", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescNotEqualTo(String value) { addCriterion("short_desc <>", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescGreaterThan(String value) { addCriterion("short_desc >", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescGreaterThanOrEqualTo(String value) { addCriterion("short_desc >=", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescLessThan(String value) { addCriterion("short_desc <", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescLessThanOrEqualTo(String value) { addCriterion("short_desc <=", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescLike(String value) { addCriterion("short_desc like", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescNotLike(String value) { addCriterion("short_desc not like", value, "shortDesc"); return (Criteria) this; } public Criteria andShortDescIn(List<String> values) { addCriterion("short_desc in", values, "shortDesc"); return (Criteria) this; } public Criteria andShortDescNotIn(List<String> values) { addCriterion("short_desc not in", values, "shortDesc"); return (Criteria) this; } public Criteria andShortDescBetween(String value1, String value2) { addCriterion("short_desc between", value1, value2, "shortDesc"); return (Criteria) this; } public Criteria andShortDescNotBetween(String value1, String value2) { addCriterion("short_desc not between", value1, value2, "shortDesc"); return (Criteria) this; } public Criteria andPriceIsNull() { addCriterion("price is null"); return (Criteria) this; } public Criteria andPriceIsNotNull() { addCriterion("price is not null"); return (Criteria) this; } public Criteria andPriceEqualTo(String value) { addCriterion("price =", value, "price"); return (Criteria) this; } public Criteria andPriceNotEqualTo(String value) { addCriterion("price <>", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThan(String value) { addCriterion("price >", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThanOrEqualTo(String value) { addCriterion("price >=", value, "price"); return (Criteria) this; } public Criteria andPriceLessThan(String value) { addCriterion("price <", value, "price"); return (Criteria) this; } public Criteria andPriceLessThanOrEqualTo(String value) { addCriterion("price <=", value, "price"); return (Criteria) this; } public Criteria andPriceLike(String value) { addCriterion("price like", value, "price"); return (Criteria) this; } public Criteria andPriceNotLike(String value) { addCriterion("price not like", value, "price"); return (Criteria) this; } public Criteria andPriceIn(List<String> values) { addCriterion("price in", values, "price"); return (Criteria) this; } public Criteria andPriceNotIn(List<String> values) { addCriterion("price not in", values, "price"); return (Criteria) this; } public Criteria andPriceBetween(String value1, String value2) { addCriterion("price between", value1, value2, "price"); return (Criteria) this; } public Criteria andPriceNotBetween(String value1, String value2) { addCriterion("price not between", value1, value2, "price"); return (Criteria) this; } public Criteria andStoreIsNull() { addCriterion("store is null"); return (Criteria) this; } public Criteria andStoreIsNotNull() { addCriterion("store is not null"); return (Criteria) this; } public Criteria andStoreEqualTo(Integer value) { addCriterion("store =", value, "store"); return (Criteria) this; } public Criteria andStoreNotEqualTo(Integer value) { addCriterion("store <>", value, "store"); return (Criteria) this; } public Criteria andStoreGreaterThan(Integer value) { addCriterion("store >", value, "store"); return (Criteria) this; } public Criteria andStoreGreaterThanOrEqualTo(Integer value) { addCriterion("store >=", value, "store"); return (Criteria) this; } public Criteria andStoreLessThan(Integer value) { addCriterion("store <", value, "store"); return (Criteria) this; } public Criteria andStoreLessThanOrEqualTo(Integer value) { addCriterion("store <=", value, "store"); return (Criteria) this; } public Criteria andStoreIn(List<Integer> values) { addCriterion("store in", values, "store"); return (Criteria) this; } public Criteria andStoreNotIn(List<Integer> values) { addCriterion("store not in", values, "store"); return (Criteria) this; } public Criteria andStoreBetween(Integer value1, Integer value2) { addCriterion("store between", value1, value2, "store"); return (Criteria) this; } public Criteria andStoreNotBetween(Integer value1, Integer value2) { addCriterion("store not between", value1, value2, "store"); return (Criteria) this; } public Criteria andCreateByIsNull() { addCriterion("create_by is null"); return (Criteria) this; } public Criteria andCreateByIsNotNull() { addCriterion("create_by is not null"); return (Criteria) this; } public Criteria andCreateByEqualTo(String value) { addCriterion("create_by =", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotEqualTo(String value) { addCriterion("create_by <>", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThan(String value) { addCriterion("create_by >", value, "createBy"); return (Criteria) this; } public Criteria andCreateByGreaterThanOrEqualTo(String value) { addCriterion("create_by >=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThan(String value) { addCriterion("create_by <", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLessThanOrEqualTo(String value) { addCriterion("create_by <=", value, "createBy"); return (Criteria) this; } public Criteria andCreateByLike(String value) { addCriterion("create_by like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByNotLike(String value) { addCriterion("create_by not like", value, "createBy"); return (Criteria) this; } public Criteria andCreateByIn(List<String> values) { addCriterion("create_by in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByNotIn(List<String> values) { addCriterion("create_by not in", values, "createBy"); return (Criteria) this; } public Criteria andCreateByBetween(String value1, String value2) { addCriterion("create_by between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateByNotBetween(String value1, String value2) { addCriterion("create_by not between", value1, value2, "createBy"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_info * * @MBG Generated do_not_delete_during_merge Wed Aug 16 06:09:46 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_prd_info * * @MBG Generated Wed Aug 16 06:09:46 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.micro.serv.msg.bean; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MsgNoticeCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_msg_notice * * @MBG Generated Wed Aug 16 06:17:58 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_msg_notice * * @MBG Generated Wed Aug 16 06:17:58 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_msg_notice * * @MBG Generated Wed Aug 16 06:17:58 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public MsgNoticeCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_msg_notice * * @MBG Generated Wed Aug 16 06:17:58 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSerialNoIsNull() { addCriterion("serial_no is null"); return (Criteria) this; } public Criteria andSerialNoIsNotNull() { addCriterion("serial_no is not null"); return (Criteria) this; } public Criteria andSerialNoEqualTo(String value) { addCriterion("serial_no =", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotEqualTo(String value) { addCriterion("serial_no <>", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThan(String value) { addCriterion("serial_no >", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThanOrEqualTo(String value) { addCriterion("serial_no >=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThan(String value) { addCriterion("serial_no <", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThanOrEqualTo(String value) { addCriterion("serial_no <=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLike(String value) { addCriterion("serial_no like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotLike(String value) { addCriterion("serial_no not like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoIn(List<String> values) { addCriterion("serial_no in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotIn(List<String> values) { addCriterion("serial_no not in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoBetween(String value1, String value2) { addCriterion("serial_no between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotBetween(String value1, String value2) { addCriterion("serial_no not between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andTargetTypeIsNull() { addCriterion("target_type is null"); return (Criteria) this; } public Criteria andTargetTypeIsNotNull() { addCriterion("target_type is not null"); return (Criteria) this; } public Criteria andTargetTypeEqualTo(String value) { addCriterion("target_type =", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeNotEqualTo(String value) { addCriterion("target_type <>", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeGreaterThan(String value) { addCriterion("target_type >", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeGreaterThanOrEqualTo(String value) { addCriterion("target_type >=", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeLessThan(String value) { addCriterion("target_type <", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeLessThanOrEqualTo(String value) { addCriterion("target_type <=", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeLike(String value) { addCriterion("target_type like", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeNotLike(String value) { addCriterion("target_type not like", value, "targetType"); return (Criteria) this; } public Criteria andTargetTypeIn(List<String> values) { addCriterion("target_type in", values, "targetType"); return (Criteria) this; } public Criteria andTargetTypeNotIn(List<String> values) { addCriterion("target_type not in", values, "targetType"); return (Criteria) this; } public Criteria andTargetTypeBetween(String value1, String value2) { addCriterion("target_type between", value1, value2, "targetType"); return (Criteria) this; } public Criteria andTargetTypeNotBetween(String value1, String value2) { addCriterion("target_type not between", value1, value2, "targetType"); return (Criteria) this; } public Criteria andTargetAddressIsNull() { addCriterion("target_address is null"); return (Criteria) this; } public Criteria andTargetAddressIsNotNull() { addCriterion("target_address is not null"); return (Criteria) this; } public Criteria andTargetAddressEqualTo(String value) { addCriterion("target_address =", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressNotEqualTo(String value) { addCriterion("target_address <>", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressGreaterThan(String value) { addCriterion("target_address >", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressGreaterThanOrEqualTo(String value) { addCriterion("target_address >=", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressLessThan(String value) { addCriterion("target_address <", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressLessThanOrEqualTo(String value) { addCriterion("target_address <=", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressLike(String value) { addCriterion("target_address like", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressNotLike(String value) { addCriterion("target_address not like", value, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressIn(List<String> values) { addCriterion("target_address in", values, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressNotIn(List<String> values) { addCriterion("target_address not in", values, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressBetween(String value1, String value2) { addCriterion("target_address between", value1, value2, "targetAddress"); return (Criteria) this; } public Criteria andTargetAddressNotBetween(String value1, String value2) { addCriterion("target_address not between", value1, value2, "targetAddress"); return (Criteria) this; } public Criteria andContentIsNull() { addCriterion("content is null"); return (Criteria) this; } public Criteria andContentIsNotNull() { addCriterion("content is not null"); return (Criteria) this; } public Criteria andContentEqualTo(String value) { addCriterion("content =", value, "content"); return (Criteria) this; } public Criteria andContentNotEqualTo(String value) { addCriterion("content <>", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThan(String value) { addCriterion("content >", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThanOrEqualTo(String value) { addCriterion("content >=", value, "content"); return (Criteria) this; } public Criteria andContentLessThan(String value) { addCriterion("content <", value, "content"); return (Criteria) this; } public Criteria andContentLessThanOrEqualTo(String value) { addCriterion("content <=", value, "content"); return (Criteria) this; } public Criteria andContentLike(String value) { addCriterion("content like", value, "content"); return (Criteria) this; } public Criteria andContentNotLike(String value) { addCriterion("content not like", value, "content"); return (Criteria) this; } public Criteria andContentIn(List<String> values) { addCriterion("content in", values, "content"); return (Criteria) this; } public Criteria andContentNotIn(List<String> values) { addCriterion("content not in", values, "content"); return (Criteria) this; } public Criteria andContentBetween(String value1, String value2) { addCriterion("content between", value1, value2, "content"); return (Criteria) this; } public Criteria andContentNotBetween(String value1, String value2) { addCriterion("content not between", value1, value2, "content"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_msg_notice * * @MBG Generated do_not_delete_during_merge Wed Aug 16 06:17:58 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_msg_notice * * @MBG Generated Wed Aug 16 06:17:58 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.simplemall.pay.bean; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PayRecordCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_pay_record * * @MBG Generated Tue Aug 29 22:25:52 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_pay_record * * @MBG Generated Tue Aug 29 22:25:52 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_pay_record * * @MBG Generated Tue Aug 29 22:25:52 CST 2017 */ protected List<Criteria> oredCriteria; /** * */ public PayRecordCriteria() { oredCriteria = new ArrayList<Criteria>(); } /** * * @param orderByClause */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * */ public String getOrderByClause() { return orderByClause; } /** * * @param distinct */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * */ public boolean isDistinct() { return distinct; } /** * */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * * @param criteria */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_pay_record * * @MBG Generated Tue Aug 29 22:25:52 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTidIsNull() { addCriterion("tid is null"); return (Criteria) this; } public Criteria andTidIsNotNull() { addCriterion("tid is not null"); return (Criteria) this; } public Criteria andTidEqualTo(String value) { addCriterion("tid =", value, "tid"); return (Criteria) this; } public Criteria andTidNotEqualTo(String value) { addCriterion("tid <>", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThan(String value) { addCriterion("tid >", value, "tid"); return (Criteria) this; } public Criteria andTidGreaterThanOrEqualTo(String value) { addCriterion("tid >=", value, "tid"); return (Criteria) this; } public Criteria andTidLessThan(String value) { addCriterion("tid <", value, "tid"); return (Criteria) this; } public Criteria andTidLessThanOrEqualTo(String value) { addCriterion("tid <=", value, "tid"); return (Criteria) this; } public Criteria andTidLike(String value) { addCriterion("tid like", value, "tid"); return (Criteria) this; } public Criteria andTidNotLike(String value) { addCriterion("tid not like", value, "tid"); return (Criteria) this; } public Criteria andTidIn(List<String> values) { addCriterion("tid in", values, "tid"); return (Criteria) this; } public Criteria andTidNotIn(List<String> values) { addCriterion("tid not in", values, "tid"); return (Criteria) this; } public Criteria andTidBetween(String value1, String value2) { addCriterion("tid between", value1, value2, "tid"); return (Criteria) this; } public Criteria andTidNotBetween(String value1, String value2) { addCriterion("tid not between", value1, value2, "tid"); return (Criteria) this; } public Criteria andSerialNoIsNull() { addCriterion("serial_no is null"); return (Criteria) this; } public Criteria andSerialNoIsNotNull() { addCriterion("serial_no is not null"); return (Criteria) this; } public Criteria andSerialNoEqualTo(String value) { addCriterion("serial_no =", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotEqualTo(String value) { addCriterion("serial_no <>", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThan(String value) { addCriterion("serial_no >", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoGreaterThanOrEqualTo(String value) { addCriterion("serial_no >=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThan(String value) { addCriterion("serial_no <", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLessThanOrEqualTo(String value) { addCriterion("serial_no <=", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoLike(String value) { addCriterion("serial_no like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotLike(String value) { addCriterion("serial_no not like", value, "serialNo"); return (Criteria) this; } public Criteria andSerialNoIn(List<String> values) { addCriterion("serial_no in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotIn(List<String> values) { addCriterion("serial_no not in", values, "serialNo"); return (Criteria) this; } public Criteria andSerialNoBetween(String value1, String value2) { addCriterion("serial_no between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andSerialNoNotBetween(String value1, String value2) { addCriterion("serial_no not between", value1, value2, "serialNo"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(String value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(String value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(String value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(String value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(String value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(String value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeLike(String value) { addCriterion("type like", value, "type"); return (Criteria) this; } public Criteria andTypeNotLike(String value) { addCriterion("type not like", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<String> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<String> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(String value1, String value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(String value1, String value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andPriceIsNull() { addCriterion("price is null"); return (Criteria) this; } public Criteria andPriceIsNotNull() { addCriterion("price is not null"); return (Criteria) this; } public Criteria andPriceEqualTo(Float value) { addCriterion("price =", value, "price"); return (Criteria) this; } public Criteria andPriceNotEqualTo(Float value) { addCriterion("price <>", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThan(Float value) { addCriterion("price >", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThanOrEqualTo(Float value) { addCriterion("price >=", value, "price"); return (Criteria) this; } public Criteria andPriceLessThan(Float value) { addCriterion("price <", value, "price"); return (Criteria) this; } public Criteria andPriceLessThanOrEqualTo(Float value) { addCriterion("price <=", value, "price"); return (Criteria) this; } public Criteria andPriceIn(List<Float> values) { addCriterion("price in", values, "price"); return (Criteria) this; } public Criteria andPriceNotIn(List<Float> values) { addCriterion("price not in", values, "price"); return (Criteria) this; } public Criteria andPriceBetween(Float value1, Float value2) { addCriterion("price between", value1, value2, "price"); return (Criteria) this; } public Criteria andPriceNotBetween(Float value1, Float value2) { addCriterion("price not between", value1, value2, "price"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("status like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("status not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andUpdateByIsNull() { addCriterion("update_by is null"); return (Criteria) this; } public Criteria andUpdateByIsNotNull() { addCriterion("update_by is not null"); return (Criteria) this; } public Criteria andUpdateByEqualTo(String value) { addCriterion("update_by =", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotEqualTo(String value) { addCriterion("update_by <>", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThan(String value) { addCriterion("update_by >", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByGreaterThanOrEqualTo(String value) { addCriterion("update_by >=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThan(String value) { addCriterion("update_by <", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLessThanOrEqualTo(String value) { addCriterion("update_by <=", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByLike(String value) { addCriterion("update_by like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotLike(String value) { addCriterion("update_by not like", value, "updateBy"); return (Criteria) this; } public Criteria andUpdateByIn(List<String> values) { addCriterion("update_by in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotIn(List<String> values) { addCriterion("update_by not in", values, "updateBy"); return (Criteria) this; } public Criteria andUpdateByBetween(String value1, String value2) { addCriterion("update_by between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateByNotBetween(String value1, String value2) { addCriterion("update_by not between", value1, value2, "updateBy"); return (Criteria) this; } public Criteria andUpdateDateIsNull() { addCriterion("update_date is null"); return (Criteria) this; } public Criteria andUpdateDateIsNotNull() { addCriterion("update_date is not null"); return (Criteria) this; } public Criteria andUpdateDateEqualTo(Date value) { addCriterion("update_date =", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotEqualTo(Date value) { addCriterion("update_date <>", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThan(Date value) { addCriterion("update_date >", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("update_date >=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThan(Date value) { addCriterion("update_date <", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateLessThanOrEqualTo(Date value) { addCriterion("update_date <=", value, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateIn(List<Date> values) { addCriterion("update_date in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotIn(List<Date> values) { addCriterion("update_date not in", values, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateBetween(Date value1, Date value2) { addCriterion("update_date between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andUpdateDateNotBetween(Date value1, Date value2) { addCriterion("update_date not between", value1, value2, "updateDate"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andStateIsNull() { addCriterion("state is null"); return (Criteria) this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return (Criteria) this; } public Criteria andStateEqualTo(Integer value) { addCriterion("state =", value, "state"); return (Criteria) this; } public Criteria andStateNotEqualTo(Integer value) { addCriterion("state <>", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThan(Integer value) { addCriterion("state >", value, "state"); return (Criteria) this; } public Criteria andStateGreaterThanOrEqualTo(Integer value) { addCriterion("state >=", value, "state"); return (Criteria) this; } public Criteria andStateLessThan(Integer value) { addCriterion("state <", value, "state"); return (Criteria) this; } public Criteria andStateLessThanOrEqualTo(Integer value) { addCriterion("state <=", value, "state"); return (Criteria) this; } public Criteria andStateIn(List<Integer> values) { addCriterion("state in", values, "state"); return (Criteria) this; } public Criteria andStateNotIn(List<Integer> values) { addCriterion("state not in", values, "state"); return (Criteria) this; } public Criteria andStateBetween(Integer value1, Integer value2) { addCriterion("state between", value1, value2, "state"); return (Criteria) this; } public Criteria andStateNotBetween(Integer value1, Integer value2) { addCriterion("state not between", value1, value2, "state"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_pay_record * * @MBG Generated do_not_delete_during_merge Tue Aug 29 22:25:52 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_pay_record * * @MBG Generated Tue Aug 29 22:25:52 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * * https://www.renren.io * * 版权所有,侵权必究! */ package io.renren.common.utils; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.renren.common.xss.SQLFilter; import org.apache.commons.lang.StringUtils; import java.util.Map; /** * 查询参数 * * @author Mark sunlightcs@gmail.com */ public class Query<T> { public IPage<T> getPage(Map<String, Object> params) { return this.getPage(params, null, false); } public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) { //分页参数 long curPage = 1; long limit = 10; if(params.get(Constant.PAGE) != null){ curPage = Long.parseLong((String)params.get(Constant.PAGE)); } if(params.get(Constant.LIMIT) != null){ limit = Long.parseLong((String)params.get(Constant.LIMIT)); } //分页对象 Page<T> page = new Page<>(curPage, limit); //分页参数 params.put(Constant.PAGE, page); //排序字段 //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险) String orderField = SQLFilter.sqlInject((String)params.get(Constant.ORDER_FIELD)); String order = (String)params.get(Constant.ORDER); //前端字段排序 if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){ if(Constant.ASC.equalsIgnoreCase(order)) { return page.addOrder(OrderItem.asc(orderField)); }else { return page.addOrder(OrderItem.desc(orderField)); } } //没有排序字段,则不排序 if(StringUtils.isBlank(defaultOrderField)){ return page; } //默认排序 if(isAsc) { page.addOrder(OrderItem.asc(defaultOrderField)); }else { page.addOrder(OrderItem.desc(defaultOrderField)); } return page; } }
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * * https://www.renren.io * * 版权所有,侵权必究! */ package io.renren.common.xss; import io.renren.common.exception.RRException; import org.apache.commons.lang.StringUtils; /** * SQL过滤 * * @author Mark sunlightcs@gmail.com */ public class SQLFilter { /** * SQL注入过滤 * @param str 待验证的字符串 */ public static String sqlInject(String str){ if(StringUtils.isBlank(str)){ return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new RRException("包含非法字符"); } } return str; } }
package com.jerusalem.common.utils; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.jerusalem.common.xss.SQLFilter; import org.apache.commons.lang.StringUtils; import java.util.Map; /**** * @Author: jerusalem * @Description: Query * 查询参数 * @Date 2020/4/16 10:00 *****/ public class Query<T> { public IPage<T> getPage(Map<String, Object> params) { return this.getPage(params, null, false); } public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) { //分页参数 long curPage = 1; long limit = 10; if(params.get(Constant.PAGE) != null){ curPage = Long.parseLong((String)params.get(Constant.PAGE)); } if(params.get(Constant.LIMIT) != null){ limit = Long.parseLong((String)params.get(Constant.LIMIT)); } //分页对象 Page<T> page = new Page<>(curPage, limit); //分页参数 params.put(Constant.PAGE, page); //排序字段 //防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险) String orderField = SQLFilter.sqlInject((String)params.get(Constant.ORDER_FIELD)); String order = (String)params.get(Constant.ORDER); //前端字段排序 if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){ if(Constant.ASC.equalsIgnoreCase(order)) { return page.addOrder(OrderItem.asc(orderField)); }else { return page.addOrder(OrderItem.desc(orderField)); } } //没有排序字段,则不排序 if(StringUtils.isBlank(defaultOrderField)){ return page; } //默认排序 if(isAsc) { page.addOrder(OrderItem.asc(defaultOrderField)); }else { page.addOrder(OrderItem.desc(defaultOrderField)); } return page; } }
package com.jerusalem.common.xss; import com.jerusalem.common.utils.RRException; import org.apache.commons.lang.StringUtils; /**** * @Author: jerusalem * @Description: SQLFilter * SQL过滤 * @Date 2020/4/16 10:00 *****/ public class SQLFilter { /** * SQL注入过滤 * @param str 待验证的字符串 */ public static String sqlInject(String str){ if(StringUtils.isBlank(str)){ return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new RRException("包含非法字符"); } } return str; } }
package adminbasic.entity; import lombok.Data; import lombok.ToString; import java.io.Serializable; import java.util.UUID; /** * @author fdse */ @ToString @Data public class Contacts implements Serializable { private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId.equals(other.getAccountId()) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package adminorder.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.util.Date; import java.util.UUID; /** * @author fdse */ @ToString @Data @NoArgsConstructor @AllArgsConstructor public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId.equals(other.getAccountId()) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber.equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package admintravel.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package fdse.microservice.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; /** * @author fdse */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class Contacts { private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId .equals( other.getAccountId() ) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package fdse.microservice.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){} public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package cancel.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "taiyuan"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package contacts.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.UUID; /** * @author fdse */ @Data @AllArgsConstructor @Document(collection = "contacts") @JsonIgnoreProperties(ignoreUnknown = true) public class Contacts { @Id private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; public Contacts() { //Default Constructor } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId .equals( other.getAccountId() ) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package execute.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "上海"; to = "太原"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package inside_payment.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "太原"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package inside_payment.init; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; import inside_payment.repository.PaymentRepository; import inside_payment.service.InsidePaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * @author fdse */ @Component public class InitData implements CommandLineRunner { @Autowired InsidePaymentService service; @Autowired PaymentRepository paymentRepository; @Autowired AddMoneyRepository addMoneyRepository; @Override public void run(String... args) throws Exception{ AccountInfo info1 = new AccountInfo(); info1.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); info1.setMoney("10000"); service.createAccount(info1,null); Payment payment = new Payment(); payment.setId("5ad7750ba68b49c0a8c035276b321701"); payment.setOrderId("5ad7750b-a68b-49c0-a8c0-32776b067702"); payment.setPrice("100.0"); payment.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); payment.setType(PaymentType.P); service.initPayment(payment,null); } }
package order.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.ToString; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @Document(collection = "orders") @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class Order { @Id private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "1"; from = "shanghai"; to = "taiyuan"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package order.entity; import lombok.Data; import java.util.Date; /** * @author fdse */ @Data public class SoldTicket { private Date travelDate; private String trainNumber; private int noSeat; private int businessSeat; private int firstClassSeat; private int secondClassSeat; private int hardSeat; private int softSeat; private int hardBed; private int softBed; private int highSoftBed; public SoldTicket(){ noSeat = 0; businessSeat = 0; firstClassSeat = 0; secondClassSeat = 0; hardSeat = 0; softSeat = 0; hardBed = 0; softBed = 0; highSoftBed = 0; } }
package preserve.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Contacts { private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; public Contacts() { //Default Constructor } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId .equals( other.getAccountId() ) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package preserve.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "taiyuan"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price == other.price; } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package preserve.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){} public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package rebook.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Contacts { private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; public Contacts() { //Default Constructor } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId .equals( other.getAccountId() ) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
package rebook.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; private String differenceMoney; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "taiyuan"; status = OrderStatus.PAID.getCode(); price = "0.0"; differenceMoney ="0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price == other.price; } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package rebook.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package plan.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package security.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Order { private UUID id; private Date boughtDate; private Date travelDate; private Date travelTime; /** * Which Account Bought it */ private UUID accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; public Order(){ boughtDate = new Date(System.currentTimeMillis()); travelDate = new Date(123456789); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "上海"; to = "太原"; status = OrderStatus.PAID.getCode(); price = "0.0"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return boughtDate.equals(other.getBoughtDate()) && travelDate.equals(other.getTravelDate()) && travelTime.equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price == other.price; } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public void setTravelDate(int year,int month,int day){ Date date = new Date(year,month,day,0,0,0); //NOSONAR this.travelDate = date; } }
package security.init; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import security.entity.SecurityConfig; import security.service.SecurityService; /** * @author fdse */ @Component public class InitData implements CommandLineRunner { @Autowired private SecurityService securityService; @Override public void run(String... args) throws Exception { // a man can not buy too many tickets in one hour SecurityConfig info1 = new SecurityConfig(); info1.setName("max_order_1_hour"); info1.setValue(Integer.MAX_VALUE + ""); info1.setDescription("Max in 1 hour"); securityService.addNewSecurityConfig(info1,null); SecurityConfig info2 = new SecurityConfig(); info2.setName("max_order_not_use"); info2.setValue(Integer.MAX_VALUE + ""); info2.setDescription("Max not used"); securityService.addNewSecurityConfig(info2,null); } }
package ticketinfo.entity; import lombok.Data; import java.io.Serializable; @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package travelplan.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private TrainTypeEnum type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'G': this.type = TrainTypeEnum.G; break; case 'D': this.type = TrainTypeEnum.D; break; case 'Z': this.type = TrainTypeEnum.Z; break; case 'T': this.type = TrainTypeEnum.T; break; case 'K': this.type = TrainTypeEnum.K; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
package travel.entity; import lombok.Data; import java.util.Date; /** * @author fdse */ @Data public class SoldTicket { private Date travelDate; private String trainNumber; private int noSeat; private int businessSeat; private int firstClassSeat; private int secondClassSeat; private int hardSeat; private int softSeat; private int hardBed; private int softBed; private int highSoftBed; public SoldTicket(){ noSeat = 0; businessSeat = 0; firstClassSeat = 0; secondClassSeat = 0; hardSeat = 0; softSeat = 0; hardBed = 0; softBed = 0; highSoftBed = 0; } }
package travel.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable { private Type type; private String number; public TripId(Type type, String number) { this.type = type; this.number = number; } public TripId() { //Default Constructor } public TripId(String trainNumber) { char type0 = trainNumber.charAt(0); switch (type0) { case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; default: break; } this.number = trainNumber.substring(1); } @Override public String toString() { return type.getName() + number; } }
package com.wanxin.repayment.message; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.wanxin.api.repayment.model.RepaymentRequest; import com.wanxin.repayment.entity.RepaymentPlan; import com.wanxin.repayment.mapper.RepaymentPlanMapper; import com.wanxin.repayment.service.RepaymentService; import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.stereotype.Component; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Component @RocketMQTransactionListener(txProducerGroup = "PID_CONFIRM_REPAYMENT") public class ConfirmRepaymentTransactionListener implements RocketMQLocalTransactionListener { @Autowired private RepaymentService repaymentService; @Autowired private RepaymentPlanMapper repaymentPlanMapper; @Override public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) { // 解析消息 final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload())); RepaymentPlan repaymentPlan = JSONObject.parseObject(jsonObject.getString("repaymentPlan"), RepaymentPlan.class); RepaymentRequest repaymentRequest = JSONObject.parseObject(jsonObject.getString("repaymentRequest"), RepaymentRequest.class); // 执行本地事务 final Boolean isCommit = repaymentService.confirmRepayment(repaymentPlan, repaymentRequest); // 返回结果 if (isCommit) { return RocketMQLocalTransactionState.COMMIT; } else { return RocketMQLocalTransactionState.ROLLBACK; } } @Override public RocketMQLocalTransactionState checkLocalTransaction(Message message) { // 解析消息 final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload())); RepaymentPlan repaymentPlan = JSONObject.parseObject(jsonObject.getString("repaymentPlan"), RepaymentPlan.class); // 事务状态回查 RepaymentPlan newRepaymentPlan = repaymentPlanMapper.selectById(repaymentPlan.getId()); // 返回结果 if (newRepaymentPlan != null && "1".equals(newRepaymentPlan.getRepaymentStatus())) { return RocketMQLocalTransactionState.COMMIT; } else { return RocketMQLocalTransactionState.ROLLBACK; } } }
package com.wanxin.transaction.message; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.wanxin.common.domain.ProjectCode; import com.wanxin.transaction.entity.Project; import com.wanxin.transaction.mapper.ProjectMapper; import com.wanxin.transaction.service.ProjectService; import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.stereotype.Component; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Component @RocketMQTransactionListener(txProducerGroup = "PID_START_REPAYMENT") public class TransactionListenerImpl implements RocketMQLocalTransactionListener { @Autowired private ProjectService projectService; @Autowired private ProjectMapper projectMapper; /** * 执行本地事务 * * @param message * @param o * @return */ @Override public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) { // 解析消息 final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload())); Project project = JSONObject.parseObject(jsonObject.getString("project"), Project.class); // 执行本地事务 Boolean result = projectService.updateProjectStatusAndStartRepayment(project); // 返回执行结果 if (result) { return RocketMQLocalTransactionState.COMMIT; } else { return RocketMQLocalTransactionState.ROLLBACK; } } /** * 事务回查 * * @param message * @return */ @Override public RocketMQLocalTransactionState checkLocalTransaction(Message message) { // 解析消息 final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload())); Project project = JSONObject.parseObject(jsonObject.getString("project"), Project.class); // 查询标的状态 Project pro = projectMapper.selectById(project.getId()); // 返回结果 if (pro.getProjectStatus().equals(ProjectCode.REPAYING.getCode())) { return RocketMQLocalTransactionState.COMMIT; } else { return RocketMQLocalTransactionState.ROLLBACK; } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsArticle implements Serializable { /** * 文章编号 * * @mbg.generated */ private Integer articleId; /** * 所属专题 * * @mbg.generated */ private Integer topicId; /** * 文章标题 * * @mbg.generated */ private String title; /** * 文章原作者 * * @mbg.generated */ private String author; /** * 转载来源网址 * * @mbg.generated */ private String fromurl; /** * 封面图 * * @mbg.generated */ private String image; /** * 关键字 * * @mbg.generated */ private String keywords; /** * 简介 * * @mbg.generated */ private String description; /** * 类型(1:普通,2:热门...) * * @mbg.generated */ private Byte type; /** * 是否允许评论(0:不允许,1:允许) * * @mbg.generated */ private Byte allowcomments; /** * 状态(-1:不通过,0未审核,1:通过) * * @mbg.generated */ private Byte status; /** * 发布人id * * @mbg.generated */ private Integer userId; /** * 阅读数量 * * @mbg.generated */ private Integer readnumber; /** * 置顶等级 * * @mbg.generated */ private Integer top; /** * 所属系统 * * @mbg.generated */ private Integer systemId; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; /** * 内容 * * @mbg.generated */ private String content; private static final long serialVersionUID = 1L; public Integer getArticleId() { return articleId; } public void setArticleId(Integer articleId) { this.articleId = articleId; } public Integer getTopicId() { return topicId; } public void setTopicId(Integer topicId) { this.topicId = topicId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getFromurl() { return fromurl; } public void setFromurl(String fromurl) { this.fromurl = fromurl; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public Byte getAllowcomments() { return allowcomments; } public void setAllowcomments(Byte allowcomments) { this.allowcomments = allowcomments; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getReadnumber() { return readnumber; } public void setReadnumber(Integer readnumber) { this.readnumber = readnumber; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", articleId=").append(articleId); sb.append(", topicId=").append(topicId); sb.append(", title=").append(title); sb.append(", author=").append(author); sb.append(", fromurl=").append(fromurl); sb.append(", image=").append(image); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", type=").append(type); sb.append(", allowcomments=").append(allowcomments); sb.append(", status=").append(status); sb.append(", userId=").append(userId); sb.append(", readnumber=").append(readnumber); sb.append(", top=").append(top); sb.append(", systemId=").append(systemId); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append(", content=").append(content); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsArticle other = (CmsArticle) that; return (this.getArticleId() == null ? other.getArticleId() == null : this.getArticleId().equals(other.getArticleId())) && (this.getTopicId() == null ? other.getTopicId() == null : this.getTopicId().equals(other.getTopicId())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getAuthor() == null ? other.getAuthor() == null : this.getAuthor().equals(other.getAuthor())) && (this.getFromurl() == null ? other.getFromurl() == null : this.getFromurl().equals(other.getFromurl())) && (this.getImage() == null ? other.getImage() == null : this.getImage().equals(other.getImage())) && (this.getKeywords() == null ? other.getKeywords() == null : this.getKeywords().equals(other.getKeywords())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getAllowcomments() == null ? other.getAllowcomments() == null : this.getAllowcomments().equals(other.getAllowcomments())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getReadnumber() == null ? other.getReadnumber() == null : this.getReadnumber().equals(other.getReadnumber())) && (this.getTop() == null ? other.getTop() == null : this.getTop().equals(other.getTop())) && (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArticleId() == null) ? 0 : getArticleId().hashCode()); result = prime * result + ((getTopicId() == null) ? 0 : getTopicId().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getAuthor() == null) ? 0 : getAuthor().hashCode()); result = prime * result + ((getFromurl() == null) ? 0 : getFromurl().hashCode()); result = prime * result + ((getImage() == null) ? 0 : getImage().hashCode()); result = prime * result + ((getKeywords() == null) ? 0 : getKeywords().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getAllowcomments() == null) ? 0 : getAllowcomments().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getReadnumber() == null) ? 0 : getReadnumber().hashCode()); result = prime * result + ((getTop() == null) ? 0 : getTop().hashCode()); result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsArticleCategory implements Serializable { /** * 编号 * * @mbg.generated */ private Integer articleCategoryId; /** * 文章编号 * * @mbg.generated */ private Integer articleId; /** * 类目编号 * * @mbg.generated */ private Integer categoryId; private static final long serialVersionUID = 1L; public Integer getArticleCategoryId() { return articleCategoryId; } public void setArticleCategoryId(Integer articleCategoryId) { this.articleCategoryId = articleCategoryId; } public Integer getArticleId() { return articleId; } public void setArticleId(Integer articleId) { this.articleId = articleId; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", articleCategoryId=").append(articleCategoryId); sb.append(", articleId=").append(articleId); sb.append(", categoryId=").append(categoryId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsArticleCategory other = (CmsArticleCategory) that; return (this.getArticleCategoryId() == null ? other.getArticleCategoryId() == null : this.getArticleCategoryId().equals(other.getArticleCategoryId())) && (this.getArticleId() == null ? other.getArticleId() == null : this.getArticleId().equals(other.getArticleId())) && (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArticleCategoryId() == null) ? 0 : getArticleCategoryId().hashCode()); result = prime * result + ((getArticleId() == null) ? 0 : getArticleId().hashCode()); result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsArticleCategoryExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsArticleCategoryExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andArticleCategoryIdIsNull() { addCriterion("article_category_id is null"); return (Criteria) this; } public Criteria andArticleCategoryIdIsNotNull() { addCriterion("article_category_id is not null"); return (Criteria) this; } public Criteria andArticleCategoryIdEqualTo(Integer value) { addCriterion("article_category_id =", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdNotEqualTo(Integer value) { addCriterion("article_category_id <>", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdGreaterThan(Integer value) { addCriterion("article_category_id >", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_category_id >=", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdLessThan(Integer value) { addCriterion("article_category_id <", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdLessThanOrEqualTo(Integer value) { addCriterion("article_category_id <=", value, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdIn(List<Integer> values) { addCriterion("article_category_id in", values, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdNotIn(List<Integer> values) { addCriterion("article_category_id not in", values, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdBetween(Integer value1, Integer value2) { addCriterion("article_category_id between", value1, value2, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleCategoryIdNotBetween(Integer value1, Integer value2) { addCriterion("article_category_id not between", value1, value2, "articleCategoryId"); return (Criteria) this; } public Criteria andArticleIdIsNull() { addCriterion("article_id is null"); return (Criteria) this; } public Criteria andArticleIdIsNotNull() { addCriterion("article_id is not null"); return (Criteria) this; } public Criteria andArticleIdEqualTo(Integer value) { addCriterion("article_id =", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotEqualTo(Integer value) { addCriterion("article_id <>", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThan(Integer value) { addCriterion("article_id >", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_id >=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThan(Integer value) { addCriterion("article_id <", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThanOrEqualTo(Integer value) { addCriterion("article_id <=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdIn(List<Integer> values) { addCriterion("article_id in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotIn(List<Integer> values) { addCriterion("article_id not in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdBetween(Integer value1, Integer value2) { addCriterion("article_id between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotBetween(Integer value1, Integer value2) { addCriterion("article_id not between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andCategoryIdIsNull() { addCriterion("category_id is null"); return (Criteria) this; } public Criteria andCategoryIdIsNotNull() { addCriterion("category_id is not null"); return (Criteria) this; } public Criteria andCategoryIdEqualTo(Integer value) { addCriterion("category_id =", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotEqualTo(Integer value) { addCriterion("category_id <>", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThan(Integer value) { addCriterion("category_id >", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThanOrEqualTo(Integer value) { addCriterion("category_id >=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThan(Integer value) { addCriterion("category_id <", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThanOrEqualTo(Integer value) { addCriterion("category_id <=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdIn(List<Integer> values) { addCriterion("category_id in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotIn(List<Integer> values) { addCriterion("category_id not in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdBetween(Integer value1, Integer value2) { addCriterion("category_id between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotBetween(Integer value1, Integer value2) { addCriterion("category_id not between", value1, value2, "categoryId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsArticleExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsArticleExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andArticleIdIsNull() { addCriterion("article_id is null"); return (Criteria) this; } public Criteria andArticleIdIsNotNull() { addCriterion("article_id is not null"); return (Criteria) this; } public Criteria andArticleIdEqualTo(Integer value) { addCriterion("article_id =", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotEqualTo(Integer value) { addCriterion("article_id <>", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThan(Integer value) { addCriterion("article_id >", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_id >=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThan(Integer value) { addCriterion("article_id <", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThanOrEqualTo(Integer value) { addCriterion("article_id <=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdIn(List<Integer> values) { addCriterion("article_id in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotIn(List<Integer> values) { addCriterion("article_id not in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdBetween(Integer value1, Integer value2) { addCriterion("article_id between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotBetween(Integer value1, Integer value2) { addCriterion("article_id not between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andTopicIdIsNull() { addCriterion("topic_id is null"); return (Criteria) this; } public Criteria andTopicIdIsNotNull() { addCriterion("topic_id is not null"); return (Criteria) this; } public Criteria andTopicIdEqualTo(Integer value) { addCriterion("topic_id =", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotEqualTo(Integer value) { addCriterion("topic_id <>", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdGreaterThan(Integer value) { addCriterion("topic_id >", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdGreaterThanOrEqualTo(Integer value) { addCriterion("topic_id >=", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdLessThan(Integer value) { addCriterion("topic_id <", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdLessThanOrEqualTo(Integer value) { addCriterion("topic_id <=", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdIn(List<Integer> values) { addCriterion("topic_id in", values, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotIn(List<Integer> values) { addCriterion("topic_id not in", values, "topicId"); return (Criteria) this; } public Criteria andTopicIdBetween(Integer value1, Integer value2) { addCriterion("topic_id between", value1, value2, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotBetween(Integer value1, Integer value2) { addCriterion("topic_id not between", value1, value2, "topicId"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andAuthorIsNull() { addCriterion("author is null"); return (Criteria) this; } public Criteria andAuthorIsNotNull() { addCriterion("author is not null"); return (Criteria) this; } public Criteria andAuthorEqualTo(String value) { addCriterion("author =", value, "author"); return (Criteria) this; } public Criteria andAuthorNotEqualTo(String value) { addCriterion("author <>", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThan(String value) { addCriterion("author >", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThanOrEqualTo(String value) { addCriterion("author >=", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThan(String value) { addCriterion("author <", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThanOrEqualTo(String value) { addCriterion("author <=", value, "author"); return (Criteria) this; } public Criteria andAuthorLike(String value) { addCriterion("author like", value, "author"); return (Criteria) this; } public Criteria andAuthorNotLike(String value) { addCriterion("author not like", value, "author"); return (Criteria) this; } public Criteria andAuthorIn(List<String> values) { addCriterion("author in", values, "author"); return (Criteria) this; } public Criteria andAuthorNotIn(List<String> values) { addCriterion("author not in", values, "author"); return (Criteria) this; } public Criteria andAuthorBetween(String value1, String value2) { addCriterion("author between", value1, value2, "author"); return (Criteria) this; } public Criteria andAuthorNotBetween(String value1, String value2) { addCriterion("author not between", value1, value2, "author"); return (Criteria) this; } public Criteria andFromurlIsNull() { addCriterion("fromurl is null"); return (Criteria) this; } public Criteria andFromurlIsNotNull() { addCriterion("fromurl is not null"); return (Criteria) this; } public Criteria andFromurlEqualTo(String value) { addCriterion("fromurl =", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlNotEqualTo(String value) { addCriterion("fromurl <>", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlGreaterThan(String value) { addCriterion("fromurl >", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlGreaterThanOrEqualTo(String value) { addCriterion("fromurl >=", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlLessThan(String value) { addCriterion("fromurl <", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlLessThanOrEqualTo(String value) { addCriterion("fromurl <=", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlLike(String value) { addCriterion("fromurl like", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlNotLike(String value) { addCriterion("fromurl not like", value, "fromurl"); return (Criteria) this; } public Criteria andFromurlIn(List<String> values) { addCriterion("fromurl in", values, "fromurl"); return (Criteria) this; } public Criteria andFromurlNotIn(List<String> values) { addCriterion("fromurl not in", values, "fromurl"); return (Criteria) this; } public Criteria andFromurlBetween(String value1, String value2) { addCriterion("fromurl between", value1, value2, "fromurl"); return (Criteria) this; } public Criteria andFromurlNotBetween(String value1, String value2) { addCriterion("fromurl not between", value1, value2, "fromurl"); return (Criteria) this; } public Criteria andImageIsNull() { addCriterion("image is null"); return (Criteria) this; } public Criteria andImageIsNotNull() { addCriterion("image is not null"); return (Criteria) this; } public Criteria andImageEqualTo(String value) { addCriterion("image =", value, "image"); return (Criteria) this; } public Criteria andImageNotEqualTo(String value) { addCriterion("image <>", value, "image"); return (Criteria) this; } public Criteria andImageGreaterThan(String value) { addCriterion("image >", value, "image"); return (Criteria) this; } public Criteria andImageGreaterThanOrEqualTo(String value) { addCriterion("image >=", value, "image"); return (Criteria) this; } public Criteria andImageLessThan(String value) { addCriterion("image <", value, "image"); return (Criteria) this; } public Criteria andImageLessThanOrEqualTo(String value) { addCriterion("image <=", value, "image"); return (Criteria) this; } public Criteria andImageLike(String value) { addCriterion("image like", value, "image"); return (Criteria) this; } public Criteria andImageNotLike(String value) { addCriterion("image not like", value, "image"); return (Criteria) this; } public Criteria andImageIn(List<String> values) { addCriterion("image in", values, "image"); return (Criteria) this; } public Criteria andImageNotIn(List<String> values) { addCriterion("image not in", values, "image"); return (Criteria) this; } public Criteria andImageBetween(String value1, String value2) { addCriterion("image between", value1, value2, "image"); return (Criteria) this; } public Criteria andImageNotBetween(String value1, String value2) { addCriterion("image not between", value1, value2, "image"); return (Criteria) this; } public Criteria andKeywordsIsNull() { addCriterion("keywords is null"); return (Criteria) this; } public Criteria andKeywordsIsNotNull() { addCriterion("keywords is not null"); return (Criteria) this; } public Criteria andKeywordsEqualTo(String value) { addCriterion("keywords =", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotEqualTo(String value) { addCriterion("keywords <>", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsGreaterThan(String value) { addCriterion("keywords >", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsGreaterThanOrEqualTo(String value) { addCriterion("keywords >=", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLessThan(String value) { addCriterion("keywords <", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLessThanOrEqualTo(String value) { addCriterion("keywords <=", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLike(String value) { addCriterion("keywords like", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotLike(String value) { addCriterion("keywords not like", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsIn(List<String> values) { addCriterion("keywords in", values, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotIn(List<String> values) { addCriterion("keywords not in", values, "keywords"); return (Criteria) this; } public Criteria andKeywordsBetween(String value1, String value2) { addCriterion("keywords between", value1, value2, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotBetween(String value1, String value2) { addCriterion("keywords not between", value1, value2, "keywords"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andAllowcommentsIsNull() { addCriterion("allowcomments is null"); return (Criteria) this; } public Criteria andAllowcommentsIsNotNull() { addCriterion("allowcomments is not null"); return (Criteria) this; } public Criteria andAllowcommentsEqualTo(Byte value) { addCriterion("allowcomments =", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsNotEqualTo(Byte value) { addCriterion("allowcomments <>", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsGreaterThan(Byte value) { addCriterion("allowcomments >", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsGreaterThanOrEqualTo(Byte value) { addCriterion("allowcomments >=", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsLessThan(Byte value) { addCriterion("allowcomments <", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsLessThanOrEqualTo(Byte value) { addCriterion("allowcomments <=", value, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsIn(List<Byte> values) { addCriterion("allowcomments in", values, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsNotIn(List<Byte> values) { addCriterion("allowcomments not in", values, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsBetween(Byte value1, Byte value2) { addCriterion("allowcomments between", value1, value2, "allowcomments"); return (Criteria) this; } public Criteria andAllowcommentsNotBetween(Byte value1, Byte value2) { addCriterion("allowcomments not between", value1, value2, "allowcomments"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andReadnumberIsNull() { addCriterion("readnumber is null"); return (Criteria) this; } public Criteria andReadnumberIsNotNull() { addCriterion("readnumber is not null"); return (Criteria) this; } public Criteria andReadnumberEqualTo(Integer value) { addCriterion("readnumber =", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberNotEqualTo(Integer value) { addCriterion("readnumber <>", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberGreaterThan(Integer value) { addCriterion("readnumber >", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberGreaterThanOrEqualTo(Integer value) { addCriterion("readnumber >=", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberLessThan(Integer value) { addCriterion("readnumber <", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberLessThanOrEqualTo(Integer value) { addCriterion("readnumber <=", value, "readnumber"); return (Criteria) this; } public Criteria andReadnumberIn(List<Integer> values) { addCriterion("readnumber in", values, "readnumber"); return (Criteria) this; } public Criteria andReadnumberNotIn(List<Integer> values) { addCriterion("readnumber not in", values, "readnumber"); return (Criteria) this; } public Criteria andReadnumberBetween(Integer value1, Integer value2) { addCriterion("readnumber between", value1, value2, "readnumber"); return (Criteria) this; } public Criteria andReadnumberNotBetween(Integer value1, Integer value2) { addCriterion("readnumber not between", value1, value2, "readnumber"); return (Criteria) this; } public Criteria andTopIsNull() { addCriterion("top is null"); return (Criteria) this; } public Criteria andTopIsNotNull() { addCriterion("top is not null"); return (Criteria) this; } public Criteria andTopEqualTo(Integer value) { addCriterion("top =", value, "top"); return (Criteria) this; } public Criteria andTopNotEqualTo(Integer value) { addCriterion("top <>", value, "top"); return (Criteria) this; } public Criteria andTopGreaterThan(Integer value) { addCriterion("top >", value, "top"); return (Criteria) this; } public Criteria andTopGreaterThanOrEqualTo(Integer value) { addCriterion("top >=", value, "top"); return (Criteria) this; } public Criteria andTopLessThan(Integer value) { addCriterion("top <", value, "top"); return (Criteria) this; } public Criteria andTopLessThanOrEqualTo(Integer value) { addCriterion("top <=", value, "top"); return (Criteria) this; } public Criteria andTopIn(List<Integer> values) { addCriterion("top in", values, "top"); return (Criteria) this; } public Criteria andTopNotIn(List<Integer> values) { addCriterion("top not in", values, "top"); return (Criteria) this; } public Criteria andTopBetween(Integer value1, Integer value2) { addCriterion("top between", value1, value2, "top"); return (Criteria) this; } public Criteria andTopNotBetween(Integer value1, Integer value2) { addCriterion("top not between", value1, value2, "top"); return (Criteria) this; } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsArticleTag implements Serializable { /** * 编号 * * @mbg.generated */ private Integer articleTagId; /** * 文章编号 * * @mbg.generated */ private Integer articleId; /** * 标签编号 * * @mbg.generated */ private Integer tagId; private static final long serialVersionUID = 1L; public Integer getArticleTagId() { return articleTagId; } public void setArticleTagId(Integer articleTagId) { this.articleTagId = articleTagId; } public Integer getArticleId() { return articleId; } public void setArticleId(Integer articleId) { this.articleId = articleId; } public Integer getTagId() { return tagId; } public void setTagId(Integer tagId) { this.tagId = tagId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", articleTagId=").append(articleTagId); sb.append(", articleId=").append(articleId); sb.append(", tagId=").append(tagId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsArticleTag other = (CmsArticleTag) that; return (this.getArticleTagId() == null ? other.getArticleTagId() == null : this.getArticleTagId().equals(other.getArticleTagId())) && (this.getArticleId() == null ? other.getArticleId() == null : this.getArticleId().equals(other.getArticleId())) && (this.getTagId() == null ? other.getTagId() == null : this.getTagId().equals(other.getTagId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArticleTagId() == null) ? 0 : getArticleTagId().hashCode()); result = prime * result + ((getArticleId() == null) ? 0 : getArticleId().hashCode()); result = prime * result + ((getTagId() == null) ? 0 : getTagId().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsArticleTagExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsArticleTagExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andArticleTagIdIsNull() { addCriterion("article_tag_id is null"); return (Criteria) this; } public Criteria andArticleTagIdIsNotNull() { addCriterion("article_tag_id is not null"); return (Criteria) this; } public Criteria andArticleTagIdEqualTo(Integer value) { addCriterion("article_tag_id =", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdNotEqualTo(Integer value) { addCriterion("article_tag_id <>", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdGreaterThan(Integer value) { addCriterion("article_tag_id >", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_tag_id >=", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdLessThan(Integer value) { addCriterion("article_tag_id <", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdLessThanOrEqualTo(Integer value) { addCriterion("article_tag_id <=", value, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdIn(List<Integer> values) { addCriterion("article_tag_id in", values, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdNotIn(List<Integer> values) { addCriterion("article_tag_id not in", values, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdBetween(Integer value1, Integer value2) { addCriterion("article_tag_id between", value1, value2, "articleTagId"); return (Criteria) this; } public Criteria andArticleTagIdNotBetween(Integer value1, Integer value2) { addCriterion("article_tag_id not between", value1, value2, "articleTagId"); return (Criteria) this; } public Criteria andArticleIdIsNull() { addCriterion("article_id is null"); return (Criteria) this; } public Criteria andArticleIdIsNotNull() { addCriterion("article_id is not null"); return (Criteria) this; } public Criteria andArticleIdEqualTo(Integer value) { addCriterion("article_id =", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotEqualTo(Integer value) { addCriterion("article_id <>", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThan(Integer value) { addCriterion("article_id >", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_id >=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThan(Integer value) { addCriterion("article_id <", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThanOrEqualTo(Integer value) { addCriterion("article_id <=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdIn(List<Integer> values) { addCriterion("article_id in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotIn(List<Integer> values) { addCriterion("article_id not in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdBetween(Integer value1, Integer value2) { addCriterion("article_id between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotBetween(Integer value1, Integer value2) { addCriterion("article_id not between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andTagIdIsNull() { addCriterion("tag_id is null"); return (Criteria) this; } public Criteria andTagIdIsNotNull() { addCriterion("tag_id is not null"); return (Criteria) this; } public Criteria andTagIdEqualTo(Integer value) { addCriterion("tag_id =", value, "tagId"); return (Criteria) this; } public Criteria andTagIdNotEqualTo(Integer value) { addCriterion("tag_id <>", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThan(Integer value) { addCriterion("tag_id >", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThanOrEqualTo(Integer value) { addCriterion("tag_id >=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThan(Integer value) { addCriterion("tag_id <", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThanOrEqualTo(Integer value) { addCriterion("tag_id <=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdIn(List<Integer> values) { addCriterion("tag_id in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdNotIn(List<Integer> values) { addCriterion("tag_id not in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdBetween(Integer value1, Integer value2) { addCriterion("tag_id between", value1, value2, "tagId"); return (Criteria) this; } public Criteria andTagIdNotBetween(Integer value1, Integer value2) { addCriterion("tag_id not between", value1, value2, "tagId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsCategory implements Serializable { /** * 类目编号 * * @mbg.generated */ private Integer categoryId; /** * 上级编号 * * @mbg.generated */ private Integer pid; /** * 层级 * * @mbg.generated */ private Byte level; /** * 名称 * * @mbg.generated */ private String name; /** * 描述 * * @mbg.generated */ private String description; /** * 图标 * * @mbg.generated */ private String icon; /** * 类型(1:普通,2:热门...) * * @mbg.generated */ private Byte type; /** * 别名 * * @mbg.generated */ private String alias; /** * 所属系统 * * @mbg.generated */ private Integer systemId; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public Byte getLevel() { return level; } public void setLevel(Byte level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", categoryId=").append(categoryId); sb.append(", pid=").append(pid); sb.append(", level=").append(level); sb.append(", name=").append(name); sb.append(", description=").append(description); sb.append(", icon=").append(icon); sb.append(", type=").append(type); sb.append(", alias=").append(alias); sb.append(", systemId=").append(systemId); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsCategory other = (CmsCategory) that; return (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getLevel() == null ? other.getLevel() == null : this.getLevel().equals(other.getLevel())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getAlias() == null ? other.getAlias() == null : this.getAlias().equals(other.getAlias())) && (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getLevel() == null) ? 0 : getLevel().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getAlias() == null) ? 0 : getAlias().hashCode()); result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsCategoryExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsCategoryExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCategoryIdIsNull() { addCriterion("category_id is null"); return (Criteria) this; } public Criteria andCategoryIdIsNotNull() { addCriterion("category_id is not null"); return (Criteria) this; } public Criteria andCategoryIdEqualTo(Integer value) { addCriterion("category_id =", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotEqualTo(Integer value) { addCriterion("category_id <>", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThan(Integer value) { addCriterion("category_id >", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThanOrEqualTo(Integer value) { addCriterion("category_id >=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThan(Integer value) { addCriterion("category_id <", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThanOrEqualTo(Integer value) { addCriterion("category_id <=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdIn(List<Integer> values) { addCriterion("category_id in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotIn(List<Integer> values) { addCriterion("category_id not in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdBetween(Integer value1, Integer value2) { addCriterion("category_id between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotBetween(Integer value1, Integer value2) { addCriterion("category_id not between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andLevelIsNull() { addCriterion("level is null"); return (Criteria) this; } public Criteria andLevelIsNotNull() { addCriterion("level is not null"); return (Criteria) this; } public Criteria andLevelEqualTo(Byte value) { addCriterion("level =", value, "level"); return (Criteria) this; } public Criteria andLevelNotEqualTo(Byte value) { addCriterion("level <>", value, "level"); return (Criteria) this; } public Criteria andLevelGreaterThan(Byte value) { addCriterion("level >", value, "level"); return (Criteria) this; } public Criteria andLevelGreaterThanOrEqualTo(Byte value) { addCriterion("level >=", value, "level"); return (Criteria) this; } public Criteria andLevelLessThan(Byte value) { addCriterion("level <", value, "level"); return (Criteria) this; } public Criteria andLevelLessThanOrEqualTo(Byte value) { addCriterion("level <=", value, "level"); return (Criteria) this; } public Criteria andLevelIn(List<Byte> values) { addCriterion("level in", values, "level"); return (Criteria) this; } public Criteria andLevelNotIn(List<Byte> values) { addCriterion("level not in", values, "level"); return (Criteria) this; } public Criteria andLevelBetween(Byte value1, Byte value2) { addCriterion("level between", value1, value2, "level"); return (Criteria) this; } public Criteria andLevelNotBetween(Byte value1, Byte value2) { addCriterion("level not between", value1, value2, "level"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andIconIsNull() { addCriterion("icon is null"); return (Criteria) this; } public Criteria andIconIsNotNull() { addCriterion("icon is not null"); return (Criteria) this; } public Criteria andIconEqualTo(String value) { addCriterion("icon =", value, "icon"); return (Criteria) this; } public Criteria andIconNotEqualTo(String value) { addCriterion("icon <>", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThan(String value) { addCriterion("icon >", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThanOrEqualTo(String value) { addCriterion("icon >=", value, "icon"); return (Criteria) this; } public Criteria andIconLessThan(String value) { addCriterion("icon <", value, "icon"); return (Criteria) this; } public Criteria andIconLessThanOrEqualTo(String value) { addCriterion("icon <=", value, "icon"); return (Criteria) this; } public Criteria andIconLike(String value) { addCriterion("icon like", value, "icon"); return (Criteria) this; } public Criteria andIconNotLike(String value) { addCriterion("icon not like", value, "icon"); return (Criteria) this; } public Criteria andIconIn(List<String> values) { addCriterion("icon in", values, "icon"); return (Criteria) this; } public Criteria andIconNotIn(List<String> values) { addCriterion("icon not in", values, "icon"); return (Criteria) this; } public Criteria andIconBetween(String value1, String value2) { addCriterion("icon between", value1, value2, "icon"); return (Criteria) this; } public Criteria andIconNotBetween(String value1, String value2) { addCriterion("icon not between", value1, value2, "icon"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andAliasIsNull() { addCriterion("alias is null"); return (Criteria) this; } public Criteria andAliasIsNotNull() { addCriterion("alias is not null"); return (Criteria) this; } public Criteria andAliasEqualTo(String value) { addCriterion("alias =", value, "alias"); return (Criteria) this; } public Criteria andAliasNotEqualTo(String value) { addCriterion("alias <>", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThan(String value) { addCriterion("alias >", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThanOrEqualTo(String value) { addCriterion("alias >=", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThan(String value) { addCriterion("alias <", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThanOrEqualTo(String value) { addCriterion("alias <=", value, "alias"); return (Criteria) this; } public Criteria andAliasLike(String value) { addCriterion("alias like", value, "alias"); return (Criteria) this; } public Criteria andAliasNotLike(String value) { addCriterion("alias not like", value, "alias"); return (Criteria) this; } public Criteria andAliasIn(List<String> values) { addCriterion("alias in", values, "alias"); return (Criteria) this; } public Criteria andAliasNotIn(List<String> values) { addCriterion("alias not in", values, "alias"); return (Criteria) this; } public Criteria andAliasBetween(String value1, String value2) { addCriterion("alias between", value1, value2, "alias"); return (Criteria) this; } public Criteria andAliasNotBetween(String value1, String value2) { addCriterion("alias not between", value1, value2, "alias"); return (Criteria) this; } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsCategoryTag implements Serializable { /** * 编号 * * @mbg.generated */ private Integer categoryTagId; /** * 类目编号 * * @mbg.generated */ private Integer categoryId; /** * 标签编号 * * @mbg.generated */ private Integer tagId; private static final long serialVersionUID = 1L; public Integer getCategoryTagId() { return categoryTagId; } public void setCategoryTagId(Integer categoryTagId) { this.categoryTagId = categoryTagId; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Integer getTagId() { return tagId; } public void setTagId(Integer tagId) { this.tagId = tagId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", categoryTagId=").append(categoryTagId); sb.append(", categoryId=").append(categoryId); sb.append(", tagId=").append(tagId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsCategoryTag other = (CmsCategoryTag) that; return (this.getCategoryTagId() == null ? other.getCategoryTagId() == null : this.getCategoryTagId().equals(other.getCategoryTagId())) && (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId())) && (this.getTagId() == null ? other.getTagId() == null : this.getTagId().equals(other.getTagId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCategoryTagId() == null) ? 0 : getCategoryTagId().hashCode()); result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode()); result = prime * result + ((getTagId() == null) ? 0 : getTagId().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsCategoryTagExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsCategoryTagExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCategoryTagIdIsNull() { addCriterion("category_tag_id is null"); return (Criteria) this; } public Criteria andCategoryTagIdIsNotNull() { addCriterion("category_tag_id is not null"); return (Criteria) this; } public Criteria andCategoryTagIdEqualTo(Integer value) { addCriterion("category_tag_id =", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdNotEqualTo(Integer value) { addCriterion("category_tag_id <>", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdGreaterThan(Integer value) { addCriterion("category_tag_id >", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdGreaterThanOrEqualTo(Integer value) { addCriterion("category_tag_id >=", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdLessThan(Integer value) { addCriterion("category_tag_id <", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdLessThanOrEqualTo(Integer value) { addCriterion("category_tag_id <=", value, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdIn(List<Integer> values) { addCriterion("category_tag_id in", values, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdNotIn(List<Integer> values) { addCriterion("category_tag_id not in", values, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdBetween(Integer value1, Integer value2) { addCriterion("category_tag_id between", value1, value2, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryTagIdNotBetween(Integer value1, Integer value2) { addCriterion("category_tag_id not between", value1, value2, "categoryTagId"); return (Criteria) this; } public Criteria andCategoryIdIsNull() { addCriterion("category_id is null"); return (Criteria) this; } public Criteria andCategoryIdIsNotNull() { addCriterion("category_id is not null"); return (Criteria) this; } public Criteria andCategoryIdEqualTo(Integer value) { addCriterion("category_id =", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotEqualTo(Integer value) { addCriterion("category_id <>", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThan(Integer value) { addCriterion("category_id >", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdGreaterThanOrEqualTo(Integer value) { addCriterion("category_id >=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThan(Integer value) { addCriterion("category_id <", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdLessThanOrEqualTo(Integer value) { addCriterion("category_id <=", value, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdIn(List<Integer> values) { addCriterion("category_id in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotIn(List<Integer> values) { addCriterion("category_id not in", values, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdBetween(Integer value1, Integer value2) { addCriterion("category_id between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andCategoryIdNotBetween(Integer value1, Integer value2) { addCriterion("category_id not between", value1, value2, "categoryId"); return (Criteria) this; } public Criteria andTagIdIsNull() { addCriterion("tag_id is null"); return (Criteria) this; } public Criteria andTagIdIsNotNull() { addCriterion("tag_id is not null"); return (Criteria) this; } public Criteria andTagIdEqualTo(Integer value) { addCriterion("tag_id =", value, "tagId"); return (Criteria) this; } public Criteria andTagIdNotEqualTo(Integer value) { addCriterion("tag_id <>", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThan(Integer value) { addCriterion("tag_id >", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThanOrEqualTo(Integer value) { addCriterion("tag_id >=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThan(Integer value) { addCriterion("tag_id <", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThanOrEqualTo(Integer value) { addCriterion("tag_id <=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdIn(List<Integer> values) { addCriterion("tag_id in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdNotIn(List<Integer> values) { addCriterion("tag_id not in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdBetween(Integer value1, Integer value2) { addCriterion("tag_id between", value1, value2, "tagId"); return (Criteria) this; } public Criteria andTagIdNotBetween(Integer value1, Integer value2) { addCriterion("tag_id not between", value1, value2, "tagId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsComment implements Serializable { /** * 编号 * * @mbg.generated */ private Integer commentId; /** * 回复楼中楼编号回复楼中楼编号 * * @mbg.generated */ private Integer pid; /** * 文章编号 * * @mbg.generated */ private Integer articleId; /** * 用户编号 * * @mbg.generated */ private Integer userId; /** * 状态(-1:不通过,0:未审核,1:通过) * * @mbg.generated */ private Byte status; /** * 评论人ip地址 * * @mbg.generated */ private String ip; /** * 评论人终端信息 * * @mbg.generated */ private String agent; /** * 所属系统 * * @mbg.generated */ private Integer systemId; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 评论内容 * * @mbg.generated */ private String content; private static final long serialVersionUID = 1L; public Integer getCommentId() { return commentId; } public void setCommentId(Integer commentId) { this.commentId = commentId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public Integer getArticleId() { return articleId; } public void setArticleId(Integer articleId) { this.articleId = articleId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getAgent() { return agent; } public void setAgent(String agent) { this.agent = agent; } public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", commentId=").append(commentId); sb.append(", pid=").append(pid); sb.append(", articleId=").append(articleId); sb.append(", userId=").append(userId); sb.append(", status=").append(status); sb.append(", ip=").append(ip); sb.append(", agent=").append(agent); sb.append(", systemId=").append(systemId); sb.append(", ctime=").append(ctime); sb.append(", content=").append(content); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsComment other = (CmsComment) that; return (this.getCommentId() == null ? other.getCommentId() == null : this.getCommentId().equals(other.getCommentId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getArticleId() == null ? other.getArticleId() == null : this.getArticleId().equals(other.getArticleId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getIp() == null ? other.getIp() == null : this.getIp().equals(other.getIp())) && (this.getAgent() == null ? other.getAgent() == null : this.getAgent().equals(other.getAgent())) && (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCommentId() == null) ? 0 : getCommentId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getArticleId() == null) ? 0 : getArticleId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getIp() == null) ? 0 : getIp().hashCode()); result = prime * result + ((getAgent() == null) ? 0 : getAgent().hashCode()); result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsCommentExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsCommentExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCommentIdIsNull() { addCriterion("comment_id is null"); return (Criteria) this; } public Criteria andCommentIdIsNotNull() { addCriterion("comment_id is not null"); return (Criteria) this; } public Criteria andCommentIdEqualTo(Integer value) { addCriterion("comment_id =", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotEqualTo(Integer value) { addCriterion("comment_id <>", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdGreaterThan(Integer value) { addCriterion("comment_id >", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdGreaterThanOrEqualTo(Integer value) { addCriterion("comment_id >=", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdLessThan(Integer value) { addCriterion("comment_id <", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdLessThanOrEqualTo(Integer value) { addCriterion("comment_id <=", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdIn(List<Integer> values) { addCriterion("comment_id in", values, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotIn(List<Integer> values) { addCriterion("comment_id not in", values, "commentId"); return (Criteria) this; } public Criteria andCommentIdBetween(Integer value1, Integer value2) { addCriterion("comment_id between", value1, value2, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotBetween(Integer value1, Integer value2) { addCriterion("comment_id not between", value1, value2, "commentId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andArticleIdIsNull() { addCriterion("article_id is null"); return (Criteria) this; } public Criteria andArticleIdIsNotNull() { addCriterion("article_id is not null"); return (Criteria) this; } public Criteria andArticleIdEqualTo(Integer value) { addCriterion("article_id =", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotEqualTo(Integer value) { addCriterion("article_id <>", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThan(Integer value) { addCriterion("article_id >", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdGreaterThanOrEqualTo(Integer value) { addCriterion("article_id >=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThan(Integer value) { addCriterion("article_id <", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdLessThanOrEqualTo(Integer value) { addCriterion("article_id <=", value, "articleId"); return (Criteria) this; } public Criteria andArticleIdIn(List<Integer> values) { addCriterion("article_id in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotIn(List<Integer> values) { addCriterion("article_id not in", values, "articleId"); return (Criteria) this; } public Criteria andArticleIdBetween(Integer value1, Integer value2) { addCriterion("article_id between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andArticleIdNotBetween(Integer value1, Integer value2) { addCriterion("article_id not between", value1, value2, "articleId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andIpIsNull() { addCriterion("ip is null"); return (Criteria) this; } public Criteria andIpIsNotNull() { addCriterion("ip is not null"); return (Criteria) this; } public Criteria andIpEqualTo(String value) { addCriterion("ip =", value, "ip"); return (Criteria) this; } public Criteria andIpNotEqualTo(String value) { addCriterion("ip <>", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThan(String value) { addCriterion("ip >", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThanOrEqualTo(String value) { addCriterion("ip >=", value, "ip"); return (Criteria) this; } public Criteria andIpLessThan(String value) { addCriterion("ip <", value, "ip"); return (Criteria) this; } public Criteria andIpLessThanOrEqualTo(String value) { addCriterion("ip <=", value, "ip"); return (Criteria) this; } public Criteria andIpLike(String value) { addCriterion("ip like", value, "ip"); return (Criteria) this; } public Criteria andIpNotLike(String value) { addCriterion("ip not like", value, "ip"); return (Criteria) this; } public Criteria andIpIn(List<String> values) { addCriterion("ip in", values, "ip"); return (Criteria) this; } public Criteria andIpNotIn(List<String> values) { addCriterion("ip not in", values, "ip"); return (Criteria) this; } public Criteria andIpBetween(String value1, String value2) { addCriterion("ip between", value1, value2, "ip"); return (Criteria) this; } public Criteria andIpNotBetween(String value1, String value2) { addCriterion("ip not between", value1, value2, "ip"); return (Criteria) this; } public Criteria andAgentIsNull() { addCriterion("agent is null"); return (Criteria) this; } public Criteria andAgentIsNotNull() { addCriterion("agent is not null"); return (Criteria) this; } public Criteria andAgentEqualTo(String value) { addCriterion("agent =", value, "agent"); return (Criteria) this; } public Criteria andAgentNotEqualTo(String value) { addCriterion("agent <>", value, "agent"); return (Criteria) this; } public Criteria andAgentGreaterThan(String value) { addCriterion("agent >", value, "agent"); return (Criteria) this; } public Criteria andAgentGreaterThanOrEqualTo(String value) { addCriterion("agent >=", value, "agent"); return (Criteria) this; } public Criteria andAgentLessThan(String value) { addCriterion("agent <", value, "agent"); return (Criteria) this; } public Criteria andAgentLessThanOrEqualTo(String value) { addCriterion("agent <=", value, "agent"); return (Criteria) this; } public Criteria andAgentLike(String value) { addCriterion("agent like", value, "agent"); return (Criteria) this; } public Criteria andAgentNotLike(String value) { addCriterion("agent not like", value, "agent"); return (Criteria) this; } public Criteria andAgentIn(List<String> values) { addCriterion("agent in", values, "agent"); return (Criteria) this; } public Criteria andAgentNotIn(List<String> values) { addCriterion("agent not in", values, "agent"); return (Criteria) this; } public Criteria andAgentBetween(String value1, String value2) { addCriterion("agent between", value1, value2, "agent"); return (Criteria) this; } public Criteria andAgentNotBetween(String value1, String value2) { addCriterion("agent not between", value1, value2, "agent"); return (Criteria) this; } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsMenu implements Serializable { /** * 编号 * * @mbg.generated */ private Integer menuId; /** * 父菜单 * * @mbg.generated */ private Integer pid; /** * 名称 * * @mbg.generated */ private String name; /** * 链接 * * @mbg.generated */ private String url; /** * 打开方式 * * @mbg.generated */ private String target; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", menuId=").append(menuId); sb.append(", pid=").append(pid); sb.append(", name=").append(name); sb.append(", url=").append(url); sb.append(", target=").append(target); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsMenu other = (CmsMenu) that; return (this.getMenuId() == null ? other.getMenuId() == null : this.getMenuId().equals(other.getMenuId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl())) && (this.getTarget() == null ? other.getTarget() == null : this.getTarget().equals(other.getTarget())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getMenuId() == null) ? 0 : getMenuId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getUrl() == null) ? 0 : getUrl().hashCode()); result = prime * result + ((getTarget() == null) ? 0 : getTarget().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsMenuExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsMenuExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andMenuIdIsNull() { addCriterion("menu_id is null"); return (Criteria) this; } public Criteria andMenuIdIsNotNull() { addCriterion("menu_id is not null"); return (Criteria) this; } public Criteria andMenuIdEqualTo(Integer value) { addCriterion("menu_id =", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdNotEqualTo(Integer value) { addCriterion("menu_id <>", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdGreaterThan(Integer value) { addCriterion("menu_id >", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdGreaterThanOrEqualTo(Integer value) { addCriterion("menu_id >=", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdLessThan(Integer value) { addCriterion("menu_id <", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdLessThanOrEqualTo(Integer value) { addCriterion("menu_id <=", value, "menuId"); return (Criteria) this; } public Criteria andMenuIdIn(List<Integer> values) { addCriterion("menu_id in", values, "menuId"); return (Criteria) this; } public Criteria andMenuIdNotIn(List<Integer> values) { addCriterion("menu_id not in", values, "menuId"); return (Criteria) this; } public Criteria andMenuIdBetween(Integer value1, Integer value2) { addCriterion("menu_id between", value1, value2, "menuId"); return (Criteria) this; } public Criteria andMenuIdNotBetween(Integer value1, Integer value2) { addCriterion("menu_id not between", value1, value2, "menuId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andUrlIsNull() { addCriterion("url is null"); return (Criteria) this; } public Criteria andUrlIsNotNull() { addCriterion("url is not null"); return (Criteria) this; } public Criteria andUrlEqualTo(String value) { addCriterion("url =", value, "url"); return (Criteria) this; } public Criteria andUrlNotEqualTo(String value) { addCriterion("url <>", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThan(String value) { addCriterion("url >", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThanOrEqualTo(String value) { addCriterion("url >=", value, "url"); return (Criteria) this; } public Criteria andUrlLessThan(String value) { addCriterion("url <", value, "url"); return (Criteria) this; } public Criteria andUrlLessThanOrEqualTo(String value) { addCriterion("url <=", value, "url"); return (Criteria) this; } public Criteria andUrlLike(String value) { addCriterion("url like", value, "url"); return (Criteria) this; } public Criteria andUrlNotLike(String value) { addCriterion("url not like", value, "url"); return (Criteria) this; } public Criteria andUrlIn(List<String> values) { addCriterion("url in", values, "url"); return (Criteria) this; } public Criteria andUrlNotIn(List<String> values) { addCriterion("url not in", values, "url"); return (Criteria) this; } public Criteria andUrlBetween(String value1, String value2) { addCriterion("url between", value1, value2, "url"); return (Criteria) this; } public Criteria andUrlNotBetween(String value1, String value2) { addCriterion("url not between", value1, value2, "url"); return (Criteria) this; } public Criteria andTargetIsNull() { addCriterion("target is null"); return (Criteria) this; } public Criteria andTargetIsNotNull() { addCriterion("target is not null"); return (Criteria) this; } public Criteria andTargetEqualTo(String value) { addCriterion("target =", value, "target"); return (Criteria) this; } public Criteria andTargetNotEqualTo(String value) { addCriterion("target <>", value, "target"); return (Criteria) this; } public Criteria andTargetGreaterThan(String value) { addCriterion("target >", value, "target"); return (Criteria) this; } public Criteria andTargetGreaterThanOrEqualTo(String value) { addCriterion("target >=", value, "target"); return (Criteria) this; } public Criteria andTargetLessThan(String value) { addCriterion("target <", value, "target"); return (Criteria) this; } public Criteria andTargetLessThanOrEqualTo(String value) { addCriterion("target <=", value, "target"); return (Criteria) this; } public Criteria andTargetLike(String value) { addCriterion("target like", value, "target"); return (Criteria) this; } public Criteria andTargetNotLike(String value) { addCriterion("target not like", value, "target"); return (Criteria) this; } public Criteria andTargetIn(List<String> values) { addCriterion("target in", values, "target"); return (Criteria) this; } public Criteria andTargetNotIn(List<String> values) { addCriterion("target not in", values, "target"); return (Criteria) this; } public Criteria andTargetBetween(String value1, String value2) { addCriterion("target between", value1, value2, "target"); return (Criteria) this; } public Criteria andTargetNotBetween(String value1, String value2) { addCriterion("target not between", value1, value2, "target"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsPage implements Serializable { /** * 编码 * * @mbg.generated */ private Integer pageId; /** * 父页面 * * @mbg.generated */ private Integer pid; /** * 标题 * * @mbg.generated */ private String title; /** * 别名 * * @mbg.generated */ private String alias; /** * 关键字 * * @mbg.generated */ private String keywords; /** * 描述 * * @mbg.generated */ private String description; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; /** * 页面内容 * * @mbg.generated */ private String content; private static final long serialVersionUID = 1L; public Integer getPageId() { return pageId; } public void setPageId(Integer pageId) { this.pageId = pageId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", pageId=").append(pageId); sb.append(", pid=").append(pid); sb.append(", title=").append(title); sb.append(", alias=").append(alias); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append(", content=").append(content); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsPage other = (CmsPage) that; return (this.getPageId() == null ? other.getPageId() == null : this.getPageId().equals(other.getPageId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getAlias() == null ? other.getAlias() == null : this.getAlias().equals(other.getAlias())) && (this.getKeywords() == null ? other.getKeywords() == null : this.getKeywords().equals(other.getKeywords())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPageId() == null) ? 0 : getPageId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getAlias() == null) ? 0 : getAlias().hashCode()); result = prime * result + ((getKeywords() == null) ? 0 : getKeywords().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsPageExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsPageExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPageIdIsNull() { addCriterion("page_id is null"); return (Criteria) this; } public Criteria andPageIdIsNotNull() { addCriterion("page_id is not null"); return (Criteria) this; } public Criteria andPageIdEqualTo(Integer value) { addCriterion("page_id =", value, "pageId"); return (Criteria) this; } public Criteria andPageIdNotEqualTo(Integer value) { addCriterion("page_id <>", value, "pageId"); return (Criteria) this; } public Criteria andPageIdGreaterThan(Integer value) { addCriterion("page_id >", value, "pageId"); return (Criteria) this; } public Criteria andPageIdGreaterThanOrEqualTo(Integer value) { addCriterion("page_id >=", value, "pageId"); return (Criteria) this; } public Criteria andPageIdLessThan(Integer value) { addCriterion("page_id <", value, "pageId"); return (Criteria) this; } public Criteria andPageIdLessThanOrEqualTo(Integer value) { addCriterion("page_id <=", value, "pageId"); return (Criteria) this; } public Criteria andPageIdIn(List<Integer> values) { addCriterion("page_id in", values, "pageId"); return (Criteria) this; } public Criteria andPageIdNotIn(List<Integer> values) { addCriterion("page_id not in", values, "pageId"); return (Criteria) this; } public Criteria andPageIdBetween(Integer value1, Integer value2) { addCriterion("page_id between", value1, value2, "pageId"); return (Criteria) this; } public Criteria andPageIdNotBetween(Integer value1, Integer value2) { addCriterion("page_id not between", value1, value2, "pageId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andAliasIsNull() { addCriterion("alias is null"); return (Criteria) this; } public Criteria andAliasIsNotNull() { addCriterion("alias is not null"); return (Criteria) this; } public Criteria andAliasEqualTo(String value) { addCriterion("alias =", value, "alias"); return (Criteria) this; } public Criteria andAliasNotEqualTo(String value) { addCriterion("alias <>", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThan(String value) { addCriterion("alias >", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThanOrEqualTo(String value) { addCriterion("alias >=", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThan(String value) { addCriterion("alias <", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThanOrEqualTo(String value) { addCriterion("alias <=", value, "alias"); return (Criteria) this; } public Criteria andAliasLike(String value) { addCriterion("alias like", value, "alias"); return (Criteria) this; } public Criteria andAliasNotLike(String value) { addCriterion("alias not like", value, "alias"); return (Criteria) this; } public Criteria andAliasIn(List<String> values) { addCriterion("alias in", values, "alias"); return (Criteria) this; } public Criteria andAliasNotIn(List<String> values) { addCriterion("alias not in", values, "alias"); return (Criteria) this; } public Criteria andAliasBetween(String value1, String value2) { addCriterion("alias between", value1, value2, "alias"); return (Criteria) this; } public Criteria andAliasNotBetween(String value1, String value2) { addCriterion("alias not between", value1, value2, "alias"); return (Criteria) this; } public Criteria andKeywordsIsNull() { addCriterion("keywords is null"); return (Criteria) this; } public Criteria andKeywordsIsNotNull() { addCriterion("keywords is not null"); return (Criteria) this; } public Criteria andKeywordsEqualTo(String value) { addCriterion("keywords =", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotEqualTo(String value) { addCriterion("keywords <>", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsGreaterThan(String value) { addCriterion("keywords >", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsGreaterThanOrEqualTo(String value) { addCriterion("keywords >=", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLessThan(String value) { addCriterion("keywords <", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLessThanOrEqualTo(String value) { addCriterion("keywords <=", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsLike(String value) { addCriterion("keywords like", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotLike(String value) { addCriterion("keywords not like", value, "keywords"); return (Criteria) this; } public Criteria andKeywordsIn(List<String> values) { addCriterion("keywords in", values, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotIn(List<String> values) { addCriterion("keywords not in", values, "keywords"); return (Criteria) this; } public Criteria andKeywordsBetween(String value1, String value2) { addCriterion("keywords between", value1, value2, "keywords"); return (Criteria) this; } public Criteria andKeywordsNotBetween(String value1, String value2) { addCriterion("keywords not between", value1, value2, "keywords"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsSetting implements Serializable { private Integer settingId; private String settingKey; private String settingValue; private static final long serialVersionUID = 1L; public Integer getSettingId() { return settingId; } public void setSettingId(Integer settingId) { this.settingId = settingId; } public String getSettingKey() { return settingKey; } public void setSettingKey(String settingKey) { this.settingKey = settingKey; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", settingId=").append(settingId); sb.append(", settingKey=").append(settingKey); sb.append(", settingValue=").append(settingValue); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsSetting other = (CmsSetting) that; return (this.getSettingId() == null ? other.getSettingId() == null : this.getSettingId().equals(other.getSettingId())) && (this.getSettingKey() == null ? other.getSettingKey() == null : this.getSettingKey().equals(other.getSettingKey())) && (this.getSettingValue() == null ? other.getSettingValue() == null : this.getSettingValue().equals(other.getSettingValue())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSettingId() == null) ? 0 : getSettingId().hashCode()); result = prime * result + ((getSettingKey() == null) ? 0 : getSettingKey().hashCode()); result = prime * result + ((getSettingValue() == null) ? 0 : getSettingValue().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsSettingExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsSettingExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andSettingIdIsNull() { addCriterion("setting_id is null"); return (Criteria) this; } public Criteria andSettingIdIsNotNull() { addCriterion("setting_id is not null"); return (Criteria) this; } public Criteria andSettingIdEqualTo(Integer value) { addCriterion("setting_id =", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdNotEqualTo(Integer value) { addCriterion("setting_id <>", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdGreaterThan(Integer value) { addCriterion("setting_id >", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdGreaterThanOrEqualTo(Integer value) { addCriterion("setting_id >=", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdLessThan(Integer value) { addCriterion("setting_id <", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdLessThanOrEqualTo(Integer value) { addCriterion("setting_id <=", value, "settingId"); return (Criteria) this; } public Criteria andSettingIdIn(List<Integer> values) { addCriterion("setting_id in", values, "settingId"); return (Criteria) this; } public Criteria andSettingIdNotIn(List<Integer> values) { addCriterion("setting_id not in", values, "settingId"); return (Criteria) this; } public Criteria andSettingIdBetween(Integer value1, Integer value2) { addCriterion("setting_id between", value1, value2, "settingId"); return (Criteria) this; } public Criteria andSettingIdNotBetween(Integer value1, Integer value2) { addCriterion("setting_id not between", value1, value2, "settingId"); return (Criteria) this; } public Criteria andSettingKeyIsNull() { addCriterion("setting_key is null"); return (Criteria) this; } public Criteria andSettingKeyIsNotNull() { addCriterion("setting_key is not null"); return (Criteria) this; } public Criteria andSettingKeyEqualTo(String value) { addCriterion("setting_key =", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyNotEqualTo(String value) { addCriterion("setting_key <>", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyGreaterThan(String value) { addCriterion("setting_key >", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyGreaterThanOrEqualTo(String value) { addCriterion("setting_key >=", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyLessThan(String value) { addCriterion("setting_key <", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyLessThanOrEqualTo(String value) { addCriterion("setting_key <=", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyLike(String value) { addCriterion("setting_key like", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyNotLike(String value) { addCriterion("setting_key not like", value, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyIn(List<String> values) { addCriterion("setting_key in", values, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyNotIn(List<String> values) { addCriterion("setting_key not in", values, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyBetween(String value1, String value2) { addCriterion("setting_key between", value1, value2, "settingKey"); return (Criteria) this; } public Criteria andSettingKeyNotBetween(String value1, String value2) { addCriterion("setting_key not between", value1, value2, "settingKey"); return (Criteria) this; } public Criteria andSettingValueIsNull() { addCriterion("setting_value is null"); return (Criteria) this; } public Criteria andSettingValueIsNotNull() { addCriterion("setting_value is not null"); return (Criteria) this; } public Criteria andSettingValueEqualTo(String value) { addCriterion("setting_value =", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueNotEqualTo(String value) { addCriterion("setting_value <>", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueGreaterThan(String value) { addCriterion("setting_value >", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueGreaterThanOrEqualTo(String value) { addCriterion("setting_value >=", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueLessThan(String value) { addCriterion("setting_value <", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueLessThanOrEqualTo(String value) { addCriterion("setting_value <=", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueLike(String value) { addCriterion("setting_value like", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueNotLike(String value) { addCriterion("setting_value not like", value, "settingValue"); return (Criteria) this; } public Criteria andSettingValueIn(List<String> values) { addCriterion("setting_value in", values, "settingValue"); return (Criteria) this; } public Criteria andSettingValueNotIn(List<String> values) { addCriterion("setting_value not in", values, "settingValue"); return (Criteria) this; } public Criteria andSettingValueBetween(String value1, String value2) { addCriterion("setting_value between", value1, value2, "settingValue"); return (Criteria) this; } public Criteria andSettingValueNotBetween(String value1, String value2) { addCriterion("setting_value not between", value1, value2, "settingValue"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsSystem implements Serializable { /** * 编号 * * @mbg.generated */ private Integer systemId; /** * 系统名称 * * @mbg.generated */ private String name; /** * 别名 * * @mbg.generated */ private String code; /** * 描述 * * @mbg.generated */ private String description; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", systemId=").append(systemId); sb.append(", name=").append(name); sb.append(", code=").append(code); sb.append(", description=").append(description); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsSystem other = (CmsSystem) that; return (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getCode() == null ? other.getCode() == null : this.getCode().equals(other.getCode())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getCode() == null) ? 0 : getCode().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsSystemExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsSystemExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andCodeIsNull() { addCriterion("code is null"); return (Criteria) this; } public Criteria andCodeIsNotNull() { addCriterion("code is not null"); return (Criteria) this; } public Criteria andCodeEqualTo(String value) { addCriterion("code =", value, "code"); return (Criteria) this; } public Criteria andCodeNotEqualTo(String value) { addCriterion("code <>", value, "code"); return (Criteria) this; } public Criteria andCodeGreaterThan(String value) { addCriterion("code >", value, "code"); return (Criteria) this; } public Criteria andCodeGreaterThanOrEqualTo(String value) { addCriterion("code >=", value, "code"); return (Criteria) this; } public Criteria andCodeLessThan(String value) { addCriterion("code <", value, "code"); return (Criteria) this; } public Criteria andCodeLessThanOrEqualTo(String value) { addCriterion("code <=", value, "code"); return (Criteria) this; } public Criteria andCodeLike(String value) { addCriterion("code like", value, "code"); return (Criteria) this; } public Criteria andCodeNotLike(String value) { addCriterion("code not like", value, "code"); return (Criteria) this; } public Criteria andCodeIn(List<String> values) { addCriterion("code in", values, "code"); return (Criteria) this; } public Criteria andCodeNotIn(List<String> values) { addCriterion("code not in", values, "code"); return (Criteria) this; } public Criteria andCodeBetween(String value1, String value2) { addCriterion("code between", value1, value2, "code"); return (Criteria) this; } public Criteria andCodeNotBetween(String value1, String value2) { addCriterion("code not between", value1, value2, "code"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsTag implements Serializable { /** * 标签编号 * * @mbg.generated */ private Integer tagId; /** * 名称 * * @mbg.generated */ private String name; /** * 描述 * * @mbg.generated */ private String description; /** * 图标 * * @mbg.generated */ private String icon; /** * 类型(1:普通,2:热门...) * * @mbg.generated */ private Byte type; /** * 别名 * * @mbg.generated */ private String alias; /** * 所属系统 * * @mbg.generated */ private Integer systemId; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getTagId() { return tagId; } public void setTagId(Integer tagId) { this.tagId = tagId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", tagId=").append(tagId); sb.append(", name=").append(name); sb.append(", description=").append(description); sb.append(", icon=").append(icon); sb.append(", type=").append(type); sb.append(", alias=").append(alias); sb.append(", systemId=").append(systemId); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsTag other = (CmsTag) that; return (this.getTagId() == null ? other.getTagId() == null : this.getTagId().equals(other.getTagId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getAlias() == null ? other.getAlias() == null : this.getAlias().equals(other.getAlias())) && (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getTagId() == null) ? 0 : getTagId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getAlias() == null) ? 0 : getAlias().hashCode()); result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsTagExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsTagExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTagIdIsNull() { addCriterion("tag_id is null"); return (Criteria) this; } public Criteria andTagIdIsNotNull() { addCriterion("tag_id is not null"); return (Criteria) this; } public Criteria andTagIdEqualTo(Integer value) { addCriterion("tag_id =", value, "tagId"); return (Criteria) this; } public Criteria andTagIdNotEqualTo(Integer value) { addCriterion("tag_id <>", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThan(Integer value) { addCriterion("tag_id >", value, "tagId"); return (Criteria) this; } public Criteria andTagIdGreaterThanOrEqualTo(Integer value) { addCriterion("tag_id >=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThan(Integer value) { addCriterion("tag_id <", value, "tagId"); return (Criteria) this; } public Criteria andTagIdLessThanOrEqualTo(Integer value) { addCriterion("tag_id <=", value, "tagId"); return (Criteria) this; } public Criteria andTagIdIn(List<Integer> values) { addCriterion("tag_id in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdNotIn(List<Integer> values) { addCriterion("tag_id not in", values, "tagId"); return (Criteria) this; } public Criteria andTagIdBetween(Integer value1, Integer value2) { addCriterion("tag_id between", value1, value2, "tagId"); return (Criteria) this; } public Criteria andTagIdNotBetween(Integer value1, Integer value2) { addCriterion("tag_id not between", value1, value2, "tagId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andIconIsNull() { addCriterion("icon is null"); return (Criteria) this; } public Criteria andIconIsNotNull() { addCriterion("icon is not null"); return (Criteria) this; } public Criteria andIconEqualTo(String value) { addCriterion("icon =", value, "icon"); return (Criteria) this; } public Criteria andIconNotEqualTo(String value) { addCriterion("icon <>", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThan(String value) { addCriterion("icon >", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThanOrEqualTo(String value) { addCriterion("icon >=", value, "icon"); return (Criteria) this; } public Criteria andIconLessThan(String value) { addCriterion("icon <", value, "icon"); return (Criteria) this; } public Criteria andIconLessThanOrEqualTo(String value) { addCriterion("icon <=", value, "icon"); return (Criteria) this; } public Criteria andIconLike(String value) { addCriterion("icon like", value, "icon"); return (Criteria) this; } public Criteria andIconNotLike(String value) { addCriterion("icon not like", value, "icon"); return (Criteria) this; } public Criteria andIconIn(List<String> values) { addCriterion("icon in", values, "icon"); return (Criteria) this; } public Criteria andIconNotIn(List<String> values) { addCriterion("icon not in", values, "icon"); return (Criteria) this; } public Criteria andIconBetween(String value1, String value2) { addCriterion("icon between", value1, value2, "icon"); return (Criteria) this; } public Criteria andIconNotBetween(String value1, String value2) { addCriterion("icon not between", value1, value2, "icon"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andAliasIsNull() { addCriterion("alias is null"); return (Criteria) this; } public Criteria andAliasIsNotNull() { addCriterion("alias is not null"); return (Criteria) this; } public Criteria andAliasEqualTo(String value) { addCriterion("alias =", value, "alias"); return (Criteria) this; } public Criteria andAliasNotEqualTo(String value) { addCriterion("alias <>", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThan(String value) { addCriterion("alias >", value, "alias"); return (Criteria) this; } public Criteria andAliasGreaterThanOrEqualTo(String value) { addCriterion("alias >=", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThan(String value) { addCriterion("alias <", value, "alias"); return (Criteria) this; } public Criteria andAliasLessThanOrEqualTo(String value) { addCriterion("alias <=", value, "alias"); return (Criteria) this; } public Criteria andAliasLike(String value) { addCriterion("alias like", value, "alias"); return (Criteria) this; } public Criteria andAliasNotLike(String value) { addCriterion("alias not like", value, "alias"); return (Criteria) this; } public Criteria andAliasIn(List<String> values) { addCriterion("alias in", values, "alias"); return (Criteria) this; } public Criteria andAliasNotIn(List<String> values) { addCriterion("alias not in", values, "alias"); return (Criteria) this; } public Criteria andAliasBetween(String value1, String value2) { addCriterion("alias between", value1, value2, "alias"); return (Criteria) this; } public Criteria andAliasNotBetween(String value1, String value2) { addCriterion("alias not between", value1, value2, "alias"); return (Criteria) this; } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.cms.dao.model; import java.io.Serializable; public class CmsTopic implements Serializable { /** * 编号 * * @mbg.generated */ private Integer topicId; /** * 标题 * * @mbg.generated */ private String title; /** * 描述 * * @mbg.generated */ private String description; /** * 链接 * * @mbg.generated */ private String url; /** * 创建时间 * * @mbg.generated */ private Long ctime; private static final long serialVersionUID = 1L; public Integer getTopicId() { return topicId; } public void setTopicId(Integer topicId) { this.topicId = topicId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", topicId=").append(topicId); sb.append(", title=").append(title); sb.append(", description=").append(description); sb.append(", url=").append(url); sb.append(", ctime=").append(ctime); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CmsTopic other = (CmsTopic) that; return (this.getTopicId() == null ? other.getTopicId() == null : this.getTopicId().equals(other.getTopicId())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getTopicId() == null) ? 0 : getTopicId().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getUrl() == null) ? 0 : getUrl().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); return result; } }
package com.zheng.cms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CmsTopicExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public CmsTopicExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andTopicIdIsNull() { addCriterion("topic_id is null"); return (Criteria) this; } public Criteria andTopicIdIsNotNull() { addCriterion("topic_id is not null"); return (Criteria) this; } public Criteria andTopicIdEqualTo(Integer value) { addCriterion("topic_id =", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotEqualTo(Integer value) { addCriterion("topic_id <>", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdGreaterThan(Integer value) { addCriterion("topic_id >", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdGreaterThanOrEqualTo(Integer value) { addCriterion("topic_id >=", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdLessThan(Integer value) { addCriterion("topic_id <", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdLessThanOrEqualTo(Integer value) { addCriterion("topic_id <=", value, "topicId"); return (Criteria) this; } public Criteria andTopicIdIn(List<Integer> values) { addCriterion("topic_id in", values, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotIn(List<Integer> values) { addCriterion("topic_id not in", values, "topicId"); return (Criteria) this; } public Criteria andTopicIdBetween(Integer value1, Integer value2) { addCriterion("topic_id between", value1, value2, "topicId"); return (Criteria) this; } public Criteria andTopicIdNotBetween(Integer value1, Integer value2) { addCriterion("topic_id not between", value1, value2, "topicId"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andUrlIsNull() { addCriterion("url is null"); return (Criteria) this; } public Criteria andUrlIsNotNull() { addCriterion("url is not null"); return (Criteria) this; } public Criteria andUrlEqualTo(String value) { addCriterion("url =", value, "url"); return (Criteria) this; } public Criteria andUrlNotEqualTo(String value) { addCriterion("url <>", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThan(String value) { addCriterion("url >", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThanOrEqualTo(String value) { addCriterion("url >=", value, "url"); return (Criteria) this; } public Criteria andUrlLessThan(String value) { addCriterion("url <", value, "url"); return (Criteria) this; } public Criteria andUrlLessThanOrEqualTo(String value) { addCriterion("url <=", value, "url"); return (Criteria) this; } public Criteria andUrlLike(String value) { addCriterion("url like", value, "url"); return (Criteria) this; } public Criteria andUrlNotLike(String value) { addCriterion("url not like", value, "url"); return (Criteria) this; } public Criteria andUrlIn(List<String> values) { addCriterion("url in", values, "url"); return (Criteria) this; } public Criteria andUrlNotIn(List<String> values) { addCriterion("url not in", values, "url"); return (Criteria) this; } public Criteria andUrlBetween(String value1, String value2) { addCriterion("url between", value1, value2, "url"); return (Criteria) this; } public Criteria andUrlNotBetween(String value1, String value2) { addCriterion("url not between", value1, value2, "url"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayInOrder implements Serializable { private Integer payInOrderId; private Integer payVendorId; private Integer payMchId; private Long amount; private Byte status; private Long ctime; private static final long serialVersionUID = 1L; public Integer getPayInOrderId() { return payInOrderId; } public void setPayInOrderId(Integer payInOrderId) { this.payInOrderId = payInOrderId; } public Integer getPayVendorId() { return payVendorId; } public void setPayVendorId(Integer payVendorId) { this.payVendorId = payVendorId; } public Integer getPayMchId() { return payMchId; } public void setPayMchId(Integer payMchId) { this.payMchId = payMchId; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payInOrderId=").append(payInOrderId); sb.append(", payVendorId=").append(payVendorId); sb.append(", payMchId=").append(payMchId); sb.append(", amount=").append(amount); sb.append(", status=").append(status); sb.append(", ctime=").append(ctime); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayInOrder other = (PayInOrder) that; return (this.getPayInOrderId() == null ? other.getPayInOrderId() == null : this.getPayInOrderId().equals(other.getPayInOrderId())) && (this.getPayVendorId() == null ? other.getPayVendorId() == null : this.getPayVendorId().equals(other.getPayVendorId())) && (this.getPayMchId() == null ? other.getPayMchId() == null : this.getPayMchId().equals(other.getPayMchId())) && (this.getAmount() == null ? other.getAmount() == null : this.getAmount().equals(other.getAmount())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayInOrderId() == null) ? 0 : getPayInOrderId().hashCode()); result = prime * result + ((getPayVendorId() == null) ? 0 : getPayVendorId().hashCode()); result = prime * result + ((getPayMchId() == null) ? 0 : getPayMchId().hashCode()); result = prime * result + ((getAmount() == null) ? 0 : getAmount().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayInOrderDetail implements Serializable { private Integer payInOrderDetailId; private Integer payInOrderId; private String productId; private String productName; private Long productPrice; private Integer productCount; private String remark; private static final long serialVersionUID = 1L; public Integer getPayInOrderDetailId() { return payInOrderDetailId; } public void setPayInOrderDetailId(Integer payInOrderDetailId) { this.payInOrderDetailId = payInOrderDetailId; } public Integer getPayInOrderId() { return payInOrderId; } public void setPayInOrderId(Integer payInOrderId) { this.payInOrderId = payInOrderId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Long getProductPrice() { return productPrice; } public void setProductPrice(Long productPrice) { this.productPrice = productPrice; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payInOrderDetailId=").append(payInOrderDetailId); sb.append(", payInOrderId=").append(payInOrderId); sb.append(", productId=").append(productId); sb.append(", productName=").append(productName); sb.append(", productPrice=").append(productPrice); sb.append(", productCount=").append(productCount); sb.append(", remark=").append(remark); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayInOrderDetail other = (PayInOrderDetail) that; return (this.getPayInOrderDetailId() == null ? other.getPayInOrderDetailId() == null : this.getPayInOrderDetailId().equals(other.getPayInOrderDetailId())) && (this.getPayInOrderId() == null ? other.getPayInOrderId() == null : this.getPayInOrderId().equals(other.getPayInOrderId())) && (this.getProductId() == null ? other.getProductId() == null : this.getProductId().equals(other.getProductId())) && (this.getProductName() == null ? other.getProductName() == null : this.getProductName().equals(other.getProductName())) && (this.getProductPrice() == null ? other.getProductPrice() == null : this.getProductPrice().equals(other.getProductPrice())) && (this.getProductCount() == null ? other.getProductCount() == null : this.getProductCount().equals(other.getProductCount())) && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayInOrderDetailId() == null) ? 0 : getPayInOrderDetailId().hashCode()); result = prime * result + ((getPayInOrderId() == null) ? 0 : getPayInOrderId().hashCode()); result = prime * result + ((getProductId() == null) ? 0 : getProductId().hashCode()); result = prime * result + ((getProductName() == null) ? 0 : getProductName().hashCode()); result = prime * result + ((getProductPrice() == null) ? 0 : getProductPrice().hashCode()); result = prime * result + ((getProductCount() == null) ? 0 : getProductCount().hashCode()); result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayInOrderDetailExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayInOrderDetailExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayInOrderDetailIdIsNull() { addCriterion("pay_in_order_detail_id is null"); return (Criteria) this; } public Criteria andPayInOrderDetailIdIsNotNull() { addCriterion("pay_in_order_detail_id is not null"); return (Criteria) this; } public Criteria andPayInOrderDetailIdEqualTo(Integer value) { addCriterion("pay_in_order_detail_id =", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdNotEqualTo(Integer value) { addCriterion("pay_in_order_detail_id <>", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdGreaterThan(Integer value) { addCriterion("pay_in_order_detail_id >", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_in_order_detail_id >=", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdLessThan(Integer value) { addCriterion("pay_in_order_detail_id <", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdLessThanOrEqualTo(Integer value) { addCriterion("pay_in_order_detail_id <=", value, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdIn(List<Integer> values) { addCriterion("pay_in_order_detail_id in", values, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdNotIn(List<Integer> values) { addCriterion("pay_in_order_detail_id not in", values, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_detail_id between", value1, value2, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderDetailIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_detail_id not between", value1, value2, "payInOrderDetailId"); return (Criteria) this; } public Criteria andPayInOrderIdIsNull() { addCriterion("pay_in_order_id is null"); return (Criteria) this; } public Criteria andPayInOrderIdIsNotNull() { addCriterion("pay_in_order_id is not null"); return (Criteria) this; } public Criteria andPayInOrderIdEqualTo(Integer value) { addCriterion("pay_in_order_id =", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotEqualTo(Integer value) { addCriterion("pay_in_order_id <>", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdGreaterThan(Integer value) { addCriterion("pay_in_order_id >", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_in_order_id >=", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdLessThan(Integer value) { addCriterion("pay_in_order_id <", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdLessThanOrEqualTo(Integer value) { addCriterion("pay_in_order_id <=", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdIn(List<Integer> values) { addCriterion("pay_in_order_id in", values, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotIn(List<Integer> values) { addCriterion("pay_in_order_id not in", values, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_id between", value1, value2, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_id not between", value1, value2, "payInOrderId"); return (Criteria) this; } public Criteria andProductIdIsNull() { addCriterion("product_id is null"); return (Criteria) this; } public Criteria andProductIdIsNotNull() { addCriterion("product_id is not null"); return (Criteria) this; } public Criteria andProductIdEqualTo(String value) { addCriterion("product_id =", value, "productId"); return (Criteria) this; } public Criteria andProductIdNotEqualTo(String value) { addCriterion("product_id <>", value, "productId"); return (Criteria) this; } public Criteria andProductIdGreaterThan(String value) { addCriterion("product_id >", value, "productId"); return (Criteria) this; } public Criteria andProductIdGreaterThanOrEqualTo(String value) { addCriterion("product_id >=", value, "productId"); return (Criteria) this; } public Criteria andProductIdLessThan(String value) { addCriterion("product_id <", value, "productId"); return (Criteria) this; } public Criteria andProductIdLessThanOrEqualTo(String value) { addCriterion("product_id <=", value, "productId"); return (Criteria) this; } public Criteria andProductIdLike(String value) { addCriterion("product_id like", value, "productId"); return (Criteria) this; } public Criteria andProductIdNotLike(String value) { addCriterion("product_id not like", value, "productId"); return (Criteria) this; } public Criteria andProductIdIn(List<String> values) { addCriterion("product_id in", values, "productId"); return (Criteria) this; } public Criteria andProductIdNotIn(List<String> values) { addCriterion("product_id not in", values, "productId"); return (Criteria) this; } public Criteria andProductIdBetween(String value1, String value2) { addCriterion("product_id between", value1, value2, "productId"); return (Criteria) this; } public Criteria andProductIdNotBetween(String value1, String value2) { addCriterion("product_id not between", value1, value2, "productId"); return (Criteria) this; } public Criteria andProductNameIsNull() { addCriterion("product_name is null"); return (Criteria) this; } public Criteria andProductNameIsNotNull() { addCriterion("product_name is not null"); return (Criteria) this; } public Criteria andProductNameEqualTo(String value) { addCriterion("product_name =", value, "productName"); return (Criteria) this; } public Criteria andProductNameNotEqualTo(String value) { addCriterion("product_name <>", value, "productName"); return (Criteria) this; } public Criteria andProductNameGreaterThan(String value) { addCriterion("product_name >", value, "productName"); return (Criteria) this; } public Criteria andProductNameGreaterThanOrEqualTo(String value) { addCriterion("product_name >=", value, "productName"); return (Criteria) this; } public Criteria andProductNameLessThan(String value) { addCriterion("product_name <", value, "productName"); return (Criteria) this; } public Criteria andProductNameLessThanOrEqualTo(String value) { addCriterion("product_name <=", value, "productName"); return (Criteria) this; } public Criteria andProductNameLike(String value) { addCriterion("product_name like", value, "productName"); return (Criteria) this; } public Criteria andProductNameNotLike(String value) { addCriterion("product_name not like", value, "productName"); return (Criteria) this; } public Criteria andProductNameIn(List<String> values) { addCriterion("product_name in", values, "productName"); return (Criteria) this; } public Criteria andProductNameNotIn(List<String> values) { addCriterion("product_name not in", values, "productName"); return (Criteria) this; } public Criteria andProductNameBetween(String value1, String value2) { addCriterion("product_name between", value1, value2, "productName"); return (Criteria) this; } public Criteria andProductNameNotBetween(String value1, String value2) { addCriterion("product_name not between", value1, value2, "productName"); return (Criteria) this; } public Criteria andProductPriceIsNull() { addCriterion("product_price is null"); return (Criteria) this; } public Criteria andProductPriceIsNotNull() { addCriterion("product_price is not null"); return (Criteria) this; } public Criteria andProductPriceEqualTo(Long value) { addCriterion("product_price =", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceNotEqualTo(Long value) { addCriterion("product_price <>", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceGreaterThan(Long value) { addCriterion("product_price >", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceGreaterThanOrEqualTo(Long value) { addCriterion("product_price >=", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceLessThan(Long value) { addCriterion("product_price <", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceLessThanOrEqualTo(Long value) { addCriterion("product_price <=", value, "productPrice"); return (Criteria) this; } public Criteria andProductPriceIn(List<Long> values) { addCriterion("product_price in", values, "productPrice"); return (Criteria) this; } public Criteria andProductPriceNotIn(List<Long> values) { addCriterion("product_price not in", values, "productPrice"); return (Criteria) this; } public Criteria andProductPriceBetween(Long value1, Long value2) { addCriterion("product_price between", value1, value2, "productPrice"); return (Criteria) this; } public Criteria andProductPriceNotBetween(Long value1, Long value2) { addCriterion("product_price not between", value1, value2, "productPrice"); return (Criteria) this; } public Criteria andProductCountIsNull() { addCriterion("product_count is null"); return (Criteria) this; } public Criteria andProductCountIsNotNull() { addCriterion("product_count is not null"); return (Criteria) this; } public Criteria andProductCountEqualTo(Integer value) { addCriterion("product_count =", value, "productCount"); return (Criteria) this; } public Criteria andProductCountNotEqualTo(Integer value) { addCriterion("product_count <>", value, "productCount"); return (Criteria) this; } public Criteria andProductCountGreaterThan(Integer value) { addCriterion("product_count >", value, "productCount"); return (Criteria) this; } public Criteria andProductCountGreaterThanOrEqualTo(Integer value) { addCriterion("product_count >=", value, "productCount"); return (Criteria) this; } public Criteria andProductCountLessThan(Integer value) { addCriterion("product_count <", value, "productCount"); return (Criteria) this; } public Criteria andProductCountLessThanOrEqualTo(Integer value) { addCriterion("product_count <=", value, "productCount"); return (Criteria) this; } public Criteria andProductCountIn(List<Integer> values) { addCriterion("product_count in", values, "productCount"); return (Criteria) this; } public Criteria andProductCountNotIn(List<Integer> values) { addCriterion("product_count not in", values, "productCount"); return (Criteria) this; } public Criteria andProductCountBetween(Integer value1, Integer value2) { addCriterion("product_count between", value1, value2, "productCount"); return (Criteria) this; } public Criteria andProductCountNotBetween(Integer value1, Integer value2) { addCriterion("product_count not between", value1, value2, "productCount"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayInOrderExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayInOrderExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayInOrderIdIsNull() { addCriterion("pay_in_order_id is null"); return (Criteria) this; } public Criteria andPayInOrderIdIsNotNull() { addCriterion("pay_in_order_id is not null"); return (Criteria) this; } public Criteria andPayInOrderIdEqualTo(Integer value) { addCriterion("pay_in_order_id =", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotEqualTo(Integer value) { addCriterion("pay_in_order_id <>", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdGreaterThan(Integer value) { addCriterion("pay_in_order_id >", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_in_order_id >=", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdLessThan(Integer value) { addCriterion("pay_in_order_id <", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdLessThanOrEqualTo(Integer value) { addCriterion("pay_in_order_id <=", value, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdIn(List<Integer> values) { addCriterion("pay_in_order_id in", values, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotIn(List<Integer> values) { addCriterion("pay_in_order_id not in", values, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_id between", value1, value2, "payInOrderId"); return (Criteria) this; } public Criteria andPayInOrderIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_in_order_id not between", value1, value2, "payInOrderId"); return (Criteria) this; } public Criteria andPayVendorIdIsNull() { addCriterion("pay_vendor_id is null"); return (Criteria) this; } public Criteria andPayVendorIdIsNotNull() { addCriterion("pay_vendor_id is not null"); return (Criteria) this; } public Criteria andPayVendorIdEqualTo(Integer value) { addCriterion("pay_vendor_id =", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotEqualTo(Integer value) { addCriterion("pay_vendor_id <>", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThan(Integer value) { addCriterion("pay_vendor_id >", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id >=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThan(Integer value) { addCriterion("pay_vendor_id <", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id <=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdIn(List<Integer> values) { addCriterion("pay_vendor_id in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotIn(List<Integer> values) { addCriterion("pay_vendor_id not in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id not between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayMchIdIsNull() { addCriterion("pay_mch_id is null"); return (Criteria) this; } public Criteria andPayMchIdIsNotNull() { addCriterion("pay_mch_id is not null"); return (Criteria) this; } public Criteria andPayMchIdEqualTo(Integer value) { addCriterion("pay_mch_id =", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotEqualTo(Integer value) { addCriterion("pay_mch_id <>", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThan(Integer value) { addCriterion("pay_mch_id >", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_mch_id >=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThan(Integer value) { addCriterion("pay_mch_id <", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThanOrEqualTo(Integer value) { addCriterion("pay_mch_id <=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdIn(List<Integer> values) { addCriterion("pay_mch_id in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotIn(List<Integer> values) { addCriterion("pay_mch_id not in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id not between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andAmountIsNull() { addCriterion("amount is null"); return (Criteria) this; } public Criteria andAmountIsNotNull() { addCriterion("amount is not null"); return (Criteria) this; } public Criteria andAmountEqualTo(Long value) { addCriterion("amount =", value, "amount"); return (Criteria) this; } public Criteria andAmountNotEqualTo(Long value) { addCriterion("amount <>", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThan(Long value) { addCriterion("amount >", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThanOrEqualTo(Long value) { addCriterion("amount >=", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThan(Long value) { addCriterion("amount <", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThanOrEqualTo(Long value) { addCriterion("amount <=", value, "amount"); return (Criteria) this; } public Criteria andAmountIn(List<Long> values) { addCriterion("amount in", values, "amount"); return (Criteria) this; } public Criteria andAmountNotIn(List<Long> values) { addCriterion("amount not in", values, "amount"); return (Criteria) this; } public Criteria andAmountBetween(Long value1, Long value2) { addCriterion("amount between", value1, value2, "amount"); return (Criteria) this; } public Criteria andAmountNotBetween(Long value1, Long value2) { addCriterion("amount not between", value1, value2, "amount"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayMch implements Serializable { private Integer payMchId; private String mchId; private String name; private String reqkey; private String reskey; private static final long serialVersionUID = 1L; public Integer getPayMchId() { return payMchId; } public void setPayMchId(Integer payMchId) { this.payMchId = payMchId; } public String getMchId() { return mchId; } public void setMchId(String mchId) { this.mchId = mchId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getReqkey() { return reqkey; } public void setReqkey(String reqkey) { this.reqkey = reqkey; } public String getReskey() { return reskey; } public void setReskey(String reskey) { this.reskey = reskey; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payMchId=").append(payMchId); sb.append(", mchId=").append(mchId); sb.append(", name=").append(name); sb.append(", reqkey=").append(reqkey); sb.append(", reskey=").append(reskey); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayMch other = (PayMch) that; return (this.getPayMchId() == null ? other.getPayMchId() == null : this.getPayMchId().equals(other.getPayMchId())) && (this.getMchId() == null ? other.getMchId() == null : this.getMchId().equals(other.getMchId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getReqkey() == null ? other.getReqkey() == null : this.getReqkey().equals(other.getReqkey())) && (this.getReskey() == null ? other.getReskey() == null : this.getReskey().equals(other.getReskey())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayMchId() == null) ? 0 : getPayMchId().hashCode()); result = prime * result + ((getMchId() == null) ? 0 : getMchId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getReqkey() == null) ? 0 : getReqkey().hashCode()); result = prime * result + ((getReskey() == null) ? 0 : getReskey().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayMchExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayMchExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayMchIdIsNull() { addCriterion("pay_mch_id is null"); return (Criteria) this; } public Criteria andPayMchIdIsNotNull() { addCriterion("pay_mch_id is not null"); return (Criteria) this; } public Criteria andPayMchIdEqualTo(Integer value) { addCriterion("pay_mch_id =", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotEqualTo(Integer value) { addCriterion("pay_mch_id <>", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThan(Integer value) { addCriterion("pay_mch_id >", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_mch_id >=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThan(Integer value) { addCriterion("pay_mch_id <", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThanOrEqualTo(Integer value) { addCriterion("pay_mch_id <=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdIn(List<Integer> values) { addCriterion("pay_mch_id in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotIn(List<Integer> values) { addCriterion("pay_mch_id not in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id not between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andMchIdIsNull() { addCriterion("mch_id is null"); return (Criteria) this; } public Criteria andMchIdIsNotNull() { addCriterion("mch_id is not null"); return (Criteria) this; } public Criteria andMchIdEqualTo(String value) { addCriterion("mch_id =", value, "mchId"); return (Criteria) this; } public Criteria andMchIdNotEqualTo(String value) { addCriterion("mch_id <>", value, "mchId"); return (Criteria) this; } public Criteria andMchIdGreaterThan(String value) { addCriterion("mch_id >", value, "mchId"); return (Criteria) this; } public Criteria andMchIdGreaterThanOrEqualTo(String value) { addCriterion("mch_id >=", value, "mchId"); return (Criteria) this; } public Criteria andMchIdLessThan(String value) { addCriterion("mch_id <", value, "mchId"); return (Criteria) this; } public Criteria andMchIdLessThanOrEqualTo(String value) { addCriterion("mch_id <=", value, "mchId"); return (Criteria) this; } public Criteria andMchIdLike(String value) { addCriterion("mch_id like", value, "mchId"); return (Criteria) this; } public Criteria andMchIdNotLike(String value) { addCriterion("mch_id not like", value, "mchId"); return (Criteria) this; } public Criteria andMchIdIn(List<String> values) { addCriterion("mch_id in", values, "mchId"); return (Criteria) this; } public Criteria andMchIdNotIn(List<String> values) { addCriterion("mch_id not in", values, "mchId"); return (Criteria) this; } public Criteria andMchIdBetween(String value1, String value2) { addCriterion("mch_id between", value1, value2, "mchId"); return (Criteria) this; } public Criteria andMchIdNotBetween(String value1, String value2) { addCriterion("mch_id not between", value1, value2, "mchId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andReqkeyIsNull() { addCriterion("reqKey is null"); return (Criteria) this; } public Criteria andReqkeyIsNotNull() { addCriterion("reqKey is not null"); return (Criteria) this; } public Criteria andReqkeyEqualTo(String value) { addCriterion("reqKey =", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyNotEqualTo(String value) { addCriterion("reqKey <>", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyGreaterThan(String value) { addCriterion("reqKey >", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyGreaterThanOrEqualTo(String value) { addCriterion("reqKey >=", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyLessThan(String value) { addCriterion("reqKey <", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyLessThanOrEqualTo(String value) { addCriterion("reqKey <=", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyLike(String value) { addCriterion("reqKey like", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyNotLike(String value) { addCriterion("reqKey not like", value, "reqkey"); return (Criteria) this; } public Criteria andReqkeyIn(List<String> values) { addCriterion("reqKey in", values, "reqkey"); return (Criteria) this; } public Criteria andReqkeyNotIn(List<String> values) { addCriterion("reqKey not in", values, "reqkey"); return (Criteria) this; } public Criteria andReqkeyBetween(String value1, String value2) { addCriterion("reqKey between", value1, value2, "reqkey"); return (Criteria) this; } public Criteria andReqkeyNotBetween(String value1, String value2) { addCriterion("reqKey not between", value1, value2, "reqkey"); return (Criteria) this; } public Criteria andReskeyIsNull() { addCriterion("resKey is null"); return (Criteria) this; } public Criteria andReskeyIsNotNull() { addCriterion("resKey is not null"); return (Criteria) this; } public Criteria andReskeyEqualTo(String value) { addCriterion("resKey =", value, "reskey"); return (Criteria) this; } public Criteria andReskeyNotEqualTo(String value) { addCriterion("resKey <>", value, "reskey"); return (Criteria) this; } public Criteria andReskeyGreaterThan(String value) { addCriterion("resKey >", value, "reskey"); return (Criteria) this; } public Criteria andReskeyGreaterThanOrEqualTo(String value) { addCriterion("resKey >=", value, "reskey"); return (Criteria) this; } public Criteria andReskeyLessThan(String value) { addCriterion("resKey <", value, "reskey"); return (Criteria) this; } public Criteria andReskeyLessThanOrEqualTo(String value) { addCriterion("resKey <=", value, "reskey"); return (Criteria) this; } public Criteria andReskeyLike(String value) { addCriterion("resKey like", value, "reskey"); return (Criteria) this; } public Criteria andReskeyNotLike(String value) { addCriterion("resKey not like", value, "reskey"); return (Criteria) this; } public Criteria andReskeyIn(List<String> values) { addCriterion("resKey in", values, "reskey"); return (Criteria) this; } public Criteria andReskeyNotIn(List<String> values) { addCriterion("resKey not in", values, "reskey"); return (Criteria) this; } public Criteria andReskeyBetween(String value1, String value2) { addCriterion("resKey between", value1, value2, "reskey"); return (Criteria) this; } public Criteria andReskeyNotBetween(String value1, String value2) { addCriterion("resKey not between", value1, value2, "reskey"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayOutOrder implements Serializable { private Integer payOutOrderId; private Integer payMchId; private Integer payVendorId; private Long amount; private Byte status; private Long ctime; private static final long serialVersionUID = 1L; public Integer getPayOutOrderId() { return payOutOrderId; } public void setPayOutOrderId(Integer payOutOrderId) { this.payOutOrderId = payOutOrderId; } public Integer getPayMchId() { return payMchId; } public void setPayMchId(Integer payMchId) { this.payMchId = payMchId; } public Integer getPayVendorId() { return payVendorId; } public void setPayVendorId(Integer payVendorId) { this.payVendorId = payVendorId; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payOutOrderId=").append(payOutOrderId); sb.append(", payMchId=").append(payMchId); sb.append(", payVendorId=").append(payVendorId); sb.append(", amount=").append(amount); sb.append(", status=").append(status); sb.append(", ctime=").append(ctime); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayOutOrder other = (PayOutOrder) that; return (this.getPayOutOrderId() == null ? other.getPayOutOrderId() == null : this.getPayOutOrderId().equals(other.getPayOutOrderId())) && (this.getPayMchId() == null ? other.getPayMchId() == null : this.getPayMchId().equals(other.getPayMchId())) && (this.getPayVendorId() == null ? other.getPayVendorId() == null : this.getPayVendorId().equals(other.getPayVendorId())) && (this.getAmount() == null ? other.getAmount() == null : this.getAmount().equals(other.getAmount())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayOutOrderId() == null) ? 0 : getPayOutOrderId().hashCode()); result = prime * result + ((getPayMchId() == null) ? 0 : getPayMchId().hashCode()); result = prime * result + ((getPayVendorId() == null) ? 0 : getPayVendorId().hashCode()); result = prime * result + ((getAmount() == null) ? 0 : getAmount().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayOutOrderDetail implements Serializable { private Integer payOutOrderDetailId; private Integer payOutOrderId; private String remark; private static final long serialVersionUID = 1L; public Integer getPayOutOrderDetailId() { return payOutOrderDetailId; } public void setPayOutOrderDetailId(Integer payOutOrderDetailId) { this.payOutOrderDetailId = payOutOrderDetailId; } public Integer getPayOutOrderId() { return payOutOrderId; } public void setPayOutOrderId(Integer payOutOrderId) { this.payOutOrderId = payOutOrderId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payOutOrderDetailId=").append(payOutOrderDetailId); sb.append(", payOutOrderId=").append(payOutOrderId); sb.append(", remark=").append(remark); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayOutOrderDetail other = (PayOutOrderDetail) that; return (this.getPayOutOrderDetailId() == null ? other.getPayOutOrderDetailId() == null : this.getPayOutOrderDetailId().equals(other.getPayOutOrderDetailId())) && (this.getPayOutOrderId() == null ? other.getPayOutOrderId() == null : this.getPayOutOrderId().equals(other.getPayOutOrderId())) && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayOutOrderDetailId() == null) ? 0 : getPayOutOrderDetailId().hashCode()); result = prime * result + ((getPayOutOrderId() == null) ? 0 : getPayOutOrderId().hashCode()); result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayOutOrderDetailExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayOutOrderDetailExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayOutOrderDetailIdIsNull() { addCriterion("pay_out_order_detail_id is null"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdIsNotNull() { addCriterion("pay_out_order_detail_id is not null"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdEqualTo(Integer value) { addCriterion("pay_out_order_detail_id =", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdNotEqualTo(Integer value) { addCriterion("pay_out_order_detail_id <>", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdGreaterThan(Integer value) { addCriterion("pay_out_order_detail_id >", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_out_order_detail_id >=", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdLessThan(Integer value) { addCriterion("pay_out_order_detail_id <", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdLessThanOrEqualTo(Integer value) { addCriterion("pay_out_order_detail_id <=", value, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdIn(List<Integer> values) { addCriterion("pay_out_order_detail_id in", values, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdNotIn(List<Integer> values) { addCriterion("pay_out_order_detail_id not in", values, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_detail_id between", value1, value2, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderDetailIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_detail_id not between", value1, value2, "payOutOrderDetailId"); return (Criteria) this; } public Criteria andPayOutOrderIdIsNull() { addCriterion("pay_out_order_id is null"); return (Criteria) this; } public Criteria andPayOutOrderIdIsNotNull() { addCriterion("pay_out_order_id is not null"); return (Criteria) this; } public Criteria andPayOutOrderIdEqualTo(Integer value) { addCriterion("pay_out_order_id =", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotEqualTo(Integer value) { addCriterion("pay_out_order_id <>", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdGreaterThan(Integer value) { addCriterion("pay_out_order_id >", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_out_order_id >=", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdLessThan(Integer value) { addCriterion("pay_out_order_id <", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdLessThanOrEqualTo(Integer value) { addCriterion("pay_out_order_id <=", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdIn(List<Integer> values) { addCriterion("pay_out_order_id in", values, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotIn(List<Integer> values) { addCriterion("pay_out_order_id not in", values, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_id between", value1, value2, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_id not between", value1, value2, "payOutOrderId"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayOutOrderExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayOutOrderExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayOutOrderIdIsNull() { addCriterion("pay_out_order_id is null"); return (Criteria) this; } public Criteria andPayOutOrderIdIsNotNull() { addCriterion("pay_out_order_id is not null"); return (Criteria) this; } public Criteria andPayOutOrderIdEqualTo(Integer value) { addCriterion("pay_out_order_id =", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotEqualTo(Integer value) { addCriterion("pay_out_order_id <>", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdGreaterThan(Integer value) { addCriterion("pay_out_order_id >", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_out_order_id >=", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdLessThan(Integer value) { addCriterion("pay_out_order_id <", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdLessThanOrEqualTo(Integer value) { addCriterion("pay_out_order_id <=", value, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdIn(List<Integer> values) { addCriterion("pay_out_order_id in", values, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotIn(List<Integer> values) { addCriterion("pay_out_order_id not in", values, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_id between", value1, value2, "payOutOrderId"); return (Criteria) this; } public Criteria andPayOutOrderIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_out_order_id not between", value1, value2, "payOutOrderId"); return (Criteria) this; } public Criteria andPayMchIdIsNull() { addCriterion("pay_mch_id is null"); return (Criteria) this; } public Criteria andPayMchIdIsNotNull() { addCriterion("pay_mch_id is not null"); return (Criteria) this; } public Criteria andPayMchIdEqualTo(Integer value) { addCriterion("pay_mch_id =", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotEqualTo(Integer value) { addCriterion("pay_mch_id <>", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThan(Integer value) { addCriterion("pay_mch_id >", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_mch_id >=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThan(Integer value) { addCriterion("pay_mch_id <", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThanOrEqualTo(Integer value) { addCriterion("pay_mch_id <=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdIn(List<Integer> values) { addCriterion("pay_mch_id in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotIn(List<Integer> values) { addCriterion("pay_mch_id not in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id not between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andPayVendorIdIsNull() { addCriterion("pay_vendor_id is null"); return (Criteria) this; } public Criteria andPayVendorIdIsNotNull() { addCriterion("pay_vendor_id is not null"); return (Criteria) this; } public Criteria andPayVendorIdEqualTo(Integer value) { addCriterion("pay_vendor_id =", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotEqualTo(Integer value) { addCriterion("pay_vendor_id <>", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThan(Integer value) { addCriterion("pay_vendor_id >", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id >=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThan(Integer value) { addCriterion("pay_vendor_id <", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id <=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdIn(List<Integer> values) { addCriterion("pay_vendor_id in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotIn(List<Integer> values) { addCriterion("pay_vendor_id not in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id not between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andAmountIsNull() { addCriterion("amount is null"); return (Criteria) this; } public Criteria andAmountIsNotNull() { addCriterion("amount is not null"); return (Criteria) this; } public Criteria andAmountEqualTo(Long value) { addCriterion("amount =", value, "amount"); return (Criteria) this; } public Criteria andAmountNotEqualTo(Long value) { addCriterion("amount <>", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThan(Long value) { addCriterion("amount >", value, "amount"); return (Criteria) this; } public Criteria andAmountGreaterThanOrEqualTo(Long value) { addCriterion("amount >=", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThan(Long value) { addCriterion("amount <", value, "amount"); return (Criteria) this; } public Criteria andAmountLessThanOrEqualTo(Long value) { addCriterion("amount <=", value, "amount"); return (Criteria) this; } public Criteria andAmountIn(List<Long> values) { addCriterion("amount in", values, "amount"); return (Criteria) this; } public Criteria andAmountNotIn(List<Long> values) { addCriterion("amount not in", values, "amount"); return (Criteria) this; } public Criteria andAmountBetween(Long value1, Long value2) { addCriterion("amount between", value1, value2, "amount"); return (Criteria) this; } public Criteria andAmountNotBetween(Long value1, Long value2) { addCriterion("amount not between", value1, value2, "amount"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayPay implements Serializable { private Integer payPayId; private Integer payTypeId; private String param; private static final long serialVersionUID = 1L; public Integer getPayPayId() { return payPayId; } public void setPayPayId(Integer payPayId) { this.payPayId = payPayId; } public Integer getPayTypeId() { return payTypeId; } public void setPayTypeId(Integer payTypeId) { this.payTypeId = payTypeId; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payPayId=").append(payPayId); sb.append(", payTypeId=").append(payTypeId); sb.append(", param=").append(param); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayPay other = (PayPay) that; return (this.getPayPayId() == null ? other.getPayPayId() == null : this.getPayPayId().equals(other.getPayPayId())) && (this.getPayTypeId() == null ? other.getPayTypeId() == null : this.getPayTypeId().equals(other.getPayTypeId())) && (this.getParam() == null ? other.getParam() == null : this.getParam().equals(other.getParam())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayPayId() == null) ? 0 : getPayPayId().hashCode()); result = prime * result + ((getPayTypeId() == null) ? 0 : getPayTypeId().hashCode()); result = prime * result + ((getParam() == null) ? 0 : getParam().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayPayExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayPayExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayPayIdIsNull() { addCriterion("pay_pay_id is null"); return (Criteria) this; } public Criteria andPayPayIdIsNotNull() { addCriterion("pay_pay_id is not null"); return (Criteria) this; } public Criteria andPayPayIdEqualTo(Integer value) { addCriterion("pay_pay_id =", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdNotEqualTo(Integer value) { addCriterion("pay_pay_id <>", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdGreaterThan(Integer value) { addCriterion("pay_pay_id >", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_pay_id >=", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdLessThan(Integer value) { addCriterion("pay_pay_id <", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdLessThanOrEqualTo(Integer value) { addCriterion("pay_pay_id <=", value, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdIn(List<Integer> values) { addCriterion("pay_pay_id in", values, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdNotIn(List<Integer> values) { addCriterion("pay_pay_id not in", values, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdBetween(Integer value1, Integer value2) { addCriterion("pay_pay_id between", value1, value2, "payPayId"); return (Criteria) this; } public Criteria andPayPayIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_pay_id not between", value1, value2, "payPayId"); return (Criteria) this; } public Criteria andPayTypeIdIsNull() { addCriterion("pay_type_id is null"); return (Criteria) this; } public Criteria andPayTypeIdIsNotNull() { addCriterion("pay_type_id is not null"); return (Criteria) this; } public Criteria andPayTypeIdEqualTo(Integer value) { addCriterion("pay_type_id =", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotEqualTo(Integer value) { addCriterion("pay_type_id <>", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThan(Integer value) { addCriterion("pay_type_id >", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_type_id >=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThan(Integer value) { addCriterion("pay_type_id <", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThanOrEqualTo(Integer value) { addCriterion("pay_type_id <=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdIn(List<Integer> values) { addCriterion("pay_type_id in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotIn(List<Integer> values) { addCriterion("pay_type_id not in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdBetween(Integer value1, Integer value2) { addCriterion("pay_type_id between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_type_id not between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andParamIsNull() { addCriterion("param is null"); return (Criteria) this; } public Criteria andParamIsNotNull() { addCriterion("param is not null"); return (Criteria) this; } public Criteria andParamEqualTo(String value) { addCriterion("param =", value, "param"); return (Criteria) this; } public Criteria andParamNotEqualTo(String value) { addCriterion("param <>", value, "param"); return (Criteria) this; } public Criteria andParamGreaterThan(String value) { addCriterion("param >", value, "param"); return (Criteria) this; } public Criteria andParamGreaterThanOrEqualTo(String value) { addCriterion("param >=", value, "param"); return (Criteria) this; } public Criteria andParamLessThan(String value) { addCriterion("param <", value, "param"); return (Criteria) this; } public Criteria andParamLessThanOrEqualTo(String value) { addCriterion("param <=", value, "param"); return (Criteria) this; } public Criteria andParamLike(String value) { addCriterion("param like", value, "param"); return (Criteria) this; } public Criteria andParamNotLike(String value) { addCriterion("param not like", value, "param"); return (Criteria) this; } public Criteria andParamIn(List<String> values) { addCriterion("param in", values, "param"); return (Criteria) this; } public Criteria andParamNotIn(List<String> values) { addCriterion("param not in", values, "param"); return (Criteria) this; } public Criteria andParamBetween(String value1, String value2) { addCriterion("param between", value1, value2, "param"); return (Criteria) this; } public Criteria andParamNotBetween(String value1, String value2) { addCriterion("param not between", value1, value2, "param"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayType implements Serializable { private Integer payTypeId; private Integer payVendorId; private Integer payMchId; private static final long serialVersionUID = 1L; public Integer getPayTypeId() { return payTypeId; } public void setPayTypeId(Integer payTypeId) { this.payTypeId = payTypeId; } public Integer getPayVendorId() { return payVendorId; } public void setPayVendorId(Integer payVendorId) { this.payVendorId = payVendorId; } public Integer getPayMchId() { return payMchId; } public void setPayMchId(Integer payMchId) { this.payMchId = payMchId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payTypeId=").append(payTypeId); sb.append(", payVendorId=").append(payVendorId); sb.append(", payMchId=").append(payMchId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayType other = (PayType) that; return (this.getPayTypeId() == null ? other.getPayTypeId() == null : this.getPayTypeId().equals(other.getPayTypeId())) && (this.getPayVendorId() == null ? other.getPayVendorId() == null : this.getPayVendorId().equals(other.getPayVendorId())) && (this.getPayMchId() == null ? other.getPayMchId() == null : this.getPayMchId().equals(other.getPayMchId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayTypeId() == null) ? 0 : getPayTypeId().hashCode()); result = prime * result + ((getPayVendorId() == null) ? 0 : getPayVendorId().hashCode()); result = prime * result + ((getPayMchId() == null) ? 0 : getPayMchId().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayTypeExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayTypeExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayTypeIdIsNull() { addCriterion("pay_type_id is null"); return (Criteria) this; } public Criteria andPayTypeIdIsNotNull() { addCriterion("pay_type_id is not null"); return (Criteria) this; } public Criteria andPayTypeIdEqualTo(Integer value) { addCriterion("pay_type_id =", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotEqualTo(Integer value) { addCriterion("pay_type_id <>", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThan(Integer value) { addCriterion("pay_type_id >", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_type_id >=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThan(Integer value) { addCriterion("pay_type_id <", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThanOrEqualTo(Integer value) { addCriterion("pay_type_id <=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdIn(List<Integer> values) { addCriterion("pay_type_id in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotIn(List<Integer> values) { addCriterion("pay_type_id not in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdBetween(Integer value1, Integer value2) { addCriterion("pay_type_id between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_type_id not between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andPayVendorIdIsNull() { addCriterion("pay_vendor_id is null"); return (Criteria) this; } public Criteria andPayVendorIdIsNotNull() { addCriterion("pay_vendor_id is not null"); return (Criteria) this; } public Criteria andPayVendorIdEqualTo(Integer value) { addCriterion("pay_vendor_id =", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotEqualTo(Integer value) { addCriterion("pay_vendor_id <>", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThan(Integer value) { addCriterion("pay_vendor_id >", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id >=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThan(Integer value) { addCriterion("pay_vendor_id <", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id <=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdIn(List<Integer> values) { addCriterion("pay_vendor_id in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotIn(List<Integer> values) { addCriterion("pay_vendor_id not in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id not between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayMchIdIsNull() { addCriterion("pay_mch_id is null"); return (Criteria) this; } public Criteria andPayMchIdIsNotNull() { addCriterion("pay_mch_id is not null"); return (Criteria) this; } public Criteria andPayMchIdEqualTo(Integer value) { addCriterion("pay_mch_id =", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotEqualTo(Integer value) { addCriterion("pay_mch_id <>", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThan(Integer value) { addCriterion("pay_mch_id >", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_mch_id >=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThan(Integer value) { addCriterion("pay_mch_id <", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdLessThanOrEqualTo(Integer value) { addCriterion("pay_mch_id <=", value, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdIn(List<Integer> values) { addCriterion("pay_mch_id in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotIn(List<Integer> values) { addCriterion("pay_mch_id not in", values, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id between", value1, value2, "payMchId"); return (Criteria) this; } public Criteria andPayMchIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_mch_id not between", value1, value2, "payMchId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayVendor implements Serializable { private Integer payVendorId; private String name; private String appid; private String appsecret; private String config; private static final long serialVersionUID = 1L; public Integer getPayVendorId() { return payVendorId; } public void setPayVendorId(Integer payVendorId) { this.payVendorId = payVendorId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getAppsecret() { return appsecret; } public void setAppsecret(String appsecret) { this.appsecret = appsecret; } public String getConfig() { return config; } public void setConfig(String config) { this.config = config; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payVendorId=").append(payVendorId); sb.append(", name=").append(name); sb.append(", appid=").append(appid); sb.append(", appsecret=").append(appsecret); sb.append(", config=").append(config); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayVendor other = (PayVendor) that; return (this.getPayVendorId() == null ? other.getPayVendorId() == null : this.getPayVendorId().equals(other.getPayVendorId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getAppid() == null ? other.getAppid() == null : this.getAppid().equals(other.getAppid())) && (this.getAppsecret() == null ? other.getAppsecret() == null : this.getAppsecret().equals(other.getAppsecret())) && (this.getConfig() == null ? other.getConfig() == null : this.getConfig().equals(other.getConfig())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayVendorId() == null) ? 0 : getPayVendorId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getAppid() == null) ? 0 : getAppid().hashCode()); result = prime * result + ((getAppsecret() == null) ? 0 : getAppsecret().hashCode()); result = prime * result + ((getConfig() == null) ? 0 : getConfig().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayVendorExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayVendorExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayVendorIdIsNull() { addCriterion("pay_vendor_id is null"); return (Criteria) this; } public Criteria andPayVendorIdIsNotNull() { addCriterion("pay_vendor_id is not null"); return (Criteria) this; } public Criteria andPayVendorIdEqualTo(Integer value) { addCriterion("pay_vendor_id =", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotEqualTo(Integer value) { addCriterion("pay_vendor_id <>", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThan(Integer value) { addCriterion("pay_vendor_id >", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id >=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThan(Integer value) { addCriterion("pay_vendor_id <", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdLessThanOrEqualTo(Integer value) { addCriterion("pay_vendor_id <=", value, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdIn(List<Integer> values) { addCriterion("pay_vendor_id in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotIn(List<Integer> values) { addCriterion("pay_vendor_id not in", values, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andPayVendorIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_vendor_id not between", value1, value2, "payVendorId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andAppidIsNull() { addCriterion("appid is null"); return (Criteria) this; } public Criteria andAppidIsNotNull() { addCriterion("appid is not null"); return (Criteria) this; } public Criteria andAppidEqualTo(String value) { addCriterion("appid =", value, "appid"); return (Criteria) this; } public Criteria andAppidNotEqualTo(String value) { addCriterion("appid <>", value, "appid"); return (Criteria) this; } public Criteria andAppidGreaterThan(String value) { addCriterion("appid >", value, "appid"); return (Criteria) this; } public Criteria andAppidGreaterThanOrEqualTo(String value) { addCriterion("appid >=", value, "appid"); return (Criteria) this; } public Criteria andAppidLessThan(String value) { addCriterion("appid <", value, "appid"); return (Criteria) this; } public Criteria andAppidLessThanOrEqualTo(String value) { addCriterion("appid <=", value, "appid"); return (Criteria) this; } public Criteria andAppidLike(String value) { addCriterion("appid like", value, "appid"); return (Criteria) this; } public Criteria andAppidNotLike(String value) { addCriterion("appid not like", value, "appid"); return (Criteria) this; } public Criteria andAppidIn(List<String> values) { addCriterion("appid in", values, "appid"); return (Criteria) this; } public Criteria andAppidNotIn(List<String> values) { addCriterion("appid not in", values, "appid"); return (Criteria) this; } public Criteria andAppidBetween(String value1, String value2) { addCriterion("appid between", value1, value2, "appid"); return (Criteria) this; } public Criteria andAppidNotBetween(String value1, String value2) { addCriterion("appid not between", value1, value2, "appid"); return (Criteria) this; } public Criteria andAppsecretIsNull() { addCriterion("appsecret is null"); return (Criteria) this; } public Criteria andAppsecretIsNotNull() { addCriterion("appsecret is not null"); return (Criteria) this; } public Criteria andAppsecretEqualTo(String value) { addCriterion("appsecret =", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretNotEqualTo(String value) { addCriterion("appsecret <>", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretGreaterThan(String value) { addCriterion("appsecret >", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretGreaterThanOrEqualTo(String value) { addCriterion("appsecret >=", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretLessThan(String value) { addCriterion("appsecret <", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretLessThanOrEqualTo(String value) { addCriterion("appsecret <=", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretLike(String value) { addCriterion("appsecret like", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretNotLike(String value) { addCriterion("appsecret not like", value, "appsecret"); return (Criteria) this; } public Criteria andAppsecretIn(List<String> values) { addCriterion("appsecret in", values, "appsecret"); return (Criteria) this; } public Criteria andAppsecretNotIn(List<String> values) { addCriterion("appsecret not in", values, "appsecret"); return (Criteria) this; } public Criteria andAppsecretBetween(String value1, String value2) { addCriterion("appsecret between", value1, value2, "appsecret"); return (Criteria) this; } public Criteria andAppsecretNotBetween(String value1, String value2) { addCriterion("appsecret not between", value1, value2, "appsecret"); return (Criteria) this; } public Criteria andConfigIsNull() { addCriterion("config is null"); return (Criteria) this; } public Criteria andConfigIsNotNull() { addCriterion("config is not null"); return (Criteria) this; } public Criteria andConfigEqualTo(String value) { addCriterion("config =", value, "config"); return (Criteria) this; } public Criteria andConfigNotEqualTo(String value) { addCriterion("config <>", value, "config"); return (Criteria) this; } public Criteria andConfigGreaterThan(String value) { addCriterion("config >", value, "config"); return (Criteria) this; } public Criteria andConfigGreaterThanOrEqualTo(String value) { addCriterion("config >=", value, "config"); return (Criteria) this; } public Criteria andConfigLessThan(String value) { addCriterion("config <", value, "config"); return (Criteria) this; } public Criteria andConfigLessThanOrEqualTo(String value) { addCriterion("config <=", value, "config"); return (Criteria) this; } public Criteria andConfigLike(String value) { addCriterion("config like", value, "config"); return (Criteria) this; } public Criteria andConfigNotLike(String value) { addCriterion("config not like", value, "config"); return (Criteria) this; } public Criteria andConfigIn(List<String> values) { addCriterion("config in", values, "config"); return (Criteria) this; } public Criteria andConfigNotIn(List<String> values) { addCriterion("config not in", values, "config"); return (Criteria) this; } public Criteria andConfigBetween(String value1, String value2) { addCriterion("config between", value1, value2, "config"); return (Criteria) this; } public Criteria andConfigNotBetween(String value1, String value2) { addCriterion("config not between", value1, value2, "config"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.pay.dao.model; import java.io.Serializable; public class PayVest implements Serializable { private Integer payVestId; private Integer payTypeId; private String prefix; private String param; private static final long serialVersionUID = 1L; public Integer getPayVestId() { return payVestId; } public void setPayVestId(Integer payVestId) { this.payVestId = payVestId; } public Integer getPayTypeId() { return payTypeId; } public void setPayTypeId(Integer payTypeId) { this.payTypeId = payTypeId; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", payVestId=").append(payVestId); sb.append(", payTypeId=").append(payTypeId); sb.append(", prefix=").append(prefix); sb.append(", param=").append(param); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } PayVest other = (PayVest) that; return (this.getPayVestId() == null ? other.getPayVestId() == null : this.getPayVestId().equals(other.getPayVestId())) && (this.getPayTypeId() == null ? other.getPayTypeId() == null : this.getPayTypeId().equals(other.getPayTypeId())) && (this.getPrefix() == null ? other.getPrefix() == null : this.getPrefix().equals(other.getPrefix())) && (this.getParam() == null ? other.getParam() == null : this.getParam().equals(other.getParam())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPayVestId() == null) ? 0 : getPayVestId().hashCode()); result = prime * result + ((getPayTypeId() == null) ? 0 : getPayTypeId().hashCode()); result = prime * result + ((getPrefix() == null) ? 0 : getPrefix().hashCode()); result = prime * result + ((getParam() == null) ? 0 : getParam().hashCode()); return result; } }
package com.zheng.pay.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class PayVestExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public PayVestExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPayVestIdIsNull() { addCriterion("pay_vest_id is null"); return (Criteria) this; } public Criteria andPayVestIdIsNotNull() { addCriterion("pay_vest_id is not null"); return (Criteria) this; } public Criteria andPayVestIdEqualTo(Integer value) { addCriterion("pay_vest_id =", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdNotEqualTo(Integer value) { addCriterion("pay_vest_id <>", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdGreaterThan(Integer value) { addCriterion("pay_vest_id >", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_vest_id >=", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdLessThan(Integer value) { addCriterion("pay_vest_id <", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdLessThanOrEqualTo(Integer value) { addCriterion("pay_vest_id <=", value, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdIn(List<Integer> values) { addCriterion("pay_vest_id in", values, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdNotIn(List<Integer> values) { addCriterion("pay_vest_id not in", values, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdBetween(Integer value1, Integer value2) { addCriterion("pay_vest_id between", value1, value2, "payVestId"); return (Criteria) this; } public Criteria andPayVestIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_vest_id not between", value1, value2, "payVestId"); return (Criteria) this; } public Criteria andPayTypeIdIsNull() { addCriterion("pay_type_id is null"); return (Criteria) this; } public Criteria andPayTypeIdIsNotNull() { addCriterion("pay_type_id is not null"); return (Criteria) this; } public Criteria andPayTypeIdEqualTo(Integer value) { addCriterion("pay_type_id =", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotEqualTo(Integer value) { addCriterion("pay_type_id <>", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThan(Integer value) { addCriterion("pay_type_id >", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdGreaterThanOrEqualTo(Integer value) { addCriterion("pay_type_id >=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThan(Integer value) { addCriterion("pay_type_id <", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdLessThanOrEqualTo(Integer value) { addCriterion("pay_type_id <=", value, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdIn(List<Integer> values) { addCriterion("pay_type_id in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotIn(List<Integer> values) { addCriterion("pay_type_id not in", values, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdBetween(Integer value1, Integer value2) { addCriterion("pay_type_id between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andPayTypeIdNotBetween(Integer value1, Integer value2) { addCriterion("pay_type_id not between", value1, value2, "payTypeId"); return (Criteria) this; } public Criteria andPrefixIsNull() { addCriterion("prefix is null"); return (Criteria) this; } public Criteria andPrefixIsNotNull() { addCriterion("prefix is not null"); return (Criteria) this; } public Criteria andPrefixEqualTo(String value) { addCriterion("prefix =", value, "prefix"); return (Criteria) this; } public Criteria andPrefixNotEqualTo(String value) { addCriterion("prefix <>", value, "prefix"); return (Criteria) this; } public Criteria andPrefixGreaterThan(String value) { addCriterion("prefix >", value, "prefix"); return (Criteria) this; } public Criteria andPrefixGreaterThanOrEqualTo(String value) { addCriterion("prefix >=", value, "prefix"); return (Criteria) this; } public Criteria andPrefixLessThan(String value) { addCriterion("prefix <", value, "prefix"); return (Criteria) this; } public Criteria andPrefixLessThanOrEqualTo(String value) { addCriterion("prefix <=", value, "prefix"); return (Criteria) this; } public Criteria andPrefixLike(String value) { addCriterion("prefix like", value, "prefix"); return (Criteria) this; } public Criteria andPrefixNotLike(String value) { addCriterion("prefix not like", value, "prefix"); return (Criteria) this; } public Criteria andPrefixIn(List<String> values) { addCriterion("prefix in", values, "prefix"); return (Criteria) this; } public Criteria andPrefixNotIn(List<String> values) { addCriterion("prefix not in", values, "prefix"); return (Criteria) this; } public Criteria andPrefixBetween(String value1, String value2) { addCriterion("prefix between", value1, value2, "prefix"); return (Criteria) this; } public Criteria andPrefixNotBetween(String value1, String value2) { addCriterion("prefix not between", value1, value2, "prefix"); return (Criteria) this; } public Criteria andParamIsNull() { addCriterion("param is null"); return (Criteria) this; } public Criteria andParamIsNotNull() { addCriterion("param is not null"); return (Criteria) this; } public Criteria andParamEqualTo(String value) { addCriterion("param =", value, "param"); return (Criteria) this; } public Criteria andParamNotEqualTo(String value) { addCriterion("param <>", value, "param"); return (Criteria) this; } public Criteria andParamGreaterThan(String value) { addCriterion("param >", value, "param"); return (Criteria) this; } public Criteria andParamGreaterThanOrEqualTo(String value) { addCriterion("param >=", value, "param"); return (Criteria) this; } public Criteria andParamLessThan(String value) { addCriterion("param <", value, "param"); return (Criteria) this; } public Criteria andParamLessThanOrEqualTo(String value) { addCriterion("param <=", value, "param"); return (Criteria) this; } public Criteria andParamLike(String value) { addCriterion("param like", value, "param"); return (Criteria) this; } public Criteria andParamNotLike(String value) { addCriterion("param not like", value, "param"); return (Criteria) this; } public Criteria andParamIn(List<String> values) { addCriterion("param in", values, "param"); return (Criteria) this; } public Criteria andParamNotIn(List<String> values) { addCriterion("param not in", values, "param"); return (Criteria) this; } public Criteria andParamBetween(String value1, String value2) { addCriterion("param between", value1, value2, "param"); return (Criteria) this; } public Criteria andParamNotBetween(String value1, String value2) { addCriterion("param not between", value1, value2, "param"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; public class UcenterOauth implements Serializable { /** * 编号 * * @mbg.generated */ private Integer oauthId; /** * 认证方式名称 * * @mbg.generated */ private String name; private static final long serialVersionUID = 1L; public Integer getOauthId() { return oauthId; } public void setOauthId(Integer oauthId) { this.oauthId = oauthId; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", oauthId=").append(oauthId); sb.append(", name=").append(name); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UcenterOauth other = (UcenterOauth) that; return (this.getOauthId() == null ? other.getOauthId() == null : this.getOauthId().equals(other.getOauthId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getOauthId() == null) ? 0 : getOauthId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); return result; } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UcenterOauthExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UcenterOauthExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andOauthIdIsNull() { addCriterion("oauth_id is null"); return (Criteria) this; } public Criteria andOauthIdIsNotNull() { addCriterion("oauth_id is not null"); return (Criteria) this; } public Criteria andOauthIdEqualTo(Integer value) { addCriterion("oauth_id =", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotEqualTo(Integer value) { addCriterion("oauth_id <>", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdGreaterThan(Integer value) { addCriterion("oauth_id >", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdGreaterThanOrEqualTo(Integer value) { addCriterion("oauth_id >=", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdLessThan(Integer value) { addCriterion("oauth_id <", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdLessThanOrEqualTo(Integer value) { addCriterion("oauth_id <=", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdIn(List<Integer> values) { addCriterion("oauth_id in", values, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotIn(List<Integer> values) { addCriterion("oauth_id not in", values, "oauthId"); return (Criteria) this; } public Criteria andOauthIdBetween(Integer value1, Integer value2) { addCriterion("oauth_id between", value1, value2, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotBetween(Integer value1, Integer value2) { addCriterion("oauth_id not between", value1, value2, "oauthId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.Date; public class UcenterUser implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userId; /** * 密码(MD5(密码+盐)) * * @mbg.generated */ private String password; /** * 盐 * * @mbg.generated */ private String salt; /** * 昵称 * * @mbg.generated */ private String nickname; /** * 性别(0:未知,1:男,2:女) * * @mbg.generated */ private Byte sex; /** * 头像 * * @mbg.generated */ private String avatar; /** * 注册时间 * * @mbg.generated */ private Date createTime; /** * 注册IP地址 * * @mbg.generated */ private String createIp; /** * 最后登录时间 * * @mbg.generated */ private Date lastLoginTime; /** * 最后登录IP地址 * * @mbg.generated */ private String lastLoginIp; private static final long serialVersionUID = 1L; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public Byte getSex() { return sex; } public void setSex(Byte sex) { this.sex = sex; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateIp() { return createIp; } public void setCreateIp(String createIp) { this.createIp = createIp; } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userId=").append(userId); sb.append(", password=").append(password); sb.append(", salt=").append(salt); sb.append(", nickname=").append(nickname); sb.append(", sex=").append(sex); sb.append(", avatar=").append(avatar); sb.append(", createTime=").append(createTime); sb.append(", createIp=").append(createIp); sb.append(", lastLoginTime=").append(lastLoginTime); sb.append(", lastLoginIp=").append(lastLoginIp); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UcenterUser other = (UcenterUser) that; return (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getSalt() == null ? other.getSalt() == null : this.getSalt().equals(other.getSalt())) && (this.getNickname() == null ? other.getNickname() == null : this.getNickname().equals(other.getNickname())) && (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex())) && (this.getAvatar() == null ? other.getAvatar() == null : this.getAvatar().equals(other.getAvatar())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (this.getCreateIp() == null ? other.getCreateIp() == null : this.getCreateIp().equals(other.getCreateIp())) && (this.getLastLoginTime() == null ? other.getLastLoginTime() == null : this.getLastLoginTime().equals(other.getLastLoginTime())) && (this.getLastLoginIp() == null ? other.getLastLoginIp() == null : this.getLastLoginIp().equals(other.getLastLoginIp())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getSalt() == null) ? 0 : getSalt().hashCode()); result = prime * result + ((getNickname() == null) ? 0 : getNickname().hashCode()); result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode()); result = prime * result + ((getAvatar() == null) ? 0 : getAvatar().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + ((getCreateIp() == null) ? 0 : getCreateIp().hashCode()); result = prime * result + ((getLastLoginTime() == null) ? 0 : getLastLoginTime().hashCode()); result = prime * result + ((getLastLoginIp() == null) ? 0 : getLastLoginIp().hashCode()); return result; } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.Date; public class UcenterUserDetails implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userId; /** * 个性签名 * * @mbg.generated */ private String signature; /** * 真实姓名 * * @mbg.generated */ private String realName; /** * 出生日期 * * @mbg.generated */ private Date birthday; /** * 帐号安全问题 * * @mbg.generated */ private String question; /** * 帐号安全答案 * * @mbg.generated */ private String answer; private static final long serialVersionUID = 1L; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userId=").append(userId); sb.append(", signature=").append(signature); sb.append(", realName=").append(realName); sb.append(", birthday=").append(birthday); sb.append(", question=").append(question); sb.append(", answer=").append(answer); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UcenterUserDetails other = (UcenterUserDetails) that; return (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getSignature() == null ? other.getSignature() == null : this.getSignature().equals(other.getSignature())) && (this.getRealName() == null ? other.getRealName() == null : this.getRealName().equals(other.getRealName())) && (this.getBirthday() == null ? other.getBirthday() == null : this.getBirthday().equals(other.getBirthday())) && (this.getQuestion() == null ? other.getQuestion() == null : this.getQuestion().equals(other.getQuestion())) && (this.getAnswer() == null ? other.getAnswer() == null : this.getAnswer().equals(other.getAnswer())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getSignature() == null) ? 0 : getSignature().hashCode()); result = prime * result + ((getRealName() == null) ? 0 : getRealName().hashCode()); result = prime * result + ((getBirthday() == null) ? 0 : getBirthday().hashCode()); result = prime * result + ((getQuestion() == null) ? 0 : getQuestion().hashCode()); result = prime * result + ((getAnswer() == null) ? 0 : getAnswer().hashCode()); return result; } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; public class UcenterUserDetailsExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UcenterUserDetailsExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andSignatureIsNull() { addCriterion("signature is null"); return (Criteria) this; } public Criteria andSignatureIsNotNull() { addCriterion("signature is not null"); return (Criteria) this; } public Criteria andSignatureEqualTo(String value) { addCriterion("signature =", value, "signature"); return (Criteria) this; } public Criteria andSignatureNotEqualTo(String value) { addCriterion("signature <>", value, "signature"); return (Criteria) this; } public Criteria andSignatureGreaterThan(String value) { addCriterion("signature >", value, "signature"); return (Criteria) this; } public Criteria andSignatureGreaterThanOrEqualTo(String value) { addCriterion("signature >=", value, "signature"); return (Criteria) this; } public Criteria andSignatureLessThan(String value) { addCriterion("signature <", value, "signature"); return (Criteria) this; } public Criteria andSignatureLessThanOrEqualTo(String value) { addCriterion("signature <=", value, "signature"); return (Criteria) this; } public Criteria andSignatureLike(String value) { addCriterion("signature like", value, "signature"); return (Criteria) this; } public Criteria andSignatureNotLike(String value) { addCriterion("signature not like", value, "signature"); return (Criteria) this; } public Criteria andSignatureIn(List<String> values) { addCriterion("signature in", values, "signature"); return (Criteria) this; } public Criteria andSignatureNotIn(List<String> values) { addCriterion("signature not in", values, "signature"); return (Criteria) this; } public Criteria andSignatureBetween(String value1, String value2) { addCriterion("signature between", value1, value2, "signature"); return (Criteria) this; } public Criteria andSignatureNotBetween(String value1, String value2) { addCriterion("signature not between", value1, value2, "signature"); return (Criteria) this; } public Criteria andRealNameIsNull() { addCriterion("real_name is null"); return (Criteria) this; } public Criteria andRealNameIsNotNull() { addCriterion("real_name is not null"); return (Criteria) this; } public Criteria andRealNameEqualTo(String value) { addCriterion("real_name =", value, "realName"); return (Criteria) this; } public Criteria andRealNameNotEqualTo(String value) { addCriterion("real_name <>", value, "realName"); return (Criteria) this; } public Criteria andRealNameGreaterThan(String value) { addCriterion("real_name >", value, "realName"); return (Criteria) this; } public Criteria andRealNameGreaterThanOrEqualTo(String value) { addCriterion("real_name >=", value, "realName"); return (Criteria) this; } public Criteria andRealNameLessThan(String value) { addCriterion("real_name <", value, "realName"); return (Criteria) this; } public Criteria andRealNameLessThanOrEqualTo(String value) { addCriterion("real_name <=", value, "realName"); return (Criteria) this; } public Criteria andRealNameLike(String value) { addCriterion("real_name like", value, "realName"); return (Criteria) this; } public Criteria andRealNameNotLike(String value) { addCriterion("real_name not like", value, "realName"); return (Criteria) this; } public Criteria andRealNameIn(List<String> values) { addCriterion("real_name in", values, "realName"); return (Criteria) this; } public Criteria andRealNameNotIn(List<String> values) { addCriterion("real_name not in", values, "realName"); return (Criteria) this; } public Criteria andRealNameBetween(String value1, String value2) { addCriterion("real_name between", value1, value2, "realName"); return (Criteria) this; } public Criteria andRealNameNotBetween(String value1, String value2) { addCriterion("real_name not between", value1, value2, "realName"); return (Criteria) this; } public Criteria andBirthdayIsNull() { addCriterion("birthday is null"); return (Criteria) this; } public Criteria andBirthdayIsNotNull() { addCriterion("birthday is not null"); return (Criteria) this; } public Criteria andBirthdayEqualTo(Date value) { addCriterion("birthday =", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotEqualTo(Date value) { addCriterion("birthday <>", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThan(Date value) { addCriterion("birthday >", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThanOrEqualTo(Date value) { addCriterion("birthday >=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThan(Date value) { addCriterion("birthday <", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThanOrEqualTo(Date value) { addCriterion("birthday <=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayIn(List<Date> values) { addCriterion("birthday in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotIn(List<Date> values) { addCriterion("birthday not in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayBetween(Date value1, Date value2) { addCriterion("birthday between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotBetween(Date value1, Date value2) { addCriterion("birthday not between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andQuestionIsNull() { addCriterion("question is null"); return (Criteria) this; } public Criteria andQuestionIsNotNull() { addCriterion("question is not null"); return (Criteria) this; } public Criteria andQuestionEqualTo(String value) { addCriterion("question =", value, "question"); return (Criteria) this; } public Criteria andQuestionNotEqualTo(String value) { addCriterion("question <>", value, "question"); return (Criteria) this; } public Criteria andQuestionGreaterThan(String value) { addCriterion("question >", value, "question"); return (Criteria) this; } public Criteria andQuestionGreaterThanOrEqualTo(String value) { addCriterion("question >=", value, "question"); return (Criteria) this; } public Criteria andQuestionLessThan(String value) { addCriterion("question <", value, "question"); return (Criteria) this; } public Criteria andQuestionLessThanOrEqualTo(String value) { addCriterion("question <=", value, "question"); return (Criteria) this; } public Criteria andQuestionLike(String value) { addCriterion("question like", value, "question"); return (Criteria) this; } public Criteria andQuestionNotLike(String value) { addCriterion("question not like", value, "question"); return (Criteria) this; } public Criteria andQuestionIn(List<String> values) { addCriterion("question in", values, "question"); return (Criteria) this; } public Criteria andQuestionNotIn(List<String> values) { addCriterion("question not in", values, "question"); return (Criteria) this; } public Criteria andQuestionBetween(String value1, String value2) { addCriterion("question between", value1, value2, "question"); return (Criteria) this; } public Criteria andQuestionNotBetween(String value1, String value2) { addCriterion("question not between", value1, value2, "question"); return (Criteria) this; } public Criteria andAnswerIsNull() { addCriterion("answer is null"); return (Criteria) this; } public Criteria andAnswerIsNotNull() { addCriterion("answer is not null"); return (Criteria) this; } public Criteria andAnswerEqualTo(String value) { addCriterion("answer =", value, "answer"); return (Criteria) this; } public Criteria andAnswerNotEqualTo(String value) { addCriterion("answer <>", value, "answer"); return (Criteria) this; } public Criteria andAnswerGreaterThan(String value) { addCriterion("answer >", value, "answer"); return (Criteria) this; } public Criteria andAnswerGreaterThanOrEqualTo(String value) { addCriterion("answer >=", value, "answer"); return (Criteria) this; } public Criteria andAnswerLessThan(String value) { addCriterion("answer <", value, "answer"); return (Criteria) this; } public Criteria andAnswerLessThanOrEqualTo(String value) { addCriterion("answer <=", value, "answer"); return (Criteria) this; } public Criteria andAnswerLike(String value) { addCriterion("answer like", value, "answer"); return (Criteria) this; } public Criteria andAnswerNotLike(String value) { addCriterion("answer not like", value, "answer"); return (Criteria) this; } public Criteria andAnswerIn(List<String> values) { addCriterion("answer in", values, "answer"); return (Criteria) this; } public Criteria andAnswerNotIn(List<String> values) { addCriterion("answer not in", values, "answer"); return (Criteria) this; } public Criteria andAnswerBetween(String value1, String value2) { addCriterion("answer between", value1, value2, "answer"); return (Criteria) this; } public Criteria andAnswerNotBetween(String value1, String value2) { addCriterion("answer not between", value1, value2, "answer"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; public class UcenterUserExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UcenterUserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andSaltIsNull() { addCriterion("salt is null"); return (Criteria) this; } public Criteria andSaltIsNotNull() { addCriterion("salt is not null"); return (Criteria) this; } public Criteria andSaltEqualTo(String value) { addCriterion("salt =", value, "salt"); return (Criteria) this; } public Criteria andSaltNotEqualTo(String value) { addCriterion("salt <>", value, "salt"); return (Criteria) this; } public Criteria andSaltGreaterThan(String value) { addCriterion("salt >", value, "salt"); return (Criteria) this; } public Criteria andSaltGreaterThanOrEqualTo(String value) { addCriterion("salt >=", value, "salt"); return (Criteria) this; } public Criteria andSaltLessThan(String value) { addCriterion("salt <", value, "salt"); return (Criteria) this; } public Criteria andSaltLessThanOrEqualTo(String value) { addCriterion("salt <=", value, "salt"); return (Criteria) this; } public Criteria andSaltLike(String value) { addCriterion("salt like", value, "salt"); return (Criteria) this; } public Criteria andSaltNotLike(String value) { addCriterion("salt not like", value, "salt"); return (Criteria) this; } public Criteria andSaltIn(List<String> values) { addCriterion("salt in", values, "salt"); return (Criteria) this; } public Criteria andSaltNotIn(List<String> values) { addCriterion("salt not in", values, "salt"); return (Criteria) this; } public Criteria andSaltBetween(String value1, String value2) { addCriterion("salt between", value1, value2, "salt"); return (Criteria) this; } public Criteria andSaltNotBetween(String value1, String value2) { addCriterion("salt not between", value1, value2, "salt"); return (Criteria) this; } public Criteria andNicknameIsNull() { addCriterion("nickname is null"); return (Criteria) this; } public Criteria andNicknameIsNotNull() { addCriterion("nickname is not null"); return (Criteria) this; } public Criteria andNicknameEqualTo(String value) { addCriterion("nickname =", value, "nickname"); return (Criteria) this; } public Criteria andNicknameNotEqualTo(String value) { addCriterion("nickname <>", value, "nickname"); return (Criteria) this; } public Criteria andNicknameGreaterThan(String value) { addCriterion("nickname >", value, "nickname"); return (Criteria) this; } public Criteria andNicknameGreaterThanOrEqualTo(String value) { addCriterion("nickname >=", value, "nickname"); return (Criteria) this; } public Criteria andNicknameLessThan(String value) { addCriterion("nickname <", value, "nickname"); return (Criteria) this; } public Criteria andNicknameLessThanOrEqualTo(String value) { addCriterion("nickname <=", value, "nickname"); return (Criteria) this; } public Criteria andNicknameLike(String value) { addCriterion("nickname like", value, "nickname"); return (Criteria) this; } public Criteria andNicknameNotLike(String value) { addCriterion("nickname not like", value, "nickname"); return (Criteria) this; } public Criteria andNicknameIn(List<String> values) { addCriterion("nickname in", values, "nickname"); return (Criteria) this; } public Criteria andNicknameNotIn(List<String> values) { addCriterion("nickname not in", values, "nickname"); return (Criteria) this; } public Criteria andNicknameBetween(String value1, String value2) { addCriterion("nickname between", value1, value2, "nickname"); return (Criteria) this; } public Criteria andNicknameNotBetween(String value1, String value2) { addCriterion("nickname not between", value1, value2, "nickname"); return (Criteria) this; } public Criteria andSexIsNull() { addCriterion("sex is null"); return (Criteria) this; } public Criteria andSexIsNotNull() { addCriterion("sex is not null"); return (Criteria) this; } public Criteria andSexEqualTo(Byte value) { addCriterion("sex =", value, "sex"); return (Criteria) this; } public Criteria andSexNotEqualTo(Byte value) { addCriterion("sex <>", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThan(Byte value) { addCriterion("sex >", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThanOrEqualTo(Byte value) { addCriterion("sex >=", value, "sex"); return (Criteria) this; } public Criteria andSexLessThan(Byte value) { addCriterion("sex <", value, "sex"); return (Criteria) this; } public Criteria andSexLessThanOrEqualTo(Byte value) { addCriterion("sex <=", value, "sex"); return (Criteria) this; } public Criteria andSexIn(List<Byte> values) { addCriterion("sex in", values, "sex"); return (Criteria) this; } public Criteria andSexNotIn(List<Byte> values) { addCriterion("sex not in", values, "sex"); return (Criteria) this; } public Criteria andSexBetween(Byte value1, Byte value2) { addCriterion("sex between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSexNotBetween(Byte value1, Byte value2) { addCriterion("sex not between", value1, value2, "sex"); return (Criteria) this; } public Criteria andAvatarIsNull() { addCriterion("avatar is null"); return (Criteria) this; } public Criteria andAvatarIsNotNull() { addCriterion("avatar is not null"); return (Criteria) this; } public Criteria andAvatarEqualTo(String value) { addCriterion("avatar =", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotEqualTo(String value) { addCriterion("avatar <>", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThan(String value) { addCriterion("avatar >", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThanOrEqualTo(String value) { addCriterion("avatar >=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThan(String value) { addCriterion("avatar <", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThanOrEqualTo(String value) { addCriterion("avatar <=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLike(String value) { addCriterion("avatar like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotLike(String value) { addCriterion("avatar not like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarIn(List<String> values) { addCriterion("avatar in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarNotIn(List<String> values) { addCriterion("avatar not in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarBetween(String value1, String value2) { addCriterion("avatar between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andAvatarNotBetween(String value1, String value2) { addCriterion("avatar not between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateIpIsNull() { addCriterion("create_ip is null"); return (Criteria) this; } public Criteria andCreateIpIsNotNull() { addCriterion("create_ip is not null"); return (Criteria) this; } public Criteria andCreateIpEqualTo(String value) { addCriterion("create_ip =", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpNotEqualTo(String value) { addCriterion("create_ip <>", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpGreaterThan(String value) { addCriterion("create_ip >", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpGreaterThanOrEqualTo(String value) { addCriterion("create_ip >=", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpLessThan(String value) { addCriterion("create_ip <", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpLessThanOrEqualTo(String value) { addCriterion("create_ip <=", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpLike(String value) { addCriterion("create_ip like", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpNotLike(String value) { addCriterion("create_ip not like", value, "createIp"); return (Criteria) this; } public Criteria andCreateIpIn(List<String> values) { addCriterion("create_ip in", values, "createIp"); return (Criteria) this; } public Criteria andCreateIpNotIn(List<String> values) { addCriterion("create_ip not in", values, "createIp"); return (Criteria) this; } public Criteria andCreateIpBetween(String value1, String value2) { addCriterion("create_ip between", value1, value2, "createIp"); return (Criteria) this; } public Criteria andCreateIpNotBetween(String value1, String value2) { addCriterion("create_ip not between", value1, value2, "createIp"); return (Criteria) this; } public Criteria andLastLoginTimeIsNull() { addCriterion("last_login_time is null"); return (Criteria) this; } public Criteria andLastLoginTimeIsNotNull() { addCriterion("last_login_time is not null"); return (Criteria) this; } public Criteria andLastLoginTimeEqualTo(Date value) { addCriterion("last_login_time =", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeNotEqualTo(Date value) { addCriterion("last_login_time <>", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeGreaterThan(Date value) { addCriterion("last_login_time >", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeGreaterThanOrEqualTo(Date value) { addCriterion("last_login_time >=", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeLessThan(Date value) { addCriterion("last_login_time <", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeLessThanOrEqualTo(Date value) { addCriterion("last_login_time <=", value, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeIn(List<Date> values) { addCriterion("last_login_time in", values, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeNotIn(List<Date> values) { addCriterion("last_login_time not in", values, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeBetween(Date value1, Date value2) { addCriterion("last_login_time between", value1, value2, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginTimeNotBetween(Date value1, Date value2) { addCriterion("last_login_time not between", value1, value2, "lastLoginTime"); return (Criteria) this; } public Criteria andLastLoginIpIsNull() { addCriterion("last_login_ip is null"); return (Criteria) this; } public Criteria andLastLoginIpIsNotNull() { addCriterion("last_login_ip is not null"); return (Criteria) this; } public Criteria andLastLoginIpEqualTo(String value) { addCriterion("last_login_ip =", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpNotEqualTo(String value) { addCriterion("last_login_ip <>", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpGreaterThan(String value) { addCriterion("last_login_ip >", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpGreaterThanOrEqualTo(String value) { addCriterion("last_login_ip >=", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpLessThan(String value) { addCriterion("last_login_ip <", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpLessThanOrEqualTo(String value) { addCriterion("last_login_ip <=", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpLike(String value) { addCriterion("last_login_ip like", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpNotLike(String value) { addCriterion("last_login_ip not like", value, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpIn(List<String> values) { addCriterion("last_login_ip in", values, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpNotIn(List<String> values) { addCriterion("last_login_ip not in", values, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpBetween(String value1, String value2) { addCriterion("last_login_ip between", value1, value2, "lastLoginIp"); return (Criteria) this; } public Criteria andLastLoginIpNotBetween(String value1, String value2) { addCriterion("last_login_ip not between", value1, value2, "lastLoginIp"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.Arrays; import java.util.Date; public class UcenterUserLog implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userLogId; /** * 用户编号 * * @mbg.generated */ private Integer userId; /** * 操作IP地址 * * @mbg.generated */ private String ip; /** * 操作时间 * * @mbg.generated */ private Date createTime; /** * 内容 * * @mbg.generated */ private byte[] content; /** * 操作环境 * * @mbg.generated */ private byte[] agent; private static final long serialVersionUID = 1L; public Integer getUserLogId() { return userLogId; } public void setUserLogId(Integer userLogId) { this.userLogId = userLogId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public byte[] getAgent() { return agent; } public void setAgent(byte[] agent) { this.agent = agent; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userLogId=").append(userLogId); sb.append(", userId=").append(userId); sb.append(", ip=").append(ip); sb.append(", createTime=").append(createTime); sb.append(", content=").append(content); sb.append(", agent=").append(agent); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UcenterUserLog other = (UcenterUserLog) that; return (this.getUserLogId() == null ? other.getUserLogId() == null : this.getUserLogId().equals(other.getUserLogId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getIp() == null ? other.getIp() == null : this.getIp().equals(other.getIp())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (Arrays.equals(this.getContent(), other.getContent())) && (Arrays.equals(this.getAgent(), other.getAgent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserLogId() == null) ? 0 : getUserLogId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getIp() == null) ? 0 : getIp().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + (Arrays.hashCode(getContent())); result = prime * result + (Arrays.hashCode(getAgent())); return result; } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; public class UcenterUserLogExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UcenterUserLogExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserLogIdIsNull() { addCriterion("user_log_id is null"); return (Criteria) this; } public Criteria andUserLogIdIsNotNull() { addCriterion("user_log_id is not null"); return (Criteria) this; } public Criteria andUserLogIdEqualTo(Integer value) { addCriterion("user_log_id =", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdNotEqualTo(Integer value) { addCriterion("user_log_id <>", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdGreaterThan(Integer value) { addCriterion("user_log_id >", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_log_id >=", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdLessThan(Integer value) { addCriterion("user_log_id <", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdLessThanOrEqualTo(Integer value) { addCriterion("user_log_id <=", value, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdIn(List<Integer> values) { addCriterion("user_log_id in", values, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdNotIn(List<Integer> values) { addCriterion("user_log_id not in", values, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdBetween(Integer value1, Integer value2) { addCriterion("user_log_id between", value1, value2, "userLogId"); return (Criteria) this; } public Criteria andUserLogIdNotBetween(Integer value1, Integer value2) { addCriterion("user_log_id not between", value1, value2, "userLogId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andIpIsNull() { addCriterion("ip is null"); return (Criteria) this; } public Criteria andIpIsNotNull() { addCriterion("ip is not null"); return (Criteria) this; } public Criteria andIpEqualTo(String value) { addCriterion("ip =", value, "ip"); return (Criteria) this; } public Criteria andIpNotEqualTo(String value) { addCriterion("ip <>", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThan(String value) { addCriterion("ip >", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThanOrEqualTo(String value) { addCriterion("ip >=", value, "ip"); return (Criteria) this; } public Criteria andIpLessThan(String value) { addCriterion("ip <", value, "ip"); return (Criteria) this; } public Criteria andIpLessThanOrEqualTo(String value) { addCriterion("ip <=", value, "ip"); return (Criteria) this; } public Criteria andIpLike(String value) { addCriterion("ip like", value, "ip"); return (Criteria) this; } public Criteria andIpNotLike(String value) { addCriterion("ip not like", value, "ip"); return (Criteria) this; } public Criteria andIpIn(List<String> values) { addCriterion("ip in", values, "ip"); return (Criteria) this; } public Criteria andIpNotIn(List<String> values) { addCriterion("ip not in", values, "ip"); return (Criteria) this; } public Criteria andIpBetween(String value1, String value2) { addCriterion("ip between", value1, value2, "ip"); return (Criteria) this; } public Criteria andIpNotBetween(String value1, String value2) { addCriterion("ip not between", value1, value2, "ip"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.Arrays; import java.util.Date; public class UcenterUserOauth implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userOauthId; /** * 帐号编号 * * @mbg.generated */ private Integer userId; /** * 认证方式编号 * * @mbg.generated */ private Integer oauthId; /** * 绑定状态(0:解绑,1:绑定) * * @mbg.generated */ private Byte status; /** * 创建时间 * * @mbg.generated */ private Date createTime; /** * 第三方ID * * @mbg.generated */ private byte[] openId; private static final long serialVersionUID = 1L; public Integer getUserOauthId() { return userOauthId; } public void setUserOauthId(Integer userOauthId) { this.userOauthId = userOauthId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getOauthId() { return oauthId; } public void setOauthId(Integer oauthId) { this.oauthId = oauthId; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public byte[] getOpenId() { return openId; } public void setOpenId(byte[] openId) { this.openId = openId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userOauthId=").append(userOauthId); sb.append(", userId=").append(userId); sb.append(", oauthId=").append(oauthId); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", openId=").append(openId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UcenterUserOauth other = (UcenterUserOauth) that; return (this.getUserOauthId() == null ? other.getUserOauthId() == null : this.getUserOauthId().equals(other.getUserOauthId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getOauthId() == null ? other.getOauthId() == null : this.getOauthId().equals(other.getOauthId())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (Arrays.equals(this.getOpenId(), other.getOpenId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserOauthId() == null) ? 0 : getUserOauthId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getOauthId() == null) ? 0 : getOauthId().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + (Arrays.hashCode(getOpenId())); return result; } }
package com.zheng.ucenter.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; public class UcenterUserOauthExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UcenterUserOauthExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserOauthIdIsNull() { addCriterion("user_oauth_id is null"); return (Criteria) this; } public Criteria andUserOauthIdIsNotNull() { addCriterion("user_oauth_id is not null"); return (Criteria) this; } public Criteria andUserOauthIdEqualTo(Integer value) { addCriterion("user_oauth_id =", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdNotEqualTo(Integer value) { addCriterion("user_oauth_id <>", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdGreaterThan(Integer value) { addCriterion("user_oauth_id >", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_oauth_id >=", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdLessThan(Integer value) { addCriterion("user_oauth_id <", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdLessThanOrEqualTo(Integer value) { addCriterion("user_oauth_id <=", value, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdIn(List<Integer> values) { addCriterion("user_oauth_id in", values, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdNotIn(List<Integer> values) { addCriterion("user_oauth_id not in", values, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdBetween(Integer value1, Integer value2) { addCriterion("user_oauth_id between", value1, value2, "userOauthId"); return (Criteria) this; } public Criteria andUserOauthIdNotBetween(Integer value1, Integer value2) { addCriterion("user_oauth_id not between", value1, value2, "userOauthId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andOauthIdIsNull() { addCriterion("oauth_id is null"); return (Criteria) this; } public Criteria andOauthIdIsNotNull() { addCriterion("oauth_id is not null"); return (Criteria) this; } public Criteria andOauthIdEqualTo(Integer value) { addCriterion("oauth_id =", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotEqualTo(Integer value) { addCriterion("oauth_id <>", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdGreaterThan(Integer value) { addCriterion("oauth_id >", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdGreaterThanOrEqualTo(Integer value) { addCriterion("oauth_id >=", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdLessThan(Integer value) { addCriterion("oauth_id <", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdLessThanOrEqualTo(Integer value) { addCriterion("oauth_id <=", value, "oauthId"); return (Criteria) this; } public Criteria andOauthIdIn(List<Integer> values) { addCriterion("oauth_id in", values, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotIn(List<Integer> values) { addCriterion("oauth_id not in", values, "oauthId"); return (Criteria) this; } public Criteria andOauthIdBetween(Integer value1, Integer value2) { addCriterion("oauth_id between", value1, value2, "oauthId"); return (Criteria) this; } public Criteria andOauthIdNotBetween(Integer value1, Integer value2) { addCriterion("oauth_id not between", value1, value2, "oauthId"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsLog implements Serializable { /** * 编号 * * @mbg.generated */ private Integer logId; /** * 操作描述 * * @mbg.generated */ private String description; /** * 操作用户 * * @mbg.generated */ private String username; /** * 操作时间 * * @mbg.generated */ private Long startTime; /** * 消耗时间 * * @mbg.generated */ private Integer spendTime; /** * 根路径 * * @mbg.generated */ private String basePath; /** * URI * * @mbg.generated */ private String uri; /** * URL * * @mbg.generated */ private String url; /** * 请求类型 * * @mbg.generated */ private String method; /** * 用户标识 * * @mbg.generated */ private String userAgent; /** * IP地址 * * @mbg.generated */ private String ip; /** * 权限值 * * @mbg.generated */ private String permissions; private String parameter; private String result; private static final long serialVersionUID = 1L; public Integer getLogId() { return logId; } public void setLogId(Integer logId) { this.logId = logId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getStartTime() { return startTime; } public void setStartTime(Long startTime) { this.startTime = startTime; } public Integer getSpendTime() { return spendTime; } public void setSpendTime(Integer spendTime) { this.spendTime = spendTime; } public String getBasePath() { return basePath; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getPermissions() { return permissions; } public void setPermissions(String permissions) { this.permissions = permissions; } public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", logId=").append(logId); sb.append(", description=").append(description); sb.append(", username=").append(username); sb.append(", startTime=").append(startTime); sb.append(", spendTime=").append(spendTime); sb.append(", basePath=").append(basePath); sb.append(", uri=").append(uri); sb.append(", url=").append(url); sb.append(", method=").append(method); sb.append(", userAgent=").append(userAgent); sb.append(", ip=").append(ip); sb.append(", permissions=").append(permissions); sb.append(", parameter=").append(parameter); sb.append(", result=").append(result); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsLog other = (UpmsLog) that; return (this.getLogId() == null ? other.getLogId() == null : this.getLogId().equals(other.getLogId())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getStartTime() == null ? other.getStartTime() == null : this.getStartTime().equals(other.getStartTime())) && (this.getSpendTime() == null ? other.getSpendTime() == null : this.getSpendTime().equals(other.getSpendTime())) && (this.getBasePath() == null ? other.getBasePath() == null : this.getBasePath().equals(other.getBasePath())) && (this.getUri() == null ? other.getUri() == null : this.getUri().equals(other.getUri())) && (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl())) && (this.getMethod() == null ? other.getMethod() == null : this.getMethod().equals(other.getMethod())) && (this.getUserAgent() == null ? other.getUserAgent() == null : this.getUserAgent().equals(other.getUserAgent())) && (this.getIp() == null ? other.getIp() == null : this.getIp().equals(other.getIp())) && (this.getPermissions() == null ? other.getPermissions() == null : this.getPermissions().equals(other.getPermissions())) && (this.getParameter() == null ? other.getParameter() == null : this.getParameter().equals(other.getParameter())) && (this.getResult() == null ? other.getResult() == null : this.getResult().equals(other.getResult())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getLogId() == null) ? 0 : getLogId().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getStartTime() == null) ? 0 : getStartTime().hashCode()); result = prime * result + ((getSpendTime() == null) ? 0 : getSpendTime().hashCode()); result = prime * result + ((getBasePath() == null) ? 0 : getBasePath().hashCode()); result = prime * result + ((getUri() == null) ? 0 : getUri().hashCode()); result = prime * result + ((getUrl() == null) ? 0 : getUrl().hashCode()); result = prime * result + ((getMethod() == null) ? 0 : getMethod().hashCode()); result = prime * result + ((getUserAgent() == null) ? 0 : getUserAgent().hashCode()); result = prime * result + ((getIp() == null) ? 0 : getIp().hashCode()); result = prime * result + ((getPermissions() == null) ? 0 : getPermissions().hashCode()); result = prime * result + ((getParameter() == null) ? 0 : getParameter().hashCode()); result = prime * result + ((getResult() == null) ? 0 : getResult().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsLogExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsLogExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andLogIdIsNull() { addCriterion("log_id is null"); return (Criteria) this; } public Criteria andLogIdIsNotNull() { addCriterion("log_id is not null"); return (Criteria) this; } public Criteria andLogIdEqualTo(Integer value) { addCriterion("log_id =", value, "logId"); return (Criteria) this; } public Criteria andLogIdNotEqualTo(Integer value) { addCriterion("log_id <>", value, "logId"); return (Criteria) this; } public Criteria andLogIdGreaterThan(Integer value) { addCriterion("log_id >", value, "logId"); return (Criteria) this; } public Criteria andLogIdGreaterThanOrEqualTo(Integer value) { addCriterion("log_id >=", value, "logId"); return (Criteria) this; } public Criteria andLogIdLessThan(Integer value) { addCriterion("log_id <", value, "logId"); return (Criteria) this; } public Criteria andLogIdLessThanOrEqualTo(Integer value) { addCriterion("log_id <=", value, "logId"); return (Criteria) this; } public Criteria andLogIdIn(List<Integer> values) { addCriterion("log_id in", values, "logId"); return (Criteria) this; } public Criteria andLogIdNotIn(List<Integer> values) { addCriterion("log_id not in", values, "logId"); return (Criteria) this; } public Criteria andLogIdBetween(Integer value1, Integer value2) { addCriterion("log_id between", value1, value2, "logId"); return (Criteria) this; } public Criteria andLogIdNotBetween(Integer value1, Integer value2) { addCriterion("log_id not between", value1, value2, "logId"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andStartTimeIsNull() { addCriterion("start_time is null"); return (Criteria) this; } public Criteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return (Criteria) this; } public Criteria andStartTimeEqualTo(Long value) { addCriterion("start_time =", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotEqualTo(Long value) { addCriterion("start_time <>", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThan(Long value) { addCriterion("start_time >", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThanOrEqualTo(Long value) { addCriterion("start_time >=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThan(Long value) { addCriterion("start_time <", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThanOrEqualTo(Long value) { addCriterion("start_time <=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeIn(List<Long> values) { addCriterion("start_time in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotIn(List<Long> values) { addCriterion("start_time not in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeBetween(Long value1, Long value2) { addCriterion("start_time between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotBetween(Long value1, Long value2) { addCriterion("start_time not between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andSpendTimeIsNull() { addCriterion("spend_time is null"); return (Criteria) this; } public Criteria andSpendTimeIsNotNull() { addCriterion("spend_time is not null"); return (Criteria) this; } public Criteria andSpendTimeEqualTo(Integer value) { addCriterion("spend_time =", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeNotEqualTo(Integer value) { addCriterion("spend_time <>", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeGreaterThan(Integer value) { addCriterion("spend_time >", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeGreaterThanOrEqualTo(Integer value) { addCriterion("spend_time >=", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeLessThan(Integer value) { addCriterion("spend_time <", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeLessThanOrEqualTo(Integer value) { addCriterion("spend_time <=", value, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeIn(List<Integer> values) { addCriterion("spend_time in", values, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeNotIn(List<Integer> values) { addCriterion("spend_time not in", values, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeBetween(Integer value1, Integer value2) { addCriterion("spend_time between", value1, value2, "spendTime"); return (Criteria) this; } public Criteria andSpendTimeNotBetween(Integer value1, Integer value2) { addCriterion("spend_time not between", value1, value2, "spendTime"); return (Criteria) this; } public Criteria andBasePathIsNull() { addCriterion("base_path is null"); return (Criteria) this; } public Criteria andBasePathIsNotNull() { addCriterion("base_path is not null"); return (Criteria) this; } public Criteria andBasePathEqualTo(String value) { addCriterion("base_path =", value, "basePath"); return (Criteria) this; } public Criteria andBasePathNotEqualTo(String value) { addCriterion("base_path <>", value, "basePath"); return (Criteria) this; } public Criteria andBasePathGreaterThan(String value) { addCriterion("base_path >", value, "basePath"); return (Criteria) this; } public Criteria andBasePathGreaterThanOrEqualTo(String value) { addCriterion("base_path >=", value, "basePath"); return (Criteria) this; } public Criteria andBasePathLessThan(String value) { addCriterion("base_path <", value, "basePath"); return (Criteria) this; } public Criteria andBasePathLessThanOrEqualTo(String value) { addCriterion("base_path <=", value, "basePath"); return (Criteria) this; } public Criteria andBasePathLike(String value) { addCriterion("base_path like", value, "basePath"); return (Criteria) this; } public Criteria andBasePathNotLike(String value) { addCriterion("base_path not like", value, "basePath"); return (Criteria) this; } public Criteria andBasePathIn(List<String> values) { addCriterion("base_path in", values, "basePath"); return (Criteria) this; } public Criteria andBasePathNotIn(List<String> values) { addCriterion("base_path not in", values, "basePath"); return (Criteria) this; } public Criteria andBasePathBetween(String value1, String value2) { addCriterion("base_path between", value1, value2, "basePath"); return (Criteria) this; } public Criteria andBasePathNotBetween(String value1, String value2) { addCriterion("base_path not between", value1, value2, "basePath"); return (Criteria) this; } public Criteria andUriIsNull() { addCriterion("uri is null"); return (Criteria) this; } public Criteria andUriIsNotNull() { addCriterion("uri is not null"); return (Criteria) this; } public Criteria andUriEqualTo(String value) { addCriterion("uri =", value, "uri"); return (Criteria) this; } public Criteria andUriNotEqualTo(String value) { addCriterion("uri <>", value, "uri"); return (Criteria) this; } public Criteria andUriGreaterThan(String value) { addCriterion("uri >", value, "uri"); return (Criteria) this; } public Criteria andUriGreaterThanOrEqualTo(String value) { addCriterion("uri >=", value, "uri"); return (Criteria) this; } public Criteria andUriLessThan(String value) { addCriterion("uri <", value, "uri"); return (Criteria) this; } public Criteria andUriLessThanOrEqualTo(String value) { addCriterion("uri <=", value, "uri"); return (Criteria) this; } public Criteria andUriLike(String value) { addCriterion("uri like", value, "uri"); return (Criteria) this; } public Criteria andUriNotLike(String value) { addCriterion("uri not like", value, "uri"); return (Criteria) this; } public Criteria andUriIn(List<String> values) { addCriterion("uri in", values, "uri"); return (Criteria) this; } public Criteria andUriNotIn(List<String> values) { addCriterion("uri not in", values, "uri"); return (Criteria) this; } public Criteria andUriBetween(String value1, String value2) { addCriterion("uri between", value1, value2, "uri"); return (Criteria) this; } public Criteria andUriNotBetween(String value1, String value2) { addCriterion("uri not between", value1, value2, "uri"); return (Criteria) this; } public Criteria andUrlIsNull() { addCriterion("url is null"); return (Criteria) this; } public Criteria andUrlIsNotNull() { addCriterion("url is not null"); return (Criteria) this; } public Criteria andUrlEqualTo(String value) { addCriterion("url =", value, "url"); return (Criteria) this; } public Criteria andUrlNotEqualTo(String value) { addCriterion("url <>", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThan(String value) { addCriterion("url >", value, "url"); return (Criteria) this; } public Criteria andUrlGreaterThanOrEqualTo(String value) { addCriterion("url >=", value, "url"); return (Criteria) this; } public Criteria andUrlLessThan(String value) { addCriterion("url <", value, "url"); return (Criteria) this; } public Criteria andUrlLessThanOrEqualTo(String value) { addCriterion("url <=", value, "url"); return (Criteria) this; } public Criteria andUrlLike(String value) { addCriterion("url like", value, "url"); return (Criteria) this; } public Criteria andUrlNotLike(String value) { addCriterion("url not like", value, "url"); return (Criteria) this; } public Criteria andUrlIn(List<String> values) { addCriterion("url in", values, "url"); return (Criteria) this; } public Criteria andUrlNotIn(List<String> values) { addCriterion("url not in", values, "url"); return (Criteria) this; } public Criteria andUrlBetween(String value1, String value2) { addCriterion("url between", value1, value2, "url"); return (Criteria) this; } public Criteria andUrlNotBetween(String value1, String value2) { addCriterion("url not between", value1, value2, "url"); return (Criteria) this; } public Criteria andMethodIsNull() { addCriterion("method is null"); return (Criteria) this; } public Criteria andMethodIsNotNull() { addCriterion("method is not null"); return (Criteria) this; } public Criteria andMethodEqualTo(String value) { addCriterion("method =", value, "method"); return (Criteria) this; } public Criteria andMethodNotEqualTo(String value) { addCriterion("method <>", value, "method"); return (Criteria) this; } public Criteria andMethodGreaterThan(String value) { addCriterion("method >", value, "method"); return (Criteria) this; } public Criteria andMethodGreaterThanOrEqualTo(String value) { addCriterion("method >=", value, "method"); return (Criteria) this; } public Criteria andMethodLessThan(String value) { addCriterion("method <", value, "method"); return (Criteria) this; } public Criteria andMethodLessThanOrEqualTo(String value) { addCriterion("method <=", value, "method"); return (Criteria) this; } public Criteria andMethodLike(String value) { addCriterion("method like", value, "method"); return (Criteria) this; } public Criteria andMethodNotLike(String value) { addCriterion("method not like", value, "method"); return (Criteria) this; } public Criteria andMethodIn(List<String> values) { addCriterion("method in", values, "method"); return (Criteria) this; } public Criteria andMethodNotIn(List<String> values) { addCriterion("method not in", values, "method"); return (Criteria) this; } public Criteria andMethodBetween(String value1, String value2) { addCriterion("method between", value1, value2, "method"); return (Criteria) this; } public Criteria andMethodNotBetween(String value1, String value2) { addCriterion("method not between", value1, value2, "method"); return (Criteria) this; } public Criteria andUserAgentIsNull() { addCriterion("user_agent is null"); return (Criteria) this; } public Criteria andUserAgentIsNotNull() { addCriterion("user_agent is not null"); return (Criteria) this; } public Criteria andUserAgentEqualTo(String value) { addCriterion("user_agent =", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentNotEqualTo(String value) { addCriterion("user_agent <>", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentGreaterThan(String value) { addCriterion("user_agent >", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentGreaterThanOrEqualTo(String value) { addCriterion("user_agent >=", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentLessThan(String value) { addCriterion("user_agent <", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentLessThanOrEqualTo(String value) { addCriterion("user_agent <=", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentLike(String value) { addCriterion("user_agent like", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentNotLike(String value) { addCriterion("user_agent not like", value, "userAgent"); return (Criteria) this; } public Criteria andUserAgentIn(List<String> values) { addCriterion("user_agent in", values, "userAgent"); return (Criteria) this; } public Criteria andUserAgentNotIn(List<String> values) { addCriterion("user_agent not in", values, "userAgent"); return (Criteria) this; } public Criteria andUserAgentBetween(String value1, String value2) { addCriterion("user_agent between", value1, value2, "userAgent"); return (Criteria) this; } public Criteria andUserAgentNotBetween(String value1, String value2) { addCriterion("user_agent not between", value1, value2, "userAgent"); return (Criteria) this; } public Criteria andIpIsNull() { addCriterion("ip is null"); return (Criteria) this; } public Criteria andIpIsNotNull() { addCriterion("ip is not null"); return (Criteria) this; } public Criteria andIpEqualTo(String value) { addCriterion("ip =", value, "ip"); return (Criteria) this; } public Criteria andIpNotEqualTo(String value) { addCriterion("ip <>", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThan(String value) { addCriterion("ip >", value, "ip"); return (Criteria) this; } public Criteria andIpGreaterThanOrEqualTo(String value) { addCriterion("ip >=", value, "ip"); return (Criteria) this; } public Criteria andIpLessThan(String value) { addCriterion("ip <", value, "ip"); return (Criteria) this; } public Criteria andIpLessThanOrEqualTo(String value) { addCriterion("ip <=", value, "ip"); return (Criteria) this; } public Criteria andIpLike(String value) { addCriterion("ip like", value, "ip"); return (Criteria) this; } public Criteria andIpNotLike(String value) { addCriterion("ip not like", value, "ip"); return (Criteria) this; } public Criteria andIpIn(List<String> values) { addCriterion("ip in", values, "ip"); return (Criteria) this; } public Criteria andIpNotIn(List<String> values) { addCriterion("ip not in", values, "ip"); return (Criteria) this; } public Criteria andIpBetween(String value1, String value2) { addCriterion("ip between", value1, value2, "ip"); return (Criteria) this; } public Criteria andIpNotBetween(String value1, String value2) { addCriterion("ip not between", value1, value2, "ip"); return (Criteria) this; } public Criteria andPermissionsIsNull() { addCriterion("permissions is null"); return (Criteria) this; } public Criteria andPermissionsIsNotNull() { addCriterion("permissions is not null"); return (Criteria) this; } public Criteria andPermissionsEqualTo(String value) { addCriterion("permissions =", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsNotEqualTo(String value) { addCriterion("permissions <>", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsGreaterThan(String value) { addCriterion("permissions >", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsGreaterThanOrEqualTo(String value) { addCriterion("permissions >=", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsLessThan(String value) { addCriterion("permissions <", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsLessThanOrEqualTo(String value) { addCriterion("permissions <=", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsLike(String value) { addCriterion("permissions like", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsNotLike(String value) { addCriterion("permissions not like", value, "permissions"); return (Criteria) this; } public Criteria andPermissionsIn(List<String> values) { addCriterion("permissions in", values, "permissions"); return (Criteria) this; } public Criteria andPermissionsNotIn(List<String> values) { addCriterion("permissions not in", values, "permissions"); return (Criteria) this; } public Criteria andPermissionsBetween(String value1, String value2) { addCriterion("permissions between", value1, value2, "permissions"); return (Criteria) this; } public Criteria andPermissionsNotBetween(String value1, String value2) { addCriterion("permissions not between", value1, value2, "permissions"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsOrganization implements Serializable { /** * 编号 * * @mbg.generated */ private Integer organizationId; /** * 所属上级 * * @mbg.generated */ private Integer pid; /** * 组织名称 * * @mbg.generated */ private String name; /** * 组织描述 * * @mbg.generated */ private String description; /** * 创建时间 * * @mbg.generated */ private Long ctime; private static final long serialVersionUID = 1L; public Integer getOrganizationId() { return organizationId; } public void setOrganizationId(Integer organizationId) { this.organizationId = organizationId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", organizationId=").append(organizationId); sb.append(", pid=").append(pid); sb.append(", name=").append(name); sb.append(", description=").append(description); sb.append(", ctime=").append(ctime); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsOrganization other = (UpmsOrganization) that; return (this.getOrganizationId() == null ? other.getOrganizationId() == null : this.getOrganizationId().equals(other.getOrganizationId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getOrganizationId() == null) ? 0 : getOrganizationId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsOrganizationExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsOrganizationExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andOrganizationIdIsNull() { addCriterion("organization_id is null"); return (Criteria) this; } public Criteria andOrganizationIdIsNotNull() { addCriterion("organization_id is not null"); return (Criteria) this; } public Criteria andOrganizationIdEqualTo(Integer value) { addCriterion("organization_id =", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotEqualTo(Integer value) { addCriterion("organization_id <>", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdGreaterThan(Integer value) { addCriterion("organization_id >", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdGreaterThanOrEqualTo(Integer value) { addCriterion("organization_id >=", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdLessThan(Integer value) { addCriterion("organization_id <", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdLessThanOrEqualTo(Integer value) { addCriterion("organization_id <=", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdIn(List<Integer> values) { addCriterion("organization_id in", values, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotIn(List<Integer> values) { addCriterion("organization_id not in", values, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdBetween(Integer value1, Integer value2) { addCriterion("organization_id between", value1, value2, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotBetween(Integer value1, Integer value2) { addCriterion("organization_id not between", value1, value2, "organizationId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsPermission implements Serializable { /** * 编号 * * @mbg.generated */ private Integer permissionId; /** * 所属系统 * * @mbg.generated */ private Integer systemId; /** * 所属上级 * * @mbg.generated */ private Integer pid; /** * 名称 * * @mbg.generated */ private String name; /** * 类型(1:目录,2:菜单,3:按钮) * * @mbg.generated */ private Byte type; /** * 权限值 * * @mbg.generated */ private String permissionValue; /** * 路径 * * @mbg.generated */ private String uri; /** * 图标 * * @mbg.generated */ private String icon; /** * 状态(0:禁止,1:正常) * * @mbg.generated */ private Byte status; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getPermissionId() { return permissionId; } public void setPermissionId(Integer permissionId) { this.permissionId = permissionId; } public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public String getPermissionValue() { return permissionValue; } public void setPermissionValue(String permissionValue) { this.permissionValue = permissionValue; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", permissionId=").append(permissionId); sb.append(", systemId=").append(systemId); sb.append(", pid=").append(pid); sb.append(", name=").append(name); sb.append(", type=").append(type); sb.append(", permissionValue=").append(permissionValue); sb.append(", uri=").append(uri); sb.append(", icon=").append(icon); sb.append(", status=").append(status); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsPermission other = (UpmsPermission) that; return (this.getPermissionId() == null ? other.getPermissionId() == null : this.getPermissionId().equals(other.getPermissionId())) && (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getPid() == null ? other.getPid() == null : this.getPid().equals(other.getPid())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getPermissionValue() == null ? other.getPermissionValue() == null : this.getPermissionValue().equals(other.getPermissionValue())) && (this.getUri() == null ? other.getUri() == null : this.getUri().equals(other.getUri())) && (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getPermissionId() == null) ? 0 : getPermissionId().hashCode()); result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getPid() == null) ? 0 : getPid().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getPermissionValue() == null) ? 0 : getPermissionValue().hashCode()); result = prime * result + ((getUri() == null) ? 0 : getUri().hashCode()); result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsPermissionExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsPermissionExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andPermissionIdIsNull() { addCriterion("permission_id is null"); return (Criteria) this; } public Criteria andPermissionIdIsNotNull() { addCriterion("permission_id is not null"); return (Criteria) this; } public Criteria andPermissionIdEqualTo(Integer value) { addCriterion("permission_id =", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotEqualTo(Integer value) { addCriterion("permission_id <>", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThan(Integer value) { addCriterion("permission_id >", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThanOrEqualTo(Integer value) { addCriterion("permission_id >=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThan(Integer value) { addCriterion("permission_id <", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThanOrEqualTo(Integer value) { addCriterion("permission_id <=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdIn(List<Integer> values) { addCriterion("permission_id in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotIn(List<Integer> values) { addCriterion("permission_id not in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdBetween(Integer value1, Integer value2) { addCriterion("permission_id between", value1, value2, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotBetween(Integer value1, Integer value2) { addCriterion("permission_id not between", value1, value2, "permissionId"); return (Criteria) this; } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andPermissionValueIsNull() { addCriterion("permission_value is null"); return (Criteria) this; } public Criteria andPermissionValueIsNotNull() { addCriterion("permission_value is not null"); return (Criteria) this; } public Criteria andPermissionValueEqualTo(String value) { addCriterion("permission_value =", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueNotEqualTo(String value) { addCriterion("permission_value <>", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueGreaterThan(String value) { addCriterion("permission_value >", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueGreaterThanOrEqualTo(String value) { addCriterion("permission_value >=", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueLessThan(String value) { addCriterion("permission_value <", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueLessThanOrEqualTo(String value) { addCriterion("permission_value <=", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueLike(String value) { addCriterion("permission_value like", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueNotLike(String value) { addCriterion("permission_value not like", value, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueIn(List<String> values) { addCriterion("permission_value in", values, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueNotIn(List<String> values) { addCriterion("permission_value not in", values, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueBetween(String value1, String value2) { addCriterion("permission_value between", value1, value2, "permissionValue"); return (Criteria) this; } public Criteria andPermissionValueNotBetween(String value1, String value2) { addCriterion("permission_value not between", value1, value2, "permissionValue"); return (Criteria) this; } public Criteria andUriIsNull() { addCriterion("uri is null"); return (Criteria) this; } public Criteria andUriIsNotNull() { addCriterion("uri is not null"); return (Criteria) this; } public Criteria andUriEqualTo(String value) { addCriterion("uri =", value, "uri"); return (Criteria) this; } public Criteria andUriNotEqualTo(String value) { addCriterion("uri <>", value, "uri"); return (Criteria) this; } public Criteria andUriGreaterThan(String value) { addCriterion("uri >", value, "uri"); return (Criteria) this; } public Criteria andUriGreaterThanOrEqualTo(String value) { addCriterion("uri >=", value, "uri"); return (Criteria) this; } public Criteria andUriLessThan(String value) { addCriterion("uri <", value, "uri"); return (Criteria) this; } public Criteria andUriLessThanOrEqualTo(String value) { addCriterion("uri <=", value, "uri"); return (Criteria) this; } public Criteria andUriLike(String value) { addCriterion("uri like", value, "uri"); return (Criteria) this; } public Criteria andUriNotLike(String value) { addCriterion("uri not like", value, "uri"); return (Criteria) this; } public Criteria andUriIn(List<String> values) { addCriterion("uri in", values, "uri"); return (Criteria) this; } public Criteria andUriNotIn(List<String> values) { addCriterion("uri not in", values, "uri"); return (Criteria) this; } public Criteria andUriBetween(String value1, String value2) { addCriterion("uri between", value1, value2, "uri"); return (Criteria) this; } public Criteria andUriNotBetween(String value1, String value2) { addCriterion("uri not between", value1, value2, "uri"); return (Criteria) this; } public Criteria andIconIsNull() { addCriterion("icon is null"); return (Criteria) this; } public Criteria andIconIsNotNull() { addCriterion("icon is not null"); return (Criteria) this; } public Criteria andIconEqualTo(String value) { addCriterion("icon =", value, "icon"); return (Criteria) this; } public Criteria andIconNotEqualTo(String value) { addCriterion("icon <>", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThan(String value) { addCriterion("icon >", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThanOrEqualTo(String value) { addCriterion("icon >=", value, "icon"); return (Criteria) this; } public Criteria andIconLessThan(String value) { addCriterion("icon <", value, "icon"); return (Criteria) this; } public Criteria andIconLessThanOrEqualTo(String value) { addCriterion("icon <=", value, "icon"); return (Criteria) this; } public Criteria andIconLike(String value) { addCriterion("icon like", value, "icon"); return (Criteria) this; } public Criteria andIconNotLike(String value) { addCriterion("icon not like", value, "icon"); return (Criteria) this; } public Criteria andIconIn(List<String> values) { addCriterion("icon in", values, "icon"); return (Criteria) this; } public Criteria andIconNotIn(List<String> values) { addCriterion("icon not in", values, "icon"); return (Criteria) this; } public Criteria andIconBetween(String value1, String value2) { addCriterion("icon between", value1, value2, "icon"); return (Criteria) this; } public Criteria andIconNotBetween(String value1, String value2) { addCriterion("icon not between", value1, value2, "icon"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsRole implements Serializable { /** * 编号 * * @mbg.generated */ private Integer roleId; /** * 角色名称 * * @mbg.generated */ private String name; /** * 角色标题 * * @mbg.generated */ private String title; /** * 角色描述 * * @mbg.generated */ private String description; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", roleId=").append(roleId); sb.append(", name=").append(name); sb.append(", title=").append(title); sb.append(", description=").append(description); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsRole other = (UpmsRole) that; return (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsRoleExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsRoleExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andRoleIdIsNull() { addCriterion("role_id is null"); return (Criteria) this; } public Criteria andRoleIdIsNotNull() { addCriterion("role_id is not null"); return (Criteria) this; } public Criteria andRoleIdEqualTo(Integer value) { addCriterion("role_id =", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotEqualTo(Integer value) { addCriterion("role_id <>", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThan(Integer value) { addCriterion("role_id >", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThanOrEqualTo(Integer value) { addCriterion("role_id >=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThan(Integer value) { addCriterion("role_id <", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThanOrEqualTo(Integer value) { addCriterion("role_id <=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdIn(List<Integer> values) { addCriterion("role_id in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotIn(List<Integer> values) { addCriterion("role_id not in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdBetween(Integer value1, Integer value2) { addCriterion("role_id between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Integer value1, Integer value2) { addCriterion("role_id not between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsRolePermission implements Serializable { /** * 编号 * * @mbg.generated */ private Integer rolePermissionId; /** * 角色编号 * * @mbg.generated */ private Integer roleId; /** * 权限编号 * * @mbg.generated */ private Integer permissionId; private static final long serialVersionUID = 1L; public Integer getRolePermissionId() { return rolePermissionId; } public void setRolePermissionId(Integer rolePermissionId) { this.rolePermissionId = rolePermissionId; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public Integer getPermissionId() { return permissionId; } public void setPermissionId(Integer permissionId) { this.permissionId = permissionId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", rolePermissionId=").append(rolePermissionId); sb.append(", roleId=").append(roleId); sb.append(", permissionId=").append(permissionId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsRolePermission other = (UpmsRolePermission) that; return (this.getRolePermissionId() == null ? other.getRolePermissionId() == null : this.getRolePermissionId().equals(other.getRolePermissionId())) && (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId())) && (this.getPermissionId() == null ? other.getPermissionId() == null : this.getPermissionId().equals(other.getPermissionId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getRolePermissionId() == null) ? 0 : getRolePermissionId().hashCode()); result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode()); result = prime * result + ((getPermissionId() == null) ? 0 : getPermissionId().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsRolePermissionExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsRolePermissionExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andRolePermissionIdIsNull() { addCriterion("role_permission_id is null"); return (Criteria) this; } public Criteria andRolePermissionIdIsNotNull() { addCriterion("role_permission_id is not null"); return (Criteria) this; } public Criteria andRolePermissionIdEqualTo(Integer value) { addCriterion("role_permission_id =", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdNotEqualTo(Integer value) { addCriterion("role_permission_id <>", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdGreaterThan(Integer value) { addCriterion("role_permission_id >", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdGreaterThanOrEqualTo(Integer value) { addCriterion("role_permission_id >=", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdLessThan(Integer value) { addCriterion("role_permission_id <", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdLessThanOrEqualTo(Integer value) { addCriterion("role_permission_id <=", value, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdIn(List<Integer> values) { addCriterion("role_permission_id in", values, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdNotIn(List<Integer> values) { addCriterion("role_permission_id not in", values, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdBetween(Integer value1, Integer value2) { addCriterion("role_permission_id between", value1, value2, "rolePermissionId"); return (Criteria) this; } public Criteria andRolePermissionIdNotBetween(Integer value1, Integer value2) { addCriterion("role_permission_id not between", value1, value2, "rolePermissionId"); return (Criteria) this; } public Criteria andRoleIdIsNull() { addCriterion("role_id is null"); return (Criteria) this; } public Criteria andRoleIdIsNotNull() { addCriterion("role_id is not null"); return (Criteria) this; } public Criteria andRoleIdEqualTo(Integer value) { addCriterion("role_id =", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotEqualTo(Integer value) { addCriterion("role_id <>", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThan(Integer value) { addCriterion("role_id >", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThanOrEqualTo(Integer value) { addCriterion("role_id >=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThan(Integer value) { addCriterion("role_id <", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThanOrEqualTo(Integer value) { addCriterion("role_id <=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdIn(List<Integer> values) { addCriterion("role_id in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotIn(List<Integer> values) { addCriterion("role_id not in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdBetween(Integer value1, Integer value2) { addCriterion("role_id between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Integer value1, Integer value2) { addCriterion("role_id not between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andPermissionIdIsNull() { addCriterion("permission_id is null"); return (Criteria) this; } public Criteria andPermissionIdIsNotNull() { addCriterion("permission_id is not null"); return (Criteria) this; } public Criteria andPermissionIdEqualTo(Integer value) { addCriterion("permission_id =", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotEqualTo(Integer value) { addCriterion("permission_id <>", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThan(Integer value) { addCriterion("permission_id >", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThanOrEqualTo(Integer value) { addCriterion("permission_id >=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThan(Integer value) { addCriterion("permission_id <", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThanOrEqualTo(Integer value) { addCriterion("permission_id <=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdIn(List<Integer> values) { addCriterion("permission_id in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotIn(List<Integer> values) { addCriterion("permission_id not in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdBetween(Integer value1, Integer value2) { addCriterion("permission_id between", value1, value2, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotBetween(Integer value1, Integer value2) { addCriterion("permission_id not between", value1, value2, "permissionId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsSystem implements Serializable { /** * 编号 * * @mbg.generated */ private Integer systemId; /** * 图标 * * @mbg.generated */ private String icon; /** * 背景 * * @mbg.generated */ private String banner; /** * 主题 * * @mbg.generated */ private String theme; /** * 根目录 * * @mbg.generated */ private String basepath; /** * 状态(-1:黑名单,1:正常) * * @mbg.generated */ private Byte status; /** * 系统名称 * * @mbg.generated */ private String name; /** * 系统标题 * * @mbg.generated */ private String title; /** * 系统描述 * * @mbg.generated */ private String description; /** * 创建时间 * * @mbg.generated */ private Long ctime; /** * 排序 * * @mbg.generated */ private Long orders; private static final long serialVersionUID = 1L; public Integer getSystemId() { return systemId; } public void setSystemId(Integer systemId) { this.systemId = systemId; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getBanner() { return banner; } public void setBanner(String banner) { this.banner = banner; } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public String getBasepath() { return basepath; } public void setBasepath(String basepath) { this.basepath = basepath; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } public Long getOrders() { return orders; } public void setOrders(Long orders) { this.orders = orders; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", systemId=").append(systemId); sb.append(", icon=").append(icon); sb.append(", banner=").append(banner); sb.append(", theme=").append(theme); sb.append(", basepath=").append(basepath); sb.append(", status=").append(status); sb.append(", name=").append(name); sb.append(", title=").append(title); sb.append(", description=").append(description); sb.append(", ctime=").append(ctime); sb.append(", orders=").append(orders); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsSystem other = (UpmsSystem) that; return (this.getSystemId() == null ? other.getSystemId() == null : this.getSystemId().equals(other.getSystemId())) && (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon())) && (this.getBanner() == null ? other.getBanner() == null : this.getBanner().equals(other.getBanner())) && (this.getTheme() == null ? other.getTheme() == null : this.getTheme().equals(other.getTheme())) && (this.getBasepath() == null ? other.getBasepath() == null : this.getBasepath().equals(other.getBasepath())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())) && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getSystemId() == null) ? 0 : getSystemId().hashCode()); result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode()); result = prime * result + ((getBanner() == null) ? 0 : getBanner().hashCode()); result = prime * result + ((getTheme() == null) ? 0 : getTheme().hashCode()); result = prime * result + ((getBasepath() == null) ? 0 : getBasepath().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsSystemExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsSystemExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andSystemIdIsNull() { addCriterion("system_id is null"); return (Criteria) this; } public Criteria andSystemIdIsNotNull() { addCriterion("system_id is not null"); return (Criteria) this; } public Criteria andSystemIdEqualTo(Integer value) { addCriterion("system_id =", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotEqualTo(Integer value) { addCriterion("system_id <>", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThan(Integer value) { addCriterion("system_id >", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdGreaterThanOrEqualTo(Integer value) { addCriterion("system_id >=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThan(Integer value) { addCriterion("system_id <", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdLessThanOrEqualTo(Integer value) { addCriterion("system_id <=", value, "systemId"); return (Criteria) this; } public Criteria andSystemIdIn(List<Integer> values) { addCriterion("system_id in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotIn(List<Integer> values) { addCriterion("system_id not in", values, "systemId"); return (Criteria) this; } public Criteria andSystemIdBetween(Integer value1, Integer value2) { addCriterion("system_id between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andSystemIdNotBetween(Integer value1, Integer value2) { addCriterion("system_id not between", value1, value2, "systemId"); return (Criteria) this; } public Criteria andIconIsNull() { addCriterion("icon is null"); return (Criteria) this; } public Criteria andIconIsNotNull() { addCriterion("icon is not null"); return (Criteria) this; } public Criteria andIconEqualTo(String value) { addCriterion("icon =", value, "icon"); return (Criteria) this; } public Criteria andIconNotEqualTo(String value) { addCriterion("icon <>", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThan(String value) { addCriterion("icon >", value, "icon"); return (Criteria) this; } public Criteria andIconGreaterThanOrEqualTo(String value) { addCriterion("icon >=", value, "icon"); return (Criteria) this; } public Criteria andIconLessThan(String value) { addCriterion("icon <", value, "icon"); return (Criteria) this; } public Criteria andIconLessThanOrEqualTo(String value) { addCriterion("icon <=", value, "icon"); return (Criteria) this; } public Criteria andIconLike(String value) { addCriterion("icon like", value, "icon"); return (Criteria) this; } public Criteria andIconNotLike(String value) { addCriterion("icon not like", value, "icon"); return (Criteria) this; } public Criteria andIconIn(List<String> values) { addCriterion("icon in", values, "icon"); return (Criteria) this; } public Criteria andIconNotIn(List<String> values) { addCriterion("icon not in", values, "icon"); return (Criteria) this; } public Criteria andIconBetween(String value1, String value2) { addCriterion("icon between", value1, value2, "icon"); return (Criteria) this; } public Criteria andIconNotBetween(String value1, String value2) { addCriterion("icon not between", value1, value2, "icon"); return (Criteria) this; } public Criteria andBannerIsNull() { addCriterion("banner is null"); return (Criteria) this; } public Criteria andBannerIsNotNull() { addCriterion("banner is not null"); return (Criteria) this; } public Criteria andBannerEqualTo(String value) { addCriterion("banner =", value, "banner"); return (Criteria) this; } public Criteria andBannerNotEqualTo(String value) { addCriterion("banner <>", value, "banner"); return (Criteria) this; } public Criteria andBannerGreaterThan(String value) { addCriterion("banner >", value, "banner"); return (Criteria) this; } public Criteria andBannerGreaterThanOrEqualTo(String value) { addCriterion("banner >=", value, "banner"); return (Criteria) this; } public Criteria andBannerLessThan(String value) { addCriterion("banner <", value, "banner"); return (Criteria) this; } public Criteria andBannerLessThanOrEqualTo(String value) { addCriterion("banner <=", value, "banner"); return (Criteria) this; } public Criteria andBannerLike(String value) { addCriterion("banner like", value, "banner"); return (Criteria) this; } public Criteria andBannerNotLike(String value) { addCriterion("banner not like", value, "banner"); return (Criteria) this; } public Criteria andBannerIn(List<String> values) { addCriterion("banner in", values, "banner"); return (Criteria) this; } public Criteria andBannerNotIn(List<String> values) { addCriterion("banner not in", values, "banner"); return (Criteria) this; } public Criteria andBannerBetween(String value1, String value2) { addCriterion("banner between", value1, value2, "banner"); return (Criteria) this; } public Criteria andBannerNotBetween(String value1, String value2) { addCriterion("banner not between", value1, value2, "banner"); return (Criteria) this; } public Criteria andThemeIsNull() { addCriterion("theme is null"); return (Criteria) this; } public Criteria andThemeIsNotNull() { addCriterion("theme is not null"); return (Criteria) this; } public Criteria andThemeEqualTo(String value) { addCriterion("theme =", value, "theme"); return (Criteria) this; } public Criteria andThemeNotEqualTo(String value) { addCriterion("theme <>", value, "theme"); return (Criteria) this; } public Criteria andThemeGreaterThan(String value) { addCriterion("theme >", value, "theme"); return (Criteria) this; } public Criteria andThemeGreaterThanOrEqualTo(String value) { addCriterion("theme >=", value, "theme"); return (Criteria) this; } public Criteria andThemeLessThan(String value) { addCriterion("theme <", value, "theme"); return (Criteria) this; } public Criteria andThemeLessThanOrEqualTo(String value) { addCriterion("theme <=", value, "theme"); return (Criteria) this; } public Criteria andThemeLike(String value) { addCriterion("theme like", value, "theme"); return (Criteria) this; } public Criteria andThemeNotLike(String value) { addCriterion("theme not like", value, "theme"); return (Criteria) this; } public Criteria andThemeIn(List<String> values) { addCriterion("theme in", values, "theme"); return (Criteria) this; } public Criteria andThemeNotIn(List<String> values) { addCriterion("theme not in", values, "theme"); return (Criteria) this; } public Criteria andThemeBetween(String value1, String value2) { addCriterion("theme between", value1, value2, "theme"); return (Criteria) this; } public Criteria andThemeNotBetween(String value1, String value2) { addCriterion("theme not between", value1, value2, "theme"); return (Criteria) this; } public Criteria andBasepathIsNull() { addCriterion("basepath is null"); return (Criteria) this; } public Criteria andBasepathIsNotNull() { addCriterion("basepath is not null"); return (Criteria) this; } public Criteria andBasepathEqualTo(String value) { addCriterion("basepath =", value, "basepath"); return (Criteria) this; } public Criteria andBasepathNotEqualTo(String value) { addCriterion("basepath <>", value, "basepath"); return (Criteria) this; } public Criteria andBasepathGreaterThan(String value) { addCriterion("basepath >", value, "basepath"); return (Criteria) this; } public Criteria andBasepathGreaterThanOrEqualTo(String value) { addCriterion("basepath >=", value, "basepath"); return (Criteria) this; } public Criteria andBasepathLessThan(String value) { addCriterion("basepath <", value, "basepath"); return (Criteria) this; } public Criteria andBasepathLessThanOrEqualTo(String value) { addCriterion("basepath <=", value, "basepath"); return (Criteria) this; } public Criteria andBasepathLike(String value) { addCriterion("basepath like", value, "basepath"); return (Criteria) this; } public Criteria andBasepathNotLike(String value) { addCriterion("basepath not like", value, "basepath"); return (Criteria) this; } public Criteria andBasepathIn(List<String> values) { addCriterion("basepath in", values, "basepath"); return (Criteria) this; } public Criteria andBasepathNotIn(List<String> values) { addCriterion("basepath not in", values, "basepath"); return (Criteria) this; } public Criteria andBasepathBetween(String value1, String value2) { addCriterion("basepath between", value1, value2, "basepath"); return (Criteria) this; } public Criteria andBasepathNotBetween(String value1, String value2) { addCriterion("basepath not between", value1, value2, "basepath"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andTitleIsNull() { addCriterion("title is null"); return (Criteria) this; } public Criteria andTitleIsNotNull() { addCriterion("title is not null"); return (Criteria) this; } public Criteria andTitleEqualTo(String value) { addCriterion("title =", value, "title"); return (Criteria) this; } public Criteria andTitleNotEqualTo(String value) { addCriterion("title <>", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThan(String value) { addCriterion("title >", value, "title"); return (Criteria) this; } public Criteria andTitleGreaterThanOrEqualTo(String value) { addCriterion("title >=", value, "title"); return (Criteria) this; } public Criteria andTitleLessThan(String value) { addCriterion("title <", value, "title"); return (Criteria) this; } public Criteria andTitleLessThanOrEqualTo(String value) { addCriterion("title <=", value, "title"); return (Criteria) this; } public Criteria andTitleLike(String value) { addCriterion("title like", value, "title"); return (Criteria) this; } public Criteria andTitleNotLike(String value) { addCriterion("title not like", value, "title"); return (Criteria) this; } public Criteria andTitleIn(List<String> values) { addCriterion("title in", values, "title"); return (Criteria) this; } public Criteria andTitleNotIn(List<String> values) { addCriterion("title not in", values, "title"); return (Criteria) this; } public Criteria andTitleBetween(String value1, String value2) { addCriterion("title between", value1, value2, "title"); return (Criteria) this; } public Criteria andTitleNotBetween(String value1, String value2) { addCriterion("title not between", value1, value2, "title"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andOrdersIsNull() { addCriterion("orders is null"); return (Criteria) this; } public Criteria andOrdersIsNotNull() { addCriterion("orders is not null"); return (Criteria) this; } public Criteria andOrdersEqualTo(Long value) { addCriterion("orders =", value, "orders"); return (Criteria) this; } public Criteria andOrdersNotEqualTo(Long value) { addCriterion("orders <>", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThan(Long value) { addCriterion("orders >", value, "orders"); return (Criteria) this; } public Criteria andOrdersGreaterThanOrEqualTo(Long value) { addCriterion("orders >=", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThan(Long value) { addCriterion("orders <", value, "orders"); return (Criteria) this; } public Criteria andOrdersLessThanOrEqualTo(Long value) { addCriterion("orders <=", value, "orders"); return (Criteria) this; } public Criteria andOrdersIn(List<Long> values) { addCriterion("orders in", values, "orders"); return (Criteria) this; } public Criteria andOrdersNotIn(List<Long> values) { addCriterion("orders not in", values, "orders"); return (Criteria) this; } public Criteria andOrdersBetween(Long value1, Long value2) { addCriterion("orders between", value1, value2, "orders"); return (Criteria) this; } public Criteria andOrdersNotBetween(Long value1, Long value2) { addCriterion("orders not between", value1, value2, "orders"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsUser implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userId; /** * 帐号 * * @mbg.generated */ private String username; /** * 密码MD5(密码+盐) * * @mbg.generated */ private String password; /** * 盐 * * @mbg.generated */ private String salt; /** * 姓名 * * @mbg.generated */ private String realname; /** * 头像 * * @mbg.generated */ private String avatar; /** * 电话 * * @mbg.generated */ private String phone; /** * 邮箱 * * @mbg.generated */ private String email; /** * 性别 * * @mbg.generated */ private Byte sex; /** * 状态(0:正常,1:锁定) * * @mbg.generated */ private Byte locked; /** * 创建时间 * * @mbg.generated */ private Long ctime; private static final long serialVersionUID = 1L; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Byte getSex() { return sex; } public void setSex(Byte sex) { this.sex = sex; } public Byte getLocked() { return locked; } public void setLocked(Byte locked) { this.locked = locked; } public Long getCtime() { return ctime; } public void setCtime(Long ctime) { this.ctime = ctime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userId=").append(userId); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", salt=").append(salt); sb.append(", realname=").append(realname); sb.append(", avatar=").append(avatar); sb.append(", phone=").append(phone); sb.append(", email=").append(email); sb.append(", sex=").append(sex); sb.append(", locked=").append(locked); sb.append(", ctime=").append(ctime); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsUser other = (UpmsUser) that; return (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getSalt() == null ? other.getSalt() == null : this.getSalt().equals(other.getSalt())) && (this.getRealname() == null ? other.getRealname() == null : this.getRealname().equals(other.getRealname())) && (this.getAvatar() == null ? other.getAvatar() == null : this.getAvatar().equals(other.getAvatar())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail())) && (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex())) && (this.getLocked() == null ? other.getLocked() == null : this.getLocked().equals(other.getLocked())) && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getSalt() == null) ? 0 : getSalt().hashCode()); result = prime * result + ((getRealname() == null) ? 0 : getRealname().hashCode()); result = prime * result + ((getAvatar() == null) ? 0 : getAvatar().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode()); result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode()); result = prime * result + ((getLocked() == null) ? 0 : getLocked().hashCode()); result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsUserExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsUserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andSaltIsNull() { addCriterion("salt is null"); return (Criteria) this; } public Criteria andSaltIsNotNull() { addCriterion("salt is not null"); return (Criteria) this; } public Criteria andSaltEqualTo(String value) { addCriterion("salt =", value, "salt"); return (Criteria) this; } public Criteria andSaltNotEqualTo(String value) { addCriterion("salt <>", value, "salt"); return (Criteria) this; } public Criteria andSaltGreaterThan(String value) { addCriterion("salt >", value, "salt"); return (Criteria) this; } public Criteria andSaltGreaterThanOrEqualTo(String value) { addCriterion("salt >=", value, "salt"); return (Criteria) this; } public Criteria andSaltLessThan(String value) { addCriterion("salt <", value, "salt"); return (Criteria) this; } public Criteria andSaltLessThanOrEqualTo(String value) { addCriterion("salt <=", value, "salt"); return (Criteria) this; } public Criteria andSaltLike(String value) { addCriterion("salt like", value, "salt"); return (Criteria) this; } public Criteria andSaltNotLike(String value) { addCriterion("salt not like", value, "salt"); return (Criteria) this; } public Criteria andSaltIn(List<String> values) { addCriterion("salt in", values, "salt"); return (Criteria) this; } public Criteria andSaltNotIn(List<String> values) { addCriterion("salt not in", values, "salt"); return (Criteria) this; } public Criteria andSaltBetween(String value1, String value2) { addCriterion("salt between", value1, value2, "salt"); return (Criteria) this; } public Criteria andSaltNotBetween(String value1, String value2) { addCriterion("salt not between", value1, value2, "salt"); return (Criteria) this; } public Criteria andRealnameIsNull() { addCriterion("realname is null"); return (Criteria) this; } public Criteria andRealnameIsNotNull() { addCriterion("realname is not null"); return (Criteria) this; } public Criteria andRealnameEqualTo(String value) { addCriterion("realname =", value, "realname"); return (Criteria) this; } public Criteria andRealnameNotEqualTo(String value) { addCriterion("realname <>", value, "realname"); return (Criteria) this; } public Criteria andRealnameGreaterThan(String value) { addCriterion("realname >", value, "realname"); return (Criteria) this; } public Criteria andRealnameGreaterThanOrEqualTo(String value) { addCriterion("realname >=", value, "realname"); return (Criteria) this; } public Criteria andRealnameLessThan(String value) { addCriterion("realname <", value, "realname"); return (Criteria) this; } public Criteria andRealnameLessThanOrEqualTo(String value) { addCriterion("realname <=", value, "realname"); return (Criteria) this; } public Criteria andRealnameLike(String value) { addCriterion("realname like", value, "realname"); return (Criteria) this; } public Criteria andRealnameNotLike(String value) { addCriterion("realname not like", value, "realname"); return (Criteria) this; } public Criteria andRealnameIn(List<String> values) { addCriterion("realname in", values, "realname"); return (Criteria) this; } public Criteria andRealnameNotIn(List<String> values) { addCriterion("realname not in", values, "realname"); return (Criteria) this; } public Criteria andRealnameBetween(String value1, String value2) { addCriterion("realname between", value1, value2, "realname"); return (Criteria) this; } public Criteria andRealnameNotBetween(String value1, String value2) { addCriterion("realname not between", value1, value2, "realname"); return (Criteria) this; } public Criteria andAvatarIsNull() { addCriterion("avatar is null"); return (Criteria) this; } public Criteria andAvatarIsNotNull() { addCriterion("avatar is not null"); return (Criteria) this; } public Criteria andAvatarEqualTo(String value) { addCriterion("avatar =", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotEqualTo(String value) { addCriterion("avatar <>", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThan(String value) { addCriterion("avatar >", value, "avatar"); return (Criteria) this; } public Criteria andAvatarGreaterThanOrEqualTo(String value) { addCriterion("avatar >=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThan(String value) { addCriterion("avatar <", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLessThanOrEqualTo(String value) { addCriterion("avatar <=", value, "avatar"); return (Criteria) this; } public Criteria andAvatarLike(String value) { addCriterion("avatar like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarNotLike(String value) { addCriterion("avatar not like", value, "avatar"); return (Criteria) this; } public Criteria andAvatarIn(List<String> values) { addCriterion("avatar in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarNotIn(List<String> values) { addCriterion("avatar not in", values, "avatar"); return (Criteria) this; } public Criteria andAvatarBetween(String value1, String value2) { addCriterion("avatar between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andAvatarNotBetween(String value1, String value2) { addCriterion("avatar not between", value1, value2, "avatar"); return (Criteria) this; } public Criteria andPhoneIsNull() { addCriterion("phone is null"); return (Criteria) this; } public Criteria andPhoneIsNotNull() { addCriterion("phone is not null"); return (Criteria) this; } public Criteria andPhoneEqualTo(String value) { addCriterion("phone =", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotEqualTo(String value) { addCriterion("phone <>", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThan(String value) { addCriterion("phone >", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThanOrEqualTo(String value) { addCriterion("phone >=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThan(String value) { addCriterion("phone <", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThanOrEqualTo(String value) { addCriterion("phone <=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLike(String value) { addCriterion("phone like", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotLike(String value) { addCriterion("phone not like", value, "phone"); return (Criteria) this; } public Criteria andPhoneIn(List<String> values) { addCriterion("phone in", values, "phone"); return (Criteria) this; } public Criteria andPhoneNotIn(List<String> values) { addCriterion("phone not in", values, "phone"); return (Criteria) this; } public Criteria andPhoneBetween(String value1, String value2) { addCriterion("phone between", value1, value2, "phone"); return (Criteria) this; } public Criteria andPhoneNotBetween(String value1, String value2) { addCriterion("phone not between", value1, value2, "phone"); return (Criteria) this; } public Criteria andEmailIsNull() { addCriterion("email is null"); return (Criteria) this; } public Criteria andEmailIsNotNull() { addCriterion("email is not null"); return (Criteria) this; } public Criteria andEmailEqualTo(String value) { addCriterion("email =", value, "email"); return (Criteria) this; } public Criteria andEmailNotEqualTo(String value) { addCriterion("email <>", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThan(String value) { addCriterion("email >", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThanOrEqualTo(String value) { addCriterion("email >=", value, "email"); return (Criteria) this; } public Criteria andEmailLessThan(String value) { addCriterion("email <", value, "email"); return (Criteria) this; } public Criteria andEmailLessThanOrEqualTo(String value) { addCriterion("email <=", value, "email"); return (Criteria) this; } public Criteria andEmailLike(String value) { addCriterion("email like", value, "email"); return (Criteria) this; } public Criteria andEmailNotLike(String value) { addCriterion("email not like", value, "email"); return (Criteria) this; } public Criteria andEmailIn(List<String> values) { addCriterion("email in", values, "email"); return (Criteria) this; } public Criteria andEmailNotIn(List<String> values) { addCriterion("email not in", values, "email"); return (Criteria) this; } public Criteria andEmailBetween(String value1, String value2) { addCriterion("email between", value1, value2, "email"); return (Criteria) this; } public Criteria andEmailNotBetween(String value1, String value2) { addCriterion("email not between", value1, value2, "email"); return (Criteria) this; } public Criteria andSexIsNull() { addCriterion("sex is null"); return (Criteria) this; } public Criteria andSexIsNotNull() { addCriterion("sex is not null"); return (Criteria) this; } public Criteria andSexEqualTo(Byte value) { addCriterion("sex =", value, "sex"); return (Criteria) this; } public Criteria andSexNotEqualTo(Byte value) { addCriterion("sex <>", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThan(Byte value) { addCriterion("sex >", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThanOrEqualTo(Byte value) { addCriterion("sex >=", value, "sex"); return (Criteria) this; } public Criteria andSexLessThan(Byte value) { addCriterion("sex <", value, "sex"); return (Criteria) this; } public Criteria andSexLessThanOrEqualTo(Byte value) { addCriterion("sex <=", value, "sex"); return (Criteria) this; } public Criteria andSexIn(List<Byte> values) { addCriterion("sex in", values, "sex"); return (Criteria) this; } public Criteria andSexNotIn(List<Byte> values) { addCriterion("sex not in", values, "sex"); return (Criteria) this; } public Criteria andSexBetween(Byte value1, Byte value2) { addCriterion("sex between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSexNotBetween(Byte value1, Byte value2) { addCriterion("sex not between", value1, value2, "sex"); return (Criteria) this; } public Criteria andLockedIsNull() { addCriterion("locked is null"); return (Criteria) this; } public Criteria andLockedIsNotNull() { addCriterion("locked is not null"); return (Criteria) this; } public Criteria andLockedEqualTo(Byte value) { addCriterion("locked =", value, "locked"); return (Criteria) this; } public Criteria andLockedNotEqualTo(Byte value) { addCriterion("locked <>", value, "locked"); return (Criteria) this; } public Criteria andLockedGreaterThan(Byte value) { addCriterion("locked >", value, "locked"); return (Criteria) this; } public Criteria andLockedGreaterThanOrEqualTo(Byte value) { addCriterion("locked >=", value, "locked"); return (Criteria) this; } public Criteria andLockedLessThan(Byte value) { addCriterion("locked <", value, "locked"); return (Criteria) this; } public Criteria andLockedLessThanOrEqualTo(Byte value) { addCriterion("locked <=", value, "locked"); return (Criteria) this; } public Criteria andLockedIn(List<Byte> values) { addCriterion("locked in", values, "locked"); return (Criteria) this; } public Criteria andLockedNotIn(List<Byte> values) { addCriterion("locked not in", values, "locked"); return (Criteria) this; } public Criteria andLockedBetween(Byte value1, Byte value2) { addCriterion("locked between", value1, value2, "locked"); return (Criteria) this; } public Criteria andLockedNotBetween(Byte value1, Byte value2) { addCriterion("locked not between", value1, value2, "locked"); return (Criteria) this; } public Criteria andCtimeIsNull() { addCriterion("ctime is null"); return (Criteria) this; } public Criteria andCtimeIsNotNull() { addCriterion("ctime is not null"); return (Criteria) this; } public Criteria andCtimeEqualTo(Long value) { addCriterion("ctime =", value, "ctime"); return (Criteria) this; } public Criteria andCtimeNotEqualTo(Long value) { addCriterion("ctime <>", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThan(Long value) { addCriterion("ctime >", value, "ctime"); return (Criteria) this; } public Criteria andCtimeGreaterThanOrEqualTo(Long value) { addCriterion("ctime >=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThan(Long value) { addCriterion("ctime <", value, "ctime"); return (Criteria) this; } public Criteria andCtimeLessThanOrEqualTo(Long value) { addCriterion("ctime <=", value, "ctime"); return (Criteria) this; } public Criteria andCtimeIn(List<Long> values) { addCriterion("ctime in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeNotIn(List<Long> values) { addCriterion("ctime not in", values, "ctime"); return (Criteria) this; } public Criteria andCtimeBetween(Long value1, Long value2) { addCriterion("ctime between", value1, value2, "ctime"); return (Criteria) this; } public Criteria andCtimeNotBetween(Long value1, Long value2) { addCriterion("ctime not between", value1, value2, "ctime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsUserOrganization implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userOrganizationId; /** * 用户编号 * * @mbg.generated */ private Integer userId; /** * 组织编号 * * @mbg.generated */ private Integer organizationId; private static final long serialVersionUID = 1L; public Integer getUserOrganizationId() { return userOrganizationId; } public void setUserOrganizationId(Integer userOrganizationId) { this.userOrganizationId = userOrganizationId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getOrganizationId() { return organizationId; } public void setOrganizationId(Integer organizationId) { this.organizationId = organizationId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userOrganizationId=").append(userOrganizationId); sb.append(", userId=").append(userId); sb.append(", organizationId=").append(organizationId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsUserOrganization other = (UpmsUserOrganization) that; return (this.getUserOrganizationId() == null ? other.getUserOrganizationId() == null : this.getUserOrganizationId().equals(other.getUserOrganizationId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getOrganizationId() == null ? other.getOrganizationId() == null : this.getOrganizationId().equals(other.getOrganizationId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserOrganizationId() == null) ? 0 : getUserOrganizationId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getOrganizationId() == null) ? 0 : getOrganizationId().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsUserOrganizationExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsUserOrganizationExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserOrganizationIdIsNull() { addCriterion("user_organization_id is null"); return (Criteria) this; } public Criteria andUserOrganizationIdIsNotNull() { addCriterion("user_organization_id is not null"); return (Criteria) this; } public Criteria andUserOrganizationIdEqualTo(Integer value) { addCriterion("user_organization_id =", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdNotEqualTo(Integer value) { addCriterion("user_organization_id <>", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdGreaterThan(Integer value) { addCriterion("user_organization_id >", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_organization_id >=", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdLessThan(Integer value) { addCriterion("user_organization_id <", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdLessThanOrEqualTo(Integer value) { addCriterion("user_organization_id <=", value, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdIn(List<Integer> values) { addCriterion("user_organization_id in", values, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdNotIn(List<Integer> values) { addCriterion("user_organization_id not in", values, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdBetween(Integer value1, Integer value2) { addCriterion("user_organization_id between", value1, value2, "userOrganizationId"); return (Criteria) this; } public Criteria andUserOrganizationIdNotBetween(Integer value1, Integer value2) { addCriterion("user_organization_id not between", value1, value2, "userOrganizationId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andOrganizationIdIsNull() { addCriterion("organization_id is null"); return (Criteria) this; } public Criteria andOrganizationIdIsNotNull() { addCriterion("organization_id is not null"); return (Criteria) this; } public Criteria andOrganizationIdEqualTo(Integer value) { addCriterion("organization_id =", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotEqualTo(Integer value) { addCriterion("organization_id <>", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdGreaterThan(Integer value) { addCriterion("organization_id >", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdGreaterThanOrEqualTo(Integer value) { addCriterion("organization_id >=", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdLessThan(Integer value) { addCriterion("organization_id <", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdLessThanOrEqualTo(Integer value) { addCriterion("organization_id <=", value, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdIn(List<Integer> values) { addCriterion("organization_id in", values, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotIn(List<Integer> values) { addCriterion("organization_id not in", values, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdBetween(Integer value1, Integer value2) { addCriterion("organization_id between", value1, value2, "organizationId"); return (Criteria) this; } public Criteria andOrganizationIdNotBetween(Integer value1, Integer value2) { addCriterion("organization_id not between", value1, value2, "organizationId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsUserPermission implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userPermissionId; /** * 用户编号 * * @mbg.generated */ private Integer userId; /** * 权限编号 * * @mbg.generated */ private Integer permissionId; /** * 权限类型(-1:减权限,1:增权限) * * @mbg.generated */ private Byte type; private static final long serialVersionUID = 1L; public Integer getUserPermissionId() { return userPermissionId; } public void setUserPermissionId(Integer userPermissionId) { this.userPermissionId = userPermissionId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getPermissionId() { return permissionId; } public void setPermissionId(Integer permissionId) { this.permissionId = permissionId; } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userPermissionId=").append(userPermissionId); sb.append(", userId=").append(userId); sb.append(", permissionId=").append(permissionId); sb.append(", type=").append(type); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsUserPermission other = (UpmsUserPermission) that; return (this.getUserPermissionId() == null ? other.getUserPermissionId() == null : this.getUserPermissionId().equals(other.getUserPermissionId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getPermissionId() == null ? other.getPermissionId() == null : this.getPermissionId().equals(other.getPermissionId())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserPermissionId() == null) ? 0 : getUserPermissionId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getPermissionId() == null) ? 0 : getPermissionId().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsUserPermissionExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsUserPermissionExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserPermissionIdIsNull() { addCriterion("user_permission_id is null"); return (Criteria) this; } public Criteria andUserPermissionIdIsNotNull() { addCriterion("user_permission_id is not null"); return (Criteria) this; } public Criteria andUserPermissionIdEqualTo(Integer value) { addCriterion("user_permission_id =", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdNotEqualTo(Integer value) { addCriterion("user_permission_id <>", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdGreaterThan(Integer value) { addCriterion("user_permission_id >", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_permission_id >=", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdLessThan(Integer value) { addCriterion("user_permission_id <", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdLessThanOrEqualTo(Integer value) { addCriterion("user_permission_id <=", value, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdIn(List<Integer> values) { addCriterion("user_permission_id in", values, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdNotIn(List<Integer> values) { addCriterion("user_permission_id not in", values, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdBetween(Integer value1, Integer value2) { addCriterion("user_permission_id between", value1, value2, "userPermissionId"); return (Criteria) this; } public Criteria andUserPermissionIdNotBetween(Integer value1, Integer value2) { addCriterion("user_permission_id not between", value1, value2, "userPermissionId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andPermissionIdIsNull() { addCriterion("permission_id is null"); return (Criteria) this; } public Criteria andPermissionIdIsNotNull() { addCriterion("permission_id is not null"); return (Criteria) this; } public Criteria andPermissionIdEqualTo(Integer value) { addCriterion("permission_id =", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotEqualTo(Integer value) { addCriterion("permission_id <>", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThan(Integer value) { addCriterion("permission_id >", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdGreaterThanOrEqualTo(Integer value) { addCriterion("permission_id >=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThan(Integer value) { addCriterion("permission_id <", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdLessThanOrEqualTo(Integer value) { addCriterion("permission_id <=", value, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdIn(List<Integer> values) { addCriterion("permission_id in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotIn(List<Integer> values) { addCriterion("permission_id not in", values, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdBetween(Integer value1, Integer value2) { addCriterion("permission_id between", value1, value2, "permissionId"); return (Criteria) this; } public Criteria andPermissionIdNotBetween(Integer value1, Integer value2) { addCriterion("permission_id not between", value1, value2, "permissionId"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.zheng.upms.dao.model; import java.io.Serializable; public class UpmsUserRole implements Serializable { /** * 编号 * * @mbg.generated */ private Integer userRoleId; /** * 用户编号 * * @mbg.generated */ private Integer userId; /** * 角色编号 * * @mbg.generated */ private Integer roleId; private static final long serialVersionUID = 1L; public Integer getUserRoleId() { return userRoleId; } public void setUserRoleId(Integer userRoleId) { this.userRoleId = userRoleId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", userRoleId=").append(userRoleId); sb.append(", userId=").append(userId); sb.append(", roleId=").append(roleId); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UpmsUserRole other = (UpmsUserRole) that; return (this.getUserRoleId() == null ? other.getUserRoleId() == null : this.getUserRoleId().equals(other.getUserRoleId())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserRoleId() == null) ? 0 : getUserRoleId().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode()); return result; } }
package com.zheng.upms.dao.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class UpmsUserRoleExample implements Serializable { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private static final long serialVersionUID = 1L; public UpmsUserRoleExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria implements Serializable { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andUserRoleIdIsNull() { addCriterion("user_role_id is null"); return (Criteria) this; } public Criteria andUserRoleIdIsNotNull() { addCriterion("user_role_id is not null"); return (Criteria) this; } public Criteria andUserRoleIdEqualTo(Integer value) { addCriterion("user_role_id =", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdNotEqualTo(Integer value) { addCriterion("user_role_id <>", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdGreaterThan(Integer value) { addCriterion("user_role_id >", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_role_id >=", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdLessThan(Integer value) { addCriterion("user_role_id <", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdLessThanOrEqualTo(Integer value) { addCriterion("user_role_id <=", value, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdIn(List<Integer> values) { addCriterion("user_role_id in", values, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdNotIn(List<Integer> values) { addCriterion("user_role_id not in", values, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdBetween(Integer value1, Integer value2) { addCriterion("user_role_id between", value1, value2, "userRoleId"); return (Criteria) this; } public Criteria andUserRoleIdNotBetween(Integer value1, Integer value2) { addCriterion("user_role_id not between", value1, value2, "userRoleId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andRoleIdIsNull() { addCriterion("role_id is null"); return (Criteria) this; } public Criteria andRoleIdIsNotNull() { addCriterion("role_id is not null"); return (Criteria) this; } public Criteria andRoleIdEqualTo(Integer value) { addCriterion("role_id =", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotEqualTo(Integer value) { addCriterion("role_id <>", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThan(Integer value) { addCriterion("role_id >", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThanOrEqualTo(Integer value) { addCriterion("role_id >=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThan(Integer value) { addCriterion("role_id <", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThanOrEqualTo(Integer value) { addCriterion("role_id <=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdIn(List<Integer> values) { addCriterion("role_id in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotIn(List<Integer> values) { addCriterion("role_id not in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdBetween(Integer value1, Integer value2) { addCriterion("role_id between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Integer value1, Integer value2) { addCriterion("role_id not between", value1, value2, "roleId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria implements Serializable { protected Criteria() { super(); } } public static class Criterion implements Serializable { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.mall4j.cloud.api.dto; import com.mall4j.cloud.common.util.PrincipalUtil; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import java.util.Arrays; /** * @author FrozenWatermelon * @date 2020/11/16 */ public class EsPageDTO{ public static final String ASC = "ASC"; public static final String DESC = "DESC"; /** * 最大分页大小,如果分页大小大于500,则用500作为分页的大小。防止有人直接传入一个较大的数,导致服务器内存溢出宕机 */ public static final Integer MAX_PAGE_SIZE = 500; /** * 当前页 */ @NotNull(message = "pageNum 不能为空") @ApiModelProperty(value = "当前页", required = true) private Integer pageNum; @NotNull(message = "pageSize 不能为空") @ApiModelProperty(value = "每页大小", required = true) private Integer pageSize; @ApiModelProperty(value = "排序字段数组,用逗号分割") private String[] columns; @ApiModelProperty(value = "排序字段方式,用逗号分割,ASC正序,DESC倒序") private String[] orders; public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { if (pageSize > MAX_PAGE_SIZE) { this.pageSize = MAX_PAGE_SIZE; return; } this.pageSize = pageSize; } public String getOrderBy() { return order(this.columns, this.orders); } public String[] getColumns() { return columns; } public void setColumns(String[] columns) { this.columns = columns; } public String[] getOrders() { return orders; } public void setOrders(String[] orders) { this.orders = orders; } public static String order(String[] columns, String[] orders) { if (columns == null || columns.length == 0) { return ""; } StringBuilder stringBuilder = new StringBuilder(); for (int x = 0; x < columns.length; x++) { String column = columns[x]; String order; if (orders != null && orders.length > x) { order = orders[x].toUpperCase(); if (!(order.equals(ASC) || order.equals(DESC))) { throw new IllegalArgumentException("非法的排序策略:" + column); } }else { order = ASC; } // 判断列名称的合法性,防止SQL注入。只能是【字母,数字,下划线】 if (PrincipalUtil.isField(column)) { throw new IllegalArgumentException("非法的排序字段名称:" + column); } // 驼峰转换为下划线 column = humpConversionUnderscore(column); if (x != 0) { stringBuilder.append(", "); } stringBuilder.append("`").append(column).append("` ").append(order); } return stringBuilder.toString(); } public static String humpConversionUnderscore(String value) { StringBuilder stringBuilder = new StringBuilder(); char[] chars = value.toCharArray(); for (char character : chars) { if (Character.isUpperCase(character)) { stringBuilder.append("_"); character = Character.toLowerCase(character); } stringBuilder.append(character); } return stringBuilder.toString(); } @Override public String toString() { return "EsPageDTO{" + "pageNum=" + pageNum + ", pageSize=" + pageSize + ", columns=" + Arrays.toString(columns) + ", orders=" + Arrays.toString(orders) + '}'; } }
package com.mall4j.cloud.common.database.dto; import com.github.pagehelper.IPage; import com.mall4j.cloud.common.util.PrincipalUtil; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import java.util.Arrays; /** * @author FrozenWatermelon * @date 2020/9/8 */ public class PageDTO implements IPage { public static final String ASC = "ASC"; public static final String DESC = "DESC"; /** * 最大分页大小,如果分页大小大于500,则用500作为分页的大小。防止有人直接传入一个较大的数,导致服务器内存溢出宕机 */ public static final Integer MAX_PAGE_SIZE = 500; /** * 当前页 */ @NotNull(message = "pageNum 不能为空") @ApiModelProperty(value = "当前页", required = true) private Integer pageNum; @NotNull(message = "pageSize 不能为空") @ApiModelProperty(value = "每页大小", required = true) private Integer pageSize; @ApiModelProperty(value = "排序字段数组,用逗号分割") private String[] columns; @ApiModelProperty(value = "排序字段方式,用逗号分割,ASC正序,DESC倒序") private String[] orders; @Override public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } @Override public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { if (pageSize > MAX_PAGE_SIZE) { this.pageSize = MAX_PAGE_SIZE; return; } this.pageSize = pageSize; } @Override public String getOrderBy() { return order(this.columns, this.orders); } public String[] getColumns() { return columns; } public void setColumns(String[] columns) { this.columns = columns; } public String[] getOrders() { return orders; } public void setOrders(String[] orders) { this.orders = orders; } public static String order(String[] columns, String[] orders) { if (columns == null || columns.length == 0) { return ""; } StringBuilder stringBuilder = new StringBuilder(); for (int x = 0; x < columns.length; x++) { String column = columns[x]; String order; if (orders != null && orders.length > x) { order = orders[x].toUpperCase(); if (!(order.equals(ASC) || order.equals(DESC))) { throw new IllegalArgumentException("非法的排序策略:" + column); } }else { order = ASC; } // 判断列名称的合法性,防止SQL注入。只能是【字母,数字,下划线】 if (PrincipalUtil.isField(column)) { throw new IllegalArgumentException("非法的排序字段名称:" + column); } // 驼峰转换为下划线 column = humpConversionUnderscore(column); if (x != 0) { stringBuilder.append(", "); } stringBuilder.append("`").append(column).append("` ").append(order); } return stringBuilder.toString(); } public static String humpConversionUnderscore(String value) { StringBuilder stringBuilder = new StringBuilder(); char[] chars = value.toCharArray(); for (char character : chars) { if (Character.isUpperCase(character)) { stringBuilder.append("_"); character = Character.toLowerCase(character); } stringBuilder.append(character); } return stringBuilder.toString(); } @Override public String toString() { return "PageDTO{" + "pageNum=" + pageNum + ", pageSize=" + pageSize + ", columns=" + Arrays.toString(columns) + ", orders=" + Arrays.toString(orders) + '}'; } }
package com.moxi.mogublog.admin.annotion.OperationLogger; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import com.moxi.mogublog.admin.global.RedisConf; import com.moxi.mogublog.admin.global.SysConf; import com.moxi.mogublog.commons.config.security.SecurityUser; import com.moxi.mogublog.commons.entity.SysLog; import com.moxi.mogublog.utils.IpUtils; import com.moxi.mogublog.utils.RedisUtil; import com.moxi.mogublog.utils.StringUtils; import com.moxi.mougblog.base.global.Constants; import com.moxi.mougblog.base.holder.AbstractRequestAwareRunnable; import java.util.Date; import java.util.concurrent.TimeUnit; /** * 异步记录日志 * * @author: 陌溪 * @create: 2020-03-05-8:59 */ public class SysLogHandle extends AbstractRequestAwareRunnable { /** * Redis工具列 */ RedisUtil redisUtil; /** * 参数列表 */ private String paramsJson; /** * 类路径 */ private String classPath; /** * 方法名 */ private String methodName; /** * 方法请求时间 */ private Date startTime; /** * 操作名称 */ private String operationName; /** * 请求IP */ private String ip; /** * 请求类型 */ private String type; /** * 请求URL */ private String requestUrl; private SecurityUser securityUser; /** * 构造函数 * * @param ip * @param type * @param requestUrl * @param securityUser * @param paramsJson * @param classPath * @param methodName * @param operationName * @param startTime * @param redisUtil */ public SysLogHandle(String ip, String type, String requestUrl, SecurityUser securityUser, String paramsJson, String classPath, String methodName, String operationName, Date startTime, RedisUtil redisUtil) { this.ip = ip; this.type = type; this.requestUrl = requestUrl; this.securityUser = securityUser; this.paramsJson = paramsJson; this.classPath = classPath; this.methodName = methodName; this.operationName = operationName; this.startTime = startTime; this.redisUtil = redisUtil; } @Override protected void onRun() { SysLog sysLog = new SysLog(); //从Redis中获取IP来源 String jsonResult = redisUtil.get(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip); if (StringUtils.isEmpty(jsonResult)) { String addresses = IpUtils.getAddresses(SysConf.IP + SysConf.EQUAL_TO + ip, SysConf.UTF_8); if (StringUtils.isNotEmpty(addresses)) { sysLog.setIpSource(addresses); redisUtil.setEx(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip, addresses, 24, TimeUnit.HOURS); } } else { sysLog.setIpSource(jsonResult); } //设置请求信息 sysLog.setIp(ip); //设置调用的类 sysLog.setClassPath(classPath); //设置调用的方法 sysLog.setMethod(methodName); //设置Request的请求方式 GET POST sysLog.setType(type); sysLog.setUrl(requestUrl); sysLog.setOperation(operationName); sysLog.setCreateTime(new Date()); sysLog.setUpdateTime(new Date()); sysLog.setUserName(securityUser.getUsername()); sysLog.setAdminUid(securityUser.getUid()); sysLog.setParams(paramsJson); Date endTime = new Date(); Long spendTime = DateUtil.between(startTime, endTime, DateUnit.MS); // 计算请求接口花费的时间,单位毫秒 sysLog.setSpendTime(spendTime); sysLog.insert(); } }
package com.moxi.mogublog.web.annotion.log; import com.moxi.mogublog.commons.entity.WebVisit; import com.moxi.mogublog.utils.IpUtils; import com.moxi.mogublog.utils.RedisUtil; import com.moxi.mogublog.utils.StringUtils; import com.moxi.mogublog.web.global.RedisConf; import com.moxi.mogublog.web.global.SysConf; import com.moxi.mougblog.base.global.Constants; import com.moxi.mougblog.base.holder.AbstractRequestAwareRunnable; import java.util.concurrent.TimeUnit; /** * 异步记录日志 * * @author: 陌溪 * @create: 2020-03-05-8:59 */ public class SysLogHandle extends AbstractRequestAwareRunnable { /** * 模块UID */ String moduleUid; /** * 其它数据 */ String otherData; /** * Redis工具类对象 */ private RedisUtil redisUtil; /** * 用户UID */ private String userUid; /** * 用户行为 */ private String behavior; /** * ip地址 */ private String ip; /** * 操作系统 */ private String os; /** * 浏览器 */ private String browser; /** * 构造函数 * * @param userUid * @param ip * @param os * @param browser * @param behavior * @param moduleUid * @param otherData * @param redisUtil */ public SysLogHandle(String userUid, String ip, String os, String browser, String behavior, String moduleUid, String otherData, RedisUtil redisUtil) { this.userUid = userUid; this.ip = ip; this.os = os; this.browser = browser; this.behavior = behavior; this.moduleUid = moduleUid; this.otherData = otherData; this.redisUtil = redisUtil; } /** * 遇见语录:Request请求结束后,异步线程拿主进程里数据会出现空指针异常【因此不能在子线程里操作Request对象】 * 这个问题不一定每一次都出现,可能100次中有4~5次出现空指针异常,也就是说当 异步线程执行比主线程快 是没问题的 * 这里为了避免这种情况,将避免在异步线程中操作Request对象 */ @Override protected void onRun() { System.out.println("============" + Thread.currentThread().getName()); WebVisit webVisit = new WebVisit(); webVisit.setIp(ip); //从Redis中获取IP来源 String jsonResult = redisUtil.get(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip); if (StringUtils.isEmpty(jsonResult)) { String addresses = IpUtils.getAddresses(SysConf.IP + SysConf.EQUAL_TO + ip, SysConf.UTF_8); if (StringUtils.isNotEmpty(addresses)) { webVisit.setIpSource(addresses); redisUtil.setEx(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip, addresses, 24, TimeUnit.HOURS); } } else { webVisit.setIpSource(jsonResult); } webVisit.setOs(os); webVisit.setBrowser(browser); webVisit.setUserUid(userUid); webVisit.setBehavior(behavior); webVisit.setModuleUid(moduleUid); webVisit.setOtherData(otherData); webVisit.insert(); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
package com.rainbowforest.orderservice.http.header; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; @Service public class HeaderGenerator { public HttpHeaders getHeadersForSuccessGetMethod() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForError() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/problem+json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForSuccessPostMethod(HttpServletRequest request, Long newResourceId) { HttpHeaders httpHeaders = new HttpHeaders(); try { httpHeaders.setLocation(new URI(request.getRequestURI() + "/" + newResourceId)); } catch (URISyntaxException e) { e.printStackTrace(); } httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
package com.rainbowforest.productcatalogservice.http.header; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; @Service public class HeaderGenerator { public HttpHeaders getHeadersForSuccessGetMethod() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForError() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/problem+json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForSuccessPostMethod(HttpServletRequest request, Long newResourceId) { HttpHeaders httpHeaders = new HttpHeaders(); try { httpHeaders.setLocation(new URI(request.getRequestURI() + "/" + newResourceId)); } catch (URISyntaxException e) { e.printStackTrace(); } httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
package com.rainbowforest.recommendationservice.http.header; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; @Service public class HeaderGenerator { public HttpHeaders getHeadersForSuccessGetMethod() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForError() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/problem+json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForSuccessPostMethod(HttpServletRequest request, Long newResourceId) { HttpHeaders httpHeaders = new HttpHeaders(); try { httpHeaders.setLocation(new URI(request.getRequestURI() + "/" + newResourceId)); } catch (URISyntaxException e) { e.printStackTrace(); } httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
package com.rainbowforest.userservice.http.header; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; @Service public class HeaderGenerator { public HttpHeaders getHeadersForSuccessGetMethod() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForError() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/problem+json; charset=UTF-8"); return httpHeaders; } public HttpHeaders getHeadersForSuccessPostMethod(HttpServletRequest request, Long newResourceId) { HttpHeaders httpHeaders = new HttpHeaders(); try { httpHeaders.setLocation(new URI(request.getRequestURI() + "/" + newResourceId)); } catch (URISyntaxException e) { e.printStackTrace(); } httpHeaders.add("Content-Type", "application/json; charset=UTF-8"); return httpHeaders; } }
package com.macro.mall.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 状态标记校验器 * Created by macro on 2018/4/26. */ public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> { private String[] values; @Override public void initialize(FlagValidator flagValidator) { this.values = flagValidator.value(); } @Override public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; if(value==null){ //当状态为空时使用默认值 return true; } for(int i=0;i<values.length;i++){ if(values[i].equals(String.valueOf(value))){ isValid = true; break; } } return isValid; } }
package com.macro.mall.demo.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 状态标记校验器 */ public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> { private String[] values; @Override public void initialize(FlagValidator flagValidator) { this.values = flagValidator.value(); } @Override public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; for(int i=0;i<values.length;i++){ if(values[i].equals(String.valueOf(value))){ isValid = true; break; } } return isValid; } }
package com.stalary.pf.message.exception; import com.stalary.pf.message.data.vo.ResponseMessage; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Stalary * @description * @date 2018/04/14 */ @ControllerAdvice @Slf4j public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseMessage handle(Exception e) { if (e instanceof MyException) { MyException myException = (MyException) e; return ResponseMessage.error(myException.getCode(), myException.getMessage()); } else { log.error("[系统异常]", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return ResponseMessage.error(500, "message 运行时异常!" + sw.toString()); } } }
package com.stalary.pf.outside.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * CacheConfig * * @author lirongqian * @since 2018/10/22 */ @Configuration @Slf4j public class CacheConfig extends CachingConfigurerSupport { /** * redis序列化配置,使用lettuce客户端 */ @Bean public <T> RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, T> template = new RedisTemplate<>(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericFastJsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Override public CacheErrorHandler errorHandler() { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("获取缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("handleCachePutError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("handleCacheEvictError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("清除缓存时异常--- 异常信息:" + e); } }; } }
package com.stalary.pf.outside.config; import com.stalary.pf.outside.data.Constant; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.nio.charset.Charset; /** * PrefixRedisSerializer * * @author lirongqian * @since 2018/10/21 */ @Component @Slf4j public class PrefixRedisSerializer implements RedisSerializer<String> { private String prefix = "pf"; private final Charset charset; public PrefixRedisSerializer() { this(Charset.forName("UTF8")); } public PrefixRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { String saveKey = new String(bytes, charset); int indexOf = saveKey.indexOf(prefix); if (indexOf > 0) { log.warn("key缺少前缀"); } else { saveKey = saveKey.substring(indexOf + prefix.length() + 1); } return saveKey; } @Override public byte[] serialize(String string) { String key = prefix + Constant.SPLIT + string; return key.getBytes(charset); } }
package com.stalary.pf.outside.exception; import com.stalary.pf.outside.data.ResponseMessage; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Stalary * @description * @date 2018/04/14 */ @ControllerAdvice @Slf4j public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseMessage handle(Exception e) { if (e instanceof MyException) { MyException myException = (MyException) e; return ResponseMessage.error(myException.getCode(), myException.getMessage()); } else { log.error("[系统异常]", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return ResponseMessage.error(500, "outside 运行时异常!" + sw.toString()); } } }
package com.stalary.pf.push.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import com.stalary.pf.push.service.MessageService; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * CacheConfig * * @author lirongqian * @since 2018/10/22 */ @Configuration @Slf4j public class CacheConfig extends CachingConfigurerSupport { /** * redis序列化配置,使用lettuce客户端 */ @Bean public <T> RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, T> template = new RedisTemplate<>(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericFastJsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Override public CacheErrorHandler errorHandler() { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("获取缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("handleCachePutError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("handleCacheEvictError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("清除缓存时异常--- 异常信息:" + e); } }; } @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); // 订阅频道 container.addMessageListener(listenerAdapter, new PatternTopic(MessageService.MESSAGE_CHANNEL)); container.addMessageListener(listenerAdapter, new PatternTopic(MessageService.CLOSE_CHANNEL)); return container; } @Bean MessageListenerAdapter listenerAdapter(MessageService receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } }
package com.stalary.pf.push.config; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.nio.charset.Charset; /** * PrefixRedisSerializer * * @author lirongqian * @since 2018/10/21 */ @Component @Slf4j public class PrefixRedisSerializer implements RedisSerializer<String> { private String prefix = "pf"; private final Charset charset; public PrefixRedisSerializer() { this(Charset.forName("UTF8")); } public PrefixRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { String saveKey = new String(bytes, charset); int indexOf = saveKey.indexOf(prefix); if (indexOf > 0) { log.warn("key缺少前缀"); } else { saveKey = saveKey.substring(indexOf + prefix.length() + 1); } return saveKey; } @Override public byte[] serialize(String string) { String key = prefix + ":" + string; return key.getBytes(charset); } }
package com.stalary.pf.recruit.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * CacheConfig * * @author lirongqian * @since 2018/10/22 */ @Configuration @Slf4j public class CacheConfig extends CachingConfigurerSupport { /** * redis序列化配置,使用lettuce客户端 */ @Bean public <T> RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, T> template = new RedisTemplate<>(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericFastJsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Override public CacheErrorHandler errorHandler() { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("获取缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("handleCachePutError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("handleCacheEvictError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("清除缓存时异常--- 异常信息:" + e); } }; } }
package com.stalary.pf.recruit.config; import com.stalary.pf.recruit.data.constant.Constant; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.nio.charset.Charset; /** * PrefixRedisSerializer * * @author lirongqian * @since 2018/10/21 */ @Component @Slf4j public class PrefixRedisSerializer implements RedisSerializer<String> { private String prefix = "pf"; private final Charset charset; public PrefixRedisSerializer() { this(Charset.forName("UTF8")); } public PrefixRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { String saveKey = new String(bytes, charset); int indexOf = saveKey.indexOf(prefix); if (indexOf > 0) { log.warn("key缺少前缀"); } else { saveKey = saveKey.substring(indexOf + prefix.length() + 1); } return saveKey; } @Override public byte[] serialize(String string) { String key = prefix + Constant.SPLIT + string; return key.getBytes(charset); } }
package com.stalary.pf.recruit.exception; import com.stalary.pf.recruit.data.vo.ResponseMessage; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Stalary * @description * @date 2018/04/14 */ @ControllerAdvice @Slf4j public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseMessage handle(Exception e) { if (e instanceof MyException) { MyException myException = (MyException) e; return ResponseMessage.error(myException.getCode(), myException.getMessage()); } else { log.error("[系统异常]", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return ResponseMessage.error(500, "recruit 运行时异常!" + sw.toString()); } } }
package com.stalary.pf.resume.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * CacheConfig * * @author lirongqian * @since 2018/10/22 */ @Configuration @Slf4j public class CacheConfig extends CachingConfigurerSupport { /** * redis序列化配置,使用lettuce客户端 */ @Bean public <T> RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, T> template = new RedisTemplate<>(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericFastJsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Override public CacheErrorHandler errorHandler() { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("获取缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("handleCachePutError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("handleCacheEvictError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("清除缓存时异常--- 异常信息:" + e); } }; } }
package com.stalary.pf.resume.config; import com.stalary.pf.resume.data.constant.Constant; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.nio.charset.Charset; /** * PrefixRedisSerializer * * @author lirongqian * @since 2018/10/21 */ @Component @Slf4j public class PrefixRedisSerializer implements RedisSerializer<String> { private String prefix = "pf"; private final Charset charset; public PrefixRedisSerializer() { this(Charset.forName("UTF8")); } public PrefixRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { String saveKey = new String(bytes, charset); int indexOf = saveKey.indexOf(prefix); if (indexOf > 0) { log.warn("key缺少前缀"); } else { saveKey = saveKey.substring(indexOf + prefix.length() + 1); } return saveKey; } @Override public byte[] serialize(String string) { String key = prefix + Constant.SPLIT + string; return key.getBytes(charset); } }
package com.stalary.pf.resume.exception; import com.stalary.pf.resume.data.vo.ResponseMessage; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Stalary * @description * @date 2018/04/14 */ @ControllerAdvice @Slf4j public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseMessage handle(Exception e) { if (e instanceof MyException) { MyException myException = (MyException) e; return ResponseMessage.error(myException.getCode(), myException.getMessage()); } else { log.error("[系统异常]", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return ResponseMessage.error(500, "resume 运行时异常!" + sw.toString()); } } }
package com.stalary.pf.user.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * CacheConfig * * @author lirongqian * @since 2018/10/22 */ @Configuration @Slf4j public class CacheConfig extends CachingConfigurerSupport { /** * redis序列化配置,使用lettuce客户端 */ @Bean public <T> RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, T> template = new RedisTemplate<>(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new GenericFastJsonRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setKeySerializer(new PrefixRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Override public CacheErrorHandler errorHandler() { return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.warn("获取缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.warn("handleCachePutError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.warn("handleCacheEvictError缓存时异常---key: " + key + " 异常信息:" + e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.warn("清除缓存时异常--- 异常信息:" + e); } }; } }
package com.stalary.pf.user.config; import com.stalary.pf.user.data.constant.Constant; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.nio.charset.Charset; /** * PrefixRedisSerializer * * @author lirongqian * @since 2018/10/21 */ @Component @Slf4j public class PrefixRedisSerializer implements RedisSerializer<String> { private String prefix = "pf"; private final Charset charset; public PrefixRedisSerializer() { this(Charset.forName("UTF8")); } public PrefixRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { String saveKey = new String(bytes, charset); int indexOf = saveKey.indexOf(prefix); if (indexOf > 0) { log.warn("key缺少前缀"); } else { saveKey = saveKey.substring(indexOf + prefix.length() + 1); } return saveKey; } @Override public byte[] serialize(String string) { String key = prefix + Constant.SPLIT + string; return key.getBytes(charset); } }
package com.stalary.pf.user.exception; import com.stalary.pf.user.data.vo.ResponseMessage; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.io.PrintWriter; import java.io.StringWriter; /** * @author Stalary * @description * @date 2018/04/14 */ @ControllerAdvice @Slf4j public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseMessage handle(Exception e) { if (e instanceof MyException) { MyException myException = (MyException) e; return ResponseMessage.error(myException.getCode(), myException.getMessage()); } else { log.error("[系统异常]", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return ResponseMessage.error(500, "user 运行时异常!" + sw.toString()); } } }
package top.quhailong.pan.core.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * 登录、注册网关 * @author 屈海龙 * */ @EnableZuulProxy @EnableDiscoveryClient @SpringBootApplication public class CoreZuulApplication { public static void main(String[] args) { SpringApplication.run(CoreZuulApplication.class, args); } @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许cookies跨域 //config.addAllowedOrigin("http://regist.727pan.cn");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin //config.addAllowedOrigin("http://727pan.cn");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin config.addAllowedHeader("*");// #允许访问的头信息,*表示全部 config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
package top.quhailong.pan.core.zuul.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import io.jsonwebtoken.Claims; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import top.quhailong.pan.response.UserInfoDTO; import top.quhailong.pan.utils.CookieUtils; import top.quhailong.pan.utils.JSONUtils; import top.quhailong.pan.utils.JWTUtils; import javax.servlet.http.HttpServletRequest; /** * token过滤器,校验token必输项方法,token不能为空 * * @author guooo */ @Component public class PreFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(PreFilter.class); /* * 过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。 * * @see com.netflix.zuul.IZuulFilter#run() */ private String getBase64Credentials(String username, String password) { String plainCreds = username + ":" + password; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); return new String(base64CredsBytes); } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader("Authorization","Basic " + getBase64Credentials("admin","admin123")); HttpServletRequest request = ctx.getRequest(); String curOrigin = request.getHeader("Origin"); log.info(String.format("%s >>> %s >>> %s", request.getMethod(), request.getRequestURI(), curOrigin)); if (request.getRequestURI().contains("/api/user")) { if (request.getRequestURI().contains("logout") || request.getRequestURI().contains("changepwd") || request.getRequestURI().contains("loadimg") || request.getRequestURI().contains("uploadpic")) { verifyToken(ctx); } } if(request.getRequestURI().contains("/api/core")){ verifyToken(ctx); } //--------------------------------------------------------------------------------------------------------------------------------------- /*if (request.getRequestURI().contains("/regcheckusername") || request.getRequestURI().contains("/regcheckphone") || request.getRequestURI().contains("/getpass") || request.getRequestURI().contains("/css") || request.getRequestURI().contains("/js") || request.getRequestURI().contains("/css") || request.getRequestURI().contains("/images")) { ctx.setSendZuulResponse(true); return null; } InputStream in = (InputStream) ctx.get("requestEntity"); if (in == null) { in = ctx.getRequest().getInputStream(); } String token = null; if (request.getRequestURI().equals("/api/edge/getpublickey")) { ctx.setSendZuulResponse(true); return null; } if (!request.getRequestURI().contains("getverfyimg") && !request.getRequestURI().contains("regsmscodestr")) { if (!request.getContentType().contains("multipart/form-data")) { token = ctx.getRequest().getParameter("token"); } else { Part part = request.getPart("token"); InputStream name = part.getInputStream(); token = StreamUtils.copyToString(name, Charset.forName("UTF-8")); } } if (request.getRequestURI().equals("/api/user/logout") || request.getRequestURI().equals("/api/user/changepwd") || request.getRequestURI().equals("/api/user/uploadpic") || request.getRequestURI().equals("/api/user/loadimg")) { Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); Userinfo userinfo = JsonUtils.jsonToPojo(subject, Userinfo.class); log.info(userinfo.getUid()); ctx.setSendZuulResponse(true); return null; } else { ctx.setSendZuulResponse(true); return null; }*/ return null; } private void verifyToken(RequestContext ctx) { try { String token = CookieUtils.getCookie("token"); Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); UserInfoDTO userinfo = JSONUtils.parseObject(subject, UserInfoDTO.class); log.info(userinfo.getUserId()); ctx.setSendZuulResponse(true); } catch (Exception e) { ctx.setSendZuulResponse(false); } } /* * 这里可以写逻辑判断,是否要过滤,本文true,永远过滤。 * * @see com.netflix.zuul.IZuulFilter#shouldFilter() */ @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return 0; } /* * (non-Javadoc) pre:路由之前 routing:路由之时 post: 路由之后 error:发送错误调用 * * @see com.netflix.zuul.ZuulFilter#filterType() */ @Override public String filterType() { return "pre"; } }
package top.quhailong.pan.file.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * 系统核心网关 * @author 屈海龙 * */ @SpringBootApplication @EnableEurekaClient @EnableZuulProxy public class FileZuulApplication { public static void main(String[] args) { SpringApplication.run(FileZuulApplication.class, args); } @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许cookies跨域 //config.addAllowedOrigin("http://localhost:8082");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin config.addAllowedHeader("*");// #允许访问的头信息,*表示全部 config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
package top.quhailong.pan.file.zuul.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import io.jsonwebtoken.Claims; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import top.quhailong.pan.response.UserInfoDTO; import top.quhailong.pan.utils.CookieUtils; import top.quhailong.pan.utils.JSONUtils; import top.quhailong.pan.utils.JWTUtils; import javax.servlet.http.HttpServletRequest; /** * token过滤器,校验token必输项方法,token不能为空 * * @author guooo */ @Component public class PreFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(PreFilter.class); /* * 过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。 * * @see com.netflix.zuul.IZuulFilter#run() */ private String getBase64Credentials(String username, String password) { String plainCreds = username + ":" + password; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); return new String(base64CredsBytes); } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); try { HttpServletRequest request = ctx.getRequest(); ctx.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials("admin", "admin123")); String curOrigin = request.getHeader("Origin"); log.info(String.format("%s >>> %s >>> %s", request.getMethod(), request.getRequestURI().toString(), curOrigin)); if (request.getRequestURI().contains("/api/file")) { verifyToken(ctx); } /*String token = ctx.getRequest().getParameter("token"); InputStream in = (InputStream) ctx.get("requestEntity"); if (in == null) { in = ctx.getRequest().getInputStream(); } if (!StringUtils.isEmpty(token)) { Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); Userinfo userinfo = JSONUtils.parseObject(subject, Userinfo.class); String body = StreamUtils.copyToString(in, Charset.forName("UTF-8")); body = StringUtils.replace(body, "token=" + token, "uid=" + userinfo.getUid()); final byte[] reqBodyBytes = body.getBytes(); ctx.setRequest(new HttpServletRequestWrapper(request) { @Override public ServletInputStream getInputStream() throws IOException { return new ServletInputStreamWrapper(reqBodyBytes); } @Override public int getContentLength() { return reqBodyBytes.length; } @Override public long getContentLengthLong() { return reqBodyBytes.length; } }); ctx.setSendZuulResponse(true); return null; } else { ctx.setSendZuulResponse(false); return null; }*/ return null; } catch (Exception e) { ctx.setSendZuulResponse(false); return null; } } private void verifyToken(RequestContext ctx) { try { String token = CookieUtils.getCookie("token"); Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes()); String subject = claims.getSubject(); UserInfoDTO userinfo = JSONUtils.parseObject(subject, UserInfoDTO.class); log.info(userinfo.getUserId()); ctx.setSendZuulResponse(true); } catch (Exception e) { ctx.setSendZuulResponse(false); } } /* * 这里可以写逻辑判断,是否要过滤,本文true,永远过滤。 * * @see com.netflix.zuul.IZuulFilter#shouldFilter() */ @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return 0; } /* * (non-Javadoc) pre:路由之前 routing:路由之时 post: 路由之后 error:发送错误调用 * * @see com.netflix.zuul.ZuulFilter#filterType() */ @Override public String filterType() { return "pre"; } }
package com.simplemall.account.config; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DruidDataSourceConfig { private static Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Autowired private DataSourceProperties dataSourceProperties; @Bean @Primary public DataSource druidDataSource(){ DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dataSourceProperties.getUrl()); datasource.setUsername(dataSourceProperties.getUsername()); datasource.setPassword(dataSourceProperties.getPassword()); datasource.setDriverClassName(dataSourceProperties.getDriverClassName()); datasource.setInitialSize(dataSourceProperties.getInitialSize()); datasource.setMinIdle(dataSourceProperties.getMinIdle()); datasource.setMaxActive(dataSourceProperties.getMaxActive()); datasource.setMaxWait(dataSourceProperties.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); datasource.setValidationQuery(dataSourceProperties.getValidationQuery()); datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); datasource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); datasource.setPoolPreparedStatements(dataSourceProperties.isPoolPreparedStatements()); try { datasource.setFilters(dataSourceProperties.getFilters()); } catch (SQLException e) { logger.error("Druid configuration initialization filter error.", e); } return datasource; } }
package com.simplemall.micro.serv.msg.config; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DruidDataSourceConfig { private static Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Autowired private DataSourceProperties dataSourceProperties; @Bean @Primary public DataSource druidDataSource(){ DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dataSourceProperties.getUrl()); datasource.setUsername(dataSourceProperties.getUsername()); datasource.setPassword(dataSourceProperties.getPassword()); datasource.setDriverClassName(dataSourceProperties.getDriverClassName()); datasource.setInitialSize(dataSourceProperties.getInitialSize()); datasource.setMinIdle(dataSourceProperties.getMinIdle()); datasource.setMaxActive(dataSourceProperties.getMaxActive()); datasource.setMaxWait(dataSourceProperties.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); datasource.setValidationQuery(dataSourceProperties.getValidationQuery()); datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); datasource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); datasource.setPoolPreparedStatements(dataSourceProperties.isPoolPreparedStatements()); try { datasource.setFilters(dataSourceProperties.getFilters()); } catch (SQLException e) { logger.error("Druid configuration initialization filter error.", e); } return datasource; } }
package com.simplemall.micro.serv.order.config; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DruidDataSourceConfig { private static Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Autowired private DataSourceProperties dataSourceProperties; @Bean @Primary public DataSource druidDataSource(){ DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dataSourceProperties.getUrl()); datasource.setUsername(dataSourceProperties.getUsername()); datasource.setPassword(dataSourceProperties.getPassword()); datasource.setDriverClassName(dataSourceProperties.getDriverClassName()); datasource.setInitialSize(dataSourceProperties.getInitialSize()); datasource.setMinIdle(dataSourceProperties.getMinIdle()); datasource.setMaxActive(dataSourceProperties.getMaxActive()); datasource.setMaxWait(dataSourceProperties.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); datasource.setValidationQuery(dataSourceProperties.getValidationQuery()); datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); datasource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); datasource.setPoolPreparedStatements(dataSourceProperties.isPoolPreparedStatements()); try { datasource.setFilters(dataSourceProperties.getFilters()); } catch (SQLException e) { logger.error("Druid configuration initialization filter error.", e); } return datasource; } }
package com.simplemall.pay.config; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DruidDataSourceConfig { private static Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Autowired private DataSourceProperties dataSourceProperties; @Bean @Primary public DataSource druidDataSource(){ DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dataSourceProperties.getUrl()); datasource.setUsername(dataSourceProperties.getUsername()); datasource.setPassword(dataSourceProperties.getPassword()); datasource.setDriverClassName(dataSourceProperties.getDriverClassName()); datasource.setInitialSize(dataSourceProperties.getInitialSize()); datasource.setMinIdle(dataSourceProperties.getMinIdle()); datasource.setMaxActive(dataSourceProperties.getMaxActive()); datasource.setMaxWait(dataSourceProperties.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); datasource.setValidationQuery(dataSourceProperties.getValidationQuery()); datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); datasource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); datasource.setPoolPreparedStatements(dataSourceProperties.isPoolPreparedStatements()); try { datasource.setFilters(dataSourceProperties.getFilters()); } catch (SQLException e) { logger.error("Druid configuration initialization filter error.", e); } return datasource; } }
package com.simplemall.micro.serv.prd.config; import com.alibaba.druid.pool.DruidDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; @Configuration @EnableConfigurationProperties(DataSourceProperties.class) public class DruidDataSourceConfig { private static Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Autowired private DataSourceProperties dataSourceProperties; @Bean @Primary public DataSource druidDataSource(){ DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dataSourceProperties.getUrl()); datasource.setUsername(dataSourceProperties.getUsername()); datasource.setPassword(dataSourceProperties.getPassword()); datasource.setDriverClassName(dataSourceProperties.getDriverClassName()); datasource.setInitialSize(dataSourceProperties.getInitialSize()); datasource.setMinIdle(dataSourceProperties.getMinIdle()); datasource.setMaxActive(dataSourceProperties.getMaxActive()); datasource.setMaxWait(dataSourceProperties.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); datasource.setValidationQuery(dataSourceProperties.getValidationQuery()); datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); datasource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); datasource.setPoolPreparedStatements(dataSourceProperties.isPoolPreparedStatements()); try { datasource.setFilters(dataSourceProperties.getFilters()); } catch (SQLException e) { logger.error("Druid configuration initialization filter error.", e); } return datasource; } }
package com.zrkworld.sns.article.interceptor; import io.jsonwebtoken.Claims; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import utils.JwtUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 拦截器,用来jwt鉴权 * @author zrk */ @Component public class JwtInterceptor implements HandlerInterceptor { @Resource private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 无论如何都放行,具体能不能操作还是在具体操作中去判断 // 拦截器只负责把请求头中包含token的令牌进行解析 String header = request.getHeader("Authorization"); if (!StringUtils.isEmpty(header)) { // 如果有包含Authorization的头信息,就对其进行解析 if (header.startsWith("Bearer ")) { // 得到token final String token = header.substring(7); // 对令牌进行验证 try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("role"); if ("admin".equals(roles)) { request.setAttribute("claims_admin", token); } if ("user".equals(roles)) { request.setAttribute("claims_user", token); } } catch (Exception e) { throw new RuntimeException("令牌有误!"); } } } return true; } }
package com.zrkworld.sns.friend.interceptor; import io.jsonwebtoken.Claims; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import utils.JwtUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class JwtInterceptor implements HandlerInterceptor { @Resource private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 无论如何都放行,具体能不能操作还是在具体操作中去判断 // 拦截器只负责把请求头中包含token的令牌进行解析 String header = request.getHeader("Authorization"); if (!StringUtils.isEmpty(header)) { // 如果有包含Authorization的头信息,就对其进行解析 if (header.startsWith("Bearer ")) { // 得到token final String token = header.substring(7); // 对令牌进行验证 try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("role"); if ("admin".equals(roles)) { request.setAttribute("claims_admin", claims); } if ("user".equals(roles)) { request.setAttribute("claims_user", claims); } } catch (Exception e) { throw new RuntimeException("令牌有误!"); } } } return true; } }
package com.zrkworld.sns.qa.interceptor; import io.jsonwebtoken.Claims; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import utils.JwtUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class JwtInterceptor implements HandlerInterceptor { @Resource private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 无论如何都放行,具体能不能操作还是在具体操作中去判断 // 拦截器只负责把请求头中包含token的令牌进行解析 String header = request.getHeader("Authorization"); if (!StringUtils.isEmpty(header)) { // 如果有包含Authorization的头信息,就对其进行解析 if (header.startsWith("Bearer ")) { // 得到token final String token = header.substring(7); // 对令牌进行验证 try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("roles"); if ("admin".equals(roles)) { request.setAttribute("claims_admin", token); } if ("user".equals(roles)) { request.setAttribute("claims_user", token); } } catch (Exception e) { throw new RuntimeException("令牌有误!"); } } } return true; } }
package com.zrkworld.sns.spit.interceptor; import io.jsonwebtoken.Claims; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import utils.JwtUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class JwtInterceptor implements HandlerInterceptor { @Resource private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 无论如何都放行,具体能不能操作还是在具体操作中去判断 // 拦截器只负责把请求头中包含token的令牌进行解析 String header = request.getHeader("Authorization"); if (!StringUtils.isEmpty(header)) { // 如果有包含Authorization的头信息,就对其进行解析 if (header.startsWith("Bearer ")) { // 得到token final String token = header.substring(7); // 对令牌进行验证 try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("role"); if ("admin".equals(roles)) { request.setAttribute("claims_admin", token); } if ("user".equals(roles)) { request.setAttribute("claims_user", token); } } catch (Exception e) { throw new RuntimeException("令牌有误!"); } } } return true; } }
package com.zrkworld.sns.user.interceptor; import io.jsonwebtoken.Claims; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import utils.JwtUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class JwtInterceptor implements HandlerInterceptor { @Resource private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 无论如何都放行,具体能不能操作还是在具体操作中去判断 // 拦截器只负责把请求头中包含token的令牌进行解析 String header = request.getHeader("Authorization"); if (!StringUtils.isEmpty(header)) { // 如果有包含Authorization的头信息,就对其进行解析 if (header.startsWith("Bearer ")) { // 得到token final String token = header.substring(7); // 对令牌进行验证 try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("role"); if ("admin".equals(roles)) { request.setAttribute("claims_admin", token); } if ("user".equals(roles)) { request.setAttribute("claims_user", token); } } catch (Exception e) { throw new RuntimeException("令牌有误!"); } } } return true; } }
package io.renren.common.xss; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * HTML filtering utility for protecting against XSS (Cross Site Scripting). * * This code is licensed LGPLv3 * * This code is a Java port of the original work in PHP by Cal Hendersen. * http://code.iamcal.com/php/lib_filter/ * * The trickiest part of the translation was handling the differences in regex handling * between PHP and Java. These resources were helpful in the process: * * http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html * http://us2.php.net/manual/en/reference.pcre.pattern.modifiers.php * http://www.regular-expressions.info/modifiers.html * * A note on naming conventions: instance variables are prefixed with a "v"; global * constants are in all caps. * * Sample use: * String input = ... * String clean = new HTMLFilter().filter( input ); * * The class is not thread safe. Create a new instance if in doubt. * * If you find bugs or have suggestions on improvement (especially regarding * performance), please contact us. The latest version of this * source, and our contact details, can be found at http://xss-html-filter.sf.net * * @author Joseph O'Connell * @author Cal Hendersen * @author Michael Semb Wever */ public final class HTMLFilter { /** regex flag union representing /si modifiers in php **/ private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL); private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); private static final Pattern P_ENTITY = Pattern.compile("(\\d+);?"); private static final Pattern P_ENTITY_UNICODE = Pattern.compile("([0-9a-f]+);?"); private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); private static final Pattern P_END_ARROW = Pattern.compile("^>"); private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_AMP = Pattern.compile("&"); private static final Pattern P_QUOTE = Pattern.compile("<"); private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); // @xxx could grow large... maybe use sesat's ReferenceMap private static final ConcurrentMap<String,Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<String, Pattern>(); private static final ConcurrentMap<String,Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>(); /** set of allowed html elements, along with allowed attributes for each element **/ private final Map<String, List<String>> vAllowed; /** counts of open tags for each (allowable) html element **/ private final Map<String, Integer> vTagCounts = new HashMap<String, Integer>(); /** html elements which must always be self-closing (e.g. "<img />") **/ private final String[] vSelfClosingTags; /** html elements which must always have separate opening and closing tags (e.g. "<b></b>") **/ private final String[] vNeedClosingTags; /** set of disallowed html elements **/ private final String[] vDisallowed; /** attributes which should be checked for valid protocols **/ private final String[] vProtocolAtts; /** allowed protocols **/ private final String[] vAllowedProtocols; /** tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />") **/ private final String[] vRemoveBlanks; /** entities allowed within html markup **/ private final String[] vAllowedEntities; /** flag determining whether comments are allowed in input String. */ private final boolean stripComment; private final boolean encodeQuotes; private boolean vDebug = false; /** * flag determining whether to try to make tags when presented with "unbalanced" * angle brackets (e.g. "<b text </b>" becomes "<b> text </b>"). If set to false, * unbalanced angle brackets will be html escaped. */ private final boolean alwaysMakeTags; /** Default constructor. * */ public HTMLFilter() { vAllowed = new HashMap<>(); final ArrayList<String> a_atts = new ArrayList<String>(); a_atts.add("href"); a_atts.add("target"); vAllowed.put("a", a_atts); final ArrayList<String> img_atts = new ArrayList<String>(); img_atts.add("src"); img_atts.add("width"); img_atts.add("height"); img_atts.add("alt"); vAllowed.put("img", img_atts); final ArrayList<String> no_atts = new ArrayList<String>(); vAllowed.put("b", no_atts); vAllowed.put("strong", no_atts); vAllowed.put("i", no_atts); vAllowed.put("em", no_atts); vSelfClosingTags = new String[]{"img"}; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; vDisallowed = new String[]{}; vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. vProtocolAtts = new String[]{"src", "href"}; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; stripComment = true; encodeQuotes = true; alwaysMakeTags = true; } /** Set debug flag to true. Otherwise use default settings. See the default constructor. * * @param debug turn debug on with a true argument */ public HTMLFilter(final boolean debug) { this(); vDebug = debug; } /** Map-parameter configurable constructor. * * @param conf map containing configuration. keys match field names. */ public HTMLFilter(final Map<String,Object> conf) { assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed")); vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); vDisallowed = (String[]) conf.get("vDisallowed"); vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); vProtocolAtts = (String[]) conf.get("vProtocolAtts"); vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); vAllowedEntities = (String[]) conf.get("vAllowedEntities"); stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; } private void reset() { vTagCounts.clear(); } private void debug(final String msg) { if (vDebug) { Logger.getAnonymousLogger().info(msg); } } //--------------------------------------------------------------- // my versions of some PHP library functions public static String chr(final int decimal) { return String.valueOf((char) decimal); } public static String htmlSpecialChars(final String s) { String result = s; result = regexReplace(P_AMP, "&", result); result = regexReplace(P_QUOTE, """, result); result = regexReplace(P_LEFT_ARROW, "<", result); result = regexReplace(P_RIGHT_ARROW, ">", result); return result; } //--------------------------------------------------------------- /** * given a user submitted input String, filter out any invalid or restricted * html. * * @param input text (i.e. submitted by a user) than may contain html * @return "clean" version of input, with only valid, whitelisted html elements allowed */ public String filter(final String input) { reset(); String s = input; debug("************************************************"); debug(" INPUT: " + input); s = escapeComments(s); debug(" escapeComments: " + s); s = balanceHTML(s); debug(" balanceHTML: " + s); s = checkTags(s); debug(" checkTags: " + s); s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s); s = validateEntities(s); debug(" validateEntites: " + s); debug("************************************************\n\n"); return s; } public boolean isAlwaysMakeTags(){ return alwaysMakeTags; } public boolean isStripComments(){ return stripComment; } private String escapeComments(final String s) { final Matcher m = P_COMMENTS.matcher(s); final StringBuffer buf = new StringBuffer(); if (m.find()) { final String match = m.group(1); //(.*?) m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->")); } m.appendTail(buf); return buf.toString(); } private String balanceHTML(String s) { if (alwaysMakeTags) { // // try and form html // s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s); } else { // // escape stray brackets // s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); // // the last regexp causes '<>' entities to appear // (we need to do a lookahead assertion so that the last bracket can // be used in the next pass of the regexp) // s = regexReplace(P_BOTH_ARROWS, "", s); } return s; } private String checkTags(String s) { Matcher m = P_TAGS.matcher(s); final StringBuffer buf = new StringBuffer(); while (m.find()) { String replaceStr = m.group(1); replaceStr = processTag(replaceStr); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); } m.appendTail(buf); s = buf.toString(); // these get tallied in processTag // (remember to reset before subsequent calls to filter method) for (String key : vTagCounts.keySet()) { for (int ii = 0; ii < vTagCounts.get(key); ii++) { s += "</" + key + ">"; } } return s; } private String processRemoveBlanks(final String s) { String result = s; for (String tag : vRemoveBlanks) { if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">")); } result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); } result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); } return result; } private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { Matcher m = regex_pattern.matcher(s); return m.replaceAll(replacement); } private String processTag(final String s) { // ending tags Matcher m = P_END_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) - 1); return "</" + name + ">"; } } } } // starting tags m = P_START_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); final String body = m.group(2); String ending = m.group(3); //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); if (allowed(name)) { String params = ""; final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final List<String> paramNames = new ArrayList<String>(); final List<String> paramValues = new ArrayList<String>(); while (m2.find()) { paramNames.add(m2.group(1)); //([a-z0-9]+) paramValues.add(m2.group(3)); //(.*?) } while (m3.find()) { paramNames.add(m3.group(1)); //([a-z0-9]+) paramValues.add(m3.group(3)); //([^\"\\s']+) } String paramName, paramValue; for (int ii = 0; ii < paramNames.size(); ii++) { paramName = paramNames.get(ii).toLowerCase(); paramValue = paramValues.get(ii); // debug( "paramName='" + paramName + "'" ); // debug( "paramValue='" + paramValue + "'" ); // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params += " " + paramName + "=\"" + paramValue + "\""; } } if (inArray(name, vSelfClosingTags)) { ending = " /"; } if (inArray(name, vNeedClosingTags)) { ending = ""; } if (ending == null || ending.length() < 1) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) + 1); } else { vTagCounts.put(name, 1); } } else { ending = " /"; } return "<" + name + params + ending + ">"; } else { return ""; } } // comments m = P_COMMENT.matcher(s); if (!stripComment && m.find()) { return "<" + m.group() + ">"; } return ""; } private String processParamProtocol(String s) { s = decodeEntities(s); final Matcher m = P_PROTOCOL.matcher(s); if (m.find()) { final String protocol = m.group(1); if (!inArray(protocol, vAllowedProtocols)) { // bad protocol, turn into local anchor link instead s = "#" + s.substring(protocol.length() + 1, s.length()); if (s.startsWith("#//")) { s = "#" + s.substring(3, s.length()); } } } return s; } private String decodeEntities(String s) { StringBuffer buf = new StringBuffer(); Matcher m = P_ENTITY.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.decode(match).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENTITY_UNICODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENCODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); s = validateEntities(s); return s; } private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); } private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } } private String checkEntity(final String preamble, final String term) { return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble; } private boolean isValidEntity(final String entity) { return inArray(entity, vAllowedEntities); } private static boolean inArray(final String s, final String[] array) { for (String item : array) { if (item != null && item.equals(s)) { return true; } } return false; } private boolean allowed(final String name) { return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); } private boolean allowedAttribute(final String name, final String paramName) { return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); } }
package com.jerusalem.cart.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class CartSentinelConfig { public CartSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.common.xss; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * HTML filtering utility for protecting against XSS (Cross Site Scripting). * * This code is licensed LGPLv3 * * This code is a Java port of the original work in PHP by Cal Hendersen. * http://code.iamcal.com/php/lib_filter/ * * The trickiest part of the translation was handling the differences in regex handling * between PHP and Java. These resources were helpful in the process: * * http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html * http://us2.php.net/manual/en/reference.pcre.pattern.modifiers.php * http://www.regular-expressions.info/modifiers.html * * A note on naming conventions: instance variables are prefixed with a "v"; global * constants are in all caps. * * Sample use: * String input = ... * String clean = new HTMLFilter().filter( input ); * * The class is not thread safe. Create a new instance if in doubt. * * If you find bugs or have suggestions on improvement (especially regarding * performance), please contact us. The latest version of this * source, and our contact details, can be found at http://xss-html-filter.sf.net * * @author Joseph O'Connell * @author Cal Hendersen * @author Michael Semb Wever */ public final class HTMLFilter { /** regex flag union representing /si modifiers in php **/ private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL); private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); private static final Pattern P_ENTITY = Pattern.compile("(\\d+);?"); private static final Pattern P_ENTITY_UNICODE = Pattern.compile("([0-9a-f]+);?"); private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); private static final Pattern P_END_ARROW = Pattern.compile("^>"); private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_AMP = Pattern.compile("&"); private static final Pattern P_QUOTE = Pattern.compile("<"); private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); // @xxx could grow large... maybe use sesat's ReferenceMap private static final ConcurrentMap<String,Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<String, Pattern>(); private static final ConcurrentMap<String,Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>(); /** set of allowed html elements, along with allowed attributes for each element **/ private final Map<String, List<String>> vAllowed; /** counts of open tags for each (allowable) html element **/ private final Map<String, Integer> vTagCounts = new HashMap<String, Integer>(); /** html elements which must always be self-closing (e.g. "<img />") **/ private final String[] vSelfClosingTags; /** html elements which must always have separate opening and closing tags (e.g. "<b></b>") **/ private final String[] vNeedClosingTags; /** set of disallowed html elements **/ private final String[] vDisallowed; /** attributes which should be checked for valid protocols **/ private final String[] vProtocolAtts; /** allowed protocols **/ private final String[] vAllowedProtocols; /** tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />") **/ private final String[] vRemoveBlanks; /** entities allowed within html markup **/ private final String[] vAllowedEntities; /** flag determining whether comments are allowed in input String. */ private final boolean stripComment; private final boolean encodeQuotes; private boolean vDebug = false; /** * flag determining whether to try to make tags when presented with "unbalanced" * angle brackets (e.g. "<b text </b>" becomes "<b> text </b>"). If set to false, * unbalanced angle brackets will be html escaped. */ private final boolean alwaysMakeTags; /** Default constructor. * */ public HTMLFilter() { vAllowed = new HashMap<>(); final ArrayList<String> a_atts = new ArrayList<String>(); a_atts.add("href"); a_atts.add("target"); vAllowed.put("a", a_atts); final ArrayList<String> img_atts = new ArrayList<String>(); img_atts.add("src"); img_atts.add("width"); img_atts.add("height"); img_atts.add("alt"); vAllowed.put("img", img_atts); final ArrayList<String> no_atts = new ArrayList<String>(); vAllowed.put("b", no_atts); vAllowed.put("strong", no_atts); vAllowed.put("i", no_atts); vAllowed.put("em", no_atts); vSelfClosingTags = new String[]{"img"}; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; vDisallowed = new String[]{}; vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. vProtocolAtts = new String[]{"src", "href"}; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; stripComment = true; encodeQuotes = true; alwaysMakeTags = true; } /** Set debug flag to true. Otherwise use default settings. See the default constructor. * * @param debug turn debug on with a true argument */ public HTMLFilter(final boolean debug) { this(); vDebug = debug; } /** Map-parameter configurable constructor. * * @param conf map containing configuration. keys match field names. */ public HTMLFilter(final Map<String,Object> conf) { assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed")); vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); vDisallowed = (String[]) conf.get("vDisallowed"); vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); vProtocolAtts = (String[]) conf.get("vProtocolAtts"); vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); vAllowedEntities = (String[]) conf.get("vAllowedEntities"); stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; } private void reset() { vTagCounts.clear(); } private void debug(final String msg) { if (vDebug) { Logger.getAnonymousLogger().info(msg); } } //--------------------------------------------------------------- // my versions of some PHP library functions public static String chr(final int decimal) { return String.valueOf((char) decimal); } public static String htmlSpecialChars(final String s) { String result = s; result = regexReplace(P_AMP, "&", result); result = regexReplace(P_QUOTE, """, result); result = regexReplace(P_LEFT_ARROW, "<", result); result = regexReplace(P_RIGHT_ARROW, ">", result); return result; } //--------------------------------------------------------------- /** * given a user submitted input String, filter out any invalid or restricted * html. * * @param input text (i.e. submitted by a user) than may contain html * @return "clean" version of input, with only valid, whitelisted html elements allowed */ public String filter(final String input) { reset(); String s = input; debug("************************************************"); debug(" INPUT: " + input); s = escapeComments(s); debug(" escapeComments: " + s); s = balanceHTML(s); debug(" balanceHTML: " + s); s = checkTags(s); debug(" checkTags: " + s); s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s); s = validateEntities(s); debug(" validateEntites: " + s); debug("************************************************\n\n"); return s; } public boolean isAlwaysMakeTags(){ return alwaysMakeTags; } public boolean isStripComments(){ return stripComment; } private String escapeComments(final String s) { final Matcher m = P_COMMENTS.matcher(s); final StringBuffer buf = new StringBuffer(); if (m.find()) { final String match = m.group(1); //(.*?) m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->")); } m.appendTail(buf); return buf.toString(); } private String balanceHTML(String s) { if (alwaysMakeTags) { // // try and form html // s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s); } else { // // escape stray brackets // s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); // // the last regexp causes '<>' entities to appear // (we need to do a lookahead assertion so that the last bracket can // be used in the next pass of the regexp) // s = regexReplace(P_BOTH_ARROWS, "", s); } return s; } private String checkTags(String s) { Matcher m = P_TAGS.matcher(s); final StringBuffer buf = new StringBuffer(); while (m.find()) { String replaceStr = m.group(1); replaceStr = processTag(replaceStr); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); } m.appendTail(buf); s = buf.toString(); // these get tallied in processTag // (remember to reset before subsequent calls to filter method) for (String key : vTagCounts.keySet()) { for (int ii = 0; ii < vTagCounts.get(key); ii++) { s += "</" + key + ">"; } } return s; } private String processRemoveBlanks(final String s) { String result = s; for (String tag : vRemoveBlanks) { if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">")); } result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); } result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); } return result; } private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { Matcher m = regex_pattern.matcher(s); return m.replaceAll(replacement); } private String processTag(final String s) { // ending tags Matcher m = P_END_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) - 1); return "</" + name + ">"; } } } } // starting tags m = P_START_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); final String body = m.group(2); String ending = m.group(3); //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); if (allowed(name)) { String params = ""; final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final List<String> paramNames = new ArrayList<String>(); final List<String> paramValues = new ArrayList<String>(); while (m2.find()) { paramNames.add(m2.group(1)); //([a-z0-9]+) paramValues.add(m2.group(3)); //(.*?) } while (m3.find()) { paramNames.add(m3.group(1)); //([a-z0-9]+) paramValues.add(m3.group(3)); //([^\"\\s']+) } String paramName, paramValue; for (int ii = 0; ii < paramNames.size(); ii++) { paramName = paramNames.get(ii).toLowerCase(); paramValue = paramValues.get(ii); // debug( "paramName='" + paramName + "'" ); // debug( "paramValue='" + paramValue + "'" ); // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params += " " + paramName + "=\"" + paramValue + "\""; } } if (inArray(name, vSelfClosingTags)) { ending = " /"; } if (inArray(name, vNeedClosingTags)) { ending = ""; } if (ending == null || ending.length() < 1) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) + 1); } else { vTagCounts.put(name, 1); } } else { ending = " /"; } return "<" + name + params + ending + ">"; } else { return ""; } } // comments m = P_COMMENT.matcher(s); if (!stripComment && m.find()) { return "<" + m.group() + ">"; } return ""; } private String processParamProtocol(String s) { s = decodeEntities(s); final Matcher m = P_PROTOCOL.matcher(s); if (m.find()) { final String protocol = m.group(1); if (!inArray(protocol, vAllowedProtocols)) { // bad protocol, turn into local anchor link instead s = "#" + s.substring(protocol.length() + 1, s.length()); if (s.startsWith("#//")) { s = "#" + s.substring(3, s.length()); } } } return s; } private String decodeEntities(String s) { StringBuffer buf = new StringBuffer(); Matcher m = P_ENTITY.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.decode(match).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENTITY_UNICODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENCODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); s = validateEntities(s); return s; } private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); } private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } } private String checkEntity(final String preamble, final String term) { return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble; } private boolean isValidEntity(final String entity) { return inArray(entity, vAllowedEntities); } private static boolean inArray(final String s, final String[] array) { for (String item : array) { if (item != null && item.equals(s)) { return true; } } return false; } private boolean allowed(final String name) { return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); } private boolean allowedAttribute(final String name, final String paramName) { return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); } }
package com.jerusalem.coupon.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class CouponSentinelConfig { public CouponSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.goods.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class GoodsSentinelConfig { public GoodsSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.oauth2.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class Oauth2SentinelConfig { public Oauth2SentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.order.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class OrderSentinelConfig { public OrderSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.order.interceptor; import com.jerusalem.common.constant.AuthConstant; import com.jerusalem.common.vo.UserResponseVo; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /**** * @Author: jerusalem * @Description: LoginInterceptor * 订单登录拦截器 * @Date 2020/11/7 12:29 *****/ @Component public class LoginInterceptor implements HandlerInterceptor { /*** * 全系统共享当前登录用户 */ public static ThreadLocal<UserResponseVo> loginUser = new ThreadLocal<>(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { /*** * 放行库存系统的个别请求 */ String uri = request.getRequestURI(); AntPathMatcher antPathMatcher = new AntPathMatcher(); boolean match = antPathMatcher.match("/order/orders/status/**", uri); //放行支付成功异步通知回调 boolean match1 = antPathMatcher.match("/payed/notify", uri); if (match || match1){ return true; } UserResponseVo userResponseVo = (UserResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER); if (userResponseVo != null){ //全系统共享 loginUser.set(userResponseVo); return true; }else { //没登陆,拦截,重定向到登录页面 request.getSession().setAttribute("msg","请先登录!"); response.sendRedirect("http://auth.tesco.com/login.html"); return false; } } }
package com.jerusalem.search.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class SearchSentinelConfig { public SearchSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.seckill.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class SeckillSentinelConfig { public SeckillSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.seckill.interceptor; import com.jerusalem.common.constant.AuthConstant; import com.jerusalem.common.vo.UserResponseVo; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /**** * @Author: jerusalem * @Description: LoginInterceptor * 秒杀登录拦截器 * @Date 2020/11/7 12:29 *****/ @Component public class LoginInterceptor implements HandlerInterceptor { /*** * 全系统共享当前登录用户 */ public static ThreadLocal<UserResponseVo> loginUser = new ThreadLocal<>(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { /*** * 拦截秒杀系统的个别请求,进行登陆检查 * 其他的放行 */ String uri = request.getRequestURI(); AntPathMatcher antPathMatcher = new AntPathMatcher(); boolean match = antPathMatcher.match("/seckill/kill", uri); if (match){ UserResponseVo userResponseVo = (UserResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER); if (userResponseVo != null){ //全系统共享 loginUser.set(userResponseVo); return true; }else { //没登陆,拦截,重定向到登录页面 request.getSession().setAttribute("msg","请先登录!"); response.sendRedirect("http://auth.tesco.com/login.html"); return false; } } return true; } }
package com.jerusalem.third.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class ThirdSentinelConfig { public ThirdSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.user.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class UserSentinelConfig { public UserSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package com.jerusalem.ware.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.fastjson.JSON; import com.jerusalem.common.exception.BizCodeEnume; import com.jerusalem.common.utils.R; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /**** * @Author: jerusalem * @Description: SeckillSentinelConfig * 自定义流控响应 * @Date 2020/11/20 16:48 *****/ @Configuration public class WareSentinelConfig { public WareSentinelConfig(){ WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application"); httpServletResponse.getWriter().write(JSON.toJSONString(error)); } }); } }
package inside_payment.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author fdse */ public class CookieUtil { private CookieUtil() { throw new IllegalStateException("Utility class"); } public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){ Cookie cookie = new Cookie(name,value); // against Cross-Site Scripting (XSS) attacks cookie.setHttpOnly(true); cookie.setPath("/"); if(maxAge>0) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); } public static Cookie getCookieByName(HttpServletRequest request, String name){ Map<String,Cookie> cookieMap = readCookieMap(request); if(cookieMap.containsKey(name)){ return cookieMap.get(name); }else{ return null; } } private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }
package verifycode.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author fdse */ public class CookieUtil { private CookieUtil() { throw new IllegalStateException("Utility class"); } public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){ Cookie cookie = new Cookie(name,value); // against Cross-Site Scripting (XSS) attacks. cookie.setHttpOnly(true); cookie.setPath("/"); if(maxAge>0) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); } public static Cookie getCookieByName(HttpServletRequest request, String name){ Map<String,Cookie> cookieMap = readCookieMap(request); return cookieMap.getOrDefault(name, null); } private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }
package com.wanxin.account.common; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } log.error("[系统异常]-" + e.getMessage()); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.account.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.text.SimpleDateFormat; import java.util.List; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { /** * 定义时间格式以及类型转换 转换器 * * @return */ @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); mapper.registerModule(simpleModule); converter.setObjectMapper(mapper); return converter; } /** * 添加转换器 * * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(jackson2HttpMessageConverter()); } /** * 添加静态资源文件, 外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); // 解决swagger无法访问 registry .addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 解决swagger的js文件无法访问 registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); registry .addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); } }
package com.wanxin.common.util; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class Base64Util { private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public Base64Util() { } public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); } }
package com.wanxin.common.util; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class HttpUtil { public static String getAccessToken(String ak, String sk) throws Exception { // 获取token地址 String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1.grant_type为固定参数 + "grant_type=client_credentials" // 2.官网获取的 API Key + "&client_id=" + ak // 3.官网获取的 Secret Key + "&client_secret=" + sk; URL realUrl = new URL(getAccessTokenUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 获取所有响应头字段 /*Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.err.println(key + "--->" + map.get(key)); }*/ // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } in.close(); connection.disconnect(); /** * 返回结果 */ Map<String, Object> resultMap = JsonUtil.jsonToMap(result); return resultMap.get("access_token").toString(); } public static String post(String requestUrl, String accessToken, String params) throws Exception { String contentType = "application/x-www-form-urlencoded"; return HttpUtil.post(requestUrl, accessToken, contentType, params); } public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception { String encoding = "UTF-8"; if (requestUrl.contains("nlp")) { encoding = "GBK"; } return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); } public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception { String url = requestUrl + "?access_token=" + accessToken; return HttpUtil.postGeneralUrl(url, contentType, params, encoding); } public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception { URL url = new URL(generalUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置通用的请求属性 connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(20000); connection.setReadTimeout(20000); // 得到请求的输出流对象 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(params.getBytes(encoding)); out.flush(); out.close(); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> headers = connection.getHeaderFields(); // 遍历所有的响应头字段 /*for (String key : headers.keySet()) { System.err.println(key + "--->" + headers.get(key)); }*/ // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = null; in = new BufferedReader( new InputStreamReader(connection.getInputStream(), encoding)); String result = ""; String getLine; while ((getLine = in.readLine()) != null) { result += getLine; } in.close(); connection.disconnect(); // System.err.println("result:" + result); return result; } }
package com.wanxin.consumer.common; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Slf4j @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } log.error("[系统异常]-" + e.getMessage()); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.consumer.common; import com.alibaba.fastjson.JSONObject; import com.wanxin.api.account.model.LoginUser; import com.wanxin.common.util.EncryptUtil; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class SecurityUtil { /** * 获取当前登录用户 */ public static LoginUser getUser() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); LoginUser loginUser = new LoginUser(); if (servletRequestAttributes != null) { HttpServletRequest request = servletRequestAttributes.getRequest(); Map jwt = JSONObject.parseObject(EncryptUtil.decodeBase64(request.getHeader("jsonToken")), Map.class); if (jwt.get("mobile").toString() != null && !"".equals(jwt.get("mobile").toString())) { loginUser.setMobile(jwt.get("mobile").toString()); } if (jwt.get("client_id").toString() != null && !"".equals(jwt.get("client_id").toString())) { loginUser.setClientId(jwt.get("client_id").toString()); } } return loginUser; } }
package com.wanxin.consumer.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.wanxin.consumer.interceptor.TokenInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.text.SimpleDateFormat; import java.util.List; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { /** * 添加自定义拦截器 * * @param registry 拦截器注册对象 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**"); } /** * 定义时间格式以及类型转换 转换器 * * @return */ @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); mapper.registerModule(simpleModule); converter.setObjectMapper(mapper); return converter; } /** * 添加转换器 * * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(jackson2HttpMessageConverter()); } /** * 添加静态资源文件, 外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); // 解决swagger无法访问 registry .addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 解决swagger的js文件无法访问 registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); registry .addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); } }
package com.wanxin.consumer.interceptor; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.wanxin.api.account.model.LoginUser; import com.wanxin.common.util.EncryptUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Token拦截处理 * * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) { String jsonToken = httpServletRequest.getParameter("jsonToken"); if (StringUtils.isNotBlank(jsonToken)) { LoginUser loginUser = JSON.parseObject(EncryptUtil.decodeUTF8StringBase64(jsonToken), new TypeReference<LoginUser>() { }); httpServletRequest.setAttribute("jsonToken", loginUser); } return true; } }
package com.wanxin.consumer.utils; /** * Base64 工具类 * * @author yuelimin * @since 1.8 */ public class Base64Util { private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public Base64Util() { } public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); } }
package com.wanxin.consumer.utils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * http 工具类 * * @author yuelimin * @since 1.8 */ public class HttpUtil { public static String post(String requestUrl, String accessToken, String params) throws Exception { String contentType = "application/x-www-form-urlencoded"; return HttpUtil.post(requestUrl, accessToken, contentType, params); } public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception { String encoding = "UTF-8"; if (requestUrl.contains("nlp")) { encoding = "GBK"; } return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); } public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception { String url = requestUrl + "?access_token=" + accessToken; return HttpUtil.postGeneralUrl(url, contentType, params, encoding); } public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception { URL url = new URL(generalUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置通用的请求属性 connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); // 得到请求的输出流对象 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(params.getBytes(encoding)); out.flush(); out.close(); // 建立实际的连接 connection.connect(); // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = null; in = new BufferedReader( new InputStreamReader(connection.getInputStream(), encoding)); String result = ""; String getLine; while ((getLine = in.readLine()) != null) { result += getLine; } in.close(); return result; } }
package com.wanxin.search.common.intercept; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.Nullable; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @ControllerAdvice public class GlobalExceptionHandler { private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = Exception.class) @ResponseBody public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } LOGGER.error("[系统异常]-{}", e); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.depository.common.intercept; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @since 1.8 */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } log.error("[系统异常]-{}", e); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.gateway.config; import com.alibaba.fastjson.JSON; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.security.oauth2.provider.token.AccessTokenConverter; import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter; import java.util.*; /** * 令牌格式json与spring OAuth2Authentication的转换 * 增加jwt对client Authorities的支持 * * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class ClientDefaultAccessTokenConverter implements AccessTokenConverter { public static final String CLIENT_AUTHORITIES = "client_authorities"; private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); private boolean includeGrantType; /** * Converter for the part of the data in the token representing a user. * * @param userTokenConverter the userTokenConverter to set */ public void setUserTokenConverter(UserAuthenticationConverter userTokenConverter) { this.userTokenConverter = userTokenConverter; } /** * Flag to indicate the the grant type should be included in the converted token. * * @param includeGrantType the flag value (default false) */ public void setIncludeGrantType(boolean includeGrantType) { this.includeGrantType = includeGrantType; } @Override public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); OAuth2Request clientToken = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) { response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); ///增加对client Authorities支持 if (authentication.getOAuth2Request().getAuthorities() != null && !authentication.getOAuth2Request().getAuthorities().isEmpty()) { response.put(CLIENT_AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getOAuth2Request().getAuthorities())); } ///结束增加对client Authorities支持 } else { if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) { response.put(UserAuthenticationConverter.AUTHORITIES, AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); } } if (token.getScope() != null) { response.put(SCOPE, token.getScope()); } if (token.getAdditionalInformation().containsKey(JTI)) { response.put(JTI, token.getAdditionalInformation().get(JTI)); } if (token.getExpiration() != null) { response.put(EXP, token.getExpiration().getTime() / 1000); } if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) { response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); } response.putAll(token.getAdditionalInformation()); response.put(CLIENT_ID, clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { response.put(AUD, clientToken.getResourceIds()); } return response; } @Override public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value); Map<String, Object> info = new HashMap<String, Object>(map); info.remove(EXP); info.remove(AUD); info.remove(CLIENT_ID); info.remove(SCOPE); if (map.containsKey(EXP)) { token.setExpiration(new Date((Long) map.get(EXP) * 1000L)); } if (map.containsKey(JTI)) { info.put(JTI, map.get(JTI)); } token.setScope(extractScope(map)); token.setAdditionalInformation(info); return token; } @Override public OAuth2Authentication extractAuthentication(Map<String, ?> map) { Map<String, String> parameters = new HashMap<String, String>(); Set<String> scope = extractScope(map); Authentication user = userTokenConverter.extractAuthentication(map); String clientId = (String) map.get(CLIENT_ID); parameters.put(CLIENT_ID, clientId); if (includeGrantType && map.containsKey(GRANT_TYPE)) { parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); } Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? getAudience(map) : Collections.<String>emptySet()); Collection<? extends GrantedAuthority> authorities = null; if (user == null && map.containsKey(AUTHORITIES)) { @SuppressWarnings("unchecked") String[] roles = ((Collection<String>) map.get(AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(roles); } // 增加对client Authorities支持 if (user != null && map.containsKey(CLIENT_AUTHORITIES)) { String[] clentRoles = ((Collection<String>) map.get(CLIENT_AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(clentRoles); // 增加额外属性 parameters.put("mobile", (String) map.get("mobile")); parameters.put("tenant_id", (String) map.get("tenant_id")); parameters.put("department_id", (String) map.get("department_id")); parameters.put("user_authorities", JSON.toJSONString(map.get("user_authorities"))); parameters.put("payload", JSON.toJSONString(map.get("payload"))); // 结束增加额外属性 } // 结束增加对client Authorities支持 OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, null); return new OAuth2Authentication(request, user); } private Collection<String> getAudience(Map<String, ?> map) { Object auds = map.get(AUD); if (auds instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> result = (Collection<String>) auds; return result; } return Collections.singleton((String) auds); } private Set<String> extractScope(Map<String, ?> map) { Set<String> scope = Collections.emptySet(); if (map.containsKey(SCOPE)) { Object scopeObj = map.get(SCOPE); if (String.class.isInstance(scopeObj)) { scope = new LinkedHashSet<String>(Arrays.asList(String.class.cast(scopeObj).split(" "))); } else if (Collection.class.isAssignableFrom(scopeObj.getClass())) { @SuppressWarnings("unchecked") Collection<String> scopeColl = (Collection<String>) scopeObj; // Preserve ordering scope = new LinkedHashSet<String>(scopeColl); } } return scope; } }
package com.wanxin.repayment.interceptor; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.wanxin.api.account.model.LoginUser; import com.wanxin.common.util.EncryptUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Token拦截处理 * * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) { String jsonToken = httpServletRequest.getParameter("jsonToken"); if (StringUtils.isNotBlank(jsonToken)) { LoginUser loginUser = JSON.parseObject(EncryptUtil.decodeUTF8StringBase64(jsonToken), new TypeReference<LoginUser>() { }); httpServletRequest.setAttribute("jsonToken", loginUser); } return true; } }
package com.wanxin.transaction.common.intercept; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } log.error("[系统异常]-{}", e); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.transaction.common.utils; import com.alibaba.fastjson.JSONObject; import com.wanxin.api.account.model.LoginUser; import com.wanxin.common.util.EncryptUtil; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class SecurityUtil { /** * 获取当前登录用户 */ public static LoginUser getUser() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); LoginUser loginUser = new LoginUser(); if (servletRequestAttributes != null) { HttpServletRequest request = servletRequestAttributes.getRequest(); Map jwt = JSONObject.parseObject(EncryptUtil.decodeBase64(request.getHeader("jsonToken")), Map.class); if (jwt.get("mobile").toString() != null && !"".equals(jwt.get("mobile").toString())) { loginUser.setMobile(jwt.get("mobile").toString()); } if (jwt.get("client_id").toString() != null && !"".equals(jwt.get("client_id").toString())) { loginUser.setClientId(jwt.get("client_id").toString()); } } return loginUser; } }
package com.wanxin.transaction.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.wanxin.transaction.interceptor.TokenInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.text.SimpleDateFormat; import java.util.List; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Configuration public class WebConfig implements WebMvcConfigurer { /** * 添加自定义拦截器 * * @param registry 拦截器注册对象 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**"); } /** * 定义时间格式以及类型转换 转换器 * * @return */ @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); mapper.registerModule(simpleModule); converter.setObjectMapper(mapper); return converter; } /** * 添加转换器 * * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(jackson2HttpMessageConverter()); } /** * 添加静态资源文件, 外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); // 解决swagger无法访问 registry .addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 解决swagger的js文件无法访问 registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); registry .addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); } }
package com.wanxin.transaction.interceptor; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.wanxin.api.account.model.LoginUser; import com.wanxin.common.util.EncryptUtil; import org.apache.commons.lang.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <P> * Token 拦截处理 * </p> * * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) { String jsonToken = httpServletRequest.getParameter("jsonToken"); if (StringUtils.isNotBlank(jsonToken)) { LoginUser loginUser = JSON.parseObject(EncryptUtil.decodeUTF8StringBase64(jsonToken), new TypeReference<LoginUser>() { }); httpServletRequest.setAttribute("jsonToken", loginUser); } return true; } }
package com.wanxin.uaa.common.intercept; import com.wanxin.common.domain.BusinessException; import com.wanxin.common.domain.CommonErrorCode; import com.wanxin.common.domain.RestResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.Nullable; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @RestControllerAdvice public class GlobalExceptionHandler { private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = Exception.class) public RestResponse<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response, Exception e) { if (e instanceof BusinessException) { BusinessException be = (BusinessException) e; if (CommonErrorCode.CUSTOM.equals(be.getErrorCode())) { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getMessage()); } else { return new RestResponse<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc()); } } else if (e instanceof NoHandlerFoundException) { return new RestResponse<Nullable>(404, "找不到资源"); } else if (e instanceof HttpRequestMethodNotSupportedException) { return new RestResponse<Nullable>(405, "method 方法不支持"); } else if (e instanceof AccessDeniedException) { return new RestResponse<Nullable>(304, "没有权限访问"); } else if (e instanceof HttpMediaTypeNotSupportedException) { return new RestResponse<Nullable>(415, "不支持媒体类型"); } LOGGER.error("[系统异常]-{0}", e); return new RestResponse<Nullable>(CommonErrorCode.UNKOWN.getCode(), CommonErrorCode.UNKOWN.getDesc()); } }
package com.wanxin.uaa.domain; import com.alibaba.fastjson.JSON; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.security.oauth2.provider.token.AccessTokenConverter; import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter; import java.util.*; /** * 令牌格式json与spring OAuth2Authentication的转换, 增加jwt对client Authorities的支持 * * @author yuelimin * @version 1.0.0 * @since 1.8 */ public class ClientDefaultAccessTokenConverter implements AccessTokenConverter { public static final String CLIENT_AUTHORITIES = "client_authorities"; private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); private boolean includeGrantType; /** * Converter for the part of the data in the token representing a user. * * @param userTokenConverter the userTokenConverter to set */ public void setUserTokenConverter(UserAuthenticationConverter userTokenConverter) { this.userTokenConverter = userTokenConverter; } /** * Flag to indicate the the grant type should be included in the converted token. * * @param includeGrantType the flag value (default false) */ public void setIncludeGrantType(boolean includeGrantType) { this.includeGrantType = includeGrantType; } public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); OAuth2Request clientToken = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) { response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); ///增加对client Authorities支持 if (authentication.getOAuth2Request().getAuthorities() != null && !authentication.getOAuth2Request().getAuthorities().isEmpty()) { response.put(CLIENT_AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getOAuth2Request().getAuthorities())); } ///结束增加对client Authorities支持 } else { if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) { response.put(UserAuthenticationConverter.AUTHORITIES, AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); } } if (token.getScope() != null) { response.put(SCOPE, token.getScope()); } if (token.getAdditionalInformation().containsKey(JTI)) { response.put(JTI, token.getAdditionalInformation().get(JTI)); } if (token.getExpiration() != null) { response.put(EXP, token.getExpiration().getTime() / 1000); } if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) { response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); } response.putAll(token.getAdditionalInformation()); response.put(CLIENT_ID, clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { response.put(AUD, clientToken.getResourceIds()); } return response; } public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value); Map<String, Object> info = new HashMap<String, Object>(map); info.remove(EXP); info.remove(AUD); info.remove(CLIENT_ID); info.remove(SCOPE); if (map.containsKey(EXP)) { token.setExpiration(new Date((Long) map.get(EXP) * 1000L)); } if (map.containsKey(JTI)) { info.put(JTI, map.get(JTI)); } token.setScope(extractScope(map)); token.setAdditionalInformation(info); return token; } public OAuth2Authentication extractAuthentication(Map<String, ?> map) { Map<String, String> parameters = new HashMap<String, String>(); Set<String> scope = extractScope(map); Authentication user = userTokenConverter.extractAuthentication(map); String clientId = (String) map.get(CLIENT_ID); parameters.put(CLIENT_ID, clientId); if (includeGrantType && map.containsKey(GRANT_TYPE)) { parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); } Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? getAudience(map) : Collections.<String>emptySet()); Collection<? extends GrantedAuthority> authorities = null; if (user == null && map.containsKey(AUTHORITIES)) { @SuppressWarnings("unchecked") String[] roles = ((Collection<String>) map.get(AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(roles); } ///增加对client Authorities支持 if (user != null && map.containsKey(CLIENT_AUTHORITIES)) { String[] clentRoles = ((Collection<String>) map.get(CLIENT_AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(clentRoles); ///增加额外属性 parameters.put("mobile", (String) map.get("mobile")); parameters.put("tenant_id", (String) map.get("tenant_id")); parameters.put("department_id", (String) map.get("department_id")); parameters.put("user_authorities", JSON.toJSONString(map.get("user_authorities"))); parameters.put("payload", JSON.toJSONString(map.get("payload"))); ///结束增加额外属性 } ///结束增加对client Authorities支持 OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, null); return new OAuth2Authentication(request, user); } private Collection<String> getAudience(Map<String, ?> map) { Object auds = map.get(AUD); if (auds instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> result = (Collection<String>) auds; return result; } return Collections.singleton((String) auds); } private Set<String> extractScope(Map<String, ?> map) { Set<String> scope = Collections.emptySet(); if (map.containsKey(SCOPE)) { Object scopeObj = map.get(SCOPE); if (String.class.isInstance(scopeObj)) { scope = new LinkedHashSet<String>(Arrays.asList(String.class.cast(scopeObj).split(" "))); } else if (Collection.class.isAssignableFrom(scopeObj.getClass())) { @SuppressWarnings("unchecked") Collection<String> scopeColl = (Collection<String>) scopeObj; scope = new LinkedHashSet<String>(scopeColl); // Preserve ordering } } return scope; } }
package com.youlai.mall.oms.config; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.mall.oms.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("订单中心") .description("<div style='font-size:14px;color:red;'>订单提交、秒杀接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.mall.pms.config; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.mall.pms.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("商品中心") .description("<div style='font-size:14px;color:red;'>商品管理、库存、分类、品牌、规格、参数等接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.mall.sms.config; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.mall.sms.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("营销中心") .description("<div style='font-size:14px;color:red;'>首页广告接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.mall.ums.config; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.mall.ums.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("会员中心") .description("<div style='font-size:14px;color:red;'>会员管理、地址接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.admin.config; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) @Slf4j public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.admin.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("系统管理") .description("<div style='font-size:14px;color:red;'>用户、角色、部门、菜单、权限、字典、客户端接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.auth.config; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @Author haoxr * @Date 2021-02-25 15:36 * @Version 1.0.0 */ @Configuration @EnableSwagger2WebMvc public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.auth.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("OAuth2认证中心") .description("<div style='font-size:14px;color:red;'>OAuth2认证、注销、获取验签公钥接口</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.youlai.laboratory.base.config; import lombok.extern.slf4j.Slf4j; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:2256222053@qq.com">zc</a> * @data 2021/11/28 0028 11:19 */ @Configuration @EnableSwagger2WebMvc @Import(BeanValidatorPluginsConfiguration.class) @Slf4j public class SwaggerConfiguration { @Bean public Docket restApi() { //schema List<GrantType> grantTypes=new ArrayList<>(); //密码模式 String passwordTokenUrl="http://localhost:9999/youlai-auth/oauth/token"; ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl); grantTypes.add(resourceOwnerPasswordCredentialsGrant); OAuth oAuth=new OAuthBuilder().name("oauth2") .grantTypes(grantTypes).build(); //context //scope方位 List<AuthorizationScope> scopes=new ArrayList<>(); scopes.add(new AuthorizationScope("read","read resources")); scopes.add(new AuthorizationScope("write","write resources")); scopes.add(new AuthorizationScope("reads","read all resources")); scopes.add(new AuthorizationScope("writes","write all resources")); SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{})); SecurityContext securityContext=new SecurityContext(Lists.newArrayList(securityReference),PathSelectors.ant("/**")); //schemas List<SecurityScheme> securitySchemes=Lists.newArrayList(oAuth); //securyContext List<SecurityContext> securityContexts=Lists.newArrayList(securityContext); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.youlai.laboratory.**.controller")) .paths(PathSelectors.any()) .build() .securityContexts(securityContexts) .securitySchemes(securitySchemes) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("系统管理") .description("<div style='font-size:14px;color:red;'>提供学习canal,elasticsearch,jvm,mybatis,mysql,netty,rabbitmq,redis,seata,sentinel,spring的环境</div>") .termsOfServiceUrl("https://www.youlai.tech") .contact(new Contact("有来技术团队", "https://github.com/hxrui", "1490493387@qq.com")) .license("Open Source") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .version("1.0.0") .build(); } }
package com.zheng.api.server.jms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * MQ消费者 * Created by shuzheng on 2017/2/19. */ public class DefaultMessageQueueListener implements MessageListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class); @Autowired ThreadPoolTaskExecutor threadPoolTaskExecutor; @Override public void onMessage(final Message message) { // 使用线程池多线程处理 threadPoolTaskExecutor.execute(new Runnable() { @Override public void run() { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; try { LOGGER.info("消费:{}", textMessage.getText()); } catch (Exception e) { e.printStackTrace(); } } } }); } }
package com.zheng.cms.admin.jms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * MQ消费者 * Created by ZhangShuzheng on 2017/01/12. */ public class DefaultMessageQueueListener implements MessageListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class); @Autowired ThreadPoolTaskExecutor threadPoolTaskExecutor; @Override public void onMessage(final Message message) { // 使用线程池多线程处理 threadPoolTaskExecutor.execute(new Runnable() { @Override public void run() { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; try { LOGGER.info("消费消息:{}", textMessage.getText()); } catch (Exception e){ e.printStackTrace(); } } } }); } }
package com.zheng.cms.job.jms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * MQ消费者 * Created by ZhangShuzheng on 2016/11/24. */ public class DefaultMessageQueueListener implements MessageListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class); @Autowired ThreadPoolTaskExecutor threadPoolTaskExecutor; @Override public void onMessage(final Message message) { // 使用线程池多线程处理 threadPoolTaskExecutor.execute(new Runnable() { @Override public void run() { TextMessage textMessage = (TextMessage) message; try { String text = textMessage.getText(); LOGGER.info("消费:{}", text); } catch (Exception e) { e.printStackTrace(); } } }); } }
package com.zheng.cms.web.jms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * MQ消费者 * Created by ZhangShuzheng on 2016/11/24. */ public class DefaultMessageQueueListener implements MessageListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class); @Autowired ThreadPoolTaskExecutor threadPoolTaskExecutor; @Override public void onMessage(final Message message) { // 使用线程池多线程处理 threadPoolTaskExecutor.execute(new Runnable() { @Override public void run() { TextMessage textMessage = (TextMessage) message; try { String text = textMessage.getText(); LOGGER.info("消费:{}", text); } catch (Exception e) { e.printStackTrace(); } } }); } }
package cc.mrbird.febs.gateway.enhance.configure; import cc.mrbird.febs.common.core.entity.constant.FebsConstant; import cc.mrbird.febs.gateway.enhance.runner.FebsRouteEnhanceRunner; import cc.mrbird.febs.gateway.enhance.service.BlackListService; import cc.mrbird.febs.gateway.enhance.service.RateLimitRuleService; import cc.mrbird.febs.gateway.enhance.service.RouteEnhanceCacheService; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * @author MrBird */ @EnableAsync @Configuration @EnableReactiveMongoRepositories(basePackages = "cc.mrbird.febs.gateway.enhance.mapper") @ConditionalOnProperty(name = "febs.gateway.enhance", havingValue = "true") public class FebsRouteEnhanceConfigure { @Bean(FebsConstant.ASYNC_POOL) public ThreadPoolTaskExecutor asyncThreadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(20); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(30); executor.setThreadNamePrefix("Febs-Gateway-Async-Thread"); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Bean public ApplicationRunner febsRouteEnhanceRunner(RouteEnhanceCacheService cacheService, BlackListService blackListService, RateLimitRuleService rateLimitRuleService) { return new FebsRouteEnhanceRunner(cacheService, blackListService, rateLimitRuleService); } }
package cc.mrbird.febs.gateway.enhance.utils; import cc.mrbird.febs.common.core.entity.constant.FebsConstant; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; /** * 根据 IP获取地址 * * @author MrBird */ @Slf4j public abstract class AddressUtil { public static String getCityInfo(String ip) { DbSearcher searcher = null; try { String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath(); File file = new File(dbPath); if (!file.exists()) { String tmpDir = System.getProperties().getProperty(FebsConstant.JAVA_TEMP_DIR); dbPath = tmpDir + "ip.db"; file = new File(dbPath); InputStream resourceAsStream = AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db"); if (resourceAsStream != null) { FileUtils.copyInputStreamToFile(resourceAsStream, file); } } DbConfig config = new DbConfig(); searcher = new DbSearcher(config, file.getPath()); Method method = searcher.getClass().getMethod("btreeSearch", String.class); DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip); return dataBlock.getRegion(); } catch (Exception e) { log.warn("获取地址信息异常,{}", e.getMessage()); return StringUtils.EMPTY; } finally { if (searcher != null) { try { searcher.close(); } catch (IOException e) { log.error("ip2region searcher close error", e); } } } } }
package cc.mrbird.febs.server.job.configure; import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; import lombok.RequiredArgsConstructor; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.jdbcjobstore.JobStoreTX; import org.quartz.simpl.SimpleThreadPool; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import javax.sql.DataSource; import java.util.Properties; import java.util.concurrent.ThreadPoolExecutor; /** * 定时任务配置 * http://www.quartz-scheduler.org/documentation/quartz-2.3.0/configuration/ * * @author MrBird */ @Configuration @RequiredArgsConstructor public class FebsJobConfigure { private final DynamicRoutingDataSource dynamicRoutingDataSource; @Bean public ThreadPoolTaskExecutor scheduleJobExecutorService() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(20); executor.setKeepAliveSeconds(30); executor.setThreadNamePrefix("Febs-Job-Thread"); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Bean public SchedulerFactoryBean schedulerFactoryBean() { SchedulerFactoryBean factory = new SchedulerFactoryBean(); // 设置数据源 DataSource job = dynamicRoutingDataSource.getDataSource("job"); factory.setDataSource(job); Properties prop = new Properties(); // 任务调度实例名称,集群时多个实例名称保持一致 prop.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, "FebsCloudScheduler"); // 任务调度实例ID,指定为AUTO时,将自动生成ID prop.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_ID, StdSchedulerFactory.AUTO_GENERATE_INSTANCE_ID); // quartz提供的简单线程池,适用于绝大部分场景 prop.put(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, SimpleThreadPool.class); // 并发执行任务的线程数,取决于服务器系统资源 prop.put("org.quartz.threadPool.threadCount", "20"); // 可以是Thread.MIN_PRIORITY(1)和Thread.MAX_PRIORITY(10)之间的任何int值 。 // 默认值为Thread.NORM_PRIORITY(5) prop.put("org.quartz.threadPool.threadPriority", "5"); // 指定任务存储策略,这里使用关系型数据库 prop.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, JobStoreTX.class); // 是否开启集群 prop.put("org.quartz.jobStore.isClustered", "true"); // 集群中任务调度实例失效的检查时间间隔,单位为毫秒 prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000"); prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); prop.put("org.quartz.jobStore.misfireThreshold", "12000"); // 数据表前缀 prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_"); factory.setQuartzProperties(prop); factory.setSchedulerName("FEBS_Cloud_Scheduler"); // 延时启动 factory.setStartupDelay(1); factory.setApplicationContextSchedulerContextKey("applicationContextKey"); // 启动时更新己存在的 Job factory.setOverwriteExistingJobs(true); // 设置自动启动,默认为 true factory.setAutoStartup(true); return factory; } }
package cc.mrbird.febs.server.system.configure; import cc.mrbird.febs.common.core.entity.constant.FebsConstant; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * @author MrBird */ @Configuration public class FebsWebConfigure { /** * 注册异步线程池 */ @Bean(FebsConstant.ASYNC_POOL) public ThreadPoolTaskExecutor asyncThreadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(20); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(30); executor.setThreadNamePrefix("Febs-Async-Thread"); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
package cc.mrbird.febs.server.system.utils; import cc.mrbird.febs.common.core.entity.constant.FebsConstant; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; /** * 根据 IP获取地址 * * @author MrBird */ @Slf4j public abstract class AddressUtil { public static String getCityInfo(String ip) { DbSearcher searcher = null; try { String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath(); File file = new File(dbPath); if (!file.exists()) { String tmpDir = System.getProperties().getProperty(FebsConstant.JAVA_TEMP_DIR); dbPath = tmpDir + "ip.db"; file = new File(dbPath); InputStream resourceAsStream = AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db"); if (resourceAsStream != null) { FileUtils.copyInputStreamToFile(resourceAsStream, file); } } DbConfig config = new DbConfig(); searcher = new DbSearcher(config, file.getPath()); Method method = searcher.getClass().getMethod("btreeSearch", String.class); DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip); return dataBlock.getRegion(); } catch (Exception e) { log.warn("获取地址信息异常,{}", e.getMessage()); return StringUtils.EMPTY; } finally { if (searcher != null) { try { searcher.close(); } catch (IOException e) { log.error("ip2region searcher close error", e); } } } } }
package com.gpmall.comment.utils;/** * Created by mic on 2019/8/1. */ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.redisson.RedissonScript; import org.redisson.api.RScript; import org.redisson.api.RedissonClient; import org.redisson.codec.JsonJacksonCodec; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/8/1-下午9:40 */ @Slf4j @Component public class GlobalIdGeneratorUtil { private static final FastDateFormat seqDateFormat = FastDateFormat.getInstance("yyMMddHHmmssSSS"); @Autowired RedissonClient redissonClient; private String keyName; private int incrby; private String sha1; private String luaScript="local function get_max_seq()\n" + " local key = tostring(KEYS[1])\n" + " local incr_amoutt = tonumber(KEYS[2])\n" + " local seq = tostring(KEYS[3])\n" + " local month_in_seconds = 24 * 60 * 60 * 30\n" + " if (1 == redis.call('setnx', key, seq))\n" + " then\n" + " redis.call('expire', key, month_in_seconds)\n" + " return seq\n" + " else\n" + " local prev_seq = redis.call('get', key)\n" + " if (prev_seq < seq)\n" + " then\n" + " redis.call('set', key, seq)\n" + " return seq\n" + " else\n" + " redis.call('incrby', key, incr_amoutt)\n" + " return redis.call('get', key)\n" + " end\n" + " end\n" + "end\n" + "return get_max_seq()"; public GlobalIdGeneratorUtil() throws IOException { } @PostConstruct private void init() throws Exception { sha1 = redissonClient.getScript().scriptLoad(luaScript); } public String getNextSeq(String keyName, int incrby) { if(StringUtils.isBlank(keyName)||incrby<0) { throw new RuntimeException("参数不正确"); } this.keyName=keyName; this.incrby=incrby; try { return getMaxSeq(); }catch (Exception e){//如果redis出现故障,则采用uuid e.printStackTrace(); return UUID.randomUUID().toString().replace("-",""); } } private String generateSeq() { String seqDate = seqDateFormat.format(System.currentTimeMillis()); String candidateSeq = new StringBuilder(17).append(seqDate).append(RandomStringUtils.randomNumeric(2)).toString(); return candidateSeq; } public String getMaxSeq() throws ExecutionException, InterruptedException { List<Object> keys= Arrays.asList(keyName,incrby,generateSeq()); RedissonScript rScript=(RedissonScript) redissonClient.getScript(); //这里遇到一个bug,默认情况下使用evalSha,不加Codec属性时,会报错。这个错误很神奇。花了3个小时才搞定。 Long seqNext=rScript.evalSha(RScript.Mode.READ_ONLY, JsonJacksonCodec.INSTANCE,sha1, RScript.ReturnType.VALUE,keys); return seqNext.toString(); } }
package com.gpmall.order.utils;/** * Created by mic on 2019/8/1. */ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.redisson.RedissonScript; import org.redisson.api.RScript; import org.redisson.api.RedissonClient; import org.redisson.codec.JsonJacksonCodec; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/8/1-下午9:40 */ @Slf4j @Component public class GlobalIdGeneratorUtil { private static final FastDateFormat seqDateFormat = FastDateFormat.getInstance("yyMMddHHmmssSSS"); @Autowired RedissonClient redissonClient; private String keyName; private int incrby; private String sha1; private String luaScript="local function get_max_seq()\n" + " local key = tostring(KEYS[1])\n" + " local incr_amoutt = tonumber(KEYS[2])\n" + " local seq = tostring(KEYS[3])\n" + " local month_in_seconds = 24 * 60 * 60 * 30\n" + " if (1 == redis.call('setnx', key, seq))\n" + " then\n" + " redis.call('expire', key, month_in_seconds)\n" + " return seq\n" + " else\n" + " local prev_seq = redis.call('get', key)\n" + " if (prev_seq < seq)\n" + " then\n" + " redis.call('set', key, seq)\n" + " return seq\n" + " else\n" + " redis.call('incrby', key, incr_amoutt)\n" + " return redis.call('get', key)\n" + " end\n" + " end\n" + "end\n" + "return get_max_seq()"; public GlobalIdGeneratorUtil() throws IOException { } @PostConstruct private void init() throws Exception { sha1 = redissonClient.getScript().scriptLoad(luaScript); } public String getNextSeq(String keyName, int incrby) { if(StringUtils.isBlank(keyName)||incrby<0) { throw new RuntimeException("参数不正确"); } this.keyName=keyName; this.incrby=incrby; try { return getMaxSeq(); }catch (Exception e){//如果redis出现故障,则采用uuid e.printStackTrace(); return UUID.randomUUID().toString().replace("-",""); } } private String generateSeq() { String seqDate = seqDateFormat.format(System.currentTimeMillis()); String candidateSeq = new StringBuilder(17).append(seqDate).append(RandomStringUtils.randomNumeric(2)).toString(); return candidateSeq; } public String getMaxSeq() throws ExecutionException, InterruptedException { List<Object> keys= Arrays.asList(keyName,incrby,generateSeq()); RedissonScript rScript=(RedissonScript) redissonClient.getScript(); //这里遇到一个bug,默认情况下使用evalSha,不加Codec属性时,会报错。这个错误很神奇。花了3个小时才搞定。 Long seqNext=rScript.evalSha(RScript.Mode.READ_ONLY, JsonJacksonCodec.INSTANCE,sha1, RScript.ReturnType.VALUE,keys); return seqNext.toString(); } }
package com.gpmall.pay.utils;/** * Created by mic on 2019/8/1. */ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.redisson.RedissonScript; import org.redisson.api.RScript; import org.redisson.api.RedissonClient; import org.redisson.codec.JsonJacksonCodec; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/8/1-下午9:40 */ @Slf4j @Component public class GlobalIdGeneratorUtil { private static final FastDateFormat seqDateFormat = FastDateFormat.getInstance("yyMMddHHmmssSSS"); @Autowired RedissonClient redissonClient; private String keyName; private int incrby; private String sha1; private String luaScript="local function get_max_seq()\n" + " local key = tostring(KEYS[1])\n" + " local incr_amoutt = tonumber(KEYS[2])\n" + " local seq = tostring(KEYS[3])\n" + " local month_in_seconds = 24 * 60 * 60 * 30\n" + " if (1 == redis.call('setnx', key, seq))\n" + " then\n" + " redis.call('expire', key, month_in_seconds)\n" + " return seq\n" + " else\n" + " local prev_seq = redis.call('get', key)\n" + " if (prev_seq < seq)\n" + " then\n" + " redis.call('set', key, seq)\n" + " return seq\n" + " else\n" + " redis.call('incrby', key, incr_amoutt)\n" + " return redis.call('get', key)\n" + " end\n" + " end\n" + "end\n" + "return get_max_seq()"; public GlobalIdGeneratorUtil() throws IOException { } @PostConstruct private void init() throws Exception { sha1 = redissonClient.getScript().scriptLoad(luaScript); } public String getNextSeq(String keyName, int incrby) { if(StringUtils.isBlank(keyName)||incrby<0) { throw new RuntimeException("参数不正确"); } this.keyName=keyName; this.incrby=incrby; try { return getMaxSeq(); }catch (Exception e){//如果redis出现故障,则采用uuid e.printStackTrace(); return UUID.randomUUID().toString().replace("-",""); } } private String generateSeq() { String seqDate = seqDateFormat.format(System.currentTimeMillis()); String candidateSeq = new StringBuilder(17).append(seqDate).append(RandomStringUtils.randomNumeric(2)).toString(); return candidateSeq; } public String getMaxSeq() throws ExecutionException, InterruptedException { List<Object> keys= Arrays.asList(keyName,incrby,generateSeq()); RedissonScript rScript=(RedissonScript) redissonClient.getScript(); //这里遇到一个bug,默认情况下使用evalSha,不加Codec属性时,会报错。这个错误很神奇。花了3个小时才搞定。 Long seqNext=rScript.evalSha(RScript.Mode.READ_ONLY, JsonJacksonCodec.INSTANCE,sha1, RScript.ReturnType.VALUE,keys); return seqNext.toString(); } }
package cn.zealon.readingcloud.account.common.config; import com.github.pagehelper.PageHelper; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import javax.sql.DataSource; import java.util.Properties; /** * MyBatis配置 * @author: zealon * @since: 2020/4/2 */ @Configuration @MapperScan(basePackages = "cn.zealon.readingcloud.account.dao", sqlSessionTemplateRef="accountCenterSqlSessionTemplate") public class MybatisConfig { private final static String MAPPER_LOCATIONS = "classpath*:mappers/*.xml"; /** 工厂配置 */ @Bean public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("accountCenterDataSource") DataSource dataSource) throws Exception { // 设置数据源 SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 添加XML映射 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources(MAPPER_LOCATIONS)); //添加插件 factory.setPlugins(new Interceptor[]{ this.getPageHelper() }); return factory.getObject(); } /** 会话模板 */ @Bean(name = "accountCenterSqlSessionTemplate") public SqlSessionTemplate setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } /** 分页插件 */ private PageHelper getPageHelper(){ //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("pageSizeZero", "true"); //页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("reasonable", "true"); //支持通过 Mapper 接口参数来传递分页参数 properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("params", "count=countSql"); //切换数据源,自动解析不同数据库的分页 properties.setProperty("autoRuntimeDialect", "true"); pageHelper.setProperties(properties); return pageHelper; } /** * swagger 配置类 * http://localhost:8080/swagger-ui.html * @author zealon * @since 2019-07-04 */ @Configuration @EnableSwagger2 public static class AccountSwaggerConfig { /** * swagger生成 * @return Docket */ @Bean public Docket customDocket() { Docket docket = new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("cn.zealon.readingcloud.account.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); return docket; } /** * swagger基础信息 * @return ApiInfo swagger信息 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("账户中心接口") .description("账户中心") .termsOfServiceUrl("") .contact(new Contact("", "", "")) .license("") .licenseUrl("") .version("1.0.0") .build(); } } }
package cn.zealon.readingcloud.account.common.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.*; import java.lang.reflect.Method; import java.time.Duration; /** * 基础redis配置 * @author: zealon * @since: 2020/4/2 */ @EnableCaching @Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redis = new RedisTemplate<>(); redis.setConnectionFactory(redisConnectionFactory); this.setSerializer(redis); return redis; } /** 配置Key的生成方式 */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(o.getClass().getName()).append(method.getName()); for (Object object : objects) { stringBuilder.append(object.toString()); } return stringBuilder.toString(); } }; } /** 缓存管理器 */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); //设置默认超过期时间是30秒 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(300)); //初始化RedisCacheManager return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } /** 设置RedisTemplate的序列化方式 */ public void setSerializer(RedisTemplate redisTemplate) { StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //设置键(key)的序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); //设置值(value)的序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); } }
package cn.zealon.readingcloud.book.common.config; import com.github.pagehelper.PageHelper; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.apache.ibatis.plugin.Interceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; import java.util.Properties; /** * MyBatis配置 * @author: zealon * @since: 2020/4/2 */ @Configuration @MapperScan(basePackages = "cn.zealon.readingcloud.book.dao", sqlSessionTemplateRef="bookCenterSqlSessionTemplate") public class MybatisConfig { private final static String MAPPER_LOCATIONS = "classpath*:mappers/*.xml"; /** 工厂配置 */ @Bean public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("bookCenterDataSource") DataSource dataSource) throws Exception { // 设置数据源 SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 添加XML映射 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources(MAPPER_LOCATIONS)); //添加插件 factory.setPlugins(new Interceptor[]{ this.getPageHelper() }); return factory.getObject(); } /** 会话模板 */ @Bean(name = "bookCenterSqlSessionTemplate") public SqlSessionTemplate setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } /** 分页插件 */ private PageHelper getPageHelper(){ //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("pageSizeZero", "true"); //页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("reasonable", "true"); //支持通过 Mapper 接口参数来传递分页参数 properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("params", "count=countSql"); //切换数据源,自动解析不同数据库的分页 properties.setProperty("autoRuntimeDialect", "true"); pageHelper.setProperties(properties); return pageHelper; } }
package cn.zealon.readingcloud.book.common.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.*; import java.lang.reflect.Method; import java.time.Duration; /** * 基础redis配置 * @author: zealon * @since: 2020/4/2 */ @EnableCaching @Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redis = new RedisTemplate<>(); redis.setConnectionFactory(redisConnectionFactory); this.setSerializer(redis); return redis; } /** 配置Key的生成方式 */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(o.getClass().getName()).append(method.getName()); for (Object object : objects) { stringBuilder.append(object.toString()); } return stringBuilder.toString(); } }; } /** 缓存管理器 */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); //设置默认超过期时间是30秒 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(300)); //初始化RedisCacheManager return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } /** 设置RedisTemplate的序列化方式 */ public void setSerializer(RedisTemplate redisTemplate) { StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //设置键(key)的序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); //设置值(value)的序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); } }
package cn.zealon.readingcloud.homepage.common.config; import com.github.pagehelper.PageHelper; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; import java.util.Properties; /** * MyBatis配置 * @author: zealon * @since: 2020/4/2 */ @Configuration @MapperScan(basePackages = "cn.zealon.readingcloud.homepage.dao", sqlSessionTemplateRef="bookCenterSqlSessionTemplate") public class MybatisConfig { private final static String MAPPER_LOCATIONS = "classpath*:mappers/*.xml"; /** 工厂配置 */ @Bean public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("bookCenterDataSource") DataSource dataSource) throws Exception { // 设置数据源 SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 添加XML映射 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources(MAPPER_LOCATIONS)); //添加插件 factory.setPlugins(new Interceptor[]{ this.getPageHelper() }); return factory.getObject(); } /** 会话模板 */ @Bean(name = "bookCenterSqlSessionTemplate") public SqlSessionTemplate setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } /** 分页插件 */ private PageHelper getPageHelper(){ //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("pageSizeZero", "true"); //页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("reasonable", "false"); //支持通过 Mapper 接口参数来传递分页参数 properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("params", "count=countSql"); //切换数据源,自动解析不同数据库的分页 properties.setProperty("autoRuntimeDialect", "true"); pageHelper.setProperties(properties); return pageHelper; } }
package cn.zealon.readingcloud.homepage.common.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.*; import java.lang.reflect.Method; import java.time.Duration; /** * 基础redis配置 * @author: zealon * @since: 2020/4/2 */ @EnableCaching @Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redis = new RedisTemplate<>(); redis.setConnectionFactory(redisConnectionFactory); this.setSerializer(redis); return redis; } /** 配置Key的生成方式 */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(o.getClass().getName()).append(method.getName()); for (Object object : objects) { stringBuilder.append(object.toString()); } return stringBuilder.toString(); } }; } /** 缓存管理器 */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); //设置CacheManager的值序列化方式为json序列化 RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer); RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); //设置默认超过期时间是30秒 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(300)); //初始化RedisCacheManager return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } /** 设置RedisTemplate的序列化方式 */ public void setSerializer(RedisTemplate redisTemplate) { StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //设置键(key)的序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); //设置值(value)的序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); } }
package com.xxl.job.core.enums; /** * Created by xuxueli on 17/5/9. */ public enum ExecutorBlockStrategyEnum { SERIAL_EXECUTION("Serial execution"), /*CONCURRENT_EXECUTION("并行"),*/ DISCARD_LATER("Discard Later"), COVER_EARLY("Cover Early"); private String title; private ExecutorBlockStrategyEnum (String title) { this.title = title; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public static ExecutorBlockStrategyEnum match(String name, ExecutorBlockStrategyEnum defaultItem) { if (name != null) { for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) { if (item.name().equals(name)) { return item; } } } return defaultItem; } }
package com.xxl.job.core.thread; import com.xxl.job.core.biz.AdminBiz; import com.xxl.job.core.biz.model.RegistryParam; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.enums.RegistryConfig; import com.xxl.job.core.executor.XxlJobExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * Created by xuxueli on 17/3/2. */ public class ExecutorRegistryThread { private static Logger logger = LoggerFactory.getLogger(ExecutorRegistryThread.class); private static ExecutorRegistryThread instance = new ExecutorRegistryThread(); public static ExecutorRegistryThread getInstance(){ return instance; } private Thread registryThread; private volatile boolean toStop = false; public void start(final String appname, final String address){ // valid if (appname==null || appname.trim().length()==0) { logger.warn(">>>>>>>>>>> xxl-job, executor registry config fail, appname is null."); return; } if (XxlJobExecutor.getAdminBizList() == null) { logger.warn(">>>>>>>>>>> xxl-job, executor registry config fail, adminAddresses is null."); return; } registryThread = new Thread(new Runnable() { @Override public void run() { // registry while (!toStop) { try { RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appname, address); for (AdminBiz adminBiz: XxlJobExecutor.getAdminBizList()) { try { ReturnT<String> registryResult = adminBiz.registry(registryParam); if (registryResult!=null && ReturnT.SUCCESS_CODE == registryResult.getCode()) { registryResult = ReturnT.SUCCESS; logger.debug(">>>>>>>>>>> xxl-job registry success, registryParam:{}, registryResult:{}", new Object[]{registryParam, registryResult}); break; } else { logger.info(">>>>>>>>>>> xxl-job registry fail, registryParam:{}, registryResult:{}", new Object[]{registryParam, registryResult}); } } catch (Exception e) { logger.info(">>>>>>>>>>> xxl-job registry error, registryParam:{}", registryParam, e); } } } catch (Exception e) { if (!toStop) { logger.error(e.getMessage(), e); } } try { if (!toStop) { TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT); } } catch (InterruptedException e) { if (!toStop) { logger.warn(">>>>>>>>>>> xxl-job, executor registry thread interrupted, error msg:{}", e.getMessage()); } } } // registry remove try { RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appname, address); for (AdminBiz adminBiz: XxlJobExecutor.getAdminBizList()) { try { ReturnT<String> registryResult = adminBiz.registryRemove(registryParam); if (registryResult!=null && ReturnT.SUCCESS_CODE == registryResult.getCode()) { registryResult = ReturnT.SUCCESS; logger.info(">>>>>>>>>>> xxl-job registry-remove success, registryParam:{}, registryResult:{}", new Object[]{registryParam, registryResult}); break; } else { logger.info(">>>>>>>>>>> xxl-job registry-remove fail, registryParam:{}, registryResult:{}", new Object[]{registryParam, registryResult}); } } catch (Exception e) { if (!toStop) { logger.info(">>>>>>>>>>> xxl-job registry-remove error, registryParam:{}", registryParam, e); } } } } catch (Exception e) { if (!toStop) { logger.error(e.getMessage(), e); } } logger.info(">>>>>>>>>>> xxl-job, executor registry thread destory."); } }); registryThread.setDaemon(true); registryThread.setName("xxl-job, executor ExecutorRegistryThread"); registryThread.start(); } public void toStop() { toStop = true; // interrupt and wait if (registryThread != null) { registryThread.interrupt(); try { registryThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } } }
package com.xxl.job.core.thread; import com.xxl.job.core.log.XxlJobFileAppender; import com.xxl.job.core.util.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; /** * job file clean thread * * @author xuxueli 2017-12-29 16:23:43 */ public class JobLogFileCleanThread { private static Logger logger = LoggerFactory.getLogger(JobLogFileCleanThread.class); private static JobLogFileCleanThread instance = new JobLogFileCleanThread(); public static JobLogFileCleanThread getInstance(){ return instance; } private Thread localThread; private volatile boolean toStop = false; public void start(final long logRetentionDays){ // limit min value if (logRetentionDays < 3 ) { return; } localThread = new Thread(new Runnable() { @Override public void run() { while (!toStop) { try { // clean log dir, over logRetentionDays File[] childDirs = new File(XxlJobFileAppender.getLogPath()).listFiles(); if (childDirs!=null && childDirs.length>0) { // today Calendar todayCal = Calendar.getInstance(); todayCal.set(Calendar.HOUR_OF_DAY,0); todayCal.set(Calendar.MINUTE,0); todayCal.set(Calendar.SECOND,0); todayCal.set(Calendar.MILLISECOND,0); Date todayDate = todayCal.getTime(); for (File childFile: childDirs) { // valid if (!childFile.isDirectory()) { continue; } if (childFile.getName().indexOf("-") == -1) { continue; } // file create date Date logFileCreateDate = null; try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); logFileCreateDate = simpleDateFormat.parse(childFile.getName()); } catch (ParseException e) { logger.error(e.getMessage(), e); } if (logFileCreateDate == null) { continue; } if ((todayDate.getTime()-logFileCreateDate.getTime()) >= logRetentionDays * (24 * 60 * 60 * 1000) ) { FileUtil.deleteRecursively(childFile); } } } } catch (Exception e) { if (!toStop) { logger.error(e.getMessage(), e); } } try { TimeUnit.DAYS.sleep(1); } catch (InterruptedException e) { if (!toStop) { logger.error(e.getMessage(), e); } } } logger.info(">>>>>>>>>>> xxl-job, executor JobLogFileCleanThread thread destory."); } }); localThread.setDaemon(true); localThread.setName("xxl-job, executor JobLogFileCleanThread"); localThread.start(); } public void toStop() { toStop = true; if (localThread == null) { return; } // interrupt and wait localThread.interrupt(); try { localThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } }
package vip.mate.core.security.config; import lombok.RequiredArgsConstructor; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.core.annotation.Order; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import vip.mate.core.security.handle.MateAccessDeniedHandler; import vip.mate.core.security.handle.MateAuthenticationEntryPoint; /** * 资源服务配置 * * @author pangu */ @Order(5) @EnableResourceServer @RequiredArgsConstructor @EnableAutoConfiguration(exclude = UserDetailsServiceAutoConfiguration.class) public class MateResourceServerConfig extends ResourceServerConfigurerAdapter { private final IgnoreUrlPropsConfiguration ignoreUrlPropsConfig; private final RedisConnectionFactory redisConnectionFactory; /** * 配置token存储到redis中 */ @Bean public RedisTokenStore redisTokenStore() { return new RedisTokenStore(redisConnectionFactory); } @Override public void configure(HttpSecurity http) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config = http.requestMatchers().anyRequest() .and() .authorizeRequests(); ignoreUrlPropsConfig.getUrls().forEach(url -> { config.antMatchers(url).permitAll(); }); ignoreUrlPropsConfig.getIgnoreSecurity().forEach(url -> { config.antMatchers(url).permitAll(); }); config //任何请求 .anyRequest() //都需要身份认证 .authenticated() //csrf跨站请求 .and() .csrf().disable(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.authenticationEntryPoint(new MateAuthenticationEntryPoint()) .accessDeniedHandler(new MateAccessDeniedHandler()); } }
package com.xxl.job.admin.core.route; import com.xxl.job.admin.core.route.strategy.*; import com.xxl.job.admin.core.util.I18nUtil; /** * Created by xuxueli on 17/3/10. */ public enum ExecutorRouteStrategyEnum { FIRST(I18nUtil.getString("jobconf_route_first"), new ExecutorRouteFirst()), LAST(I18nUtil.getString("jobconf_route_last"), new ExecutorRouteLast()), ROUND(I18nUtil.getString("jobconf_route_round"), new ExecutorRouteRound()), RANDOM(I18nUtil.getString("jobconf_route_random"), new ExecutorRouteRandom()), CONSISTENT_HASH(I18nUtil.getString("jobconf_route_consistenthash"), new ExecutorRouteConsistentHash()), LEAST_FREQUENTLY_USED(I18nUtil.getString("jobconf_route_lfu"), new ExecutorRouteLFU()), LEAST_RECENTLY_USED(I18nUtil.getString("jobconf_route_lru"), new ExecutorRouteLRU()), FAILOVER(I18nUtil.getString("jobconf_route_failover"), new ExecutorRouteFailover()), BUSYOVER(I18nUtil.getString("jobconf_route_busyover"), new ExecutorRouteBusyover()), SHARDING_BROADCAST(I18nUtil.getString("jobconf_route_shard"), null); ExecutorRouteStrategyEnum(String title, ExecutorRouter router) { this.title = title; this.router = router; } private String title; private ExecutorRouter router; public String getTitle() { return title; } public ExecutorRouter getRouter() { return router; } public static ExecutorRouteStrategyEnum match(String name, ExecutorRouteStrategyEnum defaultItem){ if (name != null) { for (ExecutorRouteStrategyEnum item: ExecutorRouteStrategyEnum.values()) { if (item.name().equals(name)) { return item; } } } return defaultItem; } }
package com.xxl.job.admin.core.thread; import com.xxl.job.admin.core.complete.XxlJobCompleter; import com.xxl.job.admin.core.conf.XxlJobAdminConfig; import com.xxl.job.admin.core.model.XxlJobLog; import com.xxl.job.admin.core.util.I18nUtil; import com.xxl.job.core.biz.model.HandleCallbackParam; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.util.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; import java.util.concurrent.*; /** * job lose-monitor instance * * @author xuxueli 2015-9-1 18:05:56 */ public class JobCompleteHelper { private static Logger logger = LoggerFactory.getLogger(JobCompleteHelper.class); private static JobCompleteHelper instance = new JobCompleteHelper(); public static JobCompleteHelper getInstance(){ return instance; } // ---------------------- monitor ---------------------- private ThreadPoolExecutor callbackThreadPool = null; private Thread monitorThread; private volatile boolean toStop = false; public void start(){ // for callback callbackThreadPool = new ThreadPoolExecutor( 2, 20, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3000), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "xxl-job, admin JobLosedMonitorHelper-callbackThreadPool-" + r.hashCode()); } }, new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { r.run(); logger.warn(">>>>>>>>>>> xxl-job, callback too fast, match threadpool rejected handler(run now)."); } }); // for monitor monitorThread = new Thread(new Runnable() { @Override public void run() { // wait for JobTriggerPoolHelper-init try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { if (!toStop) { logger.error(e.getMessage(), e); } } // monitor while (!toStop) { try { // 任务结果丢失处理:调度记录停留在 "运行中" 状态超过10min,且对应执行器心跳注册失败不在线,则将本地调度主动标记失败; Date losedTime = DateUtil.addMinutes(new Date(), -10); List<Long> losedJobIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findLostJobIds(losedTime); if (losedJobIds!=null && losedJobIds.size()>0) { for (Long logId: losedJobIds) { XxlJobLog jobLog = new XxlJobLog(); jobLog.setId(logId); jobLog.setHandleTime(new Date()); jobLog.setHandleCode(ReturnT.FAIL_CODE); jobLog.setHandleMsg( I18nUtil.getString("joblog_lost_fail") ); XxlJobCompleter.updateHandleInfoAndFinish(jobLog); } } } catch (Exception e) { if (!toStop) { logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e); } } try { TimeUnit.SECONDS.sleep(60); } catch (Exception e) { if (!toStop) { logger.error(e.getMessage(), e); } } } logger.info(">>>>>>>>>>> xxl-job, JobLosedMonitorHelper stop"); } }); monitorThread.setDaemon(true); monitorThread.setName("xxl-job, admin JobLosedMonitorHelper"); monitorThread.start(); } public void toStop(){ toStop = true; // stop registryOrRemoveThreadPool callbackThreadPool.shutdownNow(); // stop monitorThread (interrupt and wait) monitorThread.interrupt(); try { monitorThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } // ---------------------- helper ---------------------- public ReturnT<String> callback(List<HandleCallbackParam> callbackParamList) { callbackThreadPool.execute(new Runnable() { @Override public void run() { for (HandleCallbackParam handleCallbackParam: callbackParamList) { ReturnT<String> callbackResult = callback(handleCallbackParam); logger.debug(">>>>>>>>> JobApiController.callback {}, handleCallbackParam={}, callbackResult={}", (callbackResult.getCode()== ReturnT.SUCCESS_CODE?"success":"fail"), handleCallbackParam, callbackResult); } } }); return ReturnT.SUCCESS; } private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) { // valid log item XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(handleCallbackParam.getLogId()); if (log == null) { return new ReturnT<String>(ReturnT.FAIL_CODE, "log item not found."); } if (log.getHandleCode() > 0) { return new ReturnT<String>(ReturnT.FAIL_CODE, "log repeate callback."); // avoid repeat callback, trigger child job etc } // handle msg StringBuffer handleMsg = new StringBuffer(); if (log.getHandleMsg()!=null) { handleMsg.append(log.getHandleMsg()).append("<br>"); } if (handleCallbackParam.getHandleMsg() != null) { handleMsg.append(handleCallbackParam.getHandleMsg()); } // success, save log log.setHandleTime(new Date()); log.setHandleCode(handleCallbackParam.getHandleCode()); log.setHandleMsg(handleMsg.toString()); XxlJobCompleter.updateHandleInfoAndFinish(log); return ReturnT.SUCCESS; } }
package com.xxl.job.admin.core.thread; import com.xxl.job.admin.core.conf.XxlJobAdminConfig; import com.xxl.job.admin.core.model.XxlJobGroup; import com.xxl.job.admin.core.model.XxlJobRegistry; import com.xxl.job.core.biz.model.RegistryParam; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.enums.RegistryConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.util.*; import java.util.concurrent.*; /** * job registry instance * @author xuxueli 2016-10-02 19:10:24 */ public class JobRegistryHelper { private static Logger logger = LoggerFactory.getLogger(JobRegistryHelper.class); private static JobRegistryHelper instance = new JobRegistryHelper(); public static JobRegistryHelper getInstance(){ return instance; } private ThreadPoolExecutor registryOrRemoveThreadPool = null; private Thread registryMonitorThread; private volatile boolean toStop = false; public void start(){ // for registry or remove registryOrRemoveThreadPool = new ThreadPoolExecutor( 2, 10, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2000), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "xxl-job, admin JobRegistryMonitorHelper-registryOrRemoveThreadPool-" + r.hashCode()); } }, new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { r.run(); logger.warn(">>>>>>>>>>> xxl-job, registry or remove too fast, match threadpool rejected handler(run now)."); } }); // for monitor registryMonitorThread = new Thread(new Runnable() { @Override public void run() { while (!toStop) { try { // auto registry group List<XxlJobGroup> groupList = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().findByAddressType(0); if (groupList!=null && !groupList.isEmpty()) { // remove dead address (admin/executor) List<Integer> ids = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findDead(RegistryConfig.DEAD_TIMEOUT, new Date()); if (ids!=null && ids.size()>0) { XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().removeDead(ids); } // fresh online address (admin/executor) HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>(); List<XxlJobRegistry> list = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findAll(RegistryConfig.DEAD_TIMEOUT, new Date()); if (list != null) { for (XxlJobRegistry item: list) { if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) { String appname = item.getRegistryKey(); List<String> registryList = appAddressMap.get(appname); if (registryList == null) { registryList = new ArrayList<String>(); } if (!registryList.contains(item.getRegistryValue())) { registryList.add(item.getRegistryValue()); } appAddressMap.put(appname, registryList); } } } // fresh group address for (XxlJobGroup group: groupList) { List<String> registryList = appAddressMap.get(group.getAppname()); String addressListStr = null; if (registryList!=null && !registryList.isEmpty()) { Collections.sort(registryList); StringBuilder addressListSB = new StringBuilder(); for (String item:registryList) { addressListSB.append(item).append(","); } addressListStr = addressListSB.toString(); addressListStr = addressListStr.substring(0, addressListStr.length()-1); } group.setAddressList(addressListStr); group.setUpdateTime(new Date()); XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().update(group); } } } catch (Exception e) { if (!toStop) { logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e); } } try { TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT); } catch (InterruptedException e) { if (!toStop) { logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e); } } } logger.info(">>>>>>>>>>> xxl-job, job registry monitor thread stop"); } }); registryMonitorThread.setDaemon(true); registryMonitorThread.setName("xxl-job, admin JobRegistryMonitorHelper-registryMonitorThread"); registryMonitorThread.start(); } public void toStop(){ toStop = true; // stop registryOrRemoveThreadPool registryOrRemoveThreadPool.shutdownNow(); // stop monitir (interrupt and wait) registryMonitorThread.interrupt(); try { registryMonitorThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } // ---------------------- helper ---------------------- public ReturnT<String> registry(RegistryParam registryParam) { // valid if (!StringUtils.hasText(registryParam.getRegistryGroup()) || !StringUtils.hasText(registryParam.getRegistryKey()) || !StringUtils.hasText(registryParam.getRegistryValue())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument."); } // async execute registryOrRemoveThreadPool.execute(new Runnable() { @Override public void run() { int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryUpdate(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); if (ret < 1) { XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registrySave(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); // fresh freshGroupRegistryInfo(registryParam); } } }); return ReturnT.SUCCESS; } public ReturnT<String> registryRemove(RegistryParam registryParam) { // valid if (!StringUtils.hasText(registryParam.getRegistryGroup()) || !StringUtils.hasText(registryParam.getRegistryKey()) || !StringUtils.hasText(registryParam.getRegistryValue())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument."); } // async execute registryOrRemoveThreadPool.execute(new Runnable() { @Override public void run() { int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryDelete(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue()); if (ret > 0) { // fresh freshGroupRegistryInfo(registryParam); } } }); return ReturnT.SUCCESS; } private void freshGroupRegistryInfo(RegistryParam registryParam){ // Under consideration, prevent affecting core tables } }
/* * Copyright 2019-2028 Beijing Daotiandi Technology Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Author: xuzhanfu (7333791@qq.com) */ package vip.mate.uaa.config; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import vip.mate.core.security.config.IgnoreUrlPropsConfiguration; import vip.mate.core.security.handle.MateAuthenticationFailureHandler; import vip.mate.core.security.handle.MateAuthenticationSuccessHandler; import vip.mate.uaa.service.impl.UserDetailsServiceImpl; import vip.mate.uaa.sms.SmsCodeAuthenticationSecurityConfig; import vip.mate.uaa.social.SocialAuthenticationSecurityConfig; import javax.annotation.Resource; /** * 安全配置中心 * * @author xuzhanfu * @date 2019-10-11 23:25 **/ @Order(3) @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IgnoreUrlPropsConfiguration ignoreUrlPropsConfig; @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Resource private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Resource private SocialAuthenticationSecurityConfig socialAuthenticationSecurityConfig; /** * 必须要定义,否则不支持grant_type=password模式 * * @return AuthenticationManager */ @Bean @Override @SneakyThrows public AuthenticationManager authenticationManagerBean() { return super.authenticationManagerBean(); } @Bean public AuthenticationSuccessHandler mateAuthenticationSuccessHandler() { return new MateAuthenticationSuccessHandler(); } @Bean public AuthenticationFailureHandler mateAuthenticationFailureHandler() { return new MateAuthenticationFailureHandler(); } @Override @Bean public UserDetailsService userDetailsService() { return new UserDetailsServiceImpl(); } @Override protected void configure(HttpSecurity http) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config = http.requestMatchers().anyRequest() .and() .formLogin() .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .apply(socialAuthenticationSecurityConfig) .and() .authorizeRequests(); ignoreUrlPropsConfig.getUrls().forEach(url -> { config.antMatchers(url).permitAll(); }); ignoreUrlPropsConfig.getIgnoreSecurity().forEach(url -> { config.antMatchers(url).permitAll(); }); config //任何请求 .anyRequest() //都需要身份认证 .authenticated() //csrf跨站请求 .and() .csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth. userDetailsService(userDetailsService()) .passwordEncoder(passwordEncoder()); } }
package com.metamagic.ms.controller; import java.util.Arrays; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; /** * @author sagar * THIS CLASS USED FOR COMMON METHODS OF REST CONTROLLER */ public abstract class BaseComponent { /** * HERE HTTPHEADERS SET CONTENT TYPE * */ protected final HttpHeaders createHeaders(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); headers.add(key, value); } return headers; } }
package com.metamagic.ms.aspect; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.service.TokenService; import atg.taglib.json.util.JSONObject; import ch.qos.logback.classic.Logger; import io.jsonwebtoken.ExpiredJwtException; /** * @author sagar * * THIS ASPECT ADD TOKEN IN HEPLER BEAN */ @Component @Aspect @Order(2) @Scope(value = "request") public class TokenAspect { private static final Logger log = (Logger) LoggerFactory.getLogger(TokenAspect.class); @Autowired private TokenService tokenService; @Autowired private LoginInfoHelperBean loginInfoHelperBean; @Around("allOperations()") public Object validateToken(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); try { JSONObject jsonObject = tokenService.getTokenData((String) request.getHeader("tokenid")); loginInfoHelperBean.setProperty(jsonObject.getString("userId")); } catch (ExpiredJwtException e) { log.error("Token expired"); ResponseBean response = new ResponseBean(false, "Token expired.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (IllegalArgumentException e) { log.error("Token required"); ResponseBean response = new ResponseBean(false, "Token required.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (Exception e) { log.error("Invalid Token"); ResponseBean response = new ResponseBean(false, "Invalid Token.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } return joinPoint.proceed(); } @Pointcut("execution(* com.metamagic.ms.controller.read..*.*(..))") public void allOperations() { } }
package com.metamagic.ms.controller; import java.util.Arrays; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; /** * @author sagar * BASE CLASS OF CONTROLLER */ public abstract class BaseComponent { protected final HttpHeaders createHeaders(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); headers.add(key, value); } return headers; } }
package com.metamagic.ms.aspect; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.service.TokenService; import atg.taglib.json.util.JSONObject; import ch.qos.logback.classic.Logger; import io.jsonwebtoken.ExpiredJwtException; /** * @author sagar * THIS ASPECT USED FOR ADDING TOKEN */ @Component @Aspect @Order(2) @Scope(value = "request") public class TokenAspect { private static final Logger log = (Logger) LoggerFactory.getLogger(TokenAspect.class); @Autowired private TokenService tokenService; @Autowired private LoginInfoHelperBean loginInfoHelperBean; @Around("allOperations()") public Object validateToken(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); try { JSONObject jsonObject = tokenService.getTokenData((String) request.getHeader("tokenid")); loginInfoHelperBean.setProperty(jsonObject.getString("userId")); } catch (ExpiredJwtException e) { log.error("Token expired"); ResponseBean response = new ResponseBean(false, "Token expired.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (IllegalArgumentException e) { log.error("Token required"); ResponseBean response = new ResponseBean(false, "Token required.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (Exception e) { log.error("Invalid Token"); ResponseBean response = new ResponseBean(false, "Invalid Token.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } return joinPoint.proceed(); } @Pointcut("execution(* com.metamagic.ms.controller.write..*.*(..))") public void allOperations() { } }
package com.metamagic.ms.controller; import java.util.Arrays; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; /** * @author sagar * THIS CLASS USED FOR CONTROLLER HTTPHREADER ADD */ public abstract class BaseComponent { protected final HttpHeaders createHeaders(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); headers.add(key, value); } return headers; } }
package com.metamagic.ms.aspect; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; 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.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.service.TokenService; import atg.taglib.json.util.JSONObject; import ch.qos.logback.classic.Logger; import io.jsonwebtoken.ExpiredJwtException; /** * @author sagar * THIS ASPECT USED FOR TOKEN */ @Component @Aspect @Scope(value = "request") public class TokenAspect { private static final Logger log = (Logger) LoggerFactory.getLogger(ServiceAspect.class); @Autowired private TokenService tokenService; @Autowired private LoginInfoHelperBean loginInfoHelperBean; @Around("allOperations()") public Object validateToken(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); try { JSONObject jsonObject = tokenService.getTokenData((String) request.getHeader("tokenid")); loginInfoHelperBean.setProperty(jsonObject.getString("userId")); } catch (ExpiredJwtException e) { log.debug("Token expired"); ResponseBean response = new ResponseBean(false, "Token expired.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (IllegalArgumentException e) { log.error("Token required"); ResponseBean response = new ResponseBean(false, "Token required.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } catch (Exception e) { log.error("Invalid Token"); ResponseBean response = new ResponseBean(false, "Invalid Token.", "failure", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.UNAUTHORIZED); } return joinPoint.proceed(); } @Pointcut("execution(* com.metamagic.ms.controller..*.*(..))") public void allOperations() { } }
package com.own.face.util; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; public class Util { public Util() { } /** * 判断对象是否为空 * * @param object * @return */ public static boolean isNullOrEmpty(Object object) { if (object == null || "".equals(object.toString())) return true; return false; } /** * 转字符串,去空格 * @param object * @return */ public static String toStringAndTrim(Object object) { if (object == null) return ""; else return object.toString().trim(); } /** * 将图片从临时目录移动到真实目录,并删除临时路径图片 * @param tmpInfoFilePath 临时图片存放路径 * @param realInfofilePath 真实图片存放路径 * @param fileNames 移动图片的名称数组 例如 [a.png,b.jpb,c.png] */ public static void copyFileToRealPath(String tmpInfoFilePath,String realInfofilePath,String[] fileNames){ File file = null; FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; for(String fileName : fileNames){ try{ file = new File(tmpInfoFilePath+"/"+fileName); if(!file.exists()){ continue; } fis = new FileInputStream(file); bis=new BufferedInputStream(fis); fos = new FileOutputStream(realInfofilePath+"/"+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(); } } } } public static Object createJson2Bean(String value, Class calsz) { if(value == null || "".equals(value)) return null; ObjectMapper mapper = new ObjectMapper(); Object object = null; try { object = mapper.readValue(value, calsz); } catch(IOException e){ e.printStackTrace(); } return object; } }
package com.moxi.mogublog.picture.spider; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSON; import org.springframework.stereotype.Component; import us.codecraft.webmagic.ResultItems; import us.codecraft.webmagic.Task; import us.codecraft.webmagic.pipeline.Pipeline; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; @Component public class PicturePieline implements Pipeline { //下载图片 private static List<String> Download(List<String> listImgSrc) { //开始时间 Date begindate = new Date(); ArrayList<String> localFile = new ArrayList<>(); try { for (String url : listImgSrc) { //开始时间 Date begindate2 = new Date(); String imageName = url.substring(url.lastIndexOf("/") + 1, url.length()); URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"); conn.connect(); InputStream in = conn.getInputStream(); String pathname = "D:\\123\\" + imageName; File file = new File(pathname); FileOutputStream fo = new FileOutputStream(file);//文件输出流 byte[] buf = new byte[1024]; int length = 0; System.out.println("开始下载:" + url); while ((length = in.read(buf, 0, buf.length)) != -1) { fo.write(buf, 0, length); } //关闭流 in.close(); fo.close(); System.out.println(imageName + "下载完成"); //结束时间 Date overdate2 = new Date(); double time = overdate2.getTime() - begindate2.getTime(); System.out.println("耗时:" + time / 1000 + "s"); localFile.add(pathname); } Date overdate = new Date(); double time = overdate.getTime() - begindate.getTime(); System.out.println("总耗时:" + time / 1000 + "s"); } catch (Exception e) { System.out.println(e.getMessage()); } return localFile; } @Override public void process(ResultItems resultItems, Task task) { //获取图片参数 String imgSrc = resultItems.get("imgSrc"); //获取关键词 String searchKey = resultItems.get("searchKey"); List imgSrcs = JSON.parseObject(imgSrc, List.class); if (CollectionUtil.isEmpty(imgSrcs)) { return; } //下载图片并上传到七牛云 List localFileUrl = Download(imgSrcs); } }
package com.moxi.mogublog.picture.spider; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSON; import com.google.gson.Gson; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth; import org.springframework.stereotype.Component; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.selector.Html; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component public class PictureProcesser implements PageProcessor { // 获取img标签正则 private static final String IMGURL_REG = "<img.*?src=.*?photos.*?/>"; // 获取src路径的正则 private static final String IMGSRC_REG = "/photos.*?\\?"; /** * 查找输入的关键词 * * @param url * @return */ public static String findSearchKey(String url) { // 按指定模式在字符串查找 String reg = "\\?q=.*"; // 创建 Pattern 对象 // 现在创建 matcher 对象 Pattern pattern = Pattern.compile(reg);// 匹配的模式 Matcher m = pattern.matcher(url); if (m.find()) { String group = m.group(0); String replace = group.replace("?q=", "").replaceFirst("&.*", ""); return replace; } else { return url; } } /** * 解析html * * @param url * @return * @throws Exception */ private static String getHtml(String url) throws Exception { URL url1 = new URL(url);//使用java.net.URL HttpURLConnection connection = (HttpURLConnection) url1. openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); InputStream in = connection.getInputStream();//获取输入流 InputStreamReader isr = new InputStreamReader(in);//流的包装 BufferedReader br = new BufferedReader(isr); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) {//整行读取 sb.append(line, 0, line.length());//添加到StringBuffer中 sb.append('\n');//添加换行符 } //关闭各种流,先声明的后关闭 br.close(); isr.close(); in.close(); return sb.toString(); } //获取ImageUrl地址 private static List<String> getImageUrl(String html) { Pattern compile = Pattern.compile(IMGURL_REG); Matcher matcher = compile.matcher(html); List<String> listimgurl = new ArrayList<String>(); while (matcher.find()) { listimgurl.add(matcher.group()); } return listimgurl; } //获取ImageSrc地址 private static List<String> getImageSrc(List<String> listimageurl) { List<String> listImageSrc = new ArrayList<String>(); for (String image : listimageurl) { Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image); while (matcher.find()) { listImageSrc.add("https://foter.com" + matcher.group().substring(0, matcher.group().length() - 1)); } } return listImageSrc; } /** * 获取UUID,去掉了- * * @return */ public static String getUUID() { String uuid = UUID.randomUUID().toString().replaceAll("-", ""); return uuid; } //下载图片 private static List<String> Download(List<String> listImgSrc) { //开始时间 Date begindate = new Date(); ArrayList<String> localFile = new ArrayList<>(); try { for (String url : listImgSrc) { //开始时间 Date begindate2 = new Date(); String imageName = url.substring(url.lastIndexOf("/") + 1, url.length()); URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"); conn.connect(); InputStream in = conn.getInputStream(); String pathname = "D:\\123\\" + imageName; File file = new File(pathname); FileOutputStream fo = new FileOutputStream(file);//文件输出流 byte[] buf = new byte[1024]; int length = 0; System.out.println("开始下载:" + url); while ((length = in.read(buf, 0, buf.length)) != -1) { fo.write(buf, 0, length); } //关闭流 in.close(); fo.close(); System.out.println(imageName + "下载完成"); //结束时间 Date overdate2 = new Date(); double time = overdate2.getTime() - begindate2.getTime(); System.out.println("耗时:" + time / 1000 + "s"); localFile.add(pathname); } Date overdate = new Date(); double time = overdate.getTime() - begindate.getTime(); System.out.println("总耗时:" + time / 1000 + "s"); } catch (Exception e) { System.out.println(e.getMessage()); } return localFile; } private static void add(List<String> localFile) throws QiniuException { for (String ss : localFile) { //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone2()); //生成上传凭证,然后准备上传 String accessKey = "KPTcX6IBYXrR8wpE0VvcUXBu4XkC0XyhquFivGYe"; String secretKey = "bQcxUBc_c8evOPKZMxiJ2luHTROcRha3krWJmvR3"; String bucket = "mogublogforsjf"; //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); String key = getUUID(); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); File localFilePath = new File(ss); Response response = uploadManager.put(localFilePath, key, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); } } @Override public void process(Page page) { int i = 50; //page计数是从2开始的 //https://foter.com/search/instant/?q=cat&page=2 Html html = page.getHtml(); String url = page.getRequest().getUrl(); List<String> list = html.regex("<img.*?src=.*?photos.*?/>").all(); List<String> imageSrc = getImageSrc(list); String jsonString = JSON.toJSONString(imageSrc); if (CollectionUtil.isEmpty(imageSrc)) { page.putField("imgSrc", jsonString); page.putField("searchKey", findSearchKey(url)); } else { //跳过爬取 page.setSkip(true); } } @Override public Site getSite() { return Site.me().setCharset("utf8").setRetryTimes(2).setSleepTime(2000).setTimeOut(4000); } public String uploadQiniu(File localFilePath) throws QiniuException { //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone2()); //生成上传凭证,然后准备上传 String accessKey = "KPTcX6IBYXrR8wpE0VvcUXBu4XkC0XyhquFivGYe"; String secretKey = "bQcxUBc_c8evOPKZMxiJ2luHTROcRha3krWJmvR3"; String bucket = "mogublogforsjf"; //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); String key = getUUID(); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); Response response = uploadManager.put(localFilePath, key, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return putRet.key; } }
package com.moxi.mogublog.spider.pipeline; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSON; import org.springframework.stereotype.Component; import us.codecraft.webmagic.ResultItems; import us.codecraft.webmagic.Task; import us.codecraft.webmagic.pipeline.Pipeline; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 图片传输管道 * * @author 陌溪 * @date 2021年1月8日16:41:32 */ @Component public class PicturePieline implements Pipeline { //下载图片 private static List<String> Download(List<String> listImgSrc) { //开始时间 Date begindate = new Date(); ArrayList<String> localFile = new ArrayList<>(); try { for (String url : listImgSrc) { //开始时间 Date begindate2 = new Date(); String imageName = url.substring(url.lastIndexOf("/") + 1); URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"); conn.connect(); InputStream in = conn.getInputStream(); String pathname = "D:\\123\\" + imageName; File file = new File(pathname); FileOutputStream fo = new FileOutputStream(file);//文件输出流 byte[] buf = new byte[1024]; int length = 0; System.out.println("开始下载:" + url); while ((length = in.read(buf, 0, buf.length)) != -1) { fo.write(buf, 0, length); } //关闭流 in.close(); fo.close(); System.out.println(imageName + "下载完成"); //结束时间 Date overdate2 = new Date(); double time = overdate2.getTime() - begindate2.getTime(); System.out.println("耗时:" + time / 1000 + "s"); localFile.add(pathname); } Date overdate = new Date(); double time = overdate.getTime() - begindate.getTime(); System.out.println("总耗时:" + time / 1000 + "s"); } catch (Exception e) { System.out.println(e.getMessage()); } return localFile; } @Override public void process(ResultItems resultItems, Task task) { //获取图片参数 String imgSrc = resultItems.get("imgSrc"); //获取关键词 String searchKey = resultItems.get("searchKey"); List imgSrcs = JSON.parseObject(imgSrc, List.class); if (CollectionUtil.isEmpty(imgSrcs)) { return; } //下载图片并上传到七牛云 List localFileUrl = Download(imgSrcs); } }
package com.moxi.mogublog.spider.processer; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.selector.Html; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 爬取的图片页面处理 * * @author 陌溪 * @date 2021年1月8日16:47:34 */ @Component @Slf4j public class PictureProcesser implements PageProcessor { // 获取img标签正则 private static final String IMGURL_REG = "<(img|IMG)(.*?)>"; // 获取src路径的正则 private static final String IMGSRC_REG = "(src|SRC)=\"(.*?)\""; /** * 查找输入的关键词 * * @param url * @return */ public static String findSearchKey(String url) { // 按指定模式在字符串查找 String reg = "\\?q=.*"; // 创建 Pattern 对象 // 现在创建 matcher对象 匹配的模式 Pattern pattern = Pattern.compile(reg); Matcher m = pattern.matcher(url); if (m.find()) { String group = m.group(0); String replace = group.replace("?q=", "").replaceFirst("&.*", ""); return replace; } else { return url; } } //下载图片 private static List<String> Download(List<String> listImgSrc) { //开始时间 Date begindate = new Date(); ArrayList<String> localFile = new ArrayList<>(); try { for (String url : listImgSrc) { //开始时间 Date begindate2 = new Date(); String imageName = url.substring(url.lastIndexOf("/") + 1); URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"); conn.connect(); InputStream in = conn.getInputStream(); String pathname = "D:\\123\\" + imageName; File file = new File(pathname); FileOutputStream fo = new FileOutputStream(file);//文件输出流 byte[] buf = new byte[1024]; int length = 0; System.out.println("开始下载:" + url); while ((length = in.read(buf, 0, buf.length)) != -1) { fo.write(buf, 0, length); } //关闭流 in.close(); fo.close(); System.out.println(imageName + "下载完成"); //结束时间 Date overdate2 = new Date(); double time = overdate2.getTime() - begindate2.getTime(); System.out.println("耗时:" + time / 1000 + "s"); localFile.add(pathname); } Date overdate = new Date(); double time = overdate.getTime() - begindate.getTime(); System.out.println("总耗时:" + time / 1000 + "s"); } catch (Exception e) { System.out.println(e.getMessage()); } return localFile; } public static void main(String[] args) throws Exception { PictureProcesser pictureProcesser = new PictureProcesser(); String html = pictureProcesser.getHtml("https://www.hippopx.com/zh/query?q=cat"); List<String> imageUrl = pictureProcesser.getImageUrl(html); List<String> imageSrc = pictureProcesser.getImageSrc(imageUrl); System.out.println(JSON.toJSONString(imageSrc)); } //获取ImageSrc地址 public List<String> getImageSrc(List<String> listimageurl) { List<String> listImageSrc = new ArrayList<>(); for (String image : listimageurl) { Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image); while (matcher.find()) { listImageSrc.add(matcher.group(2).trim()); } } return listImageSrc; } @Override public void process(Page page) { int i = 50; //page计数是从2开始的 //https://foter.com/search/instant/?q=cat&page=2 Html html = page.getHtml(); String url = page.getRequest().getUrl(); List<String> list = html.regex("<img.*?src=.*?photos.*?/>").all(); List<String> imageSrc = getImageSrc(list); String jsonString = JSON.toJSONString(imageSrc); if (CollectionUtil.isEmpty(imageSrc)) { page.putField("imgSrc", jsonString); page.putField("searchKey", findSearchKey(url)); } else { //跳过爬取 page.setSkip(true); } } @Override public Site getSite() { return Site.me().setCharset("utf8").setRetryTimes(2).setSleepTime(2000).setTimeOut(4000); } /** * 解析html * * @param url * @return * @throws Exception */ public String getHtml(String url) { InputStream in = null; InputStreamReader isr = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { //使用java.net.URL URL url1 = new URL(url); HttpURLConnection connection = (HttpURLConnection) url1. openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.setRequestProperty("Charsert", "UTF-8"); connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8"); //获取输入流 in = connection.getInputStream(); //流的包装 isr = new InputStreamReader(in); br = new BufferedReader(isr); String line; //整行读取 while ((line = br.readLine()) != null) { //添加到StringBuffer中 sb.append(line, 0, line.length()); //添加换行符 sb.append('\n'); } } catch (Exception e) { log.error("获取图片出现异常:{}", e.getMessage()); e.printStackTrace(); } finally { //关闭各种流,先声明的后关闭 try { if (in != null) { in.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } } catch (IOException e) { log.error("获取图片出现异常:{}", e.getMessage()); e.printStackTrace(); } } return sb.toString(); } //获取ImageUrl地址 public List<String> getImageUrl(String html) { Pattern compile = Pattern.compile(IMGURL_REG); Matcher matcher = compile.matcher(html); List<String> listimgurl = new ArrayList<>(); int temp = 0; while (matcher.find()) { temp ++; // 跳过第一张logo图片 if (temp == 1) { continue; } listimgurl.add(matcher.group()); } return listimgurl; } }
package com.moxi.mogublog.spider.util; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; /** * <p>名称:IdWorker.java</p> * <p>描述:分布式自增长ID</p> * <pre> * Twitter的 Snowflake JAVA实现方案 * </pre> * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用: * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000 * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间, * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识), * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。 * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分), * 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。 * <p> * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) * * @author Polim */ public class IdWorker { /** * 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) */ private final static long twepoch = 1288834974657L; // 机器标识位数 private final static long workerIdBits = 5L; // 数据中心标识位数 private final static long datacenterIdBits = 5L; // 机器ID最大值 private final static long maxWorkerId = -1L ^ (-1L << workerIdBits); // 数据中心ID最大值 private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 毫秒内自增位 private final static long sequenceBits = 12L; // 机器ID偏左移12位 private final static long workerIdShift = sequenceBits; // 数据中心ID左移17位 private final static long datacenterIdShift = sequenceBits + workerIdBits; // 时间毫秒左移22位 private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final static long sequenceMask = -1L ^ (-1L << sequenceBits); /* 上次生产id时间戳 */ private static long lastTimestamp = -1L; private final long workerId; // 数据标识id部分 private final long datacenterId; // 0,并发控制 private long sequence = 0L; public IdWorker() { this.datacenterId = getDatacenterId(maxDatacenterId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); } /** * @param workerId 工作机器ID * @param datacenterId 序列号 */ public IdWorker(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } /** * <p> * 获取 maxWorkerId * </p> */ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** * <p> * 数据标识id部分 * </p> */ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; } public static void main(String[] args) { //推特 26万个不重复的ID IdWorker idWorker = new IdWorker(0, 0); for (int i = 0; i < 2600; i++) { System.out.println(idWorker.nextId()); } } /** * 获取下一个ID * * @return */ public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; } private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } }
package com.moxi.mogublog.utils; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; /** * <p>名称:IdWorker.java</p> * <p>描述:分布式自增长ID</p> * <pre> * Twitter的 Snowflake JAVA实现方案 * </pre> * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用: * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000 * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间, * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识), * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。 * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分), * 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。 * <p> * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) * * @author Polim */ public class IdWorkerUtils { // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) private final static long twepoch = 1288834974657L; // 机器标识位数 private final static long workerIdBits = 5L; // 数据中心标识位数 private final static long datacenterIdBits = 5L; // 机器ID最大值 private final static long maxWorkerId = -1L ^ (-1L << workerIdBits); // 数据中心ID最大值 private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 毫秒内自增位 private final static long sequenceBits = 12L; // 机器ID偏左移12位 private final static long workerIdShift = sequenceBits; // 数据中心ID左移17位 private final static long datacenterIdShift = sequenceBits + workerIdBits; // 时间毫秒左移22位 private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final static long sequenceMask = -1L ^ (-1L << sequenceBits); /* 上次生产id时间戳 */ private static long lastTimestamp = -1L; private final long workerId; // 数据标识id部分 private final long datacenterId; // 0,并发控制 private long sequence = 0L; public IdWorkerUtils() { this.datacenterId = getDatacenterId(maxDatacenterId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); } /** * @param workerId 工作机器ID * @param datacenterId 序列号 */ public IdWorkerUtils(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } /** * <p> * 获取 maxWorkerId * </p> */ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** * <p> * 数据标识id部分 * </p> */ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; } /** * 获取下一个ID * * @return */ public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; } private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } }
package com.moxi.mogublog.utils; /** * 雪花ID生成器 * * @author: 陌溪 * @create: 2020-11-13-10:36 * * Twitter开源的分布式Id生成器,使用雪花算法 * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间, * 由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截, * 可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分), * 并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右 */ public class SnowflakeIdWorker { // ==============================Fields=========================================== /** * 开始时间截 (2015-01-01) */ private final long twepoch = 1420041600000L; /** * 机器id所占的位数 默认5L */ private final long workerIdBits = 5L; /** * 数据标识id所占的位数 默认5L */ private final long dataCenterIdBits = 5L; /** * 序列在id中占的位数 默认12L */ private final long sequenceBits = 12L; /** * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ private final long maxWorkerId = -1L ^ (-1L << workerIdBits); /** * 支持的最大数据标识id,结果是31 */ private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); /** * 机器ID向左移12位 */ private final long workerIdShift = sequenceBits; /** * 数据标识id向左移17位(12+5) */ private final long datacenterIdShift = sequenceBits + workerIdBits; /** * 时间截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; /** * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */ private final long sequenceMask = -1L ^ (-1L << sequenceBits); /** * 工作机器ID(0~31) */ private long workerId ; /** * 数据中心ID(0~31) */ private long dataCenterId; /** * 毫秒内序列(0~4095) */ private long sequence = 0L; /** * 上次生成ID的时间截 */ private long lastTimestamp = -1L; //==============================Constructors===================================== /** * 构造函数 * * @param workerId 工作ID (0~31) * @param dataCenterId 数据中心ID (0~31) */ public SnowflakeIdWorker(long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; } // ==============================Methods========================================== /** * 获得下一个ID (该方法是线程安全的) * * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒内序列溢出 if (sequence == 0) { //阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } //时间戳改变,毫秒内序列重置 else { sequence = 0L; } //上次生成ID的时间截 lastTimestamp = timestamp; //移位并通过或运算拼到一起组成64位的ID return ((timestamp - twepoch) << timestampLeftShift) | (dataCenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } /** * 阻塞到下一个毫秒,直到获得新的时间戳 * * @param lastTimestamp 上次生成ID的时间截 * @return 当前时间戳 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒为单位的当前时间 * * @return 当前时间(毫秒) */ private long timeGen() { return System.currentTimeMillis(); } /** * 测试 */ public static void main(String[] args) { SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); for (int i = 0; i < 1000; i++) { long id = idWorker.nextId(); System.out.println(Long.toBinaryString(id)); System.out.println(id); } } }
package com.fly.blog.aop; import com.alibaba.fastjson.JSON; import com.fly.blog.entity.SysLog; import com.fly.blog.util.HttpUtils; import com.fly.blog.util.UserUtils; import com.fly.blog.service.LoggerService; import com.fly.common.annotation.SysLogger; import org.apache.commons.lang.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.Date; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Aspect @Component public class SysLoggerAspect { @Autowired private LoggerService loggerService; @Pointcut("@annotation(com.fly.common.annotation.SysLogger)") public void loggerPointCut() { } @Before("loggerPointCut()") public void saveSysLog(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); SysLogger sysLogger = method.getAnnotation(SysLogger.class); if (sysLogger != null) { //注解上的描述 sysLog.setOperation(sysLogger.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); String params = ""; for (Object o : args) { params += JSON.toJSONString(o); } if (!StringUtils.isEmpty(params)) { sysLog.setParams(params); } //设置IP地址 sysLog.setIp(HttpUtils.getIpAddress()); //用户名 String username = UserUtils.getCurrentPrinciple(); if (!StringUtils.isEmpty(username)) { sysLog.setUsername(username); } sysLog.setCreateDate(new Date()); //保存系统日志 loggerService.log(sysLog); } }
package com.fly.blog.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.util.FileCopyUtils; import java.io.IOException; /** * Description: <JwtConfiguration><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Configuration public class JwtConfiguration { @Autowired JwtAccessTokenConverter jwtAccessTokenConverter; @Bean @Qualifier("tokenStore") public TokenStore tokenStore() { System.out.println("Created JwtTokenStore"); return new JwtTokenStore(jwtAccessTokenConverter); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource("public.cert"); String publicKey ; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } converter.setVerifierKey(publicKey); return converter; } }
package com.fly.blog.util; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class HttpUtils { /** * 尝试获取当前请求的HttpServletRequest实例 * * @return HttpServletRequest */ public static HttpServletRequest getHttpServletRequest() { try { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } catch (Exception e) { return null; } } public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } /** * 获取请求客户端的真实ip地址 * * @param request 请求对象 * @return ip地址 */ public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } /** * 获取请求客户端的真实ip地址 * * @param * @return ip地址 */ public static String getIpAddress() { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 return getIpAddress(getHttpServletRequest()); } }
package com.fly.blog.util; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import java.util.List; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class UserUtils { private static final String AUTHORIZATION = "authorization"; /** * 获取当前请求的token * * @return */ public static String getCurrentToken() { return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION); } /** * 获取当前请求的用户Id * * @return */ public static String getCurrentPrinciple() { return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } /** * 判读当前token用户是否为接口所需的参数username * * @param username * @return */ public static boolean isMyself(String username) { return username.equals(getCurrentPrinciple()); } /** * 获取当前请求Authentication * * @return */ public static Authentication getCurrentAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 获取当前请求的权限信息 * * @return */ public static List<SimpleGrantedAuthority> getCurrentAuthorities() { return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); } /** * @param role * @return */ public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; } }
package com.fly.news.aop; import com.alibaba.fastjson.JSON; import com.fly.common.annotation.SysLogger; import com.fly.news.entity.SysLog; import com.fly.news.service.LoggerService; import com.fly.news.util.HttpUtils; import com.fly.news.util.UserUtils; import org.apache.commons.lang.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.Date; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Aspect @Component public class SysLoggerAspect { @Autowired private LoggerService loggerService; @Pointcut("@annotation(com.fly.common.annotation.SysLogger)") public void loggerPointCut() { } @Before("loggerPointCut()") public void saveSysLog(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); SysLogger sysLogger = method.getAnnotation(SysLogger.class); if (sysLogger != null) { //注解上的描述 sysLog.setOperation(sysLogger.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); String params = ""; for (Object o : args) { params += JSON.toJSONString(o); } if (!StringUtils.isEmpty(params)) { sysLog.setParams(params); } //设置IP地址 sysLog.setIp(HttpUtils.getIpAddress()); //用户名 String username = UserUtils.getCurrentPrinciple(); if (!StringUtils.isEmpty(username)) { sysLog.setUsername(username); } sysLog.setCreateDate(new Date()); //保存系统日志 loggerService.log(sysLog); } }
package com.fly.news.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.util.FileCopyUtils; import java.io.IOException; /** * Description: <JwtConfiguration><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Configuration public class JwtConfiguration { @Autowired JwtAccessTokenConverter jwtAccessTokenConverter; @Bean @Qualifier("tokenStore") public TokenStore tokenStore() { System.out.println("Created JwtTokenStore"); return new JwtTokenStore(jwtAccessTokenConverter); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource("public.cert"); String publicKey ; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } converter.setVerifierKey(publicKey); return converter; } }
package com.fly.news.util; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class HttpUtils { /** * 尝试获取当前请求的HttpServletRequest实例 * * @return HttpServletRequest */ public static HttpServletRequest getHttpServletRequest() { try { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } catch (Exception e) { return null; } } public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } /** * 获取请求客户端的真实ip地址 * * @param request 请求对象 * @return ip地址 */ public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } /** * 获取请求客户端的真实ip地址 * * @param * @return ip地址 */ public static String getIpAddress() { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 return getIpAddress(getHttpServletRequest()); } }
package com.fly.news.util; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import java.util.List; /** * Description: <><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class UserUtils { private static final String AUTHORIZATION = "authorization"; /** * 获取当前请求的token * * @return */ public static String getCurrentToken() { return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION); } /** * 获取当前请求的用户Id * * @return */ public static String getCurrentPrinciple() { return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } /** * 判读当前token用户是否为接口所需的参数username * * @param username * @return */ public static boolean isMyself(String username) { return username.equals(getCurrentPrinciple()); } /** * 获取当前请求Authentication * * @return */ public static Authentication getCurrentAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 获取当前请求的权限信息 * * @return */ public static List<SimpleGrantedAuthority> getCurrentAuthorities() { return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); } /** * @param role * @return */ public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; } }
package com.fly.user.aop; import com.alibaba.fastjson.JSON; import com.fly.common.annotation.SysLogger; import com.fly.user.util.HttpUtils; import com.fly.user.util.UserUtils; import com.fly.user.entity.SysLog; import com.fly.user.service.LoggerService; import org.apache.commons.lang.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.util.Date; /** * Description: <SysLoggerAspect><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Aspect @Component public class SysLoggerAspect { @Autowired private LoggerService loggerService; @Pointcut("@annotation(com.fly.common.annotation.SysLogger)") public void loggerPointCut() { } @Before("loggerPointCut()") public void saveSysLog(JoinPoint joinPoint) { System.out.println("MYTAG:User SysLoggerAspect saveLogger start..."); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); SysLogger sysLogger = method.getAnnotation(SysLogger.class); if(sysLogger != null){ //注解上的描述 sysLog.setOperation(sysLogger.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); String params=""; for(Object o:args){ params+= JSON.toJSONString(o); } if(!StringUtils.isEmpty(params)) { sysLog.setParams(params); } //设置IP地址 sysLog.setIp(HttpUtils.getIpAddress()); //用户名 String username = UserUtils.getCurrentPrinciple(); if(!StringUtils.isEmpty(username)) { sysLog.setUsername(username); } sysLog.setCreateDate(new Date()); //保存系统日志 loggerService.log(sysLog); } }
package com.fly.user.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.util.FileCopyUtils; import java.io.IOException; /** * Description: <JwtConfiguration><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ @Configuration public class JwtConfiguration { @Autowired JwtAccessTokenConverter jwtAccessTokenConverter; @Bean @Qualifier("tokenStore") public TokenStore tokenStore() { System.out.println("Created JwtTokenStore"); return new JwtTokenStore(jwtAccessTokenConverter); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource("public.cert"); String publicKey ; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } converter.setVerifierKey(publicKey); return converter; } }
package com.fly.user.util; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * Description: <HttpUtils><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class HttpUtils { /** * 尝试获取当前请求的HttpServletRequest实例 * * @return HttpServletRequest */ public static HttpServletRequest getHttpServletRequest() { try { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } catch (Exception e) { return null; } } public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } /** * 获取请求客户端的真实ip地址 * * @param request 请求对象 * @return ip地址 */ public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } /** * 获取请求客户端的真实ip地址 * * @param * @return ip地址 */ public static String getIpAddress() { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 return getIpAddress(getHttpServletRequest()); } }
package com.fly.user.util; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import java.util.List; /** * Description: <UserUtils><br> * Author: mxdl<br> * Date: 2019/2/19<br> * Version: V1.0.0<br> * Update: <br> */ public class UserUtils { private static final String AUTHORIZATION = "authorization"; /** * 获取当前请求的token * @return */ public static String getCurrentToken() { return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION); } /** * 获取当前请求的用户Id * @return */ public static String getCurrentPrinciple() { return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } /** * 判读当前token用户是否为接口所需的参数username * * @param username * @return */ public static boolean isMyself(String username) { return username.equals(getCurrentPrinciple()); } /** * 获取当前请求Authentication * * @return */ public static Authentication getCurrentAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 获取当前请求的权限信息 * @return */ public static List<SimpleGrantedAuthority> getCurrentAuthorities() { return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); } /** * @param role * @return */ public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; } }
package xyz.staffjoy.account.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import xyz.staffjoy.common.async.ContextCopyingDecorator; import xyz.staffjoy.common.config.StaffjoyRestConfig; import java.util.concurrent.Executor; @Configuration @EnableAsync @Import(value = {StaffjoyRestConfig.class}) @SuppressWarnings(value = "Duplicates") public class AppConfig { public static final String ASYNC_EXECUTOR_NAME = "asyncExecutor"; @Bean(name=ASYNC_EXECUTOR_NAME) public Executor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // for passing in request scope context executor.setTaskDecorator(new ContextCopyingDecorator()); executor.setCorePoolSize(3); executor.setMaxPoolSize(5); executor.setQueueCapacity(100); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("AsyncThread-"); executor.initialize(); return executor; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
package xyz.staffjoy.account; import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import xyz.staffjoy.common.auth.AuthConstant; import java.util.UUID; /** * Pass CURRENT_USER_HEADER via Feign for testing */ @Configuration public class TestConfig { public static String TEST_USER_ID = UUID.randomUUID().toString(); @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; } }
package xyz.staffjoy.bot.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import xyz.staffjoy.common.async.ContextCopyingDecorator; import xyz.staffjoy.common.config.StaffjoyRestConfig; import java.util.concurrent.Executor; @Configuration @EnableAsync @Import(value = {StaffjoyRestConfig.class}) @SuppressWarnings(value = "Duplicates") public class AppConfig { public static final String ASYNC_EXECUTOR_NAME = "asyncExecutor"; @Bean(name=ASYNC_EXECUTOR_NAME) public Executor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setTaskDecorator(new ContextCopyingDecorator()); executor.setCorePoolSize(3); executor.setMaxPoolSize(5); executor.setQueueCapacity(100); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("AsyncThread-"); executor.initialize(); return executor; } }
package xyz.staffjoy.company.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import xyz.staffjoy.common.async.ContextCopyingDecorator; import xyz.staffjoy.common.config.StaffjoyRestConfig; import java.util.concurrent.Executor; @Configuration @EnableAsync @Import(value = {StaffjoyRestConfig.class}) @SuppressWarnings(value = "Duplicates") public class AppConfig { public static final String ASYNC_EXECUTOR_NAME = "asyncExecutor"; @Bean(name=ASYNC_EXECUTOR_NAME) public Executor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // for passing in request scope context executor.setTaskDecorator(new ContextCopyingDecorator()); executor.setCorePoolSize(3); executor.setMaxPoolSize(5); executor.setQueueCapacity(100); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("AsyncThread-"); executor.initialize(); return executor; } }
package xyz.staffjoy.company; import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import xyz.staffjoy.common.auth.AuthConstant; import java.util.UUID; /** * Pass CURRENT_USER_HEADER via Feign for testing */ @Configuration public class TestConfig { public static String TEST_USER_ID = UUID.randomUUID().toString(); @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; } }
package xyz.staffjoy.mail.config; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import org.springframework.context.annotation.Import; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import xyz.staffjoy.common.config.StaffjoyRestConfig; import xyz.staffjoy.mail.MailConstant; import xyz.staffjoy.mail.props.AppProps; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import java.util.concurrent.Executor; @Configuration @EnableAsync @Import(value = StaffjoyRestConfig.class) @SuppressWarnings(value = "Duplicates") public class AppConfig { public static final String ASYNC_EXECUTOR_NAME = "asyncExecutor"; @Autowired AppProps appProps; @Bean public IAcsClient acsClient() { IClientProfile profile = DefaultProfile.getProfile(MailConstant.ALIYUN_REGION_ID, appProps.getAliyunAccessKey(), appProps.getAliyunAccessSecret()); IAcsClient client = new DefaultAcsClient(profile); return client; } @Bean(name=ASYNC_EXECUTOR_NAME) public Executor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(5); executor.setQueueCapacity(100); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("AsyncThread-"); executor.initialize(); return executor; } }
package xyz.staffjoy.whoami; import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import xyz.staffjoy.common.auth.AuthConstant; /** * Pass CURRENT_USER_HEADER via Feign for testing */ @Configuration public class TestConfig { public static String TEST_USER_ID = ""; @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; } }