From d2657fff64c00ebe630f58de018103e80fb45d90 Mon Sep 17 00:00:00 2001 From: robbie Date: Fri, 18 Jan 2019 17:42:37 +0800 Subject: [PATCH] fix bug --- common/pom.xml | 15 +- .../main/java/utils/UserContextFilter.java | 2 +- .../src/main/resources/application.properties | 4 - .../src/main/resources/application.yml | 22 +++ licensingserivce/licenseservice.iml | 34 +++-- licensingserivce/pom.xml | 130 ++++++++++++------ licensingserivce/src/main/docker/run.sh | 2 +- .../Client/FeignClient/CustomFeignClinet.java | 21 +++ .../Client/FeignClient/FeignConfig.java | 22 +++ .../FeignClient/OrganizationFeignClient.java | 38 +++++ .../OrganizationAuthRestTemplateClient.java | 44 ++++++ .../Client/OrganizationClient.java | 35 +++++ .../Client/OrganizationFeignClient.java | 18 +-- .../Client/OrganizationFeignClient1.java | 15 ++ .../OrganizationRestTemplateClient.java | 30 ++-- .../Config/AuthClientConfig.java | 62 +++++++++ .../licenseservice/Config/ClientConfig.java | 7 +- .../LicenseserviceApplication.java | 2 + .../Security/ResourceServerConfiguration.java | 17 +++ .../events/OrganizationChangeHandler.java | 11 +- .../exceptions/AppExceptionHandler.java | 21 +++ .../com/licenseservice/exceptions/Error.java | 27 ++++ .../exceptions/LicensingException.java | 33 +++++ .../licenseservice/model/Organization.java | 4 +- .../OrganizationRedisRepositoryImpl.java | 2 +- .../service/LicenseService.java | 38 ++++- .../com/licenseservice/utils/UserContext.java | 48 +++++++ .../utils/UserContextFilter.java | 39 ++++++ .../utils/UserContextHolder.java | 21 +++ .../utils/UserContextInterceptor.java | 30 ++++ .../src/main/resources/application.yml | 12 +- organizationservice/pom.xml | 6 + .../events/SimpleSourceBean.java | 2 +- .../src/main/resources/application.yml | 26 ++-- pom.xml | 16 +-- 35 files changed, 732 insertions(+), 124 deletions(-) delete mode 100644 discoverserver/src/main/resources/application.properties create mode 100644 discoverserver/src/main/resources/application.yml create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/CustomFeignClinet.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/FeignConfig.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/OrganizationFeignClient.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/OrganizationAuthRestTemplateClient.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/OrganizationClient.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient1.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Config/AuthClientConfig.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/Security/ResourceServerConfiguration.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/exceptions/AppExceptionHandler.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/exceptions/Error.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/exceptions/LicensingException.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/utils/UserContext.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/utils/UserContextFilter.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/utils/UserContextHolder.java create mode 100644 licensingserivce/src/main/java/com/licenseservice/utils/UserContextInterceptor.java diff --git a/common/pom.xml b/common/pom.xml index f2047a4..3b00506 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -10,18 +10,25 @@ 4.0.0 common + jar + - org.springframework - spring-web - 5.1.4.RELEASE + org.springframework.boot + spring-boot-starter + org.apache.tomcat.embed tomcat-embed-core 9.0.12 + + org.springframework + spring-web + 5.1.4.RELEASE + compile + - \ No newline at end of file diff --git a/common/src/main/java/utils/UserContextFilter.java b/common/src/main/java/utils/UserContextFilter.java index 84ac8df..f0e4611 100644 --- a/common/src/main/java/utils/UserContextFilter.java +++ b/common/src/main/java/utils/UserContextFilter.java @@ -23,7 +23,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo UserContextHolder.getContext().setUserId(httpServletRequest.getHeader(UserContext.USER_ID)); UserContextHolder.getContext().setOrgId(httpServletRequest.getHeader(UserContext.ORG_ID)); - logger.debug("Special Routes Service Incoming Correlation id: {}", UserContextHolder.getContext().getCorrelationId()); + logger.debug("Special Routes service Incoming Correlation id: {}", UserContextHolder.getContext().getCorrelationId()); filterChain.doFilter(httpServletRequest, servletResponse); } diff --git a/discoverserver/src/main/resources/application.properties b/discoverserver/src/main/resources/application.properties deleted file mode 100644 index fa0be81..0000000 --- a/discoverserver/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -server.port=8761 -eureka.client.register-with-eureka=false -eureka.client.fetch-registry=false -eureka.server.wait-time-in-ms-when-sync-empty=5 \ No newline at end of file diff --git a/discoverserver/src/main/resources/application.yml b/discoverserver/src/main/resources/application.yml new file mode 100644 index 0000000..3b2b1d6 --- /dev/null +++ b/discoverserver/src/main/resources/application.yml @@ -0,0 +1,22 @@ + +#eureka: +# instance: +# hostname: localhost + +server: + port: 8761 +spring: + application: + name: Discovery-Server + +eureka: + instance: + appname: ${spring.application.name} + hostname: 127.0.0.1 + + client: + register-with-eureka: true + fetch-registry: true + service-url: + defaultZone: http://127.0.0.1:8761/eureka/,http://127.0.0.1:8762/eureka/ + diff --git a/licensingserivce/licenseservice.iml b/licensingserivce/licenseservice.iml index 0c0d057..4d73178 100644 --- a/licensingserivce/licenseservice.iml +++ b/licensingserivce/licenseservice.iml @@ -1,5 +1,5 @@ - + @@ -21,7 +21,6 @@ - @@ -33,12 +32,14 @@ + + @@ -46,6 +47,7 @@ + @@ -88,7 +90,7 @@ - + @@ -110,7 +112,6 @@ - @@ -163,6 +164,7 @@ + @@ -222,11 +224,23 @@ - - - - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/licensingserivce/pom.xml b/licensingserivce/pom.xml index 9f6eb7d..85d1373 100644 --- a/licensingserivce/pom.xml +++ b/licensingserivce/pom.xml @@ -8,7 +8,7 @@ 0.0.1-SNAPSHOT jar - licenseService + licenseservice Demo project for Spring Boot @@ -22,9 +22,10 @@ UTF-8 UTF-8 1.8 + robbie Greenwich.M3 - johncarnell/tmx-licensing-service - chapter3 + + @@ -42,11 +43,23 @@ + + + + + + + + + + + + org.springframework.cloud spring-cloud-starter-netflix-eureka-client @@ -108,17 +121,14 @@ org.apache.commons commons-pool2 + - org.springframework.boot - spring-boot - 2.1.2.RELEASE + org.springframework.cloud + spring-cloud-starter-security - - com - common - 0.0.1-SNAPSHOT - compile + org.springframework.cloud + spring-cloud-starter-oauth2 @@ -144,44 +154,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - maven-resources-plugin + com.spotify + dockerfile-maven-plugin + 1.3.6 + + ${docker.image.prefix}/${project.artifactId} + + ${project.build.finalName}.jar + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin - copy-resources - - validate + unpack + package - copy-resources + unpack - ${basedir}/target/dockerfile - - - src/main/docker - true - - + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + - - com.spotify - docker-maven-plugin - 0.4.10 - - ${docker.image.name}:${docker.image.tag} - ${basedir}/target/dockerfile - - - / - ${project.build.directory} - ${project.build.finalName}.jar - - - - + + org.springframework.boot spring-boot-maven-plugin diff --git a/licensingserivce/src/main/docker/run.sh b/licensingserivce/src/main/docker/run.sh index e129e08..fd7d559 100644 --- a/licensingserivce/src/main/docker/run.sh +++ b/licensingserivce/src/main/docker/run.sh @@ -13,6 +13,6 @@ while ! `nc -z database $DATABASESERVER_PORT`; do sleep 3; done echo ">>>>>>>>>>>> Database Server has started" echo "********************************************************" -echo "Starting License Server with Configuration Service : $CONFIGSERVER_URI"; +echo "Starting License Server with Configuration service : $CONFIGSERVER_URI"; echo "********************************************************" java -Dspring.cloud.config.uri=$CONFIGSERVER_URI -Dspring.profiles.active=$PROFILE -jar /usr/local/licensingservice/@project.build.finalName@.jar diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/CustomFeignClinet.java b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/CustomFeignClinet.java new file mode 100644 index 0000000..e41996e --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/CustomFeignClinet.java @@ -0,0 +1,21 @@ +package com.licenseservice.Client.FeignClient; + +import com.licenseservice.model.Organization; +import org.springframework.web.bind.annotation.PathVariable; + +//@FeignClient("organizationservice") +public interface CustomFeignClinet { + + //@RequestMapping(method = RequestMethod.GET, value = "/v1/organizations/{organizationId}", consumes = "application/json") + Organization getOrganization(@PathVariable("organizationId") Long organizationId); + +// default RequestInterceptor authRequestInterceptor() +// { +// return new RequestInterceptor(){ +// @Override +// public void apply(RequestTemplate requestTemplate) { +// requestTemplate.header("Authorization", UserContextHolder.getContext().getAuthToken()); +// } +// }; +// } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/FeignConfig.java b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/FeignConfig.java new file mode 100644 index 0000000..3fcd217 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/FeignConfig.java @@ -0,0 +1,22 @@ +package com.licenseservice.Client.FeignClient; + +import com.licenseservice.utils.UserContextHolder; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FeignConfig { + + @Bean + RequestInterceptor authRequestInterceptor() + { + return new RequestInterceptor(){ + @Override + public void apply(RequestTemplate requestTemplate) { + requestTemplate.header("Authorization", UserContextHolder.getContext().getAuthToken()); + } + }; + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/OrganizationFeignClient.java b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/OrganizationFeignClient.java new file mode 100644 index 0000000..7c4cc11 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/FeignClient/OrganizationFeignClient.java @@ -0,0 +1,38 @@ +package com.licenseservice.Client.FeignClient; + +import com.licenseservice.model.Organization; +import com.licenseservice.utils.UserContextHolder; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +//import org.springframework.cloud.openfeign.FeignClientsConfiguration; +//import org.springframework.context.annotation.Import; +//import org.springframework.web.bind.annotation.PathVariable; + +//@Component +//@Import(FeignClientsConfiguration.class) +@FeignClient(name = "organizationservice", configuration = FeignConfig.class) +public interface OrganizationFeignClient{ + Logger logger = LoggerFactory.getLogger(OrganizationFeignClient.class); + + @RequestMapping(method = RequestMethod.GET, value = "/v1/organizations/{organizationId}", consumes = "application/json") + //@RequestLine("GET /v1/organizations/{organizationId}") + Organization getOrganization(@PathVariable("organizationId") String organizationId); + + static RequestInterceptor authRequestInterceptor() + { + return new RequestInterceptor(){ + @Override + public void apply(RequestTemplate requestTemplate) { + logger.info("OrganizationFeignClient add Authorization header: {UserContextHolder.getContext().getAuthToken()}"); + requestTemplate.header("Authorization", UserContextHolder.getContext().getAuthToken()); + } + }; + } + +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationAuthRestTemplateClient.java b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationAuthRestTemplateClient.java new file mode 100644 index 0000000..68358a5 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationAuthRestTemplateClient.java @@ -0,0 +1,44 @@ +package com.licenseservice.Client; + +import com.licenseservice.model.Organization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.client.OAuth2RestOperations; +import org.springframework.stereotype.Component; + +@Component +public class OrganizationAuthRestTemplateClient extends OrganizationClient{ + + + private final static Logger logger = LoggerFactory.getLogger(com.licenseservice.Client.OrganizationRestTemplateClient.class); + + @Autowired + @Qualifier("oAuth2RestTemplate") + private OAuth2RestOperations auth2RestTemplate = null; + + public Organization getOrganization(Long organizationId) { + //logger.debug("In Licensing service.getOrganization: {}", UserContext.getCorrelationId()); + Organization organization = checkRedisCache(organizationId); + if (organization != null){ + logger.info("retrieve data from redis cache successfully"); + return organization; + } + + ResponseEntity responseEntity = auth2RestTemplate.exchange( + "http://organizationservice/v1/organizations/{organizationId}", + //"http://zuulservice/api/organization/v1/organizations/{organizationId}", + HttpMethod.GET, null, Organization.class, organizationId); + + //return responseEntity.getBody(); + organization = responseEntity.getBody(); + if (organization != null){ + cacheOrgObject(responseEntity.getBody()); + } + + return organization; + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationClient.java b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationClient.java new file mode 100644 index 0000000..32033f0 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationClient.java @@ -0,0 +1,35 @@ +package com.licenseservice.Client; + +import com.licenseservice.model.Organization; +import com.licenseservice.repository.OrganizationRedisRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + + +public class OrganizationClient { + + private final static Logger logger = LoggerFactory.getLogger(OrganizationClient.class); + + + @Autowired + private OrganizationRedisRepository redisRepository; + + protected Organization checkRedisCache(Long orgId){ + try { + return redisRepository.findOrganization(orgId); + } catch (Exception ex) { + logger.error("error occurs when retrieve redis cache"); + return null; + } + } + + protected void cacheOrgObject(Organization organization){ + try { + redisRepository.saveOrganization(organization); + } catch (Exception ex){ + logger.error("error occurs when saving redis cache : {}", ex); + } + } + +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient.java b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient.java index e241309..8db3203 100644 --- a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient.java +++ b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient.java @@ -1,14 +1,8 @@ package com.licenseservice.Client; -import com.licenseservice.model.Organization; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@FeignClient("organizationservice") -public interface OrganizationFeignClient { - - @RequestMapping(method = RequestMethod.GET, value = "/v1/organizations/{organizationId}", consumes = "application/json") - public Organization getOrganization(@PathVariable("organizationId") Long organizationId); -} +//@FeignClient("organizationservice") +//public interface OrganizationFeignClient { +// +// @RequestMapping(method = RequestMethod.GET, value = "/v1/organizations/{organizationId}", consumes = "application/json") +// public Organization getOrganization(@PathVariable("organizationId") Long organizationId); +//} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient1.java b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient1.java new file mode 100644 index 0000000..309f43b --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationFeignClient1.java @@ -0,0 +1,15 @@ +package com.licenseservice.Client; + +import com.licenseservice.model.Organization; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@FeignClient("organizationservice1") +public interface OrganizationFeignClient1 { + + @RequestMapping(method = RequestMethod.GET, value = "/v1/organizations/{organizationId}", consumes = "application/json") + public Organization getOrganization(@PathVariable("organizationId") Long organizationId); + +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationRestTemplateClient.java b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationRestTemplateClient.java index 4c38fef..13eeab1 100644 --- a/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationRestTemplateClient.java +++ b/licensingserivce/src/main/java/com/licenseservice/Client/OrganizationRestTemplateClient.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; @@ -16,6 +17,7 @@ public class OrganizationRestTemplateClient { private final static Logger logger = LoggerFactory.getLogger(OrganizationRestTemplateClient.class); @Autowired + @Qualifier("restTemplate") private RestTemplate restTemplate = null; @Autowired @@ -41,21 +43,25 @@ private void cacheOrgObject(Organization organization){ public Organization getOrganization(Long organizationId) { - Organization organization = checkRedisCache(organizationId); - if (organization != null){ - logger.info("retrieve data from redis cache successfully"); - return organization; - } +// Organization organization = checkRedisCache(organizationId); +// if (organization != null){ +// logger.info("retrieve data from redis cache successfully"); +// return organization; +// } + + //logger.debug("In Licensing service.getOrganization: {}", UserContext.getCorrelationId()); ResponseEntity responseEntity = restTemplate.exchange( - "http://organizationservice//v1/organizations/{organizationId}", + "http://organizationservice/v1/organizations/{organizationId}", + //"http://zuulservice/api/organization/v1/organizations/{organizationId}", HttpMethod.GET, null, Organization.class, organizationId); - organization = responseEntity.getBody(); - if (organization != null){ - cacheOrgObject(responseEntity.getBody()); - } - - return organization; +// organization = responseEntity.getBody(); +// if (organization != null){ +// cacheOrgObject(responseEntity.getBody()); +// } +// +// return organization; + return responseEntity.getBody(); } } diff --git a/licensingserivce/src/main/java/com/licenseservice/Config/AuthClientConfig.java b/licensingserivce/src/main/java/com/licenseservice/Config/AuthClientConfig.java new file mode 100644 index 0000000..43603ad --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Config/AuthClientConfig.java @@ -0,0 +1,62 @@ +package com.licenseservice.Config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.client.OAuth2RestOperations; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.AccessTokenRequest; +import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest; +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; + +import java.util.ArrayList; +import java.util.List; + +@EnableOAuth2Client +@Configuration +public class AuthClientConfig { + + @Value("${oauth.resource:http://192.168.21.182:8091}") + private String baseUrl; + @Value("${oauth.authorize:http://192.168.21.182:8091/oauth/authorize}") + private String authorizeUrl; + @Value("${oauth.token:http://192.168.21.182:8091/oauth/token}") + private String tokenUrl; + + @Bean + protected OAuth2ProtectedResourceDetails resource() { + + ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails(); + + List scopes = new ArrayList(2); + //scopes.add("write"); + //scopes.add("read"); + resource.setAccessTokenUri(tokenUrl); + resource.setClientId("acme"); + resource.setClientSecret("acmesecret"); + resource.setGrantType("password"); + //resource.setScope(scopes); + + resource.setUsername("william.woodward"); + resource.setPassword("password2"); + + return resource; + } + + + //AuthorizationCodeResourceDetails + @Bean("oAuth2RestTemplate") + @LoadBalanced + //通过zuul网关访问organization服务,所以不需要负载均衡 + public OAuth2RestOperations getAuthRestTemplate(OAuth2ClientContext context, OAuth2ProtectedResourceDetails details){ + AccessTokenRequest atr = new DefaultAccessTokenRequest(); + + return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr)); + //return new OAuth2RestTemplate(details, context); + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/Config/ClientConfig.java b/licensingserivce/src/main/java/com/licenseservice/Config/ClientConfig.java index 3f5dc10..ec2dde0 100644 --- a/licensingserivce/src/main/java/com/licenseservice/Config/ClientConfig.java +++ b/licensingserivce/src/main/java/com/licenseservice/Config/ClientConfig.java @@ -10,9 +10,10 @@ import java.util.List; @Configuration + public class ClientConfig { - @Bean + @Bean("restTemplate") @LoadBalanced public RestTemplate getRestTemplate(){ @@ -29,8 +30,4 @@ public RestTemplate getRestTemplate(){ return restTemplate; } -// @Bean -// CurrentTraceContext log4jTraceContext() { -// return MDCCurrentTraceContext.create(); -// } } diff --git a/licensingserivce/src/main/java/com/licenseservice/LicenseserviceApplication.java b/licensingserivce/src/main/java/com/licenseservice/LicenseserviceApplication.java index b3916a0..e0e9e14 100644 --- a/licensingserivce/src/main/java/com/licenseservice/LicenseserviceApplication.java +++ b/licensingserivce/src/main/java/com/licenseservice/LicenseserviceApplication.java @@ -4,10 +4,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients() +@EnableResourceServer public class LicenseserviceApplication { public static void main(String[] args) { diff --git a/licensingserivce/src/main/java/com/licenseservice/Security/ResourceServerConfiguration.java b/licensingserivce/src/main/java/com/licenseservice/Security/ResourceServerConfiguration.java new file mode 100644 index 0000000..d62d903 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/Security/ResourceServerConfiguration.java @@ -0,0 +1,17 @@ +package com.licenseservice.Security; + +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers(HttpMethod.DELETE, "**/v1/organizations/**").hasRole("ADMIN") + .anyRequest().authenticated(); + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/events/OrganizationChangeHandler.java b/licensingserivce/src/main/java/com/licenseservice/events/OrganizationChangeHandler.java index 3660806..2e31ffd 100644 --- a/licensingserivce/src/main/java/com/licenseservice/events/OrganizationChangeHandler.java +++ b/licensingserivce/src/main/java/com/licenseservice/events/OrganizationChangeHandler.java @@ -19,19 +19,20 @@ public class OrganizationChangeHandler { public void loggerSink(OrgChangeModel orgChange) { logger.info("----Received a message of type " + orgChange.getTypeName()); - switch (orgChange.getTypeName()){ + switch (orgChange.getAction()){ case "get": - logger.debug("Received a GET event from the organization service for organization id {}", orgChange.getOrgId()); + logger.info("Received a GET event from the organization service for organization id {}", orgChange.getOrgId()); break; case "save": - logger.debug("Received a SAVE event from the organization service for organization id {}", orgChange.getOrgId()); + logger.info("Received a SAVE event from the organization service for organization id {}", orgChange.getOrgId()); + break; //redisRepository.saveOrganization(orgChange); case "update": - logger.debug("Received a UPDATE event from the organization service for organization id {}", orgChange.getOrgId()); + logger.info("Received a UPDATE event from the organization service for organization id {}", orgChange.getOrgId()); redisRepository.deleteOrganization(orgChange.getOrgId()); break; case "delete": - logger.debug("Received a DELETE event from the organization service for organization id {}", orgChange.getOrgId()); + logger.info("Received a DELETE event from the organization service for organization id {}", orgChange.getOrgId()); redisRepository.deleteOrganization(orgChange.getOrgId()); break; default: diff --git a/licensingserivce/src/main/java/com/licenseservice/exceptions/AppExceptionHandler.java b/licensingserivce/src/main/java/com/licenseservice/exceptions/AppExceptionHandler.java new file mode 100644 index 0000000..cfe2b78 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/exceptions/AppExceptionHandler.java @@ -0,0 +1,21 @@ +package com.licenseservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + + +@ControllerAdvice +public class AppExceptionHandler { + + @ExceptionHandler(LicensingException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public @ResponseBody Error licensingHandler(LicensingException ex) { + Long orgId = ex.getOrganizationId(); + Long licensingId = ex.getLicenseId(); + return new Error(4, "Licensing [ LicenseId: " + licensingId + + ", OrganizationId: " + orgId + " ] not found"); + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/exceptions/Error.java b/licensingserivce/src/main/java/com/licenseservice/exceptions/Error.java new file mode 100644 index 0000000..e92468b --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/exceptions/Error.java @@ -0,0 +1,27 @@ +package com.licenseservice.exceptions; + +public class Error { + private int code; + private String message; + + public Error(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/exceptions/LicensingException.java b/licensingserivce/src/main/java/com/licenseservice/exceptions/LicensingException.java new file mode 100644 index 0000000..66c7294 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/exceptions/LicensingException.java @@ -0,0 +1,33 @@ +package com.licenseservice.exceptions; + +public class LicensingException extends RuntimeException { + private Long organizationId; + private Long licenseId; + + public LicensingException(String message, Long organizationId, Long licenseId) { + super(message); + this.organizationId = organizationId; + this.licenseId = licenseId; + } + + public LicensingException( Long organizationId, Long licenseId) { + this.organizationId = organizationId; + this.licenseId = licenseId; + } + + public Long getOrganizationId() { + return organizationId; + } + + public void setOrganizationId(Long organizationId) { + this.organizationId = organizationId; + } + + public Long getLicenseId() { + return licenseId; + } + + public void setLicenseId(Long licenseId) { + this.licenseId = licenseId; + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/model/Organization.java b/licensingserivce/src/main/java/com/licenseservice/model/Organization.java index 3e21324..d9daf51 100644 --- a/licensingserivce/src/main/java/com/licenseservice/model/Organization.java +++ b/licensingserivce/src/main/java/com/licenseservice/model/Organization.java @@ -1,6 +1,8 @@ package com.licenseservice.model; -public class Organization { +import java.io.Serializable; + +public class Organization implements Serializable { private Long id; private String name; diff --git a/licensingserivce/src/main/java/com/licenseservice/repository/OrganizationRedisRepositoryImpl.java b/licensingserivce/src/main/java/com/licenseservice/repository/OrganizationRedisRepositoryImpl.java index c99cead..c48879f 100644 --- a/licensingserivce/src/main/java/com/licenseservice/repository/OrganizationRedisRepositoryImpl.java +++ b/licensingserivce/src/main/java/com/licenseservice/repository/OrganizationRedisRepositoryImpl.java @@ -13,7 +13,7 @@ public class OrganizationRedisRepositoryImpl implements OrganizationRedisReposit private final static String HASH_NAME = "organization"; - private RedisTemplate redisTemplate; + private RedisTemplate redisTemplate; private HashOperations hashOperations; @Autowired diff --git a/licensingserivce/src/main/java/com/licenseservice/service/LicenseService.java b/licensingserivce/src/main/java/com/licenseservice/service/LicenseService.java index cbf65ed..6e755f6 100644 --- a/licensingserivce/src/main/java/com/licenseservice/service/LicenseService.java +++ b/licensingserivce/src/main/java/com/licenseservice/service/LicenseService.java @@ -1,12 +1,14 @@ package com.licenseservice.service; +import com.licenseservice.Client.FeignClient.OrganizationFeignClient; +import com.licenseservice.Client.OrganizationAuthRestTemplateClient; import com.licenseservice.Client.OrganizationDiscoveryClient; -import com.licenseservice.Client.OrganizationFeignClient; import com.licenseservice.Client.OrganizationRestTemplateClient; import com.licenseservice.Config.ServiceConfig; import com.licenseservice.Mapper.LicenseMapper; import com.licenseservice.model.License; import com.licenseservice.model.Organization; +import com.licenseservice.exceptions.LicensingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -27,8 +29,22 @@ public class LicenseService { private OrganizationRestTemplateClient restTemplateClient = null; @Autowired + private OrganizationAuthRestTemplateClient authRestTemplateClient = null; + + //@Autowired private OrganizationFeignClient feignClient = null; + @Autowired + public void FeignClient(OrganizationFeignClient cleint) { + feignClient = cleint; + + } + +// @Autowired +// public void setFeignClient() { +// feignClient = Feign.builder().requestInterceptor(OrganizationFeignClient.authRequestInterceptor()).target(OrganizationFeignClient.class, "http://organizationservice"); +// } + @Autowired private ServiceConfig serviceConfig = null; @@ -37,17 +53,20 @@ private Organization retrieveOrgInfo(Long organizationId, String clientType){ switch (clientType){ case "discovery": - logger.info("using discovery client"); - System.out.println("---discovery client"); + logger.info("---discovery client"); organization = discoveryClient.getOrganization(organizationId); break; case "rest": - System.out.println("---rest client"); + logger.info("---rest client"); organization = restTemplateClient.getOrganization(organizationId); break; case "feign": - System.out.println("---feign client"); - organization = feignClient.getOrganization(organizationId); + logger.info("---feign client"); + organization = feignClient.getOrganization(organizationId.toString()); + break; + case "authrest": + logger.info("---auth rest client"); + organization = authRestTemplateClient.getOrganization(organizationId); } return organization; @@ -55,9 +74,16 @@ private Organization retrieveOrgInfo(Long organizationId, String clientType){ } public License getLicense(Long organizationId, Long licenseId, String clientType) { + //License license = new License(); License license = licenseMapper.getLicense(organizationId, licenseId); + if (license == null) { + throw new LicensingException(organizationId, licenseId); + } Organization org = retrieveOrgInfo(organizationId, clientType); + if (org == null) { + throw new LicensingException(organizationId, licenseId); + } license.setOrganizationName(org.getName()); license.setContactName(org.getContactName()); diff --git a/licensingserivce/src/main/java/com/licenseservice/utils/UserContext.java b/licensingserivce/src/main/java/com/licenseservice/utils/UserContext.java new file mode 100644 index 0000000..e147039 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/utils/UserContext.java @@ -0,0 +1,48 @@ +package com.licenseservice.utils; + +import org.springframework.stereotype.Component; + +@Component +public class UserContext { + public static final String CORRELATION_ID = "tmx-correlation-id"; + public static final String AUTH_TOKEN = "Authorization"; + public static final String USER_ID = "tmx-user-id"; + public static final String ORG_ID = "tmx-org-id"; + + private String correlationId; + private String authToken; + private String userId; + private String orgId; + + public String getCorrelationId() { + return correlationId; + } + + public void setCorrelationId(String correlationId) { + this.correlationId = correlationId; + } + + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String orgId) { + this.orgId = orgId; + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/utils/UserContextFilter.java b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextFilter.java new file mode 100644 index 0000000..0bd6371 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextFilter.java @@ -0,0 +1,39 @@ +package com.licenseservice.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@Component +public class UserContextFilter implements Filter { + + private static final Logger logger= LoggerFactory.getLogger(UserContextFilter.class); + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + + UserContextHolder.getContext().setCorrelationId(httpServletRequest.getHeader(UserContext.CORRELATION_ID)); + UserContextHolder.getContext().setAuthToken(httpServletRequest.getHeader(UserContext.AUTH_TOKEN)); + UserContextHolder.getContext().setUserId(httpServletRequest.getHeader(UserContext.USER_ID)); + UserContextHolder.getContext().setOrgId(httpServletRequest.getHeader(UserContext.ORG_ID)); + + logger.info("Special Routes service Incoming Correlation id: {}", UserContextHolder.getContext().getCorrelationId()); + logger.info("------UserContextFilter, Auth: " + httpServletRequest.getHeader("Authorization")); + filterChain.doFilter(httpServletRequest, servletResponse); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void destroy() { + + } +} diff --git a/licensingserivce/src/main/java/com/licenseservice/utils/UserContextHolder.java b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextHolder.java new file mode 100644 index 0000000..f53cdf0 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextHolder.java @@ -0,0 +1,21 @@ +package com.licenseservice.utils; + +public class UserContextHolder { + + private static final ThreadLocal userContext = new ThreadLocal<>(); + + public static UserContext getContext() { + UserContext context = userContext.get(); + + if (context == null) { + context = new UserContext(); + userContext.set(context); + } + return userContext.get(); + } + + public void setContext(UserContext context) { + userContext.set(context); + } + +} diff --git a/licensingserivce/src/main/java/com/licenseservice/utils/UserContextInterceptor.java b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextInterceptor.java new file mode 100644 index 0000000..0ae0021 --- /dev/null +++ b/licensingserivce/src/main/java/com/licenseservice/utils/UserContextInterceptor.java @@ -0,0 +1,30 @@ +package com.licenseservice.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import java.io.IOException; + +public class UserContextInterceptor implements ClientHttpRequestInterceptor { + private final static Logger logger = LoggerFactory.getLogger(UserContextInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + + HttpHeaders headers = request.getHeaders(); + logger.info("-----UserContextInterceptor: ", headers.toString()); + headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId()); + +// if (headers.getFirst("Authorization").isEmpty()){ +// logger.info("-----UserContextInterceptor set Authorization header ", UserContextHolder.getContext().getAuthToken()); +// headers.add(UserContext.AUTH_TOKEN, UserContextHolder.getContext().getAuthToken()); +// } + headers.add(UserContext.AUTH_TOKEN, UserContextHolder.getContext().getAuthToken()); + return execution.execute(request, body); + } +} diff --git a/licensingserivce/src/main/resources/application.yml b/licensingserivce/src/main/resources/application.yml index 752bfea..5c627ea 100644 --- a/licensingserivce/src/main/resources/application.yml +++ b/licensingserivce/src/main/resources/application.yml @@ -1,5 +1,5 @@ server: - port: 8989 + port: 9989 #spring.datasource.url=jdbc:mysql://192.168.21.225:3306/mytest #spring.datasource.username=testuser @@ -51,8 +51,18 @@ spring: binder: brokers: 192.168.21.225:9092 zk-nodes: 192.168.21.225:2181 +security: + oauth2: + resource: + user-info-uri: http://192.168.21.182:8091/user + +logging.level.org.springframework.web: TRACE +logging.level.org.springframework.http: TRACE +logging.level.web: TRACE + #logging.path=logs logging: level: org.springframework.cloud.config: DEBUG + org.springframework.web: DEBUG #logging.file=${logging.path}/licenseservice.log \ No newline at end of file diff --git a/organizationservice/pom.xml b/organizationservice/pom.xml index 16d69d9..d39f901 100644 --- a/organizationservice/pom.xml +++ b/organizationservice/pom.xml @@ -95,6 +95,12 @@ org.springframework.cloud spring-cloud-starter-stream-kafka + + com + common + 0.0.1-SNAPSHOT + compile + diff --git a/organizationservice/src/main/java/com/organizationservice/events/SimpleSourceBean.java b/organizationservice/src/main/java/com/organizationservice/events/SimpleSourceBean.java index 338ddbd..560282b 100644 --- a/organizationservice/src/main/java/com/organizationservice/events/SimpleSourceBean.java +++ b/organizationservice/src/main/java/com/organizationservice/events/SimpleSourceBean.java @@ -1,6 +1,5 @@ package com.organizationservice.events; -import com.organizationservice.utils.UserContextHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -8,6 +7,7 @@ import org.springframework.cloud.stream.messaging.Source; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; +import utils.UserContextHolder; @Component @EnableBinding(Source.class) diff --git a/organizationservice/src/main/resources/application.yml b/organizationservice/src/main/resources/application.yml index bb2e509..9503936 100644 --- a/organizationservice/src/main/resources/application.yml +++ b/organizationservice/src/main/resources/application.yml @@ -24,12 +24,22 @@ # register-with-eureka: true # service-url: # defaultZone: http://140.143.45.252:8761/eureka/ +spring: + cloud: + stream: + bindings: + output: + destination: orgChangeTopic + content-type: application/json + kafka: + binder: + brokers: 192.168.21.225:9092 + zk-nodes: 192.168.21.225:2181 logging.level.org.springframework.web: TRACE logging.level.org.springframework.http: TRACE logging.level.web: TRACE - mybatis: mapper-locations: classpath:organizationMapper.xml config-location: classpath:mybatis-config.xml @@ -37,16 +47,6 @@ mybatis: security: oauth2: resource: - user-info-uri: http://192.168.21.197:8091/user -spring: - cloud: - stream: - bindings: - output: - destination: orgChangeTopic - content-type: application/json - kafka: - binder: - brokers: 192.168.21.225:9092 - zk-nodes: 192.168.21.225:2181 + user-info-uri: http://192.168.21.182:8091/user + diff --git a/pom.xml b/pom.xml index e01cd8e..77a8f91 100644 --- a/pom.xml +++ b/pom.xml @@ -51,14 +51,14 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + + + + +