├── README.md ├── missyou ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── lin │ │ │ │ └── missyou │ │ │ │ ├── auth │ │ │ │ ├── AboutAuthConception.md │ │ │ │ ├── Auth0.java │ │ │ │ └── JavaJWT.java │ │ │ │ ├── dto │ │ │ │ ├── doubleTokenDTO.java │ │ │ │ ├── VerifyTokenDTO.java │ │ │ │ ├── TokenDTO.java │ │ │ │ └── validators │ │ │ │ │ ├── TokenPassword.java │ │ │ │ │ └── TokenPasswordValidator.java │ │ │ │ ├── util │ │ │ │ ├── CheckJsonToElasticsearch.java │ │ │ │ ├── CommonUtil.java │ │ │ │ ├── ImportJsonToElasticsearch.java │ │ │ │ ├── ListAndJon.java │ │ │ │ ├── MapAndJson.java │ │ │ │ ├── GenericAndJson.java │ │ │ │ └── JwtToken.java │ │ │ │ ├── service │ │ │ │ ├── BannerService.java │ │ │ │ ├── AuthenticationService.java │ │ │ │ ├── BannerServiceImpl.java │ │ │ │ ├── ActivityService.java │ │ │ │ ├── GridCategoryService.java │ │ │ │ ├── ThemeService.java │ │ │ │ ├── CategoryService.java │ │ │ │ ├── UserService.java │ │ │ │ ├── SpuService.java │ │ │ │ ├── WxAuthenticationService.java │ │ │ │ └── CouponService.java │ │ │ │ ├── exception │ │ │ │ ├── Http │ │ │ │ │ ├── ServerErrorException.java │ │ │ │ │ ├── ForbiddenException.java │ │ │ │ │ ├── ParemeterExcepiton.java │ │ │ │ │ ├── UnAuthenticatedException.java │ │ │ │ │ ├── NotFoundException.java │ │ │ │ │ └── HttpException.java │ │ │ │ ├── CreateSuccess.java │ │ │ │ ├── DeleteSuccess.java │ │ │ │ └── UpdateSuccess.java │ │ │ │ ├── bo │ │ │ │ └── PageCounter.java │ │ │ │ ├── model │ │ │ │ ├── Spec.java │ │ │ │ ├── SpuImg.java │ │ │ │ ├── SpuDetailImg.java │ │ │ │ ├── ActivityCoupon.java │ │ │ │ ├── BaseEntity.java │ │ │ │ ├── BannerItem.java │ │ │ │ ├── UserCoupon.java │ │ │ │ ├── GridCategory.java │ │ │ │ ├── Banner.java │ │ │ │ ├── Activity.java │ │ │ │ ├── User.java │ │ │ │ ├── Coupon.java │ │ │ │ ├── Category.java │ │ │ │ ├── Theme.java │ │ │ │ ├── Spu.java │ │ │ │ └── Sku.java │ │ │ │ ├── repository │ │ │ │ ├── GridCategoryRepository.java │ │ │ │ ├── BannerRepository.java │ │ │ │ ├── CategoryRepository.java │ │ │ │ ├── UserCouponRepository.java │ │ │ │ ├── ActivityRepository.java │ │ │ │ ├── UserRepository.java │ │ │ │ ├── SpuRepository.java │ │ │ │ ├── ThemeRepository.java │ │ │ │ └── CouponRepository.java │ │ │ │ ├── core │ │ │ │ ├── enumeration │ │ │ │ │ ├── LoginType.java │ │ │ │ │ └── CouponStatus.java │ │ │ │ ├── interceptors │ │ │ │ │ ├── ScopeLevel.java │ │ │ │ │ └── PermissionInterceptor.java │ │ │ │ ├── configuration │ │ │ │ │ ├── AutoPrefixConfiguration.java │ │ │ │ │ ├── ExceptionCodeConfiguration.java │ │ │ │ │ └── InterceptorConfiguration.java │ │ │ │ ├── UnifyResponse.java │ │ │ │ ├── LocalUser.java │ │ │ │ ├── hack │ │ │ │ │ └── AutoPrefixUrlMapping.java │ │ │ │ └── GlobalHttpExceptionAdvice.java │ │ │ │ ├── MissyouApplication.java │ │ │ │ ├── vo │ │ │ │ ├── ThemePureVO.java │ │ │ │ ├── SpuSimplifyVO.java │ │ │ │ ├── CategoryPureVO.java │ │ │ │ ├── ActivityCouponVO.java │ │ │ │ ├── CategoryAllVO.java │ │ │ │ ├── ActivityPureVO.java │ │ │ │ ├── CouponCategoryVO.java │ │ │ │ ├── PagingDozer.java │ │ │ │ ├── Paging.java │ │ │ │ └── CouponPureVO.java │ │ │ │ ├── mark │ │ │ │ ├── token.md │ │ │ │ ├── tencentSerivce.md │ │ │ │ ├── testOptional.java │ │ │ │ ├── doubleToken.md │ │ │ │ ├── tokenDevelopment.md │ │ │ │ └── testCollection.java │ │ │ │ └── api │ │ │ │ └── v1 │ │ │ │ ├── CategoryController.java │ │ │ │ ├── ActivityController.java │ │ │ │ ├── ThemeController.java │ │ │ │ ├── TokenController.java │ │ │ │ ├── SpuController.java │ │ │ │ ├── TestTool.java │ │ │ │ ├── CouponController.java │ │ │ │ └── BannerController.java │ │ └── resources │ │ │ ├── config │ │ │ ├── application-prod.yml │ │ │ ├── application-dev.yml │ │ │ └── exception-code.properties │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── lin │ │ └── missyou │ │ ├── optional │ │ └── OptionalTest.java │ │ ├── MissyouApplicationTests.java │ │ └── MissyouApplication.java ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ ├── maven-wrapper.properties │ │ └── MavenWrapperDownloader.java ├── .gitignore └── pom.xml └── .idea ├── misc.xml ├── vcs.xml ├── modules.xml ├── .gitignore └── mini-program-backend.iml /README.md: -------------------------------------------------------------------------------- 1 | # mini-program-backend 2 | 3 | 学习springboot相关知识 4 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/auth/AboutAuthConception.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/dto/doubleTokenDTO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.dto; 2 | 3 | public class doubleTokenDTO { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /missyou/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Until-You-Possible/mini-program-backend/HEAD/missyou/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/auth/Auth0.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.auth; 2 | 3 | 4 | // 关于Java Auth0的基本概念和实现 5 | public class Auth0 { 6 | } 7 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/auth/JavaJWT.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.auth; 2 | 3 | 4 | // 关于jjjwt的基本概念和基本权限实现 5 | public class JavaJWT { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/CheckJsonToElasticsearch.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | public class CheckJsonToElasticsearch { 4 | 5 | 6 | } 7 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/BannerService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | import com.lin.missyou.model.Banner; 4 | 5 | public interface BannerService { 6 | Banner getByName(String name); 7 | } 8 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/AuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service 7 | public class AuthenticationService { 8 | 9 | 10 | 11 | } 12 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/dto/VerifyTokenDTO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.dto; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | public class VerifyTokenDTO { 10 | private String token; 11 | } 12 | -------------------------------------------------------------------------------- /missyou/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /missyou/src/main/resources/config/application-prod.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:mysql:http://localhost:3306/testMissyou?characterEncoding=utf-8&serverTimeZone=GMT%2B8 7 | username: root 8 | password: dyh18215153215 -------------------------------------------------------------------------------- /missyou/src/test/java/com/lin/missyou/optional/OptionalTest.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.optional; 2 | 3 | 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class OptionalTest { 7 | 8 | @Test 9 | public void testOptional () { 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/ServerErrorException.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | public class ServerErrorException extends HttpException { 4 | public ServerErrorException(int code) { 5 | this.code = code; 6 | this.httpStatusCode = 500; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/ForbiddenException.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | public class ForbiddenException extends HttpException{ 4 | public ForbiddenException(int code) { 5 | this.httpStatusCode = 403; 6 | this.code = code; 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/ParemeterExcepiton.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | public class ParemeterExcepiton extends HttpException{ 4 | public ParemeterExcepiton(int code) { 5 | this.httpStatusCode = 400; 6 | this.code = code; 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/UnAuthenticatedException.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | public class UnAuthenticatedException extends HttpException{ 4 | public UnAuthenticatedException(int code){ 5 | this.code = code; 6 | this.httpStatusCode = 401; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/bo/PageCounter.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.bo; 2 | 3 | 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | @Getter 9 | @Setter 10 | @Builder 11 | public class PageCounter { 12 | 13 | public Integer page; 14 | public Integer count; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /../../../../../../../../../:\Users\C5312072\Desktop\arthur\frontMiniprogram\mini-program-backend\mini-program-backend\.idea/dataSources/ 6 | /dataSources.local.xml 7 | # Editor-based HTTP Client requests 8 | /httpRequests/ 9 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Spec.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | public class Spec { 10 | 11 | private Long id; 12 | private Long valueId; 13 | private String key; 14 | private String value; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /missyou/src/test/java/com/lin/missyou/MissyouApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class MissyouApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/CreateSuccess.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception; 2 | 3 | import com.lin.missyou.exception.Http.HttpException; 4 | 5 | public class CreateSuccess extends HttpException { 6 | public CreateSuccess(int code){ 7 | this.httpStatusCode = 201; 8 | this.code = code; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/DeleteSuccess.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception; 2 | 3 | import com.lin.missyou.exception.Http.HttpException; 4 | 5 | public class DeleteSuccess extends HttpException { 6 | public DeleteSuccess(int code){ 7 | this.httpStatusCode = 200; 8 | this.code = code; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/UpdateSuccess.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception; 2 | 3 | import com.lin.missyou.exception.Http.HttpException; 4 | 5 | public class UpdateSuccess extends HttpException { 6 | public UpdateSuccess(int code){ 7 | this.httpStatusCode = 200; 8 | this.code = code; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | public class NotFoundException extends HttpException{ 6 | public NotFoundException(int code) { 7 | this.code = code; 8 | this.httpStatusCode = 404; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/GridCategoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.GridCategory; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.List; 7 | 8 | public interface GridCategoryRepository extends JpaRepository { 9 | } 10 | -------------------------------------------------------------------------------- /.idea/mini-program-backend.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/enumeration/LoginType.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.enumeration; 2 | 3 | public enum LoginType { 4 | 5 | USER_WX(0, "微信登陆"), 6 | USER_Email(1, "邮箱登陆"); 7 | 8 | private Integer value; 9 | LoginType(Integer value, String description) { 10 | this.value = value; 11 | } 12 | public void test() { 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/BannerRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Banner; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | 7 | public interface BannerRepository extends JpaRepository { 8 | 9 | Banner findOneById(Long id); 10 | Banner findOneByName(String name); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /missyou/src/test/java/com/lin/missyou/MissyouApplication.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MissyouApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(MissyouApplication.class, args); 10 | } 11 | } -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/CategoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Category; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.List; 7 | 8 | public interface CategoryRepository extends JpaRepository { 9 | 10 | List findAllByIsRootOrderByIndexAsc(Boolean isRoot); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/MissyouApplication.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MissyouApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MissyouApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/exception/Http/HttpException.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.exception.Http; 2 | 3 | public class HttpException extends RuntimeException{ 4 | protected Integer code; 5 | 6 | protected Integer httpStatusCode = 500; 7 | 8 | public Integer getCode() { 9 | return code; 10 | } 11 | 12 | public Integer getHttpStatusCode() { 13 | return httpStatusCode; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/SpuImg.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Table(name = "spu_img", schema = "missyou-v2", catalog = "") 10 | @Setter 11 | @Getter 12 | public class SpuImg extends BaseEntity { 13 | @Id 14 | private Long id; 15 | private String img; 16 | private Long spuId; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/UserCouponRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.UserCoupon; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserCouponRepository extends JpaRepository { 9 | 10 | Optional findFirstByUserIdAndCouponId(Long uid, Long couponId); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/interceptors/ScopeLevel.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.interceptors; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.METHOD, ElementType.TYPE}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ScopeLevel { 11 | int value() default 4; 12 | } 13 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/SpuDetailImg.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Table(name = "spu_detail_img", schema = "missyou-v2", catalog = "") 10 | @Getter 11 | @Setter 12 | public class SpuDetailImg extends BaseEntity { 13 | @Id 14 | private Long id; 15 | private String img; 16 | private Long spuId; 17 | private Long index; 18 | } 19 | -------------------------------------------------------------------------------- /missyou/src/main/resources/config/application-dev.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8088 3 | 4 | 5 | spring: 6 | datasource: 7 | url: jdbc:mysql://localhost:3306/missyou-v2?&characterEncoding=UTF-8&serverTimezone=GMT%2B8 8 | username: root 9 | password: dyh18215153215 10 | jpa: 11 | properties: 12 | hibernate: 13 | show_sql: true 14 | format_sql: true 15 | 16 | 17 | missyou: 18 | security: 19 | jwt-key: 1234567 20 | token-expired-in: 86400000 -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/ActivityCoupon.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.util.Objects; 8 | 9 | @Entity 10 | @Setter 11 | @Getter 12 | @Table(name = "activity_coupon", schema = "missyou", catalog = "") 13 | public class ActivityCoupon extends BaseEntity { 14 | @Id 15 | private Long id; 16 | private Long couponId; 17 | private Long activityId; 18 | } 19 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/ActivityRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Activity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface ActivityRepository extends JpaRepository { 9 | 10 | Activity findByName(String name); 11 | 12 | // 根据优惠券id查询对应的优惠券 13 | Optional findByCouponListId(Long couponId); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserRepository extends JpaRepository { 9 | 10 | User findByEmail(String email); 11 | Optional findByOpenid(String openid); 12 | User findFirstById(Long id); 13 | User findByUnifyUid(Long uuid); 14 | } 15 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/ThemePureVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | public class ThemePureVO { 10 | private Long id; 11 | private String title; 12 | private String description; 13 | private String name; 14 | private String entranceImg; 15 | private String extend; 16 | private String internalTopImg; 17 | private String titleImg; 18 | private String tplName; 19 | private Boolean online; 20 | } 21 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.MappedSuperclass; 8 | import java.util.Date; 9 | 10 | @Getter 11 | @Setter 12 | @MappedSuperclass 13 | public abstract class BaseEntity { 14 | 15 | @JsonIgnore 16 | private Date createTime; 17 | @JsonIgnore 18 | private Date updateTime; 19 | @JsonIgnore 20 | private Date deleteTime; 21 | } 22 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/SpuSimplifyVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | public class SpuSimplifyVO { 10 | 11 | private Long id; 12 | private String title; 13 | private String subtitle; 14 | private String img; 15 | private String discountPrice; 16 | private String description; 17 | private String tags; 18 | private String price; 19 | private String sketchSpecId; 20 | private String forThemeImg; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /missyou/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/token.md: -------------------------------------------------------------------------------- 1 | ###### 关于token 2 | 3 | ###### token的出现 4 | Token的引入:Token是在客户端频繁向服务端请求数据,服务端频繁的去数据库查询用户名和密码并进行对比, 5 | 判断用户名和密码正确与否,并作出相应提示,在这样的背景下,Token便应运而生。 6 | 7 | ###### token的定义 8 | Token是服务端生成的一串字符串,以作客户端进行请求的一个令牌,当第一次登录后, 9 | 服务器生成一个Token便将此Token返回给客户端,以后客户端只需带上这个Token前来请求数据即可, 10 | 无需再次带上用户名和密码 11 | 12 | ###### token的目的 13 | 14 | Token的目的是为了减轻服务器的压力,减少频繁的查询数据库,使服务器更加健壮。 15 | 16 | 17 | ###### token和jwt存在什么区别 18 | 19 | 相同: 都是访问资源的令牌, 都可以记录用户信息,都是只有验证成功后。 20 | 区别:服务端验证客户端发来的token信息要进行数据的查询操作;JWT验证客户端发来的token信息就不用, 21 | 在服务端使用密钥校验就可以,不用数据库的查询。 -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/dto/TokenDTO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.dto; 2 | 3 | 4 | import com.lin.missyou.core.enumeration.LoginType; 5 | import com.lin.missyou.dto.validators.TokenPassword; 6 | import lombok.Getter; 7 | import lombok.Setter; 8 | 9 | import javax.validation.constraints.NotBlank; 10 | 11 | @Getter 12 | @Setter 13 | public class TokenDTO { 14 | @NotBlank(message = "Account 不允许为空") 15 | private String account; 16 | @TokenPassword(min = 6, max = 30, message = "{token.password}") 17 | private String password; 18 | private LoginType type; 19 | } 20 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/SpuRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Spu; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | public interface SpuRepository extends JpaRepository { 9 | 10 | Spu findOneById(Long id); 11 | 12 | Page findByCategoryIdOrderByCreateTimeDesc(Long cid, Pageable pageable); 13 | Page findByRootCategoryIdOrderByCreateTime(Long cid, Pageable pageable); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/BannerServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.model.Banner; 5 | import com.lin.missyou.repository.BannerRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | @Service 10 | public class BannerServiceImpl implements BannerService { 11 | 12 | @Autowired 13 | private BannerRepository bannerRepository; 14 | public Banner getByName(String name) { 15 | // 查询数据库 16 | return bannerRepository.findOneByName(name); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/ActivityService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.model.Activity; 5 | import com.lin.missyou.repository.ActivityRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | @Service 10 | public class ActivityService { 11 | // 调用repository 根据名称查询优惠券 12 | @Autowired 13 | private ActivityRepository activityRepository; 14 | 15 | 16 | public Activity findByName(String name) { 17 | return activityRepository.findByName(name); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/BannerItem.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Date; 9 | import java.util.Objects; 10 | 11 | @Entity 12 | @Table(name = "banner_item", schema = "missyou", catalog = "") 13 | @Getter 14 | @Setter 15 | public class BannerItem extends BaseEntity { 16 | @Id 17 | private Long id; 18 | private String img; 19 | private String keyword; 20 | private short type; 21 | private Long bannerId; 22 | private String name; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/CategoryPureVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | import com.lin.missyou.model.Category; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | import org.springframework.beans.BeanUtils; 7 | 8 | @Getter 9 | @Setter 10 | public class CategoryPureVO { 11 | private Long id; 12 | 13 | private String name; 14 | 15 | private Boolean isRoot; 16 | 17 | private String img; 18 | 19 | private Long parentId; 20 | 21 | private Long index; 22 | 23 | public CategoryPureVO(Category category) { 24 | BeanUtils.copyProperties(category, this); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/dto/validators/TokenPassword.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.dto.validators; 2 | 3 | 4 | import javax.validation.Constraint; 5 | import javax.validation.Payload; 6 | import java.lang.annotation.*; 7 | 8 | @Documented 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target({ElementType.TYPE, ElementType.FIELD}) 11 | @Constraint(validatedBy = TokenPasswordValidator.class) 12 | public @interface TokenPassword { 13 | String message() default "字段不符合要求"; 14 | int min() default 0; 15 | int max() default 8; 16 | Class[] groups() default {}; 17 | Class[] payload() default {}; 18 | } 19 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/GridCategoryService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | import com.lin.missyou.model.GridCategory; 4 | import com.lin.missyou.repository.GridCategoryRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | 10 | @Service 11 | public class GridCategoryService { 12 | 13 | @Autowired 14 | private GridCategoryRepository gridCategoryRepository; 15 | 16 | public List getGridListAll() { 17 | return gridCategoryRepository.findAll(); 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/ActivityCouponVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | 4 | import com.lin.missyou.model.Activity; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | import java.util.List; 9 | import java.util.stream.Collectors; 10 | 11 | @Getter 12 | @Setter 13 | public class ActivityCouponVO extends ActivityPureVO{ 14 | 15 | private List coupons; 16 | 17 | 18 | public ActivityCouponVO(Activity activity) { 19 | super(activity); 20 | coupons = activity.getCouponList() 21 | .stream().map(CouponPureVO::new) 22 | .collect(Collectors.toList()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/configuration/AutoPrefixConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.configuration; 2 | 3 | import com.lin.missyou.core.hack.AutoPrefixUrlMapping; 4 | import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 7 | 8 | @Component 9 | public class AutoPrefixConfiguration implements WebMvcRegistrations { 10 | 11 | @Override 12 | public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { 13 | return new AutoPrefixUrlMapping(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/ThemeRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Theme; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | @Repository 12 | public interface ThemeRepository extends JpaRepository { 13 | 14 | @Query("select t from Theme t where t.name in (:names)") 15 | List findByNames(List names); 16 | 17 | @Query 18 | Optional findByName(String name); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/UserCoupon.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | import java.sql.Timestamp; 7 | import java.util.Date; 8 | import java.util.Objects; 9 | 10 | @Entity 11 | @Setter 12 | @Getter 13 | @Builder 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | @Table(name = "user_coupon", schema = "missyou", catalog = "") 17 | public class UserCoupon extends BaseEntity { 18 | @Id 19 | private Long id; 20 | private Long userId; 21 | private Long couponId; 22 | private Integer status; 23 | private Long orderId; 24 | private Date updateTime; 25 | private Date createTime; 26 | } 27 | -------------------------------------------------------------------------------- /missyou/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | spring: 3 | profiles: 4 | active: dev 5 | jpa: 6 | hibernate: 7 | ddl-auto: update 8 | jackson: 9 | property-naming-strategy: SNAKE_CASE 10 | serialization: 11 | WRITE_DATES_AS_TIMESTAMPS: true 12 | 13 | missyou: 14 | api-package: com.lin.missyou.api 15 | 16 | server: 17 | servlet: 18 | encoding: 19 | force: true 20 | charset: utf-8 21 | enabled: true 22 | 23 | 24 | wx: 25 | appid: wx0d1cc0de3e7e3d53 26 | appsecret: b8177e8cd7a7dc411576e49124270025 27 | code2session: https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code 28 | 29 | 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/enumeration/CouponStatus.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.enumeration; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public enum CouponStatus { 6 | 7 | AVAILABLE(1, "可以使用为过期"), 8 | USED(2, "已使用"), 9 | EXPIRED(3, "未使用,已过期"); 10 | 11 | private Integer value; 12 | 13 | public Integer getValue() { 14 | return this.value; 15 | } 16 | 17 | CouponStatus(Integer value, String description) { 18 | this.value = value; 19 | } 20 | 21 | public static CouponStatus toType(int value) { 22 | return Stream.of(CouponStatus.values()).filter(c -> c.value == value) 23 | .findAny() 24 | .orElse(null); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/GridCategory.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Date; 9 | import java.util.Objects; 10 | 11 | @Entity 12 | @Setter 13 | @Getter 14 | @Table(name = "grid_category", schema = "missyou", catalog = "") 15 | public class GridCategory { 16 | @Id 17 | private Long id; 18 | private String title; 19 | private String img; 20 | private String name; 21 | private Date createTime; 22 | private Date updateTime; 23 | private Date deleteTime; 24 | private Integer categoryId; 25 | private Integer rootCategoryId; 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/tencentSerivce.md: -------------------------------------------------------------------------------- 1 | 1: df -h 查看分区情况以及数据盘名称 2 | 2: sudo -i 切换到root超级用户 3 | 4 | 5 | 6 | ### Linux yum命令 7 | 8 | yum( Yellow dog Updater Modified) 是一个再Fedoras和Redhat以及Shell前端软件包管理器 9 | 基于 RPM包管理,能够从指定的服务器自动下载RPM包并且安装,可以自己处理依赖关系,并且可以一次安装所有依赖的软件包 10 | 11 | yum语法 12 | 13 | ```shell script 14 | yum [options] [command] [package] 15 | ``` 16 | 17 | - options 可选 选项包括 -h(help) -y(当安装过程提示全部为yes) q(不显示安装过程) 等等 18 | - command 要进行的操作 19 | - package 安装包的包名 20 | 21 | yum的常用命令 22 | 23 | - 列出所有可能更新的软件清单命令 24 | - yum list 25 | - yum install 26 | - yum remove 27 | - yum search 28 | - yum update 29 | 30 | - yum clean package 31 | - yum clean headers 32 | - yum clean oldheaders 33 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Banner.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Date; 9 | import java.util.List; 10 | import java.util.Objects; 11 | 12 | @Entity 13 | @Table(name = "banner", schema = "missyou", catalog = "") 14 | @Getter 15 | @Setter 16 | public class Banner extends BaseEntity { 17 | @Id 18 | private Long id; 19 | private String name; 20 | private String description; 21 | private String title; 22 | private String img; 23 | 24 | @OneToMany(fetch = FetchType.LAZY) 25 | @JoinColumn(name = "bannerId") 26 | private List items; 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/CategoryAllVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | import com.lin.missyou.model.Category; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | import org.springframework.beans.BeanUtils; 7 | 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.stream.Collectors; 11 | 12 | @Setter 13 | @Getter 14 | public class CategoryAllVO { 15 | 16 | private List roots; 17 | private List subs; 18 | 19 | public CategoryAllVO(Map> map) { 20 | this.roots = map.get(1).stream().map(CategoryPureVO::new).collect(Collectors.toList()); 21 | this.subs = map.get(2).stream().map(CategoryPureVO::new).collect(Collectors.toList()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/CommonUtil.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | 4 | import com.lin.missyou.bo.PageCounter; 5 | 6 | import java.util.Date; 7 | 8 | public class CommonUtil { 9 | 10 | public static PageCounter ConvertToPageParameter (Integer start, Integer count) { 11 | 12 | int pageNum = start / count; 13 | return PageCounter.builder() 14 | .page(pageNum) 15 | .count(count) 16 | .build(); 17 | } 18 | 19 | 20 | public static Boolean isInTimeLine(Date date, Date start, Date end) { 21 | long time = date.getTime(); 22 | long startTime = start.getTime(); 23 | long endTime = end.getTime(); 24 | return time > startTime && time < endTime; 25 | } 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/UnifyResponse.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core; 2 | 3 | import com.lin.missyou.exception.CreateSuccess; 4 | 5 | public class UnifyResponse { 6 | 7 | private int code; 8 | private String message; 9 | private String request; 10 | 11 | public static void createSuccess(int code) { 12 | throw new CreateSuccess(code); 13 | } 14 | public int getCode() { 15 | return code; 16 | } 17 | 18 | public String getMessage() { 19 | return message; 20 | } 21 | 22 | public String getRequest() { 23 | return request; 24 | } 25 | 26 | public UnifyResponse(int code, String message, String request) { 27 | this.code = code; 28 | this.message = message; 29 | this.request = request; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/ActivityPureVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | 4 | import com.lin.missyou.model.Activity; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | import org.springframework.beans.BeanUtils; 9 | 10 | @Setter 11 | @Getter 12 | @NoArgsConstructor 13 | public class ActivityPureVO { 14 | private Long id; 15 | private String title; 16 | private String entranceImg; 17 | private Boolean online; 18 | private String remark; 19 | private String startTime; 20 | private String endTime; 21 | 22 | public ActivityPureVO(Activity activity) { 23 | BeanUtils.copyProperties(activity,this); 24 | } 25 | 26 | public ActivityPureVO(Object object){ 27 | BeanUtils.copyProperties(object, this); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/CouponCategoryVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | 4 | import com.lin.missyou.model.Category; 5 | import com.lin.missyou.model.Coupon; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | @Getter 14 | @Setter 15 | @NoArgsConstructor 16 | public class CouponCategoryVO extends CouponPureVO { 17 | private List categories = new ArrayList<>(); 18 | 19 | public CouponCategoryVO(Coupon coupon) { 20 | super(coupon); 21 | List categories = coupon.getCategoryList(); 22 | categories.forEach(category -> { 23 | CategoryPureVO vo = new CategoryPureVO(category); 24 | this.categories.add(vo); 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/ThemeService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | import com.lin.missyou.model.Theme; 4 | import com.lin.missyou.repository.ThemeRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | 12 | @Service 13 | public class ThemeService { 14 | // service 调用repository 15 | // repository jpa去查数据库返回结果 16 | // 引入repository 17 | @Autowired 18 | private ThemeRepository themeRepository; 19 | 20 | public List findByNames (List names) { 21 | return themeRepository.findByNames(names); 22 | } 23 | 24 | public Optional findByName(String name) { 25 | return themeRepository.findByName(name); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/configuration/ExceptionCodeConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.configuration; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.context.annotation.PropertySource; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | 11 | @ConfigurationProperties(prefix = "lin") 12 | @PropertySource(value = "classpath:config/exception-code.properties") 13 | @Component 14 | public class ExceptionCodeConfiguration { 15 | 16 | private final Map codes = new HashMap<>(); 17 | 18 | public Map getCodes() { 19 | return codes; 20 | } 21 | 22 | 23 | public String getMessage(int code) { 24 | return codes.get(code); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/PagingDozer.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | import com.github.dozermapper.core.DozerBeanMapperBuilder; 4 | import com.github.dozermapper.core.Mapper; 5 | import org.springframework.data.domain.Page; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class PagingDozer extends Paging { 11 | 12 | @SuppressWarnings("unchecked") 13 | public PagingDozer(Page pageT, Class classK) { 14 | this.initPageParameters(pageT); 15 | List tList = pageT.getContent(); 16 | Mapper mapper = DozerBeanMapperBuilder.buildDefault(); 17 | List voList = new ArrayList<>(); 18 | tList.forEach(s-> { 19 | K vo = mapper.map(s, classK); 20 | voList.add(vo); 21 | }); 22 | this.setItems(voList); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Activity.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Date; 9 | import java.util.List; 10 | import java.util.Objects; 11 | 12 | @Entity 13 | @Getter 14 | @Setter 15 | public class Activity extends BaseEntity{ 16 | @Id 17 | private Long id; 18 | private String title; 19 | private String description; 20 | private Date startTime; 21 | private Date endTime; 22 | private String remark; 23 | private Boolean online; 24 | private String entranceImg; 25 | private String internalTopImg; 26 | private String name; 27 | 28 | 29 | @OneToMany(fetch = FetchType.LAZY) 30 | @JoinColumn(name = "activityId") 31 | private List couponList; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/Paging.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | import lombok.Setter; 6 | import org.springframework.data.domain.Page; 7 | 8 | import java.util.List; 9 | 10 | 11 | @Getter 12 | @Setter 13 | @NoArgsConstructor 14 | public class Paging { 15 | 16 | private Long total; 17 | private Integer count; 18 | private Integer page; 19 | private Integer totalPage; 20 | private List items; 21 | 22 | public Paging(Page pageT) { 23 | this.initPageParameters(pageT); 24 | this.items = pageT.getContent(); 25 | } 26 | 27 | void initPageParameters(Page pageT) { 28 | this.total = pageT.getTotalElements(); 29 | this.count = pageT.getSize(); 30 | this.page = pageT.getNumber(); 31 | this.totalPage = this.getTotalPage(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/User.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import com.lin.missyou.util.MapAndJson; 4 | import lombok.*; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Map; 9 | import java.util.Objects; 10 | 11 | import static javax.persistence.GenerationType.IDENTITY; 12 | 13 | @Entity 14 | @Getter 15 | @Setter 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | public class User extends BaseEntity{ 20 | @Id 21 | @GeneratedValue(strategy = IDENTITY) 22 | private Long id; 23 | private String openid; 24 | private String nickname; 25 | private Long unifyUid; 26 | private String email; 27 | private String password; 28 | private String mobile; 29 | // private Object wxProfile; 30 | 31 | @Convert(converter = MapAndJson.class) 32 | @Transient 33 | private Map wxProfile; 34 | 35 | } 36 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/ImportJsonToElasticsearch.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | 4 | 5 | import java.io.*; 6 | import java.nio.charset.StandardCharsets; 7 | 8 | public class ImportJsonToElasticsearch { 9 | 10 | 11 | // 以本地json为例子 12 | public static String readJsonFile() throws IOException { 13 | String jsonString = ""; 14 | // 读取本地json 15 | File file = new File("/Users/wanggang/Desktop/index.json"); 16 | FileReader fileReader = new FileReader(file); 17 | Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); 18 | int ch = 0; 19 | StringBuilder sb = new StringBuilder(); 20 | while ((ch = reader.read()) != -1) { 21 | sb.append((char) ch); 22 | } 23 | fileReader.close(); 24 | reader.close(); 25 | jsonString = sb.toString(); 26 | return jsonString; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/dto/validators/TokenPasswordValidator.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.dto.validators; 2 | 3 | import org.springframework.util.StringUtils; 4 | 5 | import javax.validation.ConstraintValidator; 6 | import javax.validation.ConstraintValidatorContext; 7 | 8 | public class TokenPasswordValidator implements ConstraintValidator { 9 | 10 | private Integer min; 11 | private Integer max; 12 | 13 | @Override 14 | public void initialize(TokenPassword constraintAnnotation) { 15 | this.max = constraintAnnotation.max(); 16 | this.min = constraintAnnotation.min(); 17 | } 18 | 19 | @Override 20 | public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { 21 | // isEmpty已经被遗弃 22 | if(StringUtils.hasLength(s)) { 23 | return true; 24 | } 25 | return s.length() >= this.min && s.length() <= this.max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/CategoryService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.model.Category; 5 | import com.lin.missyou.repository.CategoryRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @Service 14 | public class CategoryService { 15 | 16 | @Autowired 17 | private CategoryRepository categoryRepository; 18 | 19 | public Map> getALl () { 20 | List roots = categoryRepository.findAllByIsRootOrderByIndexAsc(true); 21 | List subs = categoryRepository.findAllByIsRootOrderByIndexAsc(false); 22 | Map> categories = new HashMap<>(); 23 | categories.put(1, roots); 24 | categories.put(2, subs); 25 | return categories; 26 | } 27 | 28 | } 29 | 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/configuration/InterceptorConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.configuration; 2 | 3 | import com.lin.missyou.core.interceptors.PermissionInterceptor; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.web.servlet.HandlerInterceptor; 8 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 10 | 11 | 12 | @Configuration 13 | public class InterceptorConfiguration implements WebMvcConfigurer { 14 | 15 | @Bean 16 | public HandlerInterceptor permissionInterceptor() { 17 | return new PermissionInterceptor(); 18 | } 19 | 20 | @Override 21 | public void addInterceptors(InterceptorRegistry registry) { 22 | registry.addInterceptor(this.permissionInterceptor()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Coupon.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import com.sun.org.apache.xpath.internal.operations.Bool; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.*; 8 | import java.math.BigDecimal; 9 | import java.sql.Timestamp; 10 | import java.util.Date; 11 | import java.util.List; 12 | import java.util.Objects; 13 | 14 | @Entity 15 | @Setter 16 | @Getter 17 | public class Coupon extends BaseEntity { 18 | 19 | @Id 20 | private Long id; 21 | private String title; 22 | private Date startTime; 23 | private Date endTime; 24 | private String description; 25 | private BigDecimal fullMoney; 26 | private BigDecimal minus; 27 | private BigDecimal rate; 28 | private short type; 29 | private Long activityId; 30 | private String remark; 31 | private Boolean wholeStore; 32 | 33 | @ManyToMany(fetch = FetchType.LAZY, mappedBy = "couponList") 34 | private List categoryList; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/LocalUser.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core; 2 | 3 | import com.lin.missyou.model.User; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class LocalUser { 9 | 10 | private static final ThreadLocal> mapThreadLocal = new ThreadLocal>(); 11 | 12 | private static User user; 13 | public static void set(User user, Integer scope) { 14 | Map map = new HashMap<>(); 15 | map.put("user", user); 16 | map.put("scope", scope); 17 | LocalUser.mapThreadLocal.set(map); 18 | } 19 | public static void clear() { 20 | LocalUser.mapThreadLocal.remove(); 21 | } 22 | public static User getUser() { 23 | Map map = LocalUser.mapThreadLocal.get(); 24 | return (User) map.get("user"); 25 | } 26 | 27 | public static Integer getScoped() { 28 | Map map = LocalUser.mapThreadLocal.get(); 29 | return (Integer) map.get("scope"); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Category.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import javax.persistence.*; 8 | import java.sql.Timestamp; 9 | import java.util.Date; 10 | import java.util.List; 11 | import java.util.Objects; 12 | 13 | @Entity 14 | @Getter 15 | @Setter 16 | @Table(name = "category", schema = "missyou", catalog = "") 17 | public class Category { 18 | 19 | @Id 20 | private Long id; 21 | 22 | private String name; 23 | 24 | private String description; 25 | 26 | private Boolean isRoot; 27 | 28 | private String img; 29 | 30 | private Long parentId; 31 | 32 | private Long index; 33 | 34 | // 和优惠券的关系 多对多 35 | 36 | @ManyToMany(fetch = FetchType.LAZY) 37 | @JoinTable(name = "coupon_category", 38 | joinColumns = @JoinColumn(name = "category_id"), 39 | inverseJoinColumns = @JoinColumn(name = "coupon_id") 40 | ) 41 | private List couponList; 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Theme.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.persistence.*; 8 | import java.sql.Timestamp; 9 | import java.util.List; 10 | import java.util.Objects; 11 | 12 | @Entity 13 | @Setter 14 | @Getter 15 | public class Theme extends BaseEntity { 16 | @Id 17 | private Long id; 18 | private String title; 19 | private String description; 20 | private String name; 21 | private Timestamp createTime; 22 | private String tplName; 23 | private Timestamp updateTime; 24 | private Timestamp deleteTime; 25 | private String entranceImg; 26 | private String extend; 27 | private String internalTopImg; 28 | private String titleImg; 29 | private Boolean online; 30 | 31 | 32 | @ManyToMany(fetch = FetchType.LAZY) 33 | @JoinTable(name = "theme_spu", joinColumns = @JoinColumn(name="theme_id") 34 | , inverseJoinColumns = @JoinColumn(name = "spu_id")) 35 | private List spuList; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.core.LocalUser; 5 | import com.lin.missyou.model.User; 6 | import com.lin.missyou.repository.UserRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.Map; 11 | 12 | @Service 13 | public class UserService { 14 | 15 | @Autowired 16 | private UserRepository userRepository; 17 | 18 | public User getUserById(Long id) { 19 | return userRepository.findFirstById(id); 20 | } 21 | public void updateUserWxInfo(Map wxUser) { 22 | User user =this.getUserById(LocalUser.getUser().getId()); 23 | user.setNickname(wxUser.get("nickName").toString()); 24 | user.setWxProfile(wxUser); 25 | userRepository.save(user); 26 | } 27 | 28 | // public User createDevUser(Long uid) { 29 | // User newUser = User.builder().unifyUid(uid).build(); 30 | // userRepository.save(newUser); 31 | // return newUser; 32 | // } 33 | 34 | public User getUserByUnifyUid(Long uuid) { 35 | return userRepository.findByUnifyUid(uuid); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/hack/AutoPrefixUrlMapping.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.hack; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 5 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 6 | 7 | import java.lang.reflect.Method; 8 | 9 | public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping { 10 | 11 | @Value("${missyou.api-package}") 12 | private String apiPackagePath; 13 | 14 | @Override 15 | protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { 16 | RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType); 17 | if (mappingInfo != null) { 18 | String prefix = this.getPrefix(handlerType); 19 | return RequestMappingInfo.paths(prefix).build().combine(mappingInfo); 20 | } 21 | return mappingInfo; 22 | } 23 | 24 | private String getPrefix(Class handlerType) { 25 | String packageName = handlerType.getPackage().getName(); 26 | String dotPath = packageName.replaceAll(this.apiPackagePath, ""); 27 | return dotPath.replace(".", "/"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Spu.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.sql.Timestamp; 8 | import java.util.Date; 9 | import java.util.List; 10 | import java.util.Objects; 11 | 12 | @Entity 13 | @Getter 14 | @Setter 15 | public class Spu extends BaseEntity { 16 | @Id 17 | private Long id; 18 | private String title; 19 | private String subtitle; 20 | private Long categoryId; 21 | private Long rootCategoryId; 22 | private Boolean online; 23 | private String price; 24 | private Long sketchSpecId; 25 | private Long defaultSkuId; 26 | private String img; 27 | private String discountPrice; 28 | private String description; 29 | private String tags; 30 | private Boolean isTest; 31 | // private Object spuThemeImg; 32 | private String forThemeImg; 33 | 34 | 35 | @OneToMany(fetch = FetchType.LAZY) 36 | @JoinColumn(name = "spuId") 37 | private List skuList; 38 | 39 | @OneToMany(fetch = FetchType.LAZY) 40 | @JoinColumn(name = "spuId") 41 | private List spuImgList; 42 | 43 | @OneToMany(fetch = FetchType.LAZY) 44 | @JoinColumn(name = "spuId") 45 | private List spuDetailImgList; 46 | 47 | } 48 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/vo/CouponPureVO.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.vo; 2 | 3 | import com.lin.missyou.model.Coupon; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | import org.springframework.beans.BeanUtils; 8 | 9 | import java.math.BigDecimal; 10 | import java.util.Date; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | 14 | 15 | @Setter 16 | @Getter 17 | @NoArgsConstructor 18 | public class CouponPureVO { 19 | private Long id; 20 | private String title; 21 | private Date startTime; 22 | private Date endTime; 23 | private String description; 24 | private BigDecimal fullMoney; 25 | private BigDecimal minus; 26 | private BigDecimal rate; 27 | private Integer type; 28 | private String remark; 29 | private Boolean wholeStore; 30 | 31 | public CouponPureVO(Object[] objects){ 32 | Coupon coupon = (Coupon) objects[0]; 33 | BeanUtils.copyProperties(coupon, this); 34 | } 35 | 36 | public CouponPureVO(Coupon coupon){ 37 | BeanUtils.copyProperties(coupon, this); 38 | } 39 | 40 | public static List getList(List couponList) { 41 | return couponList.stream() 42 | .map(CouponPureVO::new) 43 | .collect(Collectors.toList()); 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/model/Sku.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.model; 2 | 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import com.lin.missyou.util.GenericAndJson; 5 | import com.lin.missyou.util.ListAndJon; 6 | import com.lin.missyou.util.MapAndJson; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | 10 | import javax.persistence.*; 11 | import java.math.BigDecimal; 12 | import java.sql.Timestamp; 13 | import java.util.*; 14 | 15 | @Entity 16 | @Getter 17 | @Setter 18 | public class Sku { 19 | @Id 20 | private Long id; 21 | private BigDecimal price; 22 | private BigDecimal discountPrice; 23 | private Boolean online; 24 | private String img; 25 | private String title; 26 | private Long spuId; 27 | private String specs; 28 | 29 | 30 | public List getSpecs() { 31 | if (this.specs == null) { 32 | return Collections.emptyList(); 33 | } 34 | return GenericAndJson.jsonToObject(this.specs, new TypeReference>() { 35 | }); 36 | } 37 | 38 | public void setSpecs(List specs) { 39 | if (specs.isEmpty()) { 40 | return; 41 | } 42 | this.specs = GenericAndJson.objectToJson(specs); 43 | } 44 | 45 | private String code; 46 | private Long stock; 47 | private Long categoryId; 48 | private Long rootCategoryId; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/ListAndJon.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.lin.missyou.exception.Http.ServerErrorException; 6 | import org.apache.commons.collections.map.HashedMap; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | 9 | import javax.persistence.AttributeConverter; 10 | import java.util.List; 11 | 12 | public class ListAndJon implements AttributeConverter, String> { 13 | 14 | @Autowired 15 | private ObjectMapper mapper; 16 | 17 | @Override 18 | public String convertToDatabaseColumn(List objects) { 19 | try { 20 | return mapper.writeValueAsString(objects); 21 | } catch (JsonProcessingException e) { 22 | e.printStackTrace(); 23 | throw new ServerErrorException(9999); 24 | } 25 | } 26 | 27 | @Override 28 | @SuppressWarnings("unchecked") 29 | public List convertToEntityAttribute(String s) { 30 | try { 31 | if (s == null) { 32 | return null; 33 | } 34 | List t = mapper.readValue(s, List.class); 35 | return t; 36 | } catch (JsonProcessingException e) { 37 | e.printStackTrace(); 38 | throw new ServerErrorException(9999); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/MapAndJson.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.lin.missyou.exception.Http.ServerErrorException; 7 | import org.apache.commons.collections.map.HashedMap; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | 10 | import javax.persistence.AttributeConverter; 11 | import javax.persistence.Converter; 12 | import java.util.Map; 13 | 14 | //java实体的类型 15 | // 数据类型? 16 | @Converter 17 | public class MapAndJson implements AttributeConverter, String> { 18 | 19 | @Autowired 20 | private ObjectMapper mapper; 21 | 22 | @Override 23 | public String convertToDatabaseColumn(Map stringObjectMap) { 24 | try { 25 | return mapper.writeValueAsString(stringObjectMap); 26 | } catch (JsonProcessingException e) { 27 | e.printStackTrace(); 28 | throw new ServerErrorException(9999); 29 | } 30 | } 31 | 32 | @Override 33 | @SuppressWarnings("unchecked") 34 | public Map convertToEntityAttribute(String s) { 35 | try { 36 | return mapper.readValue(s, HashedMap.class); 37 | } catch (JsonProcessingException e) { 38 | e.printStackTrace(); 39 | throw new ServerErrorException(9999); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/testOptional.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.mark; 2 | 3 | 4 | // 关于optional 5 | // optional类是Java8的新特性 可以理解是一个为null的对象,如果值存在 则isPresent() 方法返回true, 条用get()方法会返回该对象。 6 | // optional是个容器,可以保存类型T的值,或者仅仅保存null,不用显示的检测空值,很好的解决了空指针的异常 7 | 8 | 9 | public class testOptional { 10 | // 访问optional的值 11 | // String name = "arthur"; 12 | // Optional optionalString = Optional.of(name); 13 | // String tesName = optionalString.get(); 14 | 15 | // 可以使用of()和ofNullable()方法创建包含值的Optional。两个方法的不同之处在于如果你把null作为参数传递进去,of方法会抛出NullpointerException错误 16 | // 因此明确对象不为null的时候 用of()方法 17 | // 如果对象可能是null或者是非null 使用 ofNullable()方法 18 | // User user = new User("john@gmail.com", "1234"); 19 | // Optional optionalUser = Optional.ofNullable(user); 20 | // 因为optional传入的值为null的时候 也会抛出异常 因此首先要验证是否有值 21 | //if (opt.isPresent()) { 22 | // 如果值存在.. 23 | //} 24 | 25 | // orElse() 26 | // @Test 27 | // public void whenEmptyValue_thenReturnDefault() { 28 | // User user = null; 29 | // User user2 = new User("anna@gmail.com", "1234"); 30 | // User result = Optional.ofNullable(user).orElse(user2); 31 | // 32 | // assertEquals(user2.getEmail(), result.getEmail()); 33 | // } 34 | // 这里 user 对象是空的,所以返回了作为默认值的 user2。 35 | // 如果对象的初始值不是 null,那么默认值会被忽略: 36 | 37 | // 返回异常 38 | // orElseThrow 对象为空的时候抛出异常 39 | // 可以自定义这样的异常 40 | } -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/SpuService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.bo.PageCounter; 5 | import com.lin.missyou.model.Spu; 6 | import com.lin.missyou.repository.SpuRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.PageRequest; 10 | import org.springframework.data.domain.Pageable; 11 | import org.springframework.data.domain.Sort; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.util.List; 15 | 16 | @Service 17 | public class SpuService { 18 | 19 | @Autowired 20 | SpuRepository spuRepository; 21 | 22 | public Spu getSpu(Long id) { 23 | return this.spuRepository.findOneById(id); 24 | } 25 | 26 | public Page getLatestPagingSpu(Integer pageNum, Integer size) { 27 | Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending()); 28 | return this.spuRepository.findAll(page); 29 | } 30 | 31 | public Page getByCategory(Long cid, Boolean isRoot, Integer pageNum, Integer size) { 32 | Pageable page = PageRequest.of(pageNum, size); 33 | if (isRoot) { 34 | return this.spuRepository.findByRootCategoryIdOrderByCreateTime(cid, page); 35 | } 36 | else { 37 | return this.spuRepository.findByCategoryIdOrderByCreateTimeDesc(cid, page); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/GenericAndJson.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.core.type.TypeReference; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.lin.missyou.exception.Http.ServerErrorException; 7 | import javafx.scene.image.PixelFormat; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.List; 12 | 13 | 14 | @Component 15 | public class GenericAndJson { 16 | 17 | 18 | private static ObjectMapper mapper; 19 | 20 | @Autowired 21 | public void setMapper(ObjectMapper mapper) { 22 | GenericAndJson.mapper = mapper; 23 | } 24 | 25 | public static String objectToJson(T o) { 26 | try { 27 | return GenericAndJson.mapper.writeValueAsString(o); 28 | } catch (JsonProcessingException e) { 29 | e.printStackTrace(); 30 | throw new ServerErrorException(9999); 31 | } 32 | } 33 | 34 | public static T jsonToObject(String s, TypeReference tr) { 35 | if (s == null) { 36 | return null; 37 | } 38 | try { 39 | return GenericAndJson.mapper.readValue(s, tr); 40 | } catch (JsonProcessingException e) { 41 | e.printStackTrace(); 42 | throw new ServerErrorException(9999); 43 | } 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/CategoryController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | 4 | import com.lin.missyou.exception.Http.NotFoundException; 5 | import com.lin.missyou.model.Category; 6 | import com.lin.missyou.model.GridCategory; 7 | import com.lin.missyou.service.CategoryService; 8 | import com.lin.missyou.service.GridCategoryService; 9 | import com.lin.missyou.vo.CategoryAllVO; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | @RequestMapping("category") 16 | @RestController 17 | @ResponseBody 18 | public class CategoryController { 19 | 20 | private final CategoryService categoryService; 21 | 22 | private final GridCategoryService gridCategoryService; 23 | 24 | public CategoryController(CategoryService categoryService, GridCategoryService gridCategoryService) { 25 | this.categoryService = categoryService; 26 | this.gridCategoryService = gridCategoryService; 27 | } 28 | 29 | @GetMapping("/all") 30 | public CategoryAllVO getAll () { 31 | Map> categories = categoryService.getALl(); 32 | return new CategoryAllVO(categories); 33 | } 34 | 35 | @GetMapping("/grid/all") 36 | public List getGridCategory() { 37 | List gridCategories = gridCategoryService.getGridListAll(); 38 | if (gridCategories.isEmpty()) { 39 | throw new NotFoundException(30009); 40 | } 41 | return gridCategories; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/doubleToken.md: -------------------------------------------------------------------------------- 1 | ### 双token验证机制 2 | 3 | ###### 前置场景 4 | 5 | 在基于token验证登录态这个情境下。token突然就过期了,然后只好被迫停止现在正在进行的操作跳转到登录页进行重新登录操作,这就非常的智熄了,这带给用户, 6 | 特别是经常使用或正在进行某个操作的用户,一种非常不好的体验。这就是单token验证登录的一个缺点。 7 | 因此对于经常/正在使用或经常/正在进行操作的用户(我称之为活跃用户)就不应当跳转到登录页面进行登陆操作(除了某些敏感系统或包含敏感信息进行敏感操作的网页、app、系统), 8 | 对于这个缺点的解决,来一个双token的验证机制。 9 | 10 | ###### 什么是双token机制 11 | 12 | 就是在登陆操作之后由服务端返回两个token:accessToken和refreshToken,在之后的验证登录态的操作中使用这两个token进行验证, 13 | 其中accessToken的过期时间相当短,refreshToken的过期时间相对于accessToken而言相当长,且会不断的刷新,每次刷新后的refreshToken都是不同的 14 | 15 | ###### 双token验证的优点 16 | 17 | - accessToken的存在,保证了登录态的正常验证,因其过期时间的短暂也保证了帐号的安全性 18 | - refreshToken的存在,保证了用户(即使是非活跃用户)无需在短时间内进行反复的登陆操作来保证登录态的有效性, 19 | 同时也保证了活跃用户的登录态可以一直存续而不需要进行重新登录,其反复刷新也防止某些不怀好意的人获取refreshToken后对用户帐号进行动手动脚的操作 20 | 21 | ###### 双token检验流程 22 | 23 | 首先进行正常的登录操作,在后台服务器验证账号密码成功之后返回2个token:accessToken和refreshToken。在进行服务器请求的时候,先将Token发送验证, 24 | 如果accessToken有效,则正常返回请求结果;如果accessToken无效,则验证refreshToken。 25 | 此时如果refreshToken有效则返回请求结果和新的accessToken和新的refreshToken。如果refreshToken无效,则提示用户进行重新登陆操作。 26 | 27 | ###### 流程图如下 28 | 29 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/bf0e12a2b67b41b0ae70dacfe5ff1c2d.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAYXJ0aHVyd2FuZ2dhbmc=,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center) 30 | 31 | 32 | ### 应用 33 | 34 | ###### PC端应用 35 | 36 | 由于token可以直接直观地获取到,因此不管是accessToken还是refreshToken为了安全起见,其过期时间都不应该设置得很长,且需要不停地更换token, 37 | 因此PC网络应用的accessToken一般设置为2h过期,而refreshToken设置为1天到2天比较好,不足1天也是可以的,如果设置的时间比较短就在活跃期间时常刷新freshToken就好了 38 | 39 | ###### 手机应用 40 | ###### 无效的Token的处理 41 | 42 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/ActivityController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | 4 | import com.lin.missyou.exception.Http.NotFoundException; 5 | import com.lin.missyou.model.Activity; 6 | import com.lin.missyou.service.ActivityService; 7 | import com.lin.missyou.vo.ActivityCouponVO; 8 | import com.lin.missyou.vo.ActivityPureVO; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | @RestController 15 | @RequestMapping("activity") 16 | public class ActivityController { 17 | 18 | private final ActivityService activityService; 19 | 20 | public ActivityController(ActivityService activityService) { 21 | this.activityService = activityService; 22 | } 23 | 24 | // 根据名称查询对应的优惠券 25 | @GetMapping("/name/{name}") 26 | public ActivityPureVO getCouponByName(@PathVariable String name) { 27 | Activity activity = activityService.findByName(name); 28 | if (activity == null) { 29 | throw new NotFoundException(40001); 30 | } 31 | return new ActivityPureVO(activity); 32 | } 33 | // 根据spu 查询对应的优惠券 34 | @GetMapping("/name/{name}/with_coupon") 35 | public ActivityCouponVO getActivityWithCoupon(@PathVariable String name) { 36 | Activity activity = activityService.findByName(name); 37 | if (activity == null) { 38 | throw new NotFoundException(40001); 39 | } 40 | return new ActivityCouponVO(activity); 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/ThemeController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | import com.github.dozermapper.core.DozerBeanMapperBuilder; 3 | import com.github.dozermapper.core.Mapper; 4 | import com.lin.missyou.exception.Http.NotFoundException; 5 | import com.lin.missyou.model.Theme; 6 | import com.lin.missyou.service.ThemeService; 7 | import com.lin.missyou.vo.ThemePureVO; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.List; 13 | import java.util.Optional; 14 | 15 | @RestController 16 | @RequestMapping("theme") 17 | public class ThemeController { 18 | 19 | private final ThemeService themeService; 20 | 21 | public ThemeController(ThemeService themeService) { 22 | this.themeService = themeService; 23 | } 24 | 25 | // 提供两个接口 26 | @GetMapping("/by/names") 27 | public List getThemeGroupByNames(@RequestParam(name = "names") String names) { 28 | // 前端传参数,分割 29 | List nameList = Arrays.asList(names.split(",")); 30 | List themes = themeService.findByNames(nameList); 31 | List list = new ArrayList<>(); 32 | themes.forEach(theme -> { 33 | Mapper mapper = DozerBeanMapperBuilder.buildDefault(); 34 | ThemePureVO vo = mapper.map(theme, ThemePureVO.class); 35 | list.add(vo); 36 | }); 37 | return list; 38 | } 39 | 40 | // with_spu接口 41 | @GetMapping("/by/{name}/with_spu") 42 | public Theme getThemeByNameWithSpu(@PathVariable(name = "name") String themeName) { 43 | Optional optionalTheme = themeService.findByName(themeName); 44 | return optionalTheme.orElseThrow(() -> new NotFoundException(30003)); 45 | } 46 | 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/TokenController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | 4 | import com.lin.missyou.dto.TokenDTO; 5 | import com.lin.missyou.dto.VerifyTokenDTO; 6 | import com.lin.missyou.dto.doubleTokenDTO; 7 | import com.lin.missyou.exception.Http.NotFoundException; 8 | import com.lin.missyou.service.WxAuthenticationService; 9 | import com.lin.missyou.util.JwtToken; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | @RestController 19 | @RequestMapping(value = "token") 20 | public class TokenController { 21 | 22 | private final WxAuthenticationService wxAuthenticationService; 23 | public TokenController(WxAuthenticationService wxAuthenticationService) { 24 | this.wxAuthenticationService = wxAuthenticationService; 25 | } 26 | 27 | @PostMapping("/getToken") 28 | public Map getToken(@RequestBody TokenDTO useData) { 29 | Map map = new HashMap<>(); 30 | String token = null; 31 | switch (useData.getType()) { 32 | case USER_WX: 33 | token = wxAuthenticationService.code2Session(useData.getAccount()); 34 | break; 35 | case USER_Email: 36 | break; 37 | default: 38 | throw new NotFoundException(10003); 39 | } 40 | map.put("token", token); 41 | return map; 42 | } 43 | 44 | // 验证token 45 | @PostMapping("/verify") 46 | public Map verifyToken(@RequestBody VerifyTokenDTO tokenDTO) { 47 | // 去验证前端传过来的token 48 | String token = tokenDTO.getToken(); 49 | Map map = new HashMap<>(); 50 | map.put("is_valid", JwtToken.verifyToken(token)); 51 | return map; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/GlobalHttpExceptionAdvice.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core; 2 | 3 | import com.lin.missyou.core.configuration.ExceptionCodeConfiguration; 4 | import com.lin.missyou.exception.Http.HttpException; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.core.annotation.Order; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.ControllerAdvice; 12 | import org.springframework.web.bind.annotation.ExceptionHandler; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | import org.springframework.web.bind.annotation.ResponseStatus; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | 18 | @ControllerAdvice 19 | public class GlobalHttpExceptionAdvice { 20 | 21 | @Autowired 22 | private ExceptionCodeConfiguration codeConfiguration; 23 | 24 | @ExceptionHandler(value = Exception.class) 25 | @ResponseBody 26 | @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) 27 | public UnifyResponse handleException(HttpServletRequest request, Exception e) { 28 | String url = request.getRequestURI(); 29 | String method = request.getMethod(); 30 | return new UnifyResponse(9999, "server error", method + "" + url); 31 | } 32 | 33 | @ExceptionHandler(HttpException.class) 34 | public ResponseEntity handleHttpException(HttpServletRequest req, HttpException e){ 35 | String requestUrl = req.getRequestURI(); 36 | String method = req.getMethod(); 37 | UnifyResponse message = new UnifyResponse(e.getCode(),codeConfiguration.getMessage(e.getCode()), method + " " + requestUrl); 38 | HttpHeaders headers = new HttpHeaders(); 39 | headers.setContentType(MediaType.APPLICATION_JSON); 40 | HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode()); 41 | if (httpStatus == null) { 42 | return new ResponseEntity<>(message, headers, 500); 43 | } 44 | return new ResponseEntity<>(message, headers, httpStatus); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/WxAuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.lin.missyou.exception.Http.ParemeterExcepiton; 7 | import com.lin.missyou.model.User; 8 | import com.lin.missyou.repository.UserRepository; 9 | import com.lin.missyou.util.JwtToken; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.web.client.RestTemplate; 14 | 15 | import java.text.MessageFormat; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | import java.util.Optional; 19 | 20 | @Service 21 | public class WxAuthenticationService { 22 | 23 | @Autowired 24 | private ObjectMapper mapper; 25 | @Autowired 26 | private UserRepository userRepository; 27 | 28 | @Value("${wx.code2session}") 29 | private String code2sessionUrl; 30 | @Value("${wx.appid}") 31 | private String appid; 32 | @Value("${wx.appsecret}") 33 | private String appsecret; 34 | 35 | public String code2Session(String code) { 36 | // 信息配置在yml里面 37 | // 去微信服务器验证code码 38 | String url = MessageFormat.format(this.code2sessionUrl, this.appid, this.appsecret, code); 39 | RestTemplate restTemplate = new RestTemplate(); 40 | String sessionText = restTemplate.getForObject(url,String.class); 41 | Map session = new HashMap<>(); 42 | try { 43 | session = mapper.readValue(sessionText, Map.class); 44 | } catch (JsonProcessingException e) { 45 | e.printStackTrace(); 46 | } 47 | return this.registerUser(session); 48 | } 49 | 50 | public String registerUser(Map session) { 51 | String openid = (String) session.get("openid"); 52 | if (openid == null) { 53 | throw new ParemeterExcepiton(20004); 54 | } 55 | Optional optionalUser = userRepository.findByOpenid(openid); 56 | // exist 57 | if (optionalUser.isPresent()) { 58 | // 返回jwt令牌 59 | return JwtToken.makeToken(optionalUser.get().getId()); 60 | } 61 | // 获取的openid写入实体存入数据库 62 | User user = User.builder().openid(openid).build(); 63 | userRepository.save(user); 64 | Long uid = user.getId(); 65 | // 返回jwt令牌 66 | return JwtToken.makeToken(uid); 67 | 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/repository/CouponRepository.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.repository; 2 | 3 | import com.lin.missyou.model.Coupon; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.util.Date; 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | public interface CouponRepository extends JpaRepository { 13 | 14 | 15 | @Query("select c from Coupon c\n" + 16 | "join c.categoryList ca\n" + 17 | "join Activity a on a.id = c.activityId\n" + 18 | "where ca.id = :cid\n" + 19 | "and a.startTime < :now\n" + 20 | "and a.endTime > :now\n") 21 | List findByCategory(Long cid, Date now); 22 | @Query("select c from Coupon c\n" + 23 | "join Activity a on c.activityId = a.id\n" + 24 | "where c.wholeStore = :isWholeStore\n" + 25 | "and a.startTime < :now\n" + 26 | "and a.endTime > :now\n" ) 27 | 28 | List findByWholeStore(Boolean isWholeStore, Date now); 29 | 30 | 31 | @Query("select c from Coupon c\n" + 32 | "join UserCoupon uc\n" + 33 | "on c.id = uc.couponId\n" + 34 | "join User u\n" + 35 | "on u.id = uc.userId\n" + 36 | "where uc.status = 1 \n" + 37 | "and u.id = :uid\n" + 38 | "and c.startTime < :now\n" + 39 | "and c.endTime > :now\n" + 40 | "and uc.orderId is null") 41 | List findMyAvailable(Long uid, Date now); 42 | 43 | 44 | 45 | @Query("select c From Coupon c\n" + 46 | "join UserCoupon uc\n" + 47 | "on c.id = uc.couponId\n" + 48 | "join User u\n" + 49 | "on u.id = uc.userId\n" + 50 | "where u.id = :uid\n" + 51 | "and uc.status = 2\n" + 52 | "and uc.orderId is not null \n" + 53 | "and c.startTime < :now\n" + 54 | "and c.endTime > :now") 55 | List findMyUsed(@Param("uid") Long uid, @Param("now") Date now); 56 | 57 | 58 | @Query("select c From Coupon c\n" + 59 | "join UserCoupon uc\n" + 60 | "on c.id = uc.couponId\n" + 61 | "join User u\n" + 62 | "on u.id = uc.userId\n" + 63 | "where u.id = :uid\n" + 64 | "and uc.orderId is null\n" + 65 | "and uc.status <> 2\n" + 66 | "and c.endTime < :now") 67 | List findMyExpired(Long uid, Date now); 68 | 69 | 70 | Optional findByIdAndCreateTimeLessThanAndEndTimeGreaterThan(Long id, Date now1, Date now2); 71 | 72 | } 73 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/SpuController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | 4 | import com.lin.missyou.bo.PageCounter; 5 | import com.lin.missyou.exception.Http.NotFoundException; 6 | import com.lin.missyou.model.Spu; 7 | import com.lin.missyou.service.SpuService; 8 | import com.lin.missyou.util.CommonUtil; 9 | import com.lin.missyou.vo.PagingDozer; 10 | import com.lin.missyou.vo.SpuSimplifyVO; 11 | import org.springframework.beans.BeanUtils; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.validation.annotation.Validated; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | 17 | @RestController 18 | @RequestMapping("/spu") 19 | @Validated 20 | public class SpuController { 21 | 22 | private final SpuService spuService; 23 | public SpuController(SpuService spuService) { 24 | this.spuService = spuService; 25 | } 26 | 27 | @GetMapping("/id/{id}/detail") 28 | public Spu getDetail(@PathVariable Long id) { 29 | Spu spu = spuService.getSpu(id); 30 | if (spu == null) { 31 | throw new NotFoundException(30003); 32 | } 33 | return spu; 34 | } 35 | 36 | @GetMapping("/id/{id}/simplify") 37 | public SpuSimplifyVO getSimplifySpu (@PathVariable Long id) { 38 | Spu spu = this.spuService.getSpu(id); 39 | SpuSimplifyVO vo = new SpuSimplifyVO(); 40 | BeanUtils.copyProperties(spu, vo); 41 | return vo; 42 | 43 | } 44 | 45 | 46 | @GetMapping("/latest") 47 | public PagingDozer getLatestSpuList(@RequestParam(defaultValue = "0") Integer start, 48 | @RequestParam(defaultValue = "10") Integer count) { 49 | PageCounter pageCounter = CommonUtil.ConvertToPageParameter(start, count); 50 | Page page = this.spuService.getLatestPagingSpu(pageCounter.getPage(), pageCounter.getCount()); 51 | return new PagingDozer<>(page, SpuSimplifyVO.class); 52 | 53 | } 54 | 55 | @GetMapping("/by/category/{id}") 56 | public PagingDozer getByCategoryId(@PathVariable(name = "id") Long id, 57 | @RequestParam(name = "is_root", defaultValue = "false") Boolean isRoot, 58 | @RequestParam(name = "start", defaultValue = "0") Integer start, 59 | @RequestParam(name = "count", defaultValue = "10") Integer count) { 60 | PageCounter pageCounter = CommonUtil.ConvertToPageParameter(start, count); 61 | Page page = this.spuService.getByCategory(id, isRoot, pageCounter.getPage(), pageCounter.getCount()); 62 | return new PagingDozer<>(page, SpuSimplifyVO.class); 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/TestTool.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | import co.elastic.clients.elasticsearch._core.IndexRequest; 3 | import com.alibaba.fastjson.JSON; 4 | import com.lin.missyou.util.ImportJsonToElasticsearch; 5 | import org.apache.http.HttpHost; 6 | import org.elasticsearch.action.admin.indices.alias.Alias; 7 | import org.elasticsearch.client.RequestOptions; 8 | import org.elasticsearch.client.RestClient; 9 | import org.elasticsearch.client.RestHighLevelClient; 10 | import org.elasticsearch.client.indices.CreateIndexRequest; 11 | import org.elasticsearch.client.indices.CreateIndexResponse; 12 | import org.elasticsearch.common.settings.Settings; 13 | import org.elasticsearch.common.xcontent.XContentType; 14 | import org.springframework.web.bind.annotation.GetMapping; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RestController; 17 | import java.io.IOException; 18 | import java.util.Date; 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | @RestController 24 | @RequestMapping("/test") 25 | public class TestTool { 26 | 27 | 28 | @GetMapping("/es") 29 | public List testElasticTool () throws IOException { 30 | String jsonString = ImportJsonToElasticsearch.readJsonFile(); 31 | return convertStringToList(jsonString); 32 | } 33 | 34 | @SuppressWarnings("unchecked") 35 | public List convertStringToList(String jsonString) throws IOException { 36 | createIndex(); 37 | return (List) JSON.parse(jsonString); 38 | } 39 | 40 | public Map makeMappingInfo() { 41 | Map stringMap = new HashMap<>(); 42 | stringMap.put("index", "index_test_name"); 43 | stringMap.put("type", "_doc"); 44 | return stringMap; 45 | } 46 | 47 | public RestHighLevelClient getClient() { 48 | return new RestHighLevelClient( 49 | RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))); 50 | } 51 | 52 | // 创建索引 53 | public void createIndex() throws IOException { 54 | CreateIndexRequest request = new CreateIndexRequest("posts"); 55 | request.settings(Settings.builder() 56 | .put("index.number_of_shards", 3) 57 | .put("index.number_of_replicas", 2) 58 | ); 59 | request.mapping( 60 | "{\n" + 61 | " \"properties\": {\n" + 62 | " \"message\": {\n" + 63 | " \"type\": \"text\"\n" + 64 | " }\n" + 65 | " }\n" + 66 | "}", 67 | XContentType.JSON); 68 | CreateIndexResponse createIndexResponse = this.getClient().indices().create(request, RequestOptions.DEFAULT); 69 | System.out.println("createIndexResponse" + createIndexResponse); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/util/JwtToken.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.util; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.exceptions.JWTVerificationException; 7 | import com.auth0.jwt.interfaces.Claim; 8 | import com.auth0.jwt.interfaces.DecodedJWT; 9 | import com.auth0.jwt.interfaces.Verification; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.stereotype.Component; 12 | 13 | import java.util.*; 14 | 15 | 16 | @Component 17 | public class JwtToken { 18 | 19 | private static String jwtKey; 20 | private static Integer expiredTimeIn; 21 | private static Integer defaultScope = 8; 22 | 23 | // 读取私有key 24 | @Value("${missyou.security.jwt-key}") 25 | public void setJwtKey(String jwtKey) { 26 | JwtToken.jwtKey = jwtKey; 27 | } 28 | 29 | @Value("${missyou.security.token-expired-in}") 30 | public void setJwtKey(Integer expiredTimeIn) { 31 | JwtToken.expiredTimeIn = expiredTimeIn; 32 | } 33 | 34 | public static String makeToken(Long uid, Integer scope) { 35 | return JwtToken.getToken(uid, scope); 36 | } 37 | public static String makeToken(Long uid) { 38 | return JwtToken.getToken(uid, JwtToken.defaultScope); 39 | } 40 | 41 | public static Optional> getClaim(String token) { 42 | DecodedJWT decodedJWT; 43 | Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey); 44 | Verification jwtVerifier = JWT.require(algorithm); 45 | try { 46 | decodedJWT = jwtVerifier.build().verify(token); 47 | } 48 | catch (JWTVerificationException e) { 49 | return Optional.empty(); 50 | } 51 | return Optional.of(decodedJWT.getClaims()); 52 | } 53 | 54 | public static String getToken(Long uid, Integer scoped) { 55 | //auth0 56 | Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey); 57 | Map map = JwtToken.calculateExpiredIssues(); 58 | return JWT.create() 59 | .withClaim("uid", uid) 60 | .withClaim("scope", scoped) 61 | .withExpiresAt(map.get("expiredTime")) 62 | .withIssuedAt(map.get("now")) 63 | .sign(algorithm); 64 | } 65 | 66 | // verify token 67 | public static Boolean verifyToken(String token) { 68 | try { 69 | Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey); 70 | JWTVerifier jwtVerifier = JWT.require(algorithm).build(); 71 | jwtVerifier.verify(token); 72 | } catch (JWTVerificationException e) { 73 | return false; 74 | } 75 | return true; 76 | } 77 | 78 | // set expired time 79 | private static Map calculateExpiredIssues() { 80 | Map map = new HashMap<>(); 81 | Calendar calendar = Calendar.getInstance(); 82 | Date now = calendar.getTime(); 83 | calendar.add(Calendar.SECOND, JwtToken.expiredTimeIn); 84 | map.put("now", now); 85 | map.put("expiredTime", calendar.getTime()); 86 | return map; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/CouponController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | 4 | import com.lin.missyou.core.LocalUser; 5 | import com.lin.missyou.core.UnifyResponse; 6 | import com.lin.missyou.core.enumeration.CouponStatus; 7 | import com.lin.missyou.core.interceptors.ScopeLevel; 8 | import com.lin.missyou.exception.Http.ParemeterExcepiton; 9 | import com.lin.missyou.model.Coupon; 10 | import com.lin.missyou.model.User; 11 | import com.lin.missyou.service.CouponService; 12 | import com.lin.missyou.vo.CouponCategoryVO; 13 | import com.lin.missyou.vo.CouponPureVO; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.web.bind.annotation.*; 16 | 17 | import java.util.Collections; 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | 21 | @RestController 22 | @ResponseBody 23 | @RequestMapping("/coupon") 24 | public class CouponController { 25 | 26 | private final CouponService couponService; 27 | 28 | public CouponController(CouponService couponService) { 29 | this.couponService = couponService; 30 | } 31 | 32 | // 进入详情后查询当前spu对应的优惠券 33 | // 逻辑关系 34 | // coupon查询 根据分类来查询 35 | // 每个spu肯定是所属某一个分类的 36 | // 所以先查询当前spu所属费分类 37 | @GetMapping("/by/category/{cid}") 38 | public List getCouponListByCategory(@PathVariable long cid) { 39 | List couponList = couponService.getCategory(cid); 40 | if (couponList.isEmpty()) { 41 | return Collections.emptyList(); 42 | } 43 | return CouponPureVO.getList(couponList); 44 | } 45 | @GetMapping("/whole_store") 46 | public List getWholeStoreCouponList(@Autowired CouponService couponService) { 47 | List coupons = this.couponService.getWholeStoreCoupons(); 48 | if (coupons.isEmpty()) { 49 | return Collections.emptyList(); 50 | } 51 | return CouponPureVO.getList(coupons); 52 | } 53 | 54 | @ScopeLevel() 55 | @PostMapping("/collect/{id}") 56 | public void collectCoupon(@PathVariable Long id) { 57 | Long uid = LocalUser.getUser().getId(); 58 | couponService.collectOneCoupon(uid, id); 59 | UnifyResponse.createSuccess(0); 60 | } 61 | 62 | @ScopeLevel 63 | @GetMapping("/myself/by/status/{status}") 64 | public List getMyCouponByStatus(@PathVariable Integer status) { 65 | Long uid = LocalUser.getUser().getId(); 66 | List couponList; 67 | 68 | //触发机制 时机 过期 69 | switch (CouponStatus.toType(status)) { 70 | case AVAILABLE: 71 | couponList = couponService.getMyAvailableCoupons(uid); 72 | break; 73 | case USED: 74 | couponList = couponService.getMyUsedCoupons(uid); 75 | break; 76 | case EXPIRED: 77 | couponList = couponService.getMyExpiredCoupons(uid); 78 | break; 79 | default: 80 | throw new ParemeterExcepiton(40001); 81 | } 82 | return CouponPureVO.getList(couponList); 83 | } 84 | 85 | @ScopeLevel() 86 | @GetMapping("/myself/available/with_category") 87 | public List getUserCouponWithCategory() { 88 | User user = LocalUser.getUser(); 89 | List coupons = couponService.getMyAvailableCoupons(user.getId()); 90 | if (coupons.isEmpty()) { 91 | return Collections.emptyList(); 92 | } 93 | return coupons.stream().map(CouponCategoryVO::new).collect(Collectors.toList()); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/service/CouponService.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.service; 2 | 3 | 4 | import com.lin.missyou.core.enumeration.CouponStatus; 5 | import com.lin.missyou.exception.Http.NotFoundException; 6 | import com.lin.missyou.exception.Http.ParemeterExcepiton; 7 | import com.lin.missyou.model.Activity; 8 | import com.lin.missyou.model.Coupon; 9 | import com.lin.missyou.model.UserCoupon; 10 | import com.lin.missyou.repository.ActivityRepository; 11 | import com.lin.missyou.repository.CouponRepository; 12 | import com.lin.missyou.repository.UserCouponRepository; 13 | import com.lin.missyou.util.CommonUtil; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.util.Date; 17 | import java.util.List; 18 | 19 | @Service 20 | public class CouponService { 21 | // 从repository中查询数据 22 | // @Autowired 23 | // private CouponRepository couponRepository; 24 | // 25 | // @Autowired 26 | // private ActivityRepository activityRepository; 27 | // 28 | // @Autowired 29 | // private UserCouponRepository userCouponRepository; 30 | 31 | private final CouponRepository couponRepository; 32 | private final ActivityRepository activityRepository; 33 | private final UserCouponRepository userCouponRepository; 34 | 35 | public CouponService(CouponRepository couponRepository, 36 | ActivityRepository activityRepository, 37 | UserCouponRepository userCouponRepository) { 38 | this.couponRepository = couponRepository; 39 | this.activityRepository = activityRepository; 40 | this.userCouponRepository = userCouponRepository; 41 | } 42 | 43 | 44 | public List getCategory(long cid) { 45 | Date now = new Date(); 46 | return couponRepository.findByCategory(cid, now); 47 | } 48 | public List getWholeStoreCoupons() { 49 | Date now = new Date(); 50 | return couponRepository.findByWholeStore(true, now); 51 | } 52 | 53 | public void collectOneCoupon(Long uid, Long couponId) { 54 | // 查询一次数据库 检验couponId是否对应一张优惠券 55 | this.couponRepository.findById(couponId).orElseThrow(() -> new NotFoundException(40003)); 56 | // 如果存在 查看优惠券的时间 57 | // 领取时间(是否能领取,没到时间不能领取) 58 | // 领取时间和活动关联 59 | Activity activity = activityRepository.findByCouponListId(couponId).orElseThrow(() -> new NotFoundException(40001)); 60 | Date now = new Date(); 61 | Boolean isIn = CommonUtil.isInTimeLine(now, activity.getStartTime(), activity.getEndTime()); 62 | if (!isIn) { 63 | throw new ParemeterExcepiton(40006); 64 | } 65 | // 如果用户领领取过,先查询是否存在 66 | this.userCouponRepository.findFirstByUserIdAndCouponId(uid,couponId) 67 | .ifPresent((uc) -> { throw new ParemeterExcepiton(40006);}); 68 | // 可以正常领取的插入数据库 69 | UserCoupon userCouponNew = UserCoupon.builder() 70 | .couponId(couponId) 71 | .userId(uid) 72 | .status(CouponStatus.AVAILABLE.getValue()) 73 | .createTime(now) 74 | .build(); 75 | userCouponRepository.save(userCouponNew); 76 | 77 | } 78 | 79 | public List getMyAvailableCoupons(Long uid) { 80 | Date now = new Date(); 81 | return this.couponRepository.findMyAvailable(uid, now); 82 | } 83 | 84 | public List getMyUsedCoupons(Long uid) { 85 | Date now = new Date(); 86 | return this.couponRepository.findMyUsed(uid, now); 87 | } 88 | 89 | public List getMyExpiredCoupons(Long uid) { 90 | Date now = new Date(); 91 | return this.couponRepository.findMyExpired(uid, now); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /missyou/src/main/resources/config/exception-code.properties: -------------------------------------------------------------------------------- 1 | lin.codes[9999] = \u670D\u52A1\u5668\u672A\u77E5\u5F02\u5E38O(\u2229_\u2229)O\u54C8\u54C8~ 2 | 3 | lin.codes[10000] = \u901A\u7528\u5F02\u5E38 4 | 5 | lin.codes[10001] = \u901A\u7528\u53C2\u6570\u9519\u8BEF 6 | 7 | lin.codes[30003] = \u5546\u54C1\u4FE1\u606F\u4E0D\u5B58 8 | lin.codes[30005] = Banner\u7C7B\u8D44\u6E90\u4E0D\u5B58\u5728 9 | 10 | lin.codes[0] = ok 11 | 12 | lin.codes[10002] = \u8D44\u6E90\u672A\u627E\u5230 13 | lin.codes[10003] = \u6CA1\u6709\u627E\u5230\u5408\u9002\u7684\u767B\u9646\u5904\u7406\u65B9\u6CD5 14 | lin.codes[10004] = \u4EE4\u724C\u4E0D\u5408\u6CD5\u6216\u8005\u8FC7\u671F 15 | lin.codes[10005] = \u7528\u6237\u672A\u88AB\u6388\u6743 16 | lin.codes[10006] = \u767B\u9646\u5931\u8D25 17 | lin.codes[10007] = \u5FAE\u4FE1\u7EDF\u4E00\u4E0B\u5355\u5931\u8D25 18 | 19 | lin.codes[20000] = \u7528\u6237\u7C7B\u901A\u7528\u9519\u8BEF 20 | lin.codes[20001] = \u7528\u6237\u5DF2\u5B58\u5728 21 | lin.codes[20002] = \u7528\u6237\u4E0D\u5B58\u5728 22 | lin.codes[20003] = \u7528\u6237\u5BC6\u7801\u9519\u8BEF 23 | lin.codes[20004] = \u83B7\u53D6\u7528\u6237wx openid\u5931\u8D25 24 | 25 | lin.codes[30000] = \u5546\u54C1\u7C7B\u901A\u7528\u9519\u8BEF 26 | lin.codes[30001] = \u5206\u7C7B\u4E0D\u5B58\u5728 27 | lin.codes[30002] = \u5546\u54C1\u4FE1\u606F\u4E0D\u5B58 28 | lin.codes[30004] = complexity\u53C2\u6570\u9519\u8BEF 29 | lin.codes[30006] = \u5F53\u524D\u6682\u4E0D\u652F\u6301\u7EA7\u8054\u83B7\u53D6sku-list 30 | lin.codes[30007] = \u5F53\u524D\u6682\u4E0D\u652F\u6301\u7EA7\u8054\u83B7\u53D6spu-list\uFF0C\u8BF7\u8C03\u7528\u5176\u4ED6\u63A5\u53E3 31 | lin.codes[30008] = \u5F53\u524D\u6CA1\u6709\u66F4\u591A\u7684\u5546\u54C1\u4FE1\u606F\u4E86 32 | lin.codes[30009] = Grid\u5206\u7C7B\u4E0D\u5B58\u5728 33 | lin.codes[30010] = \u8BF7\u6C42\u7684\u5355\u54C1\u5217\u8868\u4E0D\u5B58\u5728 34 | lin.codes[30011] = \u8BF7\u6C42\u7684\u5546\u54C1SaleExplain\u4E0D\u5B58\u5728 35 | 36 | lin.codes[40000] = \u6D3B\u52A8\u4E0E\u4F18\u60E0\u5238\u901A\u7528\u9519\u8BEF 37 | lin.codes[40001] = \u672A\u627E\u5230\u9996\u9875\u4F18\u60E0\u5238\u6D3B\u52A8 38 | lin.codes[40002] = \u672A\u627E\u5230\u5546\u54C1\u53EF\u7528\u4F18\u60E0\u5238 39 | lin.codes[40003] = \u672A\u627E\u5230\u6D3B\u52A8\u5C01\u9762 40 | lin.codes[40004] = \u672A\u627E\u5230\u4F18\u60E0\u5238 41 | lin.codes[40005] = \u4F18\u60E0\u5238\u5DF2\u8FC7\u671F 42 | lin.codes[40006] = \u60A8\u5DF2\u7ECF\u9886\u53D6\u4E86\u8FD9\u5F20\u4F18\u60E0\u5238 43 | lin.codes[40007] = \u4F18\u60E0\u5238\u5DF2\u88AB\u4F7F\u7528\uFF0C\u4E0D\u80FD\u91CD\u590D\u4F7F\u7528 44 | lin.codes[40008] = \u4F18\u60E0\u5238\u4E0D\u6EE1\u8DB3\u4F7F\u7528\u6761\u4EF6 45 | lin.codes[40009] = \u4E0D\u652F\u6301\u7684\u4F18\u60E0\u5238\u7C7B\u578B 46 | lin.codes[40010] = \u672A\u627E\u5230\u4F18\u60E0\u5238\u5BF9\u5E94\u7684\u6D3B\u52A8 47 | lin.codes[40011] = \u4F18\u60E0\u5238\u53EA\u5B58\u5728\u53EF\u4F7F\u7528/\u5DF2\u4F7F\u7528/\u5DF2\u8FC7\u671F\u7684\u60C5\u51B5 48 | lin.codes[40012] = \u4F18\u60E0\u5238\u6838\u9500\u5931\u8D25 49 | 50 | lin.codes[50000] = \u8BA2\u5355\u901A\u7528\u7C7B\u9519\u8BEF 51 | lin.codes[50001] = \u8BA2\u5355\u4E2D\u6709\u5546\u54C1\u5DF2\u552E\u7F44 52 | lin.codes[50002] = \u8BA2\u5355\u4E2D\u6709\u5DF2\u4E0B\u67B6\u5546\u54C1 53 | lin.codes[50003] = \u8BA2\u5355\u4E2D\u6709\u5546\u54C1\u5E93\u5B58\u4E0D\u8DB3 54 | lin.codes[50004] = \u8BA2\u5355\u4E2D\u6709\u5546\u54C1\u8D85\u51FA\u4E86\u8D2D\u4E70\u4E0A\u9650 55 | lin.codes[50005] = \u8BA2\u5355\u91D1\u989D\u4E0E\u5B9E\u9645\u91D1\u989D\u4E0D\u5339\u914D,\u53EF\u80FD\u67D0\u4E9B\u5546\u54C1\u4EF7\u683C\u6709\u6D6E\u52A8 56 | lin.codes[50006] = \u7528\u6237\u6CA1\u6709\u8FD9\u5F20\u4F18\u60E0\u5238 57 | lin.codes[50007] = \u8BA2\u5355\u4E2D\u7684\u5546\u54C1\u6570\u91CF\u4E0D\u80FD\u662F0\u4EF6 58 | lin.codes[50008] = \u8BA2\u5355\u4F18\u60E0\u91D1\u989D\u4E0E\u5B9E\u9645\u4F18\u60E0\u91D1\u989D\u4E0D\u5339\u914D 59 | lin.codes[50009] = \u8BA2\u5355\u4E0D\u5B58\u5728 60 | lin.codes[50010] = \u8BA2\u5355\u5DF2\u8FC7\u671F 61 | lin.codes[50011] = \u6211\u4EEC\u5546\u54C1\u5E76\u4E0D\u514D\u8D39~ 62 | 63 | 64 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/tokenDevelopment.md: -------------------------------------------------------------------------------- 1 | ### token 出现的背景 2 | 3 | - 在早前的Web应用中,Web 基本上就是文档的浏览而已, 因为是浏览,作为服务器, 不需要记录谁在某一段时间里都浏览了什么文档, 4 | 每次请求都是一个新的HTTP协议, 就是请求加响应, 尤其是我不用记住是谁刚刚发了HTTP请求,每个请求对我来说都是全新的; 5 | 6 | - 但是随着交互式Web应用的兴起,像在线购物网站,需要登录的网站等等,面临一个问题,那就是要管理会话,必须记住哪些人登录系统, 哪些人往自己的购物车中放商品, 也就是说我必须把每个人区分开, 7 | 这就是一个不小的挑战,因为HTTP请求是无状态的,所以想出的办法就是给大家发一个会话标识(session id), 说白了就是一个随机的字串,每个人收到的都不一样, 每次大家向我发起HTTP请求的时候,把这个字符串给一并捎过来, 这样我就能区分开谁是谁了; 8 | 9 | - 但是客户端只需要保存自身的session id,而服务器端则要保存所有客户端的session id ,这对服务器说是一个巨大的开销 , 严重的限制了服务器扩展能力; 10 | Token的出现解决了这个问题,因为服务端不需要存储Token的信息,而是通过CPU的计算 + 数据的加密解密再核对Token的方式来验证用户是否合法(即HTTP请求信息有没有被篡改), 11 | 让服务器内存得到释放; 12 | 13 | 14 | ### token的出现 15 | Token的引入:Token是在客户端频繁向服务端请求数据,服务端频繁的去数据库查询用户名和密码并进行对比, 16 | 判断用户名和密码正确与否,并作出相应提示,在这样的背景下,Token便应运而生。 17 | 18 | ### token的定义 19 | Token是服务端生成的一串字符串,以作客户端进行请求的一个令牌,当第一次登录后, 20 | 服务器生成一个Token便将此Token返回给客户端,以后客户端只需带上这个Token前来请求数据即可, 21 | 无需再次带上用户名和密码 22 | 23 | ### token的目的 24 | 25 | Token的目的是为了减轻服务器的压力,减少频繁的查询数据库,使服务器更加健壮。 26 | 27 | 28 | ### token原理 29 | 30 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/ece2c1e79cd1461e9782908c0048245e.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAYXJ0aHVyd2FuZ2dhbmc=,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center) 31 | 32 | 33 | ### 具体描述 34 | 35 | - 将荷载payload,以及Header信息进行Base64加密,形成密文payload密文,header密文。 36 | - 将形成的密文用句号链接起来,用服务端秘钥进行HS256加密,生成签名。 37 | - 将前面的两个密文后面用句号链接签名形成最终的token返回给服务端 38 | 39 | --- 备注: 40 | 41 | - 用户请求时携带此token(分为三部分,header密文,payload密文,签名)到服务端,服务端解析第一部分(header密文),用Base64解密,可以知道用了什么算法进行签名 42 | - 服务端使用原来的秘钥与密文(header密文+"."+payload密文)同样进行HS256运算,然后用生成的签名与token携带的签名进行对比,若一致说明token合法,不一致说明原文被修改 43 | - 判断是否过期,客户端通过用Base64解密第二部分(payload密文),可以知道荷载中授权时间,以及有效期。通过这个与当前时间对比发现token是否过期 44 | 45 | ### token实现思路 46 | 47 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/76152a2096c346ba8ce32202f665e077.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAYXJ0aHVyd2FuZ2dhbmc=,size_15,color_FFFFFF,t_70,g_se,x_16#pic_center) 48 | 49 | ### 具体描述 50 | 51 | - 用户登录校验,校验成功后就返回Token给客户端 52 | - 客户端收到数据后保存在客户端 53 | - 客户端每次访问API是携带Token到服务器端 54 | - 服务器端采用filter过滤器校验。校验成功则返回请求数据,校验失败则返回错误码 55 | 56 | 57 | 58 | ### token代码的实现 59 | ###### 具体在代码中的util中对token的生成和验证进行了封装 60 | 61 | 62 | ### 基于jwt Token的组成部分 63 | 64 | ###### header 65 | jwt的header承载两部分的内容 66 | 67 | - 声明类型 (这里是JWT) 68 | - 声明加密算法 一般是HMAC 和SHA256 69 | 70 | 完整的头部如下 71 | 72 | ```javascript 73 | { 74 | "typ": "jwt", 75 | "alg": "HS256" 76 | } 77 | ``` 78 | 然后对头部进行base64进行加密(该加密是可以进行对称解密的)构成了第一部分的内容 79 | 80 | ```javascript 81 | eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 82 | ``` 83 | 84 | 85 | ###### payload 86 | payload是存放有些信息得地方,包括三部分 87 | - 标准中注册的声明 88 | - 公共声明 89 | - 私有得声明 90 | 91 | 标准中注册的声明(建议但不强制) 92 | - iss: jwt签发者 93 | - sub: jwt所面向的用户 94 | - aud: 接收jwt的一方 95 | - exp: jwt的过期时间,这个过期时间必须要大于签发时间 96 | - nbf: 定义在什么时间之前,该jwt都是不可用的. 97 | - iat: jwt的签发时间 98 | - jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。 99 | 100 | ###### 公共的声明 : 101 | 公共的声明可以添加任何的信息,一般添加用户的相关信息或其他业务需要的必要信息.但不建议添加敏感信息,因为该部分在客户端可解密. 102 | 103 | ###### 私有的声明 : 104 | 私有声明是提供者和消费者所共同定义的声明,一般不建议存放敏感信息,因为base64是对称解密的,意味着该部分信息可以归类为明文信息。 105 | 106 | ###### 定义一个payload 107 | 108 | ```javascript 109 | { 110 | "sub": "test", 111 | "name": "test", 112 | "admin": "test" 113 | } 114 | ``` 115 | 然后将其进行base64加密,得到Jwt的第二部分 116 | 117 | ```javascript 118 | eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9 119 | ``` 120 | 121 | ###### signature 122 | 第三部分是一个签名信息,这个签名信息由三部分组成 123 | - header (base64后的) 124 | - payload (base64后的) 125 | - secret 126 | 127 | 这个部分需要base64加密后的header和base64加密后的payload使用.连接组成的字符串(头部在前),然后通过header中声明的加密方式进行加盐secret组合加密,然后就构成了jwt的第三部分。 128 | 129 | ```javascript 130 | UQmqAUhUrpDVV2ST7mZKyLTomVfg7sYkEjmdDI5XF8Q 131 | ``` 132 | 密钥secret是保存在服务端的,服务端会根据这个密钥进行生成token和验证,所以需要保护好。 133 | 134 | 135 | ### 签名的目的 136 | 137 | 最后一步签名的过程,实际上是对头部以及载荷内容进行签名。一般而言,加密算法对于不同的输入产生的输出总是不一样的。对于两个不同的输入,产生同样的输出的概率极其地小 138 | 所以,如果有人对头部以及载荷的内容解码之后进行修改,再进行编码的话,那么新的头部和载荷的签名和之前的签名就将是不一样的。而且,如果不知道服务器加密的时候用的密钥的话,得出来的签名也一定会是不一样的。 139 | 服务器应用在接受到JWT后,会首先对头部和载荷的内容用同一算法再次签名。那么服务器应用是怎么知道我们用的是哪一种算法呢?别忘了,我们在JWT的头部中已经用alg字段指明了我们的加密算法了。 140 | 141 | token验证 142 | https://jwt.io/ -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/api/v1/BannerController.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.api.v1; 2 | 3 | import com.lin.missyou.core.interceptors.ScopeLevel; 4 | import com.lin.missyou.exception.Http.NotFoundException; 5 | import com.lin.missyou.service.BannerService; 6 | import org.springframework.validation.annotation.Validated; 7 | import org.springframework.web.bind.annotation.*; 8 | import com.lin.missyou.model.Banner; 9 | 10 | import java.text.SimpleDateFormat; 11 | import java.util.*; 12 | 13 | @RestController 14 | @RequestMapping("/banner") 15 | @Validated 16 | public class BannerController { 17 | 18 | private final BannerService bannerService; 19 | private final Integer cycleDate = 5; 20 | private final String URL = "/url"; 21 | 22 | public BannerController(BannerService bannerService) { 23 | this.bannerService = bannerService; 24 | } 25 | 26 | @GetMapping("/name/{name}") 27 | @ScopeLevel() 28 | public Banner getByName(@PathVariable String name) { 29 | Banner banner = bannerService.getByName(name); 30 | if (banner == null) { 31 | throw new NotFoundException(30005); 32 | } 33 | return banner; 34 | } 35 | 36 | 37 | @GetMapping("/test/date2") 38 | public List getDateRange2() { 39 | return this.getRangeDate2(); 40 | } 41 | 42 | @GetMapping("/test/getListLength") 43 | public Integer getListLength() { 44 | return this.getDateRange2().size(); 45 | } 46 | 47 | public List getRangeDate2 () { 48 | List stringList2 = new ArrayList<>(); 49 | int currentYear = Calendar.getInstance().get(Calendar.YEAR); 50 | int earliestDate = 1997; 51 | int dateRange = currentYear - earliestDate; 52 | for (int i = 0; i <= dateRange; i++) { 53 | stringList2.add(this.getPreviousYear(i)); 54 | } 55 | Collections.sort(stringList2); 56 | return this.testChange(stringList2); 57 | } 58 | 59 | public List testChange(List stringList2) { 60 | List listChange = new ArrayList<>(); 61 | for (int i = 0; i < stringList2.size() -1; i++) { 62 | String t2 = stringList2.get(i+1); 63 | String t1 = stringList2.get(i); 64 | listChange.add(this.URL + "?" + "t1=" + t1 + "&" + "t2=" + t2); 65 | } 66 | return listChange; 67 | } 68 | 69 | 70 | @GetMapping("/test/date") 71 | public List> getDateRange() { 72 | return this.getRangeDate(); 73 | } 74 | @GetMapping("/date/list") 75 | public List dateStringList() { 76 | List> lists = this.getDateRange(); 77 | List stringList = new ArrayList<>(); 78 | for (List list : lists) { 79 | if (list.size() == 1) { 80 | return stringList; 81 | } else { 82 | String t2 = list.get(0); 83 | String t1 = list.get(1); 84 | stringList.add(this.URL + "?" + "t1=" + t1 + "&" + "t2=" + t2); 85 | } 86 | } 87 | return stringList; 88 | } 89 | 90 | public String getPreviousYear(Integer number) { 91 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); 92 | Calendar calendar = Calendar.getInstance(); 93 | calendar.setTime(new Date()); 94 | calendar.add(Calendar.YEAR, Integer.parseInt("-" + number)); 95 | Date y = calendar.getTime(); 96 | return simpleDateFormat.format(y); 97 | } 98 | 99 | public List> getRangeDate() { 100 | List stringList = new ArrayList<>(); 101 | int currentYear = Calendar.getInstance().get(Calendar.YEAR); 102 | int earliestDate = 1996; 103 | int dateRange = currentYear - earliestDate; 104 | for (int i = 0; i < dateRange; i++) { 105 | stringList.add(this.getPreviousYear(i)); 106 | } 107 | // Collections.sort(stringList); 108 | return this.getSplitList(2,stringList); 109 | } 110 | public List> getSplitList(int splitNum, List list) { 111 | List> splitList = new LinkedList<>(); 112 | int groupFlag = list.size() % splitNum == 0 ? (list.size() / splitNum) : (list.size() / splitNum + 1); 113 | for (int j = 1; j <= groupFlag; j++) { 114 | if ((j * splitNum) <= list.size()) { 115 | splitList.add(list.subList(j * splitNum - splitNum, j * splitNum)); 116 | } else if ((j * splitNum) > list.size()) { 117 | splitList.add(list.subList(j * splitNum - splitNum, list.size())); 118 | } 119 | } 120 | return splitList; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /missyou/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.5.1 9 | 10 | 11 | com.lin 12 | missyou 13 | 0.0.1-SNAPSHOT 14 | missyou 15 | Demo project for Spring Boot 16 | 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-devtools 28 | runtime 29 | true 30 | 31 | 32 | javax.validation 33 | validation-api 34 | 2.0.1.Final 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | 1.16.8 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-data-jpa 53 | 54 | 55 | com.auth0 56 | java-jwt 57 | 3.10.2 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-jdbc 62 | 63 | 64 | mysql 65 | mysql-connector-java 66 | runtime 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-thymeleaf 71 | 72 | 73 | com.alibaba 74 | fastjson 75 | 1.2.49 76 | 77 | 78 | com.github.dozermapper 79 | dozer-core 80 | 6.5.0 81 | 82 | 83 | co.elastic.clients 84 | elasticsearch-java 85 | 7.15.0 86 | 87 | 88 | com.fasterxml.jackson.core 89 | jackson-databind 90 | 2.12.3 91 | 92 | 93 | 94 | com.auth0 95 | java-jwt 96 | 3.9.0 97 | 98 | 99 | 100 | org.elasticsearch.client 101 | elasticsearch-rest-high-level-client 102 | 7.15.0 103 | 104 | 105 | org.elasticsearch 106 | elasticsearch 107 | 5.6.3 108 | 109 | 110 | 111 | 112 | 113 | 114 | org.springframework.boot 115 | spring-boot-maven-plugin 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/core/interceptors/PermissionInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.core.interceptors; 2 | 3 | import com.auth0.jwt.interfaces.Claim; 4 | import com.lin.missyou.core.LocalUser; 5 | import com.lin.missyou.exception.Http.ForbiddenException; 6 | import com.lin.missyou.exception.Http.UnAuthenticatedException; 7 | import com.lin.missyou.model.User; 8 | import com.lin.missyou.service.UserService; 9 | import com.lin.missyou.util.JwtToken; 10 | import org.apache.tomcat.websocket.AuthenticationException; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.util.StringUtils; 13 | import org.springframework.web.method.HandlerMethod; 14 | import org.springframework.web.servlet.AsyncHandlerInterceptor; 15 | import org.springframework.web.servlet.HandlerInterceptor; 16 | import org.springframework.web.servlet.ModelAndView; 17 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 18 | 19 | import javax.servlet.http.Cookie; 20 | import javax.servlet.http.HttpServletRequest; 21 | import javax.servlet.http.HttpServletResponse; 22 | import java.util.Map; 23 | import java.util.Optional; 24 | 25 | public class PermissionInterceptor implements AsyncHandlerInterceptor { 26 | 27 | //查询数据库 查User 28 | @Autowired 29 | private UserService userService; 30 | 31 | @Override 32 | public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 33 | AsyncHandlerInterceptor.super.afterConcurrentHandlingStarted(request, response, handler); 34 | } 35 | 36 | @Override 37 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 38 | Optional scopeLevel = this.getScopeLevel(handler); 39 | if (!scopeLevel.isPresent()) { 40 | return true; 41 | } 42 | String token = this.getToken(request); 43 | if(!StringUtils.hasLength(token)) { 44 | throw new UnAuthenticatedException(10004); 45 | } 46 | // 标准 Bearer 开头 47 | if (!token.startsWith("Bearer")) { 48 | throw new UnAuthenticatedException(10004); 49 | } 50 | String[] splitToken = token.split(" "); 51 | if (!(splitToken.length ==2)) { 52 | throw new UnAuthenticatedException(10004); 53 | } 54 | // 提取token 55 | String realToken = splitToken[1]; 56 | Optional> optionalStringClaimMap = JwtToken.getClaim(realToken); 57 | Map map = optionalStringClaimMap.orElseThrow(() -> new UnAuthenticatedException(10004)); 58 | Boolean valid = this.hasPermission(scopeLevel.get(), map); 59 | if (valid) { 60 | this.setToLocalUser(map); 61 | } 62 | return valid; 63 | } 64 | 65 | private void setToLocalUser(Map map) { 66 | Long uid = map.get("uid").asLong(); 67 | Integer scope = map.get("scope").asInt(); 68 | User user = this.userService.getUserById(uid); 69 | LocalUser.set(user, scope); 70 | } 71 | 72 | 73 | private Boolean hasPermission(ScopeLevel scopeLevel, Map map) { 74 | Integer level = scopeLevel.value(); 75 | Integer scope = map.get("scope").asInt(); 76 | // 进入的权限大于固定权限 无权访问 77 | if (level > scope) { 78 | throw new ForbiddenException(10005); 79 | } 80 | return true; 81 | } 82 | 83 | @Override 84 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 85 | AsyncHandlerInterceptor.super.postHandle(request, response, handler, modelAndView); 86 | } 87 | 88 | @Override 89 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 90 | // 释放进程资源 91 | LocalUser.clear(); 92 | AsyncHandlerInterceptor.super.afterCompletion(request, response, handler, ex); 93 | } 94 | // 获取对应的scope 95 | private Optional getScopeLevel(Object handler) { 96 | if (handler instanceof HandlerMethod) { 97 | HandlerMethod handlerMethod = (HandlerMethod) handler; 98 | ScopeLevel scopeLevel = handlerMethod.getMethod().getAnnotation(ScopeLevel.class); 99 | if (scopeLevel == null) { 100 | return Optional.empty(); 101 | } 102 | return Optional.of(scopeLevel); 103 | } 104 | return Optional.empty(); 105 | } 106 | // 获取前端带回的token 107 | private String getToken(HttpServletRequest request) { 108 | return request.getHeader("Authorization"); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /missyou/src/main/java/com/lin/missyou/mark/testCollection.java: -------------------------------------------------------------------------------- 1 | package com.lin.missyou.mark; 2 | 3 | // 做个基本的总结 4 | 5 | import javax.xml.bind.Element; 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | import java.util.List; 9 | 10 | public class testCollection { 11 | 12 | // List 常用方法 13 | // 向list集合添加元素 14 | // void add (Element element) {} 15 | // 指定位置添加 (指定index) 16 | // void add (int index, Element element) {} 17 | // 向集合添加另一个指定的集合元素 18 | // void addAll(Collection c) {} 19 | 20 | // 删除 21 | // void clear(); 清空集合所有原色 22 | 23 | // remove(int index) 根据指定索引删除元素 24 | // boolean remove(Object o):从集合中删除指定的元素 25 | // boolean removeAll(Collection c):从集合中删除一个指定的集合元素。 26 | // 27 | // C:修改功能 28 | // E set(int index, E element):把指定索引位置的元素修改为指定的值,返回修改前的值。 29 | // 30 | // D:获取功能 31 | // E get(int index):获取指定位置的元素 32 | // Iterator iterator():就是用来获取集合中每一个元素。 33 | // 34 | // E:判断功能 35 | // boolean isEmpty():判断集合是否为空。 36 | // boolean contains(Object o):判断集合中是否存在指定的元素。 37 | // boolean containsAll(Collection c):判断集合中是否存在指定的一个集合中的元素。 38 | // 39 | // F:长度功能 40 | // int size():获取集合中的元素个数 41 | // 42 | // G:把集合转换成数组 43 | // Object[] toArray():把集合变成数组。 44 | 45 | 46 | 47 | // ArrayList基本操作 48 | 49 | // List list = new ArrayList(); 50 | // System.out.println("ArrayList集合初始化容量:"+list.size()); 51 | // 52 | // //添加功能: 53 | // list.add("Hello"); 54 | // list.add("world"); 55 | // list.add(2,"!"); 56 | // System.out.println("ArrayList当前容量:"+list.size()); 57 | // 58 | // //修改功能: 59 | // list.set(0,"my"); 60 | // list.set(1,"name"); 61 | // System.out.println("ArrayList当前内容:"+list.toString()); 62 | // 63 | // //获取功能: 64 | // String element = list.get(0); 65 | // System.out.println(element); 66 | // 67 | // //迭代器遍历集合:(ArrayList实际的跌倒器是Itr对象) 68 | // Iterator iterator = list.iterator(); 69 | // while(iterator.hasNext()){ 70 | // String next = iterator.next(); 71 | // System.out.println(next); 72 | // } 73 | // 74 | // //for循环迭代集合: 75 | // for(String str:list){ 76 | // System.out.println(str); 77 | // } 78 | // 79 | // //判断功能: 80 | // boolean isEmpty = list.isEmpty(); 81 | // boolean isContain = list.contains("my"); 82 | // 83 | // //长度功能: 84 | // int size = list.size(); 85 | // 86 | // //把集合转换成数组: 87 | // String[] strArray = list.toArray(new String[]{}); 88 | // 89 | // //删除功能: 90 | // list.remove(0); 91 | // list.remove("world"); 92 | // list.clear(); 93 | // System.out.println("ArrayList当前容量:"+list.size()); 94 | 95 | 96 | // LinkedList基本操作 97 | 98 | // List linkedList = new LinkedList(); 99 | // System.out.println("LinkedList初始容量:"+linkedList.size()); 100 | // 101 | // //添加功能: 102 | // linkedList.add("my"); 103 | // linkedList.add("name"); 104 | // linkedList.add("is"); 105 | // linkedList.add("jiaboyan"); 106 | // System.out.println("LinkedList当前容量:"+ linkedList.size()); 107 | // 108 | // //修改功能: 109 | // linkedList.set(0,"hello"); 110 | // linkedList.set(1,"world"); 111 | // System.out.println("LinkedList当前内容:"+ linkedList.toString()); 112 | // 113 | // //获取功能: 114 | // String element = linkedList.get(0); 115 | // System.out.println(element); 116 | // 117 | // //遍历集合:(LinkedList实际的跌倒器是ListItr对象) 118 | // Iterator iterator = linkedList.iterator(); 119 | // while(iterator.hasNext()){ 120 | // String next = iterator.next(); 121 | // System.out.println(next); 122 | // } 123 | // //for循环迭代集合: 124 | // for(String str:linkedList){ 125 | // System.out.println(str); 126 | // } 127 | // 128 | // //判断功能: 129 | // boolean isEmpty = linkedList.isEmpty(); 130 | // boolean isContains = linkedList.contains("jiaboyan"); 131 | // 132 | // //长度功能: 133 | // int size = linkedList.size(); 134 | // 135 | // //删除功能: 136 | // linkedList.remove(0); 137 | // linkedList.remove("jiaboyan"); 138 | // linkedList.clear(); 139 | // System.out.println("LinkedList当前容量:" + linkedList.size()); 140 | 141 | 142 | // 新用的到java9的一些特性 143 | public void test () { 144 | // java 9 doc https://docs.oracle.com/javase/9/docs/api/java/util/List.html 145 | List stringList = new ArrayList<>(); 146 | // List.of(); 147 | // https://docs.oracle.com/javase/9/docs/api/java/util/Map.html 148 | // Map.of() Returns an immutable map containing zero mappings. 149 | 150 | // optional 151 | // java9为Optional添加了三个方法 152 | // or() ifPresentOrElse() stream() 153 | 154 | } 155 | 156 | 157 | } 158 | -------------------------------------------------------------------------------- /missyou/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.net.*; 18 | import java.io.*; 19 | import java.nio.channels.*; 20 | import java.util.Properties; 21 | 22 | public class MavenWrapperDownloader { 23 | 24 | private static final String WRAPPER_VERSION = "0.5.6"; 25 | /** 26 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 27 | */ 28 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 29 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 30 | 31 | /** 32 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 33 | * use instead of the default one. 34 | */ 35 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 36 | ".mvn/wrapper/maven-wrapper.properties"; 37 | 38 | /** 39 | * Path where the maven-wrapper.jar will be saved to. 40 | */ 41 | private static final String MAVEN_WRAPPER_JAR_PATH = 42 | ".mvn/wrapper/maven-wrapper.jar"; 43 | 44 | /** 45 | * Name of the property which should be used to override the default download url for the wrapper. 46 | */ 47 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 48 | 49 | public static void main(String args[]) { 50 | System.out.println("- Downloader started"); 51 | File baseDirectory = new File(args[0]); 52 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 53 | 54 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 55 | // wrapperUrl parameter. 56 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 57 | String url = DEFAULT_DOWNLOAD_URL; 58 | if (mavenWrapperPropertyFile.exists()) { 59 | FileInputStream mavenWrapperPropertyFileInputStream = null; 60 | try { 61 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 62 | Properties mavenWrapperProperties = new Properties(); 63 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 64 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 65 | } catch (IOException e) { 66 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 67 | } finally { 68 | try { 69 | if (mavenWrapperPropertyFileInputStream != null) { 70 | mavenWrapperPropertyFileInputStream.close(); 71 | } 72 | } catch (IOException e) { 73 | // Ignore ... 74 | } 75 | } 76 | } 77 | System.out.println("- Downloading from: " + url); 78 | 79 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 80 | if (!outputFile.getParentFile().exists()) { 81 | if (!outputFile.getParentFile().mkdirs()) { 82 | System.out.println( 83 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 84 | } 85 | } 86 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 87 | try { 88 | downloadFileFromURL(url, outputFile); 89 | System.out.println("Done"); 90 | System.exit(0); 91 | } catch (Throwable e) { 92 | System.out.println("- Error downloading"); 93 | e.printStackTrace(); 94 | System.exit(1); 95 | } 96 | } 97 | 98 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 99 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 100 | String username = System.getenv("MVNW_USERNAME"); 101 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 102 | Authenticator.setDefault(new Authenticator() { 103 | @Override 104 | protected PasswordAuthentication getPasswordAuthentication() { 105 | return new PasswordAuthentication(username, password); 106 | } 107 | }); 108 | } 109 | URL website = new URL(urlString); 110 | ReadableByteChannel rbc; 111 | rbc = Channels.newChannel(website.openStream()); 112 | FileOutputStream fos = new FileOutputStream(destination); 113 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 114 | fos.close(); 115 | rbc.close(); 116 | } 117 | 118 | } 119 | --------------------------------------------------------------------------------