diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 00000000..02ad4c6d --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,2 @@ +repo_token: nV7wobmoTexZCucPnylWvD6VmRGl0s1nH + diff --git a/README.md b/README.md index 01cd84ba..e06e6991 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,17 @@ -[![Build Status](https://travis-ci.org/stackroute/boeing-wave3-mashup.svg?branch=master)](https://travis-ci.org/stackroute/boeing-wave3-mashup) -[![codecov](https://codecov.io/gh/stackroute/boeing-wave3-mashup/branch/master/graph/badge.svg)](https://codecov.io/gh/stackroute/boeing-wave3-mashup) -![](https://img.shields.io/codecov/c/github/stackroute/boeing-wave3-mashup.svg?style=flat) +[![Build Status](https://travis-ci.org/stackroute/boeing-wave3-mashup.svg?branch=v1.0.0)](https://travis-ci.org/stackroute/boeing-wave3-mashup) +[![codecov](https://codecov.io/gh/stackroute/boeing-wave3-mashup/branch/v1.0.0/graph/badge.svg)](https://codecov.io/gh/stackroute/boeing-wave3-mashup) +![](https://img.shields.io/codecov/c/github/stackroute/boeing-wave3-mashup.svg?style=flat) ![](https://img.shields.io/snyk/vulnerabilities/github/stackroute/boeing-wave3-mashup.svg?style=popout) -![](https://img.shields.io/github/issues/stackroute/boeing-wave3-mashup.svg?style=popout) +![](https://img.shields.io/github/issues/stackroute/boeing-wave3-mashup.svg?style=popout) ![](https://img.shields.io/github/contributors/stackroute/boeing-wave3-mashup.svg?style=popout) ![](https://img.shields.io/github/last-commit/stackroute/boeing-wave3-mashup.svg?style=popout) - ![](https://img.shields.io/github/repo-size/stackroute/boeing-wave3-mashup.svg?style=popout) + [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ****Running the System**** Run ```mvn clean compile package``` on all the services - - diff --git a/authentication-service/.gitignore b/authentication-service/.gitignore new file mode 100644 index 00000000..c456c4a3 --- /dev/null +++ b/authentication-service/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ diff --git a/authentication-service/Dockerfile b/authentication-service/Dockerfile new file mode 100644 index 00000000..768cc09e --- /dev/null +++ b/authentication-service/Dockerfile @@ -0,0 +1,6 @@ +FROM openjdk:10 + +ADD ./target/authentication-service-0.0.1-SNAPSHOT.jar authentication-service.jar +EXPOSE 8021 + +ENTRYPOINT ["java","-jar","authentication-service.jar"] diff --git a/authentication-service/pom.xml b/authentication-service/pom.xml new file mode 100644 index 00000000..03f72cba --- /dev/null +++ b/authentication-service/pom.xml @@ -0,0 +1,117 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.stackroute + authentication-service + 0.0.1-SNAPSHOT + authentication-service + Authentication Service + + + 10 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + io.jsonwebtoken + jjwt + 0.9.0 + + + + io.springfox + springfox-swagger2 + 2.6.1 + compile + + + + io.springfox + springfox-swagger-ui + 2.6.1 + compile + + + org.springframework.kafka + spring-kafka + + + org.springframework.kafka + spring-kafka-test + test + + + org.codehaus.jackson + jackson-xc + 1.9.11 + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.0.2.RELEASE + + + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/authenticationserviceApplication.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/authenticationserviceApplication.java new file mode 100644 index 00000000..febc4598 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/authenticationserviceApplication.java @@ -0,0 +1,17 @@ +package com.stackroute.authenticationservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@EnableEurekaClient +@SpringBootApplication +public class authenticationserviceApplication { + + public static void main(String[] args) { + + SpringApplication.run(authenticationserviceApplication.class, args); + } + +} + diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/config/KafkaConfiguration.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/config/KafkaConfiguration.java new file mode 100644 index 00000000..ea8fdaf8 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/config/KafkaConfiguration.java @@ -0,0 +1,36 @@ +package com.stackroute.authenticationservice.config; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; + +import java.util.HashMap; +import java.util.Map; + +@EnableKafka +@Configuration +public class KafkaConfiguration { + @Bean + public ConsumerFactory consumerFactory(){ + Map config = new HashMap<>(); + + config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092"); + config.put(ConsumerConfig.GROUP_ID_CONFIG,"group_id"); + config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); + config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class); + + return new DefaultKafkaConsumerFactory<>(config); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(){ + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/config/SwaggerConfig.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/config/SwaggerConfig.java new file mode 100644 index 00000000..2a938e03 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/config/SwaggerConfig.java @@ -0,0 +1,22 @@ +package com.stackroute.authenticationservice.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import static springfox.documentation.builders.PathSelectors.regex; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + @Bean + public Docket productApi() { + return new Docket(DocumentationType.SWAGGER_2) + .select().apis(RequestHandlerSelectors.basePackage("com.grokonez.jwtauthentication.controller")) + .paths(regex("/api/auth.*")) + .build(); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/AuthRestAPIs.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/AuthRestAPIs.java new file mode 100644 index 00000000..bc42d3e7 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/AuthRestAPIs.java @@ -0,0 +1,62 @@ +package com.stackroute.authenticationservice.controller; + +import java.util.HashSet; +import java.util.Set; + +import javax.validation.Valid; + +import com.stackroute.authenticationservice.message.request.LoginForm; +import com.stackroute.authenticationservice.message.response.JwtResponse; +import com.stackroute.authenticationservice.repository.RoleRepository; +import com.stackroute.authenticationservice.repository.UserRepository; +import com.stackroute.authenticationservice.security.jwt.JwtProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + + +@CrossOrigin("*") +@RestController +@RequestMapping("/api/auth") +public class AuthRestAPIs { + + @Autowired + AuthenticationManager authenticationManager; + + @Autowired + UserRepository userRepository; + + @Autowired + RoleRepository roleRepository; + + @Autowired + PasswordEncoder encoder; + + @Autowired + JwtProvider jwtProvider; + + @PostMapping("/signin") + public ResponseEntity authenticateUser(@Valid @RequestBody LoginForm loginRequest) { + + Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + String jwt = jwtProvider.generateJwtToken(authentication); + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + + return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities())); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/TestRestAPIs.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/TestRestAPIs.java new file mode 100644 index 00000000..76604027 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/controller/TestRestAPIs.java @@ -0,0 +1,29 @@ +package com.stackroute.authenticationservice.controller; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@CrossOrigin(origins = "*", maxAge = 3600) +@RestController +public class TestRestAPIs { + + @GetMapping("/api/test/user") + @PreAuthorize("hasRole('USER') or hasRole('ADMIN')") + public String userAccess() { + return ">>> User Contents!"; + } + + @GetMapping("/api/test/pm") + @PreAuthorize("hasRole('PM') or hasRole('ADMIN')") + public String projectManagementAccess() { + return ">>> Project Management Board"; + } + + @GetMapping("/api/test/admin") + @PreAuthorize("hasRole('ADMIN')") + public String adminAccess() { + return ">>> Admin Contents"; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/LoginForm.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/LoginForm.java new file mode 100644 index 00000000..3aaaf1af --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/LoginForm.java @@ -0,0 +1,30 @@ +package com.stackroute.authenticationservice.message.request; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +public class LoginForm { + @NotBlank + @Size(min=3, max = 60) + private String username; + + @NotBlank + @Size(min = 6, max = 40) + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/SignUpForm.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/SignUpForm.java new file mode 100644 index 00000000..6523a381 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/request/SignUpForm.java @@ -0,0 +1,66 @@ +package com.stackroute.authenticationservice.message.request; + +import java.util.Set; + +import javax.validation.constraints.*; + +public class SignUpForm { + @NotBlank + @Size(min = 3, max = 50) + private String name; + + @NotBlank + @Size(min = 3, max = 50) + private String username; + + @NotBlank + @Size(max = 60) + @Email + private String email; + + private Set role; + + @NotBlank + @Size(min = 6, max = 40) + private String password; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRole() { + return this.role; + } + + public void setRole(Set role) { + this.role = role; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/JwtResponse.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/JwtResponse.java new file mode 100644 index 00000000..571fa878 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/JwtResponse.java @@ -0,0 +1,46 @@ +package com.stackroute.authenticationservice.message.response; + +import java.util.Collection; + +import org.springframework.security.core.GrantedAuthority; + +public class JwtResponse { + private String token; + private String type = "Bearer"; + private String username; + private Collection authorities; + + public JwtResponse(String accessToken, String username, Collection authorities) { + this.token = accessToken; + this.username = username; + this.authorities = authorities; + } + + public String getAccessToken() { + return token; + } + + public void setAccessToken(String accessToken) { + this.token = accessToken; + } + + public String getTokenType() { + return type; + } + + public void setTokenType(String tokenType) { + this.type = tokenType; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Collection getAuthorities() { + return authorities; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/ResponseMessage.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/ResponseMessage.java new file mode 100644 index 00000000..551c140e --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/message/response/ResponseMessage.java @@ -0,0 +1,17 @@ +package com.stackroute.authenticationservice.message.response; + +public class ResponseMessage { + private String message; + + public ResponseMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/model/Role.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/Role.java new file mode 100644 index 00000000..3d9e19b2 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/Role.java @@ -0,0 +1,48 @@ +package com.stackroute.authenticationservice.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.stackroute.authenticationservice.model.RoleName; +import org.hibernate.annotations.NaturalId; + +@Entity +@Table(name = "roles") +public class Role { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @NaturalId + @Column(length = 60) + private RoleName name; + + public Role() {} + + public Role(RoleName name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public RoleName getName() { + return name; + } + + public void setName(RoleName name) { + this.name = name; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/model/RoleName.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/RoleName.java new file mode 100644 index 00000000..d10acd1b --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/RoleName.java @@ -0,0 +1,6 @@ +package com.stackroute.authenticationservice.model; + +public enum RoleName { + ROLE_USER, + ROLE_ADMIN +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/model/User.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/User.java new file mode 100644 index 00000000..a1723cdf --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/model/User.java @@ -0,0 +1,116 @@ +package com.stackroute.authenticationservice.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +import org.hibernate.annotations.NaturalId; + +@Entity +@Table(name = "users", uniqueConstraints = { + @UniqueConstraint(columnNames = { + "username" + }), + @UniqueConstraint(columnNames = { + "email" + }) +}) +public class User{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotBlank + @Size(min=3, max = 50) + private String name; + + @NotBlank + @Size(min=3, max = 50) + private String username; + + @NaturalId + @NotBlank + @Size(max = 50) + @Email + private String email; + + @NotBlank + @Size(min=6, max = 100) + private String password; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "user_roles", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new HashSet<>(); + + public User() {} + + public User(String name, String username, String email, String password) { + this.name = name; + this.username = username; + this.email = email; + this.password = password; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/RoleRepository.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/RoleRepository.java new file mode 100644 index 00000000..7c5878dc --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/RoleRepository.java @@ -0,0 +1,13 @@ +package com.stackroute.authenticationservice.repository; + +import java.util.Optional; + +import com.stackroute.authenticationservice.model.Role; +import com.stackroute.authenticationservice.model.RoleName; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface RoleRepository extends JpaRepository { + Optional findByName(RoleName roleName); +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/UserRepository.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/UserRepository.java new file mode 100644 index 00000000..9ccf83f3 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/repository/UserRepository.java @@ -0,0 +1,16 @@ +package com.stackroute.authenticationservice.repository; + +import java.util.Optional; + +import com.stackroute.authenticationservice.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByUsername(String username); + Boolean existsByUsername(String username); + Boolean existsByEmail(String email); + +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/WebSecurityConfig.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/WebSecurityConfig.java new file mode 100644 index 00000000..883a5f10 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/WebSecurityConfig.java @@ -0,0 +1,68 @@ +package com.stackroute.authenticationservice.security; + +import com.stackroute.authenticationservice.security.jwt.JwtAuthEntryPoint; +import com.stackroute.authenticationservice.security.jwt.JwtAuthTokenFilter; +import com.stackroute.authenticationservice.security.services.UserDetailsServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity( + prePostEnabled = true +) +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + UserDetailsServiceImpl userDetailsService; + + @Autowired + private JwtAuthEntryPoint unauthorizedHandler; + + @Bean + public JwtAuthTokenFilter authenticationJwtTokenFilter() { + return new JwtAuthTokenFilter(); + } + + @Override + public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { + authenticationManagerBuilder + .userDetailsService(userDetailsService) + .passwordEncoder(passwordEncoder()); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and().csrf().disable(). + authorizeRequests() + .antMatchers("/api/auth/**").permitAll() + .anyRequest().authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthEntryPoint.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthEntryPoint.java new file mode 100644 index 00000000..15fb74a6 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthEntryPoint.java @@ -0,0 +1,29 @@ +package com.stackroute.authenticationservice.security.jwt; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +@Component +public class JwtAuthEntryPoint implements AuthenticationEntryPoint { + + private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class); + + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, + AuthenticationException e) + throws IOException, ServletException { + + logger.error("Unauthorized error. Message - {}", e.getMessage()); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error -> Unauthorized"); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthTokenFilter.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthTokenFilter.java new file mode 100644 index 00000000..71812a65 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtAuthTokenFilter.java @@ -0,0 +1,63 @@ +package com.stackroute.authenticationservice.security.jwt; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.stackroute.authenticationservice.security.services.UserDetailsServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.web.filter.OncePerRequestFilter; + + +public class JwtAuthTokenFilter extends OncePerRequestFilter { + + @Autowired + private JwtProvider tokenProvider; + + @Autowired + private UserDetailsServiceImpl userDetailsService; + + private static final Logger logger = LoggerFactory.getLogger(JwtAuthTokenFilter.class); + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + try { + + String jwt = getJwt(request); + if (jwt != null && tokenProvider.validateJwtToken(jwt)) { + String username = tokenProvider.getUserNameFromJwtToken(jwt); + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + } catch (Exception e) { + logger.error("Can NOT set user authentication -> Message: {}", e); + } + + filterChain.doFilter(request, response); + } + + private String getJwt(HttpServletRequest request) { + String authHeader = request.getHeader("Authorization"); + + if (authHeader != null && authHeader.startsWith("Bearer ")) { + return authHeader.replace("Bearer ", ""); + } + + return null; + } +} diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtProvider.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtProvider.java new file mode 100644 index 00000000..0ef89cf0 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/jwt/JwtProvider.java @@ -0,0 +1,62 @@ +package com.stackroute.authenticationservice.security.jwt; + +import com.stackroute.authenticationservice.security.services.UserPrinciple; +import io.jsonwebtoken.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + + +import java.util.Date; + +@Component +public class JwtProvider { + + private static final Logger logger = LoggerFactory.getLogger(JwtProvider.class); + + @Value("${grokonez.app.jwtSecret}") + private String jwtSecret; + + @Value("${grokonez.app.jwtExpiration}") + private int jwtExpiration; + + public String generateJwtToken(Authentication authentication) { + + UserPrinciple userPrincipal = (UserPrinciple) authentication.getPrincipal(); + + return Jwts.builder() + .setSubject((userPrincipal.getUsername())) + .setIssuedAt(new Date()) + .setExpiration(new Date((new Date()).getTime() + jwtExpiration*1000)) + .signWith(SignatureAlgorithm.HS512, jwtSecret) + .compact(); + } + + public boolean validateJwtToken(String authToken) { + try { + Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); + return true; + } catch (SignatureException e) { + logger.error("Invalid JWT signature -> Message: {} ", e); + } catch (MalformedJwtException e) { + logger.error("Invalid JWT token -> Message: {}", e); + } catch (ExpiredJwtException e) { + logger.error("Expired JWT token -> Message: {}", e); + } catch (UnsupportedJwtException e) { + logger.error("Unsupported JWT token -> Message: {}", e); + } catch (IllegalArgumentException e) { + logger.error("JWT claims string is empty -> Message: {}", e); + } + + return false; + } + + public String getUserNameFromJwtToken(String token) { + return Jwts.parser() + .setSigningKey(jwtSecret) + .parseClaimsJws(token) + .getBody().getSubject(); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/KafkaListenerService.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/KafkaListenerService.java new file mode 100644 index 00000000..222137f5 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/KafkaListenerService.java @@ -0,0 +1,39 @@ +package com.stackroute.authenticationservice.security.services; + +import com.stackroute.authenticationservice.model.User; +import com.stackroute.authenticationservice.repository.RoleRepository; +import com.stackroute.authenticationservice.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class KafkaListenerService { + + @Autowired + UserRepository userRepository; + + @Autowired + RoleRepository roleRepository; + + @Autowired + PasswordEncoder encoder; + + @KafkaListener(topics = "AuthMessage", groupId = "group_id") + public void consume(String message){ + String[] strMessage = message.split(","); + User user = new User(); + user.setName(strMessage[6].split(":")[1].replace("\"","") + + " " + strMessage[7].split(":")[1].replace("\"","")); + user.setEmail(strMessage[11].split(":")[1].replace("\"","")); + user.setUsername(strMessage[0].split(":")[1].replace("\"","")); + user.setPassword(strMessage[1].split(":")[1].replace("\"","")); + System.out.println(user.getName()); + System.out.println(user.getEmail()); + System.out.println(user.getPassword()); + System.out.println(user.getUsername()); + userRepository.save(user); + System.out.println("Consumed msg : " + message); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserDetailsServiceImpl.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserDetailsServiceImpl.java new file mode 100644 index 00000000..f27649ee --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserDetailsServiceImpl.java @@ -0,0 +1,29 @@ +package com.stackroute.authenticationservice.security.services; + + +import com.stackroute.authenticationservice.model.User; +import com.stackroute.authenticationservice.repository.UserRepository; +import com.stackroute.authenticationservice.security.services.UserPrinciple; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + @Autowired + UserRepository userRepository; + + @Override + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + + User user = userRepository.findByUsername(username).orElseThrow( + () -> new UsernameNotFoundException("User Not Found with -> username or email : " + username)); + + return UserPrinciple.build(user); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserPrinciple.java b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserPrinciple.java new file mode 100644 index 00000000..6ad2e5d0 --- /dev/null +++ b/authentication-service/src/main/java/com/stackroute.authenticationservice/security/services/UserPrinciple.java @@ -0,0 +1,111 @@ +package com.stackroute.authenticationservice.security.services; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.stackroute.authenticationservice.model.User; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class UserPrinciple implements UserDetails { + private static final long serialVersionUID = 1L; + + private Long id; + + private String name; + + private String username; + + private String email; + + @JsonIgnore + private String password; + + private Collection authorities; + + public UserPrinciple(Long id, String name, + String username, String email, String password, + Collection authorities) { + this.id = id; + this.name = name; + this.username = username; + this.email = email; + this.password = password; + this.authorities = authorities; + } + + public static UserPrinciple build(User user) { + List authorities = user.getRoles().stream().map(role -> + new SimpleGrantedAuthority(role.getName().name()) + ).collect(Collectors.toList()); + + return new UserPrinciple( + user.getId(), + user.getName(), + user.getUsername(), + user.getEmail(), + user.getPassword(), + authorities + ); + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + UserPrinciple user = (UserPrinciple) o; + return Objects.equals(id, user.id); + } +} \ No newline at end of file diff --git a/authentication-service/src/main/resources/application.properties b/authentication-service/src/main/resources/application.properties new file mode 100644 index 00000000..7922e96f --- /dev/null +++ b/authentication-service/src/main/resources/application.properties @@ -0,0 +1,17 @@ +server.port=8021 + +spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useSSL=false +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.hibernate.ddl-auto=update + +spring.jpa.generate-ddl=true +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect +spring.jpa.hibernate.show-sql= true + +# App Properties +grokonez.app.jwtSecret=jwtGrokonezSecretKey +grokonez.app.jwtExpiration=86400 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/authentication-service/src/main/resources/application.yml b/authentication-service/src/main/resources/application.yml new file mode 100644 index 00000000..be2f8678 --- /dev/null +++ b/authentication-service/src/main/resources/application.yml @@ -0,0 +1,26 @@ +##server: +## port: 8098 #default port where the service will be started +## +eureka: #tells about the Eureka server details and its refresh time + instance: + leaseRenewalIntervalInSeconds: 1 + leaseExpirationDurationInSeconds: 2 + client: + serviceUrl: + defaultZone: http://localhost:8093/eureka/ + healthcheck: + enabled: true + lease: + duration: 5 + +spring: + application: + name: authentication-service #current service name to be used by the eureka server + +management: + security: + enabled: false #disable the spring security on the management endpoints like /env, /refresh etc. + +logging: + level: + com.stckroute.authentication-service: DEBUG \ No newline at end of file diff --git a/authentication-service/src/main/resources/roles.sql b/authentication-service/src/main/resources/roles.sql new file mode 100644 index 00000000..b871468d --- /dev/null +++ b/authentication-service/src/main/resources/roles.sql @@ -0,0 +1,3 @@ +INSERT INTO roles(name) VALUES('ROLE_USER'); +INSERT INTO roles(name) VALUES('ROLE_PM'); +INSERT INTO roles(name) VALUES('ROLE_ADMIN'); \ No newline at end of file diff --git a/authentication-service/src/test/java/com/grokonez/jwtauthentication/JwtauthenticationApplicationTests.java b/authentication-service/src/test/java/com/grokonez/jwtauthentication/JwtauthenticationApplicationTests.java new file mode 100644 index 00000000..d6392be5 --- /dev/null +++ b/authentication-service/src/test/java/com/grokonez/jwtauthentication/JwtauthenticationApplicationTests.java @@ -0,0 +1,17 @@ +//package com.grokonez.jwtauthentication; +// +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.springframework.boot.test.context.SpringBootTest; +//import org.springframework.test.context.junit4.SpringRunner; +// +//@RunWith(SpringRunner.class) +//@SpringBootTest +//public class JwtauthenticationApplicationTests { +// +// @Test +// public void contextLoads() { +// } +// +//} +// diff --git a/config-server/Dockerfile b/config-server/Dockerfile index 3ee3b45e..7f287e32 100644 --- a/config-server/Dockerfile +++ b/config-server/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM openjdk:10 ADD ./target/config-server-0.0.1-SNAPSHOT.jar /event/src/config-server-0.0.1-SNAPSHOT.jar EXPOSE 8888 diff --git a/config-server/pom.xml b/config-server/pom.xml index d67d6aa8..baf82432 100644 --- a/config-server/pom.xml +++ b/config-server/pom.xml @@ -19,7 +19,7 @@ UTF-8 UTF-8 - 1.8 + 10 ${java.version} ${java.version} Greenwich.RELEASE diff --git a/docker-compose.yml b/docker-compose.yml index 898dc54d..8fe80e6e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,38 +1,200 @@ -version: "2" +version: "2.1" services: apigateway: - image: zuul-service - build: zuul-gatewayservice/ - restart: always - network_mode: host - depends_on: - - eurekaserver - ports: - - 8092:8092 - expose: - - 8092 + image: zuul-service + build: zuul-gatewayservice/ + restart: always + network_mode: host + depends_on: + - eurekaserver + ports: + - 8092:8092 + expose: + - 8092 + healthcheck: + test: "exit 0" eurekaserver: - image: eureka-servcie:latest - build: eureka-server/ - restart: always + image: eureka-service:latest + build: eureka-server/ + restart: always + network_mode: host + ports: + - 8093:8093 + expose: + - 8093 + healthcheck: + test: "exit 0" + + configserver: + image: config-service:latest + build: config-server/ + restart: always + network_mode: host + ports: + - 8888:8888 + expose: + - 8888 + healthcheck: + test: "exit 0" + + mongo: + image: mongo:3.4-jessie + ports: + - 27017:27017 + container_name: mongo_docker + network_mode: host + hostname: localhost + restart: always + volumes: + - ~/Desktop/db:/data/db + healthcheck: + test: "exit 0" + + neo4j: + image: neo4j:latest + ports: + - 7474:7474 + - 7687:7687 + container_name: neo4j_docker network_mode: host + hostname: localhost + restart: always + volumes: + - ~/Desktop/neo4j:/data/db + healthcheck: + test: "exit 0" + + mysql: + image: mysql:5.7 ports: - - 9091:9091 - expose: - - 9091 + - 3306:3306 + container_name: mysql + environment: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: springbootdb + MYSQL_PASSWORD: root + MYSQL_USER: root + network_mode: "host" + hostname: localhost + restart: always + healthcheck: + test: "exit 0" - configserver: - image: config-servcie:latest - build: config-server/ - restart: always - network_mode: host - ports: - - 8888:8888 - expose: - - 8888 + kafka: + image: landoop/fast-data-dev:latest + ports: + - 2181:2181 + - 3030:3030 + - 9092:9092 + - 8081:8081 + - 8082:8082 + - 8083:8083 + container_name: kafka_docker + network_mode: host + hostname: localhost + restart: always + volumes: + - ~/Desktop/DockerKafka:/data/kafka + healthcheck: + test: "exit 0" + expose: + - 9092 + - 2181 + - 3030 + - 8081 + - 8082 + - 8083 + registration-service: + image: registration-service + build: ./registration-service/ + container_name: reg_docker + restart: always + network_mode: host + hostname: localhost + depends_on: + mongo: + condition: service_healthy + apigateway: + condition: service_healthy + eurekaserver: + condition: service_healthy + configserver: + condition: service_healthy + kafka: + condition: service_healthy + ports: + - 8020:8020 + healthcheck: + test: "exit 0" + authentication-service: + image: authentication-service + build: ./authentication-service/ + container_name: auth_docker + restart: always + network_mode: host + hostname: localhost + depends_on: + mysql: + condition: service_healthy + apigateway: + condition: service_healthy + eurekaserver: + condition: service_healthy + configserver: + condition: service_healthy + kafka: + condition: service_healthy + ports: + - 8021:8021 + healthcheck: + test: "exit 0" + question-service: + image: question-service + build: ./question-service/ + container_name: qp_docker + restart: always + network_mode: host + hostname: localhost + depends_on: + mongo: + condition: service_healthy + apigateway: + condition: service_healthy + eurekaserver: + condition: service_healthy + configserver: + condition: service_healthy + kafka: + condition: service_healthy + ports: + - 8022:8022 + healthcheck: + test: "exit 0" + recommendation-service: + image: recommendation-service + build: ./recommendation-service/ + container_name: rs_docker + restart: always + network_mode: host + hostname: localhost + depends_on: + neo4j: + condition: service_healthy + apigateway: + condition: service_healthy + eurekaserver: + condition: service_healthy + configserver: + condition: service_healthy + kafka: + condition: service_healthy + ports: + - 8023:8023 + healthcheck: + test: "exit 0" diff --git a/eureka-server/Dockerfile b/eureka-server/Dockerfile index c2da8798..8b5265c5 100644 --- a/eureka-server/Dockerfile +++ b/eureka-server/Dockerfile @@ -1,6 +1,6 @@ -FROM openjdk:11 +FROM openjdk:10 ADD ./target/eureka-server-0.0.1-SNAPSHOT.jar /event/src/eureka-server-0.0.1-SNAPSHOT.jar -EXPOSE 9091 +EXPOSE 8093 WORKDIR event/src ENTRYPOINT ["java","-jar","eureka-server-0.0.1-SNAPSHOT.jar"] \ No newline at end of file diff --git a/eureka-server/pom.xml b/eureka-server/pom.xml index 3fd7cea9..1c00d0db 100644 --- a/eureka-server/pom.xml +++ b/eureka-server/pom.xml @@ -24,7 +24,7 @@ UTF-8 UTF-8 - 1.8 + 10 ${java.version} ${java.version} Finchley.SR1 diff --git a/eureka-server/src/main/resources/application.properties b/eureka-server/src/main/resources/application.properties index 8031a442..c57b56b6 100644 --- a/eureka-server/src/main/resources/application.properties +++ b/eureka-server/src/main/resources/application.properties @@ -1,6 +1,6 @@ spring.application.name=EurekaServer -eureka.client.serviceUrl.defaultZone:http://localhost:9091/eureka/ -server.port=9091 +eureka.client.serviceUrl.defaultZone:http://localhost:8093/eureka/ +server.port=8093 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false diff --git a/eventbrite-service/Dockerfile b/eventbrite-service/Dockerfile index 9ead3adb..c26f014d 100644 --- a/eventbrite-service/Dockerfile +++ b/eventbrite-service/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM openjdk:10 ADD ./target/nextevent-0.0.1-SNAPSHOT.jar /event/src/nextevent-0.0.1-SNAPSHOT.jar EXPOSE 8082 diff --git a/eventbrite-service/pom.xml b/eventbrite-service/pom.xml index 2e6ab28a..a5ead100 100644 --- a/eventbrite-service/pom.xml +++ b/eventbrite-service/pom.xml @@ -17,7 +17,7 @@ UTF-8 UTF-8 - 1.8 + 10 ${java.version} ${java.version} @@ -42,6 +42,7 @@ org.springframework.cloud spring-cloud-starter-netflix-zuul + 2.0.2.RELEASE io.springfox @@ -52,10 +53,12 @@ org.springframework.cloud spring-cloud-starter + 2.0.2.RELEASE org.springframework.cloud spring-cloud-starter-netflix-eureka-client + 2.0.2.RELEASE org.springframework.boot diff --git a/eventbrite-service/src/main/resources/application.properties b/eventbrite-service/src/main/resources/application.properties index 68822ed7..7b3b614e 100644 --- a/eventbrite-service/src/main/resources/application.properties +++ b/eventbrite-service/src/main/resources/application.properties @@ -22,6 +22,9 @@ spring.application.name=event-service eureka.client.serviceUrl.defaultZone=http://localhost:9091/eureka/ eureka.client.register-with-eureka=true eureka.client.fetch-registry=true +spring.datasource.tomcat.testWhileIdle = true +spring.datasource.tomcat.timeBetweenEvictionRunsMillis = 60000 +spring.datasource.tomcat.validationQuery = SELECT 1 diff --git a/pom.xml b/pom.xml index 42b8770a..9abbc193 100644 --- a/pom.xml +++ b/pom.xml @@ -20,16 +20,21 @@ 2.3.0 UTF-8 UTF-8 - 11 + 10 ${java.version} ${java.version} + eureka-server zuul-gatewayservice config-server eventbrite-service + recommendation-service + registration-service + question-service + authentication-service @@ -63,21 +68,22 @@ commons-lang3 3.8.1 + - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - + + + + + + + + + + + - + org.apache.maven.plugins @@ -233,4 +239,4 @@ - \ No newline at end of file + diff --git a/question-service/.gitignore b/question-service/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/question-service/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/question-service/Dockerfile b/question-service/Dockerfile new file mode 100644 index 00000000..05bf0e96 --- /dev/null +++ b/question-service/Dockerfile @@ -0,0 +1,6 @@ +FROM openjdk:10 + +ADD ./target/question-service-0.0.1-SNAPSHOT.jar question-service.jar +EXPOSE 8022 + +ENTRYPOINT ["java","-jar","question-service.jar"] diff --git a/question-service/pom.xml b/question-service/pom.xml new file mode 100644 index 00000000..2598989f --- /dev/null +++ b/question-service/pom.xml @@ -0,0 +1,120 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.1.RELEASE + + + com.stackroute + question-service + 0.0.1-SNAPSHOT + question-service + Demo project for Spring Boot + + + 10 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.data + spring-data-mongodb + 2.1.3.RELEASE + + + + org.mongodb + mongo-java-driver + 3.9.1 + + + + + org.projectlombok + lombok + 1.18.2 + provided + + + + junit + junit + 4.12 + compile + + + + org.assertj + assertj-core + 3.8.0 + compile + + + + org.mockito + mockito-core + 2.11.0 + compile + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.hibernate + hibernate-core + 5.4.0.Final + + + + + + + + + org.springframework.kafka + spring-kafka + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.0.2.RELEASE + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/question-service/src/main/java/com/stackroute/QuestionsRest.java b/question-service/src/main/java/com/stackroute/QuestionsRest.java new file mode 100644 index 00000000..005c7db0 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/QuestionsRest.java @@ -0,0 +1,16 @@ +package com.stackroute; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.stereotype.Component; + +@EnableEurekaClient +//@Component +@SpringBootApplication +public class QuestionsRest { + + public static void main(String[] args) { + SpringApplication.run(QuestionsRest.class, args); + } +} \ No newline at end of file diff --git a/question-service/src/main/java/com/stackroute/config/ApplicationListner.java b/question-service/src/main/java/com/stackroute/config/ApplicationListner.java new file mode 100644 index 00000000..6d73f45e --- /dev/null +++ b/question-service/src/main/java/com/stackroute/config/ApplicationListner.java @@ -0,0 +1,43 @@ +package com.stackroute.config; + + +import com.stackroute.domain.Counters; +import com.stackroute.domain.Questions; +import com.stackroute.repository.CounterRepository; +import com.stackroute.repository.QuestionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationListner implements ApplicationListener { + + // @Autowired + private QuestionRepository questionRepository; + private CounterRepository counterRepository; + + + @Autowired + public ApplicationListner(QuestionRepository questionRepository, CounterRepository counterRepository) { + this.questionRepository = questionRepository; + this.counterRepository = counterRepository; + } + + + @Override + public void onApplicationEvent(final ApplicationReadyEvent applicationReadyEvent) { + seedData(); + } + + public void seedData(){ + //counterRepository.delete(new Counters("questionId",3)); + counterRepository.deleteAll(); + counterRepository.save(new Counters("questionId",3)); + questionRepository.deleteAll(); + // questionRepository.delete(new Questions(0,"Awesome" ,"Question1","Beginner","java","url")); + // questionRepository.delete(new Questions(1,"Awesome1" ,"Question2","Intermediate","java","url")); + questionRepository.save(new Questions(0,"Awesome" ,"Question1","input format","output Format","Beginner","java","url")); + questionRepository.save(new Questions(1,"Awesome1" ,"Question2","input format","output Format","Intermediate","java","url")); + } +} diff --git a/question-service/src/main/java/com/stackroute/config/KafkaConfiguration.java b/question-service/src/main/java/com/stackroute/config/KafkaConfiguration.java new file mode 100644 index 00000000..a76ee88c --- /dev/null +++ b/question-service/src/main/java/com/stackroute/config/KafkaConfiguration.java @@ -0,0 +1,36 @@ +package com.stackroute.config; + + +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ser.std.StringSerializer; +import com.stackroute.domain.Questions; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; + + +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class KafkaConfiguration { + + @Bean + public ProducerFactory producerFactory(){ + Map config = new HashMap<>(); + + config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092"); + config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); + config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + + return new DefaultKafkaProducerFactory<>(config); + } + + @Bean + public KafkaTemplate kafkaTemplate(){ + return new KafkaTemplate<>(producerFactory()); + } +} \ No newline at end of file diff --git a/question-service/src/main/java/com/stackroute/controller/QuestionController.java b/question-service/src/main/java/com/stackroute/controller/QuestionController.java new file mode 100644 index 00000000..5c4af2b1 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/controller/QuestionController.java @@ -0,0 +1,45 @@ +package com.stackroute.controller; + +import com.stackroute.domain.Questions; +import com.stackroute.exceptions.QuestionAlreadyExistsException; +import com.stackroute.service.QuestionService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.web.bind.annotation.*; + + + +//Main controller +@CrossOrigin("*") +@RestController +@RequestMapping("api/v1/") +public class QuestionController { + + private QuestionService questionService; + + @Autowired + public QuestionController(QuestionService questionService) { + this.questionService = questionService; + } + + @Autowired + KafkaTemplate kafkaTemplate; + + @PostMapping("question") + public ResponseEntity saveQuestions(@RequestBody Questions question) { + System.out.println(question); + try { + Questions question1 = questionService.saveQuestion(question); + kafkaTemplate.send("QuestionMessage",question1); + return new ResponseEntity(question1, HttpStatus.OK); + } + catch(QuestionAlreadyExistsException ex){ + return new ResponseEntity<>(ex.getMessage(), HttpStatus.CONFLICT); + } + catch (Exception exception) { + return new ResponseEntity<>(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } +} diff --git a/question-service/src/main/java/com/stackroute/domain/Counters.java b/question-service/src/main/java/com/stackroute/domain/Counters.java new file mode 100644 index 00000000..c265ee09 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/domain/Counters.java @@ -0,0 +1,20 @@ +package com.stackroute.domain; + +import lombok.Builder; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +@Document(collection="counters") +@Builder +public class Counters { + + @Id + public String _id; + public int seq; + + public Counters(String _id, int seq) { + this._id = _id; + this.seq = seq; + } +} diff --git a/question-service/src/main/java/com/stackroute/domain/Questions.java b/question-service/src/main/java/com/stackroute/domain/Questions.java new file mode 100644 index 00000000..429a13b0 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/domain/Questions.java @@ -0,0 +1,49 @@ +package com.stackroute.domain; + +import lombok.*; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; +import org.springframework.data.annotation.Id; + +@Data +@Document(collection="questions") +//@AllArgsConstructor +@NoArgsConstructor +@Builder +public class Questions{ + @Id + public int questionId; + @Field + private String questionTitle; + @Field + private String questionDescription; + @Field + private String inputFormat; + @Field + private String outputFormat; + @Field + private String difficulty; + @Field + private String tags; + @Field + private String gitUrl; + + public Questions(int questionId, String questionTitle, String questionDescription, String inputFormat, String outputFormat, String difficulty, String tags, String gitUrl) { + this.questionId = questionId; + this.questionTitle = questionTitle; + this.questionDescription = questionDescription; + this.inputFormat = inputFormat; + this.outputFormat = outputFormat; + this.difficulty = difficulty; + this.tags = tags; + this.gitUrl = gitUrl; + } + + public int getQuestionId() { + return questionId; + } + + public void setQuestionId(int questionId) { + this.questionId = questionId; + } +} diff --git a/question-service/src/main/java/com/stackroute/exceptions/QuestionAlreadyExistsException.java b/question-service/src/main/java/com/stackroute/exceptions/QuestionAlreadyExistsException.java new file mode 100644 index 00000000..59bc1dc4 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/exceptions/QuestionAlreadyExistsException.java @@ -0,0 +1,8 @@ +package com.stackroute.exceptions; + +public class QuestionAlreadyExistsException extends Exception { + + public QuestionAlreadyExistsException(String message) { + super(message); + } +} diff --git a/question-service/src/main/java/com/stackroute/repository/CounterRepository.java b/question-service/src/main/java/com/stackroute/repository/CounterRepository.java new file mode 100644 index 00000000..e095257d --- /dev/null +++ b/question-service/src/main/java/com/stackroute/repository/CounterRepository.java @@ -0,0 +1,7 @@ +package com.stackroute.repository; + +import com.stackroute.domain.Counters; +import org.springframework.data.mongodb.repository.MongoRepository; + +public interface CounterRepository extends MongoRepository { +} diff --git a/question-service/src/main/java/com/stackroute/repository/QuestionRepository.java b/question-service/src/main/java/com/stackroute/repository/QuestionRepository.java new file mode 100644 index 00000000..eb9f67cd --- /dev/null +++ b/question-service/src/main/java/com/stackroute/repository/QuestionRepository.java @@ -0,0 +1,9 @@ +package com.stackroute.repository; + +import com.stackroute.domain.Questions; +import org.springframework.data.mongodb.repository.MongoRepository; + + +public interface QuestionRepository extends MongoRepository { + +} diff --git a/question-service/src/main/java/com/stackroute/service/QuestionService.java b/question-service/src/main/java/com/stackroute/service/QuestionService.java new file mode 100644 index 00000000..6142552a --- /dev/null +++ b/question-service/src/main/java/com/stackroute/service/QuestionService.java @@ -0,0 +1,10 @@ +package com.stackroute.service; + +import com.stackroute.domain.Questions; +import com.stackroute.exceptions.QuestionAlreadyExistsException; + +public interface QuestionService { + + Questions saveQuestion(Questions question) throws QuestionAlreadyExistsException; + +} diff --git a/question-service/src/main/java/com/stackroute/service/QuestionServiceImpl.java b/question-service/src/main/java/com/stackroute/service/QuestionServiceImpl.java new file mode 100644 index 00000000..e7026563 --- /dev/null +++ b/question-service/src/main/java/com/stackroute/service/QuestionServiceImpl.java @@ -0,0 +1,42 @@ +package com.stackroute.service; + +import com.mongodb.*; +import com.mongodb.client.MongoCollection; +import com.stackroute.domain.Questions; +import com.stackroute.exceptions.QuestionAlreadyExistsException; +import com.stackroute.repository.QuestionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.mongodb.BasicDBObject; +import com.mongodb.BasicDBObjectBuilder; + +@Service +public class QuestionServiceImpl implements QuestionService { + + @Autowired + private QuestionRepository questionRepository; + + @Override + public Questions saveQuestion(Questions question) throws QuestionAlreadyExistsException{ + BasicDBObject document = new BasicDBObject(); + document.put("_id", getNextSequence("questionId")); + question.setQuestionId((int)document.get("_id")+1); + + if(questionRepository.existsById((int)(question.getQuestionId()))) { + throw new QuestionAlreadyExistsException("This Question already exists"); + } + Questions question1 = questionRepository.save(question); + return question1; + } + + public static Object getNextSequence(String name){ + MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); + DB db = mongoClient.getDB("mashup"); + DBCollection collection = db.getCollection("counters"); + BasicDBObject find = new BasicDBObject(); + BasicDBObject update = new BasicDBObject(); + update.put("$inc", new BasicDBObject("seq", 1)); + DBObject obj = collection.findAndModify(find, update); + return obj.get("seq"); + } +} diff --git a/question-service/src/main/resources/application.properties b/question-service/src/main/resources/application.properties new file mode 100644 index 00000000..601ceff4 --- /dev/null +++ b/question-service/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8022 +spring.data.mongodb.host=localhost +spring.data.mongodb.port=27017 +#spring.data.mongodb.database=register +spring.data.mongodb.uri=mongodb://localhost/mashup + diff --git a/question-service/src/main/resources/application.yml b/question-service/src/main/resources/application.yml new file mode 100644 index 00000000..3db4f81d --- /dev/null +++ b/question-service/src/main/resources/application.yml @@ -0,0 +1,34 @@ +#server: +# port: 8022 +#spring: +# data: +# mongodb: +# database: mashup +# host: localhost +# port: 27017 +# application: +# name: question-service #current service name to be used by the eureka server + +eureka: #tells about the Eureka server details and its refresh time + instance: + leaseRenewalIntervalInSeconds: 1 + leaseExpirationDurationInSeconds: 2 + client: + serviceUrl: + defaultZone: http://localhost:8093/eureka/ + healthcheck: + enabled: true + lease: + duration: 5 + +spring: + application: + name: question-service #current service name to be used by the eureka server + +management: + security: + enabled: false #disable the spring security on the management endpoints like /env, /refresh etc. + +logging: + level: + com.stackroute.question-service: DEBUG diff --git a/question-service/src/test/java/com/stackroute/controller/QuestionControllerTest.java b/question-service/src/test/java/com/stackroute/controller/QuestionControllerTest.java new file mode 100644 index 00000000..d923b68b --- /dev/null +++ b/question-service/src/test/java/com/stackroute/controller/QuestionControllerTest.java @@ -0,0 +1,73 @@ +//package com.stackroute.controller; +// +//import com.fasterxml.jackson.core.JsonProcessingException; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.stackroute.domain.Questions; +//import com.stackroute.service.QuestionServiceImpl; +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.Mockito; +//import org.mockito.MockitoAnnotations; +//import org.mockito.junit.MockitoJUnitRunner; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +//import org.springframework.http.MediaType; +//import org.springframework.test.web.servlet.MockMvc; +//import org.springframework.test.web.servlet.setup.MockMvcBuilders; +// +//import static org.junit.Assert.*; +//import static org.mockito.Mockito.*; +//import static org.mockito.internal.verification.VerificationModeFactory.times; +//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +// +//@RunWith(MockitoJUnitRunner.class) +////@RunWith(SpringRunner.class) +//@WebMvcTest(QuestionController.class) +//public class QuestionControllerTest { +// +// private Questions question; +// +// @Autowired +// private MockMvc mockMvc; +// +// @Mock +// QuestionServiceImpl questionService; +// +// @InjectMocks +// QuestionController questionController; +// +// @Before +// public void setUp()throws Exception{ +// mockMvc = MockMvcBuilders.standaloneSetup(questionController).build(); +// question=new Questions(11,"Awesome" ,"Question1","input Format","output Format","Beginner","java","url"); +// MockitoAnnotations.initMocks(this); +// } +// +// @Test +// public void testSave() throws Exception { +// when( questionService.saveQuestion(question)).thenReturn(question); +// mockMvc.perform(post("/api/v1/question").contentType(MediaType.APPLICATION_JSON) +// .accept(MediaType.APPLICATION_JSON) +// .content(jsonToString(question))) +// .andExpect(status().isOk()); +// verify(questionService,times(1)).saveQuestion(Mockito.any(Questions.class)); +// verifyNoMoreInteractions(questionService); +// } +// +// private static String jsonToString(final Object obj) throws JsonProcessingException { +// String result; +// try { +// final ObjectMapper mapper = new ObjectMapper(); +// final String jsonContent = mapper.writeValueAsString(obj); +// result = jsonContent; +// } catch (JsonProcessingException e) { +// result = "Json processing error"; +// } +// return result; +// } +//} diff --git a/question-service/src/test/java/com/stackroute/service/QuestionServiceImplTest.java b/question-service/src/test/java/com/stackroute/service/QuestionServiceImplTest.java new file mode 100644 index 00000000..2471c57f --- /dev/null +++ b/question-service/src/test/java/com/stackroute/service/QuestionServiceImplTest.java @@ -0,0 +1,52 @@ +//package com.stackroute.service; +//import com.stackroute.domain.Questions; +//import com.stackroute.exceptions.QuestionAlreadyExistsException; +//import com.stackroute.repository.QuestionRepository; +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.MockitoAnnotations; +//import org.mockito.junit.MockitoJUnitRunner; +//import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +// +//import java.util.Optional; +// +//import static org.junit.Assert.*; +//import static org.mockito.Mockito.verify; +//import static org.mockito.Mockito.when; +//import static org.mockito.internal.verification.VerificationModeFactory.times; +// +//@RunWith(MockitoJUnitRunner.class) +//@WebMvcTest(QuestionService.class) +//public class QuestionServiceImplTest { +// +// private Questions question; +// +// @Mock +// private QuestionRepository questionRepository; +// +// +// @InjectMocks +// private QuestionServiceImpl musicServiceImpl; +// +// Optional options; +// +// @Before +// public void setUp() { +// +// MockitoAnnotations.initMocks(this); +// question = new Questions(0,"Awesome" ,"Question1","input Format","output Format","Beginner","java","url"); +// options = Optional.of(question); +// } +// +// @Test +// public void testSaveMusicSuccess() throws QuestionAlreadyExistsException { +// +// when(questionRepository.save(question)).thenReturn(question); +// Questions questions= musicServiceImpl.saveQuestion(question); +// assertEquals(questions,question); +// verify(questionRepository, times(1)).save(question); +// } +//} diff --git a/recommendation-service/.gitignore b/recommendation-service/.gitignore new file mode 100644 index 00000000..c456c4a3 --- /dev/null +++ b/recommendation-service/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ diff --git a/recommendation-service/Dockerfile b/recommendation-service/Dockerfile new file mode 100644 index 00000000..49b6a624 --- /dev/null +++ b/recommendation-service/Dockerfile @@ -0,0 +1,6 @@ +FROM openjdk:10 + +ADD ./target/recommendation-service-0.0.1-SNAPSHOT.jar recommendation-service.jar +EXPOSE 8023 + +ENTRYPOINT ["java","-jar","recommendation-service.jar"] diff --git a/recommendation-service/pom.xml b/recommendation-service/pom.xml new file mode 100644 index 00000000..71e83d05 --- /dev/null +++ b/recommendation-service/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.stackroute + recommendation-service + 0.0.1-SNAPSHOT + recommendation-service + Demo project for Spring Boot + + + 10 + + + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-neo4j + + + org.springframework.boot + spring-boot-starter-data-rest + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + + + + + + + + + org.neo4j + neo4j-ogm-bolt-driver + 2.0.1 + + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.0.2.RELEASE + + + org.springframework.cloud + spring-cloud-starter-config + 1.1.2.RELEASE + + + org.springframework.boot + spring-boot + 2.1.2.RELEASE + + + org.springframework.kafka + spring-kafka + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/RecommendApplication.java b/recommendation-service/src/main/java/com/stackroute/recommend/RecommendApplication.java new file mode 100644 index 00000000..a686fbc8 --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/RecommendApplication.java @@ -0,0 +1,17 @@ +package com.stackroute.recommend; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.stereotype.Component; + +@Component +@EnableEurekaClient +@SpringBootApplication +public class RecommendApplication { + + public static void main(String[] args) { + SpringApplication.run(RecommendApplication.class, args); + } + +} + diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/config/KafkaConfiguration.java b/recommendation-service/src/main/java/com/stackroute/recommend/config/KafkaConfiguration.java new file mode 100644 index 00000000..5fcbfc3c --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/config/KafkaConfiguration.java @@ -0,0 +1,36 @@ +package com.stackroute.recommend.config; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; + +import java.util.HashMap; +import java.util.Map; + +@EnableKafka +@Configuration +public class KafkaConfiguration { + @Bean + public ConsumerFactory consumerFactory(){ + Map config = new HashMap<>(); + + config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092"); + config.put(ConsumerConfig.GROUP_ID_CONFIG,"group_id"); + config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); + config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class); + + return new DefaultKafkaConsumerFactory<>(config); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(){ + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} \ No newline at end of file diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/model/Question.java b/recommendation-service/src/main/java/com/stackroute/recommend/model/Question.java new file mode 100644 index 00000000..9c900faa --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/model/Question.java @@ -0,0 +1,39 @@ +package com.stackroute.recommend.model; +import org.neo4j.ogm.annotation.Id; +import org.neo4j.ogm.annotation.NodeEntity; + +@NodeEntity +public class Question { + + @Id + private Long id; + private String title; + private String difficulty; + + public Question() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDifficulty() { + return difficulty; + } + + public void setDifficulty(String difficulty) { + this.difficulty = difficulty; + } +} diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/model/User.java b/recommendation-service/src/main/java/com/stackroute/recommend/model/User.java new file mode 100644 index 00000000..c2be55ff --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/model/User.java @@ -0,0 +1,37 @@ +package com.stackroute.recommend.model; + +import org.neo4j.ogm.annotation.Id; +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +import java.util.List; + +@NodeEntity +public class User { + + @Id + private Long id; + private String name; + + @Relationship(type = "ATTEMPTED", direction = Relationship.INCOMING) + List questions; + + public User() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/repository/UserRepository.java b/recommendation-service/src/main/java/com/stackroute/recommend/repository/UserRepository.java new file mode 100644 index 00000000..bcf7fc07 --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.stackroute.recommend.repository; + +import com.stackroute.recommend.model.User; +import org.springframework.data.neo4j.annotation.Query; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import java.util.Collection; + + +public interface UserRepository extends Neo4jRepository { + + @Query("MATCH (u:User)<-[a:ATTEMPTED]-(q:Question) RETURN u,a,q") + Collection getAllUsers(); +} diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/resource/UserResource.java b/recommendation-service/src/main/java/com/stackroute/recommend/resource/UserResource.java new file mode 100644 index 00000000..ef0997ec --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/resource/UserResource.java @@ -0,0 +1,24 @@ +package com.stackroute.recommend.resource; + +import com.stackroute.recommend.model.User; +import com.stackroute.recommend.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collection; + +@RestController +@RequestMapping("/rest/neo4j/user") +public class UserResource { + + + @Autowired + UserService userService; + + @GetMapping + public Collection getAlloo(){ + return userService.getAll(); + } +} diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/service/KafkaListenerService.java b/recommendation-service/src/main/java/com/stackroute/recommend/service/KafkaListenerService.java new file mode 100644 index 00000000..63d57e7a --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/service/KafkaListenerService.java @@ -0,0 +1,13 @@ +package com.stackroute.recommend.service; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Service; + +@Service +public class KafkaListenerService { + + @KafkaListener(topics = "QuestionMessage", groupId = "group_id") + public void consume(String message){ + System.out.println("Consumed msg : " + message); + } +} \ No newline at end of file diff --git a/recommendation-service/src/main/java/com/stackroute/recommend/service/UserService.java b/recommendation-service/src/main/java/com/stackroute/recommend/service/UserService.java new file mode 100644 index 00000000..1971d83c --- /dev/null +++ b/recommendation-service/src/main/java/com/stackroute/recommend/service/UserService.java @@ -0,0 +1,19 @@ +package com.stackroute.recommend.service; + +import com.stackroute.recommend.model.User; +import com.stackroute.recommend.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +@Service +public class UserService { + + @Autowired + UserRepository userRepository; + + public Collection getAll() { + return userRepository.getAllUsers(); + } +} diff --git a/recommendation-service/src/main/resources/application.properties b/recommendation-service/src/main/resources/application.properties new file mode 100644 index 00000000..fcc62563 --- /dev/null +++ b/recommendation-service/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.port=8023 + +spring.data.neo4j.uri=bolt://localhost +spring.data.neo4j.username=neo4j +spring.data.neo4j.password=mash123 \ No newline at end of file diff --git a/recommendation-service/src/main/resources/application.yml b/recommendation-service/src/main/resources/application.yml new file mode 100644 index 00000000..0a82dfbb --- /dev/null +++ b/recommendation-service/src/main/resources/application.yml @@ -0,0 +1,26 @@ +##server: +## port: 8098 #default port where the service will be started +## +eureka: #tells about the Eureka server details and its refresh time + instance: + leaseRenewalIntervalInSeconds: 1 + leaseExpirationDurationInSeconds: 2 + client: + serviceUrl: + defaultZone: http://localhost:8093/eureka/ + healthcheck: + enabled: true + lease: + duration: 5 + +spring: + application: + name: recommendation-service #current service name to be used by the eureka server + +management: + security: + enabled: false #disable the spring security on the management endpoints like /env, /refresh etc. + +logging: + level: + com.stckroute.recommendation-service: DEBUG \ No newline at end of file diff --git a/registration-service/.gitignore b/registration-service/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/registration-service/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/registration-service/Dockerfile b/registration-service/Dockerfile new file mode 100644 index 00000000..c83380c8 --- /dev/null +++ b/registration-service/Dockerfile @@ -0,0 +1,6 @@ +FROM openjdk:10 + +ADD ./target/registration-service-0.0.1-SNAPSHOT.jar registration-service.jar +EXPOSE 8020 + +ENTRYPOINT ["java","-jar","registration-service.jar"] diff --git a/registration-service/pom.xml b/registration-service/pom.xml new file mode 100644 index 00000000..5018ab37 --- /dev/null +++ b/registration-service/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.stackroute + registration-service + 0.0.1-SNAPSHOT + registration-service + Registration Service + + + 10 + Greenwich.RC2 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-data-rest + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 2.1.1.RELEASE + + + org.projectlombok + lombok + + + io.springfox + springfox-swagger2 + 2.6.1 + compile + + + + org.springframework.boot + spring-boot-devtools + 2.1.2.RELEASE + + + org.springframework.kafka + spring-kafka + + + org.springframework.kafka + spring-kafka-test + test + + + + io.springfox + springfox-swagger-ui + 2.6.1 + compile + + + org.mongodb + mongo-java-driver + 3.9.1 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-starter-config + 1.1.2.RELEASE + + + org.springframework.boot + spring-boot + 2.1.2.RELEASE + + + org.springframework.boot + spring-boot + 2.1.2.RELEASE + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/registration-service/src/main/java/com/stackroute/UserserviceApplication.java b/registration-service/src/main/java/com/stackroute/UserserviceApplication.java new file mode 100644 index 00000000..683996f1 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/UserserviceApplication.java @@ -0,0 +1,16 @@ +package com.stackroute; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@EnableEurekaClient +@SpringBootApplication +public class UserserviceApplication { + + public static void main(String[] args) { + SpringApplication.run(UserserviceApplication.class, args); + } + +} + diff --git a/registration-service/src/main/java/com/stackroute/config/Bcrypt.java b/registration-service/src/main/java/com/stackroute/config/Bcrypt.java new file mode 100644 index 00000000..a60df6d9 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/config/Bcrypt.java @@ -0,0 +1,16 @@ +package com.stackroute.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class Bcrypt { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/registration-service/src/main/java/com/stackroute/config/DatabaseLoader.java b/registration-service/src/main/java/com/stackroute/config/DatabaseLoader.java new file mode 100644 index 00000000..6a417074 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/config/DatabaseLoader.java @@ -0,0 +1,90 @@ +package com.stackroute.config; + +import com.stackroute.domain.User; +import com.stackroute.repository.UserRepository; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +@Configuration +@PropertySource("classpath:seed.properties") +@Component +public class DatabaseLoader implements ApplicationListener { + +// @Value("${userId1}") +// private int userId1; +// @Value("${userName1}") +// private String userName1; +// @Value("${password1}") +// private String password1; +// @Value("${age1}") +// private int age1; +// @Value("${gender1}") + + @Value("${gender2}") + private String gender1; + @Value("${username2}") + private String username1; + @Value("${password2}") + private String password1; + @Value("${age2}") + private int age1; + @Value("${currentCompany2}") + private String currentCompany1; + @Value("${course2}") + private String course1; + @Value("${firstName2}") + private String firstName1; + @Value("${lastName2}") + private String lastName1; + @Value("${discipline2}") + private String discipline1; + @Value("${emailId2}") + private String emailId1; + @Value("${collegeName2}") + private String collegeName1; + +// @Value("${userId2}") +// private int userId2; +// @Value("${userName2}") +// private String userName2; +// @Value("${password2}") +// private String password2; +// @Value("${age2}") +// private int age2; +// @Value("${gender2}") +// private String gender2; + + + @Autowired + private UserRepository userRepository; + + //Method to be over-ridden for applicationListener + @Override + public void onApplicationEvent(final ApplicationReadyEvent applicationReadyEvent) { + seedData(); + } + + private void seedData() { + User user2 = new User(); + user2.setAge(age1); + user2.setPassword(password1); + user2.setCourse(course1); + user2.setDiscipline(discipline1); + user2.setCompany(currentCompany1); + user2.setEmailId(emailId1); + user2.setFirstName(firstName1); + user2.setLastName(lastName1); + user2.setGender(gender1); + user2.setUsername(username1); + user2.setCollege(collegeName1); + userRepository.save(user2); + + } + +} + + diff --git a/registration-service/src/main/java/com/stackroute/config/KafkaConfiguration.java b/registration-service/src/main/java/com/stackroute/config/KafkaConfiguration.java new file mode 100644 index 00000000..3b8bf60f --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/config/KafkaConfiguration.java @@ -0,0 +1,34 @@ +package com.stackroute.config; + +import com.stackroute.domain.User; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; + +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class KafkaConfiguration { + + @Bean + public ProducerFactory producerFactory(){ + Map config = new HashMap<>(); + + config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092"); + config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); + config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + + return new DefaultKafkaProducerFactory<>(config); + } + + @Bean + public KafkaTemplate kafkaTemplate(){ + return new KafkaTemplate<>(producerFactory()); + } +} \ No newline at end of file diff --git a/registration-service/src/main/java/com/stackroute/config/SwaggerDataReader.java b/registration-service/src/main/java/com/stackroute/config/SwaggerDataReader.java new file mode 100644 index 00000000..af4b219f --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/config/SwaggerDataReader.java @@ -0,0 +1,23 @@ +package com.stackroute.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class SwaggerDataReader { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select().apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } + +} diff --git a/registration-service/src/main/java/com/stackroute/controller/UserController.java b/registration-service/src/main/java/com/stackroute/controller/UserController.java new file mode 100644 index 00000000..3fe6930e --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/controller/UserController.java @@ -0,0 +1,97 @@ +package com.stackroute.controller; + +import com.stackroute.domain.User; +import com.stackroute.exception.UserAlreadyExistsException; +import com.stackroute.exception.UserNotFoundException; +import com.stackroute.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +@CrossOrigin("*") +@RestController +@RequestMapping("/api/v1/") +public class UserController { + + private UserService userService; + @Autowired + KafkaTemplate kafkaTemplate; + + @Autowired + public UserController(UserService userService) { + this.userService = userService; + } +//Request mapping for posting user details + @PostMapping("register") + public ResponseEntity saveUser(@RequestBody User user) { + ResponseEntity responseEntity; + try { + userService.saveUser(user); + responseEntity = new ResponseEntity("Successfully created", HttpStatus.CREATED); + kafkaTemplate.send("AuthMessage",user); + } + catch (UserAlreadyExistsException ex){ + responseEntity = new ResponseEntity(ex.getMessage(),HttpStatus.BAD_REQUEST); + ex.printStackTrace(); + } + return responseEntity; + } +//Request mapping for getting user details + @GetMapping("users") + public ResponseEntity> listOfUsers() { + List allUsers = userService.getAllUsers(); + return new ResponseEntity>(allUsers, HttpStatus.OK); + } +//Request mapping for deleting user details + @DeleteMapping("users/{id}") + public ResponseEntity deleteUser(@PathVariable("id") String userId){ + ResponseEntity responseEntity; + try { + User user = userService.deleteUser(userId); + responseEntity = new ResponseEntity(user, HttpStatus.GONE); + } + catch (UserNotFoundException userNotFoundException){ + responseEntity = new ResponseEntity<>(userNotFoundException.getMessage(), HttpStatus.NOT_FOUND); + + } + return responseEntity; + } + //Request mapping for updating user details + @PutMapping("users/{id}") + public ResponseEntity updateUser(@PathVariable("id") String userId, @RequestBody User user) { + ResponseEntity responseEntity; + System.out.println("I am in controller"); + try{ + User user1 = userService.updateUser(userId,user); + responseEntity = new ResponseEntity(user1, HttpStatus.OK); + } + catch (UserNotFoundException ex){ + responseEntity = new ResponseEntity(ex.getMessage(),HttpStatus.NOT_FOUND); + ex.printStackTrace(); + } + return responseEntity; + + } + +// @GetMapping("user/authenticate/{id}/{password}") +// public ResponseEntity authenticateUser(@PathVariable("id") String id, @PathVariable("password") String password){ +// ResponseEntity responseEntity; +// try{ +// responseEntity = new ResponseEntity(userService.findByPassword(id,password),HttpStatus.ACCEPTED); +// }catch (UserNotFoundException e){ +// responseEntity=new ResponseEntity(e.getMessage(),HttpStatus.NOT_FOUND); +// } +// return responseEntity; +// } + @GetMapping("/publish/{email}") + public String post(@PathVariable("email") String email){ + User user = userService.getUserByEmailid(email); + kafkaTemplate.send("AuthMessage",user); + return "Published Successfully"; + } + +} + diff --git a/registration-service/src/main/java/com/stackroute/domain/User.java b/registration-service/src/main/java/com/stackroute/domain/User.java new file mode 100644 index 00000000..f7038402 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/domain/User.java @@ -0,0 +1,134 @@ +package com.stackroute.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "User") +//@Data +//@NoArgsConstructor +//@AllArgsConstructor +public class User { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getCourse() { + return course; + } + + public void setCourse(String course) { + this.course = course; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getInterest() { + return interest; + } + + public void setInterest(String interest) { + this.interest = interest; + } + + public String getDiscipline() { + return discipline; + } + + public void setDiscipline(String discipline) { + this.discipline = discipline; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(String emailId) { + this.emailId = emailId; + } + + public String getCollege() { + return college; + } + + public void setCollege(String college) { + this.college = college; + } + + private int age; + private String gender; + private String company; + private String course; + private String firstName; + private String lastName; + private String interest; + private String discipline; + @Id + private String id; + private String emailId; + private String college; +// private String token; +} diff --git a/registration-service/src/main/java/com/stackroute/exception/UserAlreadyExistsException.java b/registration-service/src/main/java/com/stackroute/exception/UserAlreadyExistsException.java new file mode 100644 index 00000000..0cf0757c --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/exception/UserAlreadyExistsException.java @@ -0,0 +1,10 @@ +package com.stackroute.exception; + +public class UserAlreadyExistsException extends Exception{ + private String message; + public UserAlreadyExistsException(){} + public UserAlreadyExistsException(String message){ + super(message); + this.message = message; + } +} diff --git a/registration-service/src/main/java/com/stackroute/exception/UserNotFoundException.java b/registration-service/src/main/java/com/stackroute/exception/UserNotFoundException.java new file mode 100644 index 00000000..f5e3b316 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/exception/UserNotFoundException.java @@ -0,0 +1,11 @@ +package com.stackroute.exception; + +public class UserNotFoundException extends Exception{ + + private String message; + public UserNotFoundException(){} + public UserNotFoundException(String message){ + super(message); + this.message = message; + } +} diff --git a/registration-service/src/main/java/com/stackroute/repository/UserRepository.java b/registration-service/src/main/java/com/stackroute/repository/UserRepository.java new file mode 100644 index 00000000..ee12f36c --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.stackroute.repository; + +import com.stackroute.domain.User; + +import com.stackroute.exception.UserNotFoundException; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + + +@Repository +public interface UserRepository extends MongoRepository { + + boolean existsByEmailId(String emailId); + User findByEmailId(String emailId); +// boolean existsById(String id); + +} diff --git a/registration-service/src/main/java/com/stackroute/service/UserService.java b/registration-service/src/main/java/com/stackroute/service/UserService.java new file mode 100644 index 00000000..a1017ce6 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/service/UserService.java @@ -0,0 +1,18 @@ +package com.stackroute.service; + +import com.stackroute.domain.User; +import com.stackroute.exception.UserAlreadyExistsException; +import com.stackroute.exception.UserNotFoundException; + +import java.util.List; + +public interface UserService { + + public User saveUser (User user) throws UserAlreadyExistsException; + public List getAllUsers(); + public User deleteUser(String userId) throws UserNotFoundException; + public User updateUser(String userId, User user) throws UserNotFoundException; + public User getUserByEmailid(String emailId); +// public String findByPassword(String id, String password) throws UserNotFoundException; + } + diff --git a/registration-service/src/main/java/com/stackroute/service/UserServiceImpl.java b/registration-service/src/main/java/com/stackroute/service/UserServiceImpl.java new file mode 100644 index 00000000..b33a2921 --- /dev/null +++ b/registration-service/src/main/java/com/stackroute/service/UserServiceImpl.java @@ -0,0 +1,92 @@ +package com.stackroute.service; + +import com.stackroute.domain.User; +import com.stackroute.exception.UserAlreadyExistsException; +import com.stackroute.exception.UserNotFoundException; +import com.stackroute.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.security.crypto.bcrypt.BCrypt; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import java.util.List; +import java.util.Optional; + +@Primary +@Service +public class UserServiceImpl implements UserService { + + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + public UserServiceImpl(UserRepository userRepository) { + this.userRepository = userRepository; + } + + public User saveUser(User user) throws UserAlreadyExistsException { + if (userRepository.existsByEmailId(user.getEmailId())) { + throw new UserAlreadyExistsException("User already exists"); + } + //Encrypting password + user.setPassword(passwordEncoder.encode(user.getPassword())); + User user1 = userRepository.save(user); + if (user1 == null) { + throw new UserAlreadyExistsException("User already exists"); + } + return user1; + } + + public List getAllUsers() { + List userList = (List) userRepository.findAll(); + return userList; + } + + public User deleteUser(String userId) throws UserNotFoundException { + User user1 = userRepository.findById(userId).get(); + if (userRepository.existsById(userId)) + userRepository.deleteById(userId); + else { + throw new UserNotFoundException("User not found"); + } + return user1; + + } + + public User updateUser(String userId, User user) throws UserNotFoundException { + if (userRepository.existsById(userId)) { + User user1 = userRepository.save(user); + return user1; + } else + throw new UserNotFoundException("User not found"); + + } + + @Override + public User getUserByEmailid(String emailId) { + User user = userRepository.findByEmailId(emailId); + return user; + } +} + + //Method to authenticate password for time-being +// @Override +// public String findByPassword(String id,String password) throws UserNotFoundException { +// //check if user exists +// if (userRepository.existsById(id)){ +// //extract user from db with encrypted password +// User dbUser=userRepository.findById(id); +// //returns true if entered plain and stored encrypted password matches +// if(BCrypt.checkpw(password,dbUser.getPassword())){ +// return "Password matches!"; +// }else{ +// return "Password Incorrect!"; +// } +// }else{ +// throw new UserNotFoundException("User not found"); +// } +// } +// +//} diff --git a/registration-service/src/main/resources/application.properties b/registration-service/src/main/resources/application.properties new file mode 100644 index 00000000..0a5dc494 --- /dev/null +++ b/registration-service/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8020 +spring.data.mongodb.host=localhost +spring.data.mongodb.port=27017 +#spring.data.mongodb.database=register +spring.data.mongodb.uri=mongodb://localhost/registration + diff --git a/registration-service/src/main/resources/application.yml b/registration-service/src/main/resources/application.yml new file mode 100644 index 00000000..ee4c615a --- /dev/null +++ b/registration-service/src/main/resources/application.yml @@ -0,0 +1,26 @@ +#server: +# port: 8098 #default port where the service will be started + +eureka: #tells about the Eureka server details and its refresh time + instance: + leaseRenewalIntervalInSeconds: 1 + leaseExpirationDurationInSeconds: 2 + client: + serviceUrl: + defaultZone: http://localhost:8093/eureka/ + healthcheck: + enabled: true + lease: + duration: 5 + +spring: + application: + name: registration-service #current service name to be used by the eureka server + +management: + security: + enabled: false #disable the spring security on the management endpoints like /env, /refresh etc. + +logging: + level: + com.stackroute.registration-service: DEBUG \ No newline at end of file diff --git a/registration-service/src/main/resources/seed.properties b/registration-service/src/main/resources/seed.properties new file mode 100644 index 00000000..40a62021 --- /dev/null +++ b/registration-service/src/main/resources/seed.properties @@ -0,0 +1,11 @@ + username2=mahesh + password2=mahe123 + age2=22 + gender2=male + currentCompany2=Boeing + course2=CSE +firstName2=mahi + lastName2=eswar + discipline2=BE +emailId2=example@gmail.com +collegeName2=BIT \ No newline at end of file diff --git a/registration-service/src/test/java/com/stackroute/Controller/RegistrationControllerTest.java b/registration-service/src/test/java/com/stackroute/Controller/RegistrationControllerTest.java new file mode 100644 index 00000000..de9981c9 --- /dev/null +++ b/registration-service/src/test/java/com/stackroute/Controller/RegistrationControllerTest.java @@ -0,0 +1,228 @@ +package com.stackroute.Controller; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.stackroute.config.KafkaConfiguration; +import com.stackroute.controller.UserController; +import com.stackroute.domain.User; +import com.stackroute.exception.UserAlreadyExistsException; +import com.stackroute.exception.UserNotFoundException; +import com.stackroute.service.UserService; +import org.hamcrest.Matcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.OngoingStubbing; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.concurrent.ListenableFuture; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.core.Is.is; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import static org.hamcrest.Matchers.hasSize; + +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.mockito.Mockito.*; +import static org.mockito.internal.verification.VerificationModeFactory.times; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +public class RegistrationControllerTest { + + @InjectMocks + private UserController userController; + + @Mock + private UserService service; + + @Mock + private KafkaConfiguration configuration; + + //@Mock + private KafkaTemplate template; + + +// username2=mahesh +// password2=mahe123 +// age2=22 +// gender2=male +// currentCompany2=Boeing +// course2=CSE +// firstName2=mahi +// lastName2=eswar +// discipline2=BE +// emailId2=example@gmail.com +// collegeName2=BIT + +// private String username; +// private String password; +// private int age; +// private String gender; +// private String company; +// private String course; +// private String firstName; +// private String lastName; +// private String interest; +// private String discipline; +// @Id +// private String id; +// private String emailId; +// private String college; + + User user; + List userList; + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); +// template = Mockito.mock(KafkaTemplate.class); +// Mockito.when(configuration.getKafkaTemplateObject()).thenReturn(template); + //KafkaTemplate template = Mockito.mock(KafkaTemplate.class); + //ject mock = when(template.send(Mockito.any(), Mockito.any())).getMock(); + + user = new User(); + user.setUsername("mahe12"); + user.setPassword("blowin in the wind"); + user.setGender("Nice song"); + user.setLastName("mahe12"); + user.setFirstName("blowin in the wind"); + user.setEmailId("Nice song"); + user.setCourse("mahe12"); + user.setDiscipline("blowin in the wind"); + user.setCollege("Nice song"); + user.setAge(25); + user.setInterest("blowin in the wind"); + user.setCompany("Nice song"); + + userList = new ArrayList(); + userList.add(user); + + } + +// @Test +// public void saveUser() throws UserAlreadyExistsException { +// User user1 = Mockito.mock(User.class); +// //OngoingStubbing>> mockFuture = Mockito.mock(OngoingStubbing>); +//// Mockito.when(template.send("AuthMessage", user1)).thenReturn(Mockito.any()); +// Mockito.when(service.saveUser(user)).thenReturn(user1); +// ResponseEntity result = userController.saveUser(this.user); +// verify(service).saveUser(Mockito.any()); +// Assert.assertEquals(HttpStatus.CREATED,result.getStatusCode()); +// } + + /* public static String asJsonString(final Object object) { + try { + return new ObjectMapper().writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + + + }*/ + + @Test + public void listallUsers_success(){ + Mockito.when(service.getAllUsers()).thenReturn(userList); + ResponseEntity result = userController.listOfUsers(); + verify(service).getAllUsers(); + Assert.assertEquals(HttpStatus.OK,result.getStatusCode()); + } + + @Test + public void deleteUser_sucess() throws UserNotFoundException { + Mockito.when(service.deleteUser("User")).thenReturn(user); + ResponseEntity result = userController.deleteUser("User"); + verify(service).deleteUser("User"); + Assert.assertEquals(HttpStatus.GONE,result.getStatusCode()); + } + + @Test + public void UpdateUser_success() throws UserNotFoundException { + Mockito.when(service.updateUser("User",user)).thenReturn(user); + ResponseEntity result = userController.updateUser("User",user); + verify(service).updateUser("User",user); + Assert.assertEquals(HttpStatus.OK,result.getStatusCode()); + } + + /*@Test + public void post_success(){ + User user1 = Mockito.mock(User.class); + Mockito.when(template.send("AuthMessage", user1)).thenReturn(Mockito.any()); + Mockito.when(service.getUserByEmailid("User")).thenReturn(user1); + String result = userController.post("User"); + verify(service).getUserByEmailid("User"); + Assert.assertEquals("Published Successfully", result); + }*/ + + +// @Test +// public void test_get_all_success() throws Exception { +// List muzixs = Arrays.asList( +// new User("mahe12","blowin in the wind",25,"Nice song","Nice song","mahe12","nice"), +// new User(2, "californication","wow")); +// when(userService.getAllUsers()).thenReturn(muzixs); +// mockMvc.perform(get("/api/v2/tracks")) +// .andExpect(status().isOk()) +// .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) +// .andExpect(jsonPath("$[0].id", is(1))) +// .andExpect(jsonPath("$[0].name", is("dont let me down"))) +// .andExpect(jsonPath("$[0].comments", is("nice"))) +// .andExpect(jsonPath("$[1].id", is(2))) +// .andExpect(jsonPath("$[1].name", is("californication"))) +// .andExpect(jsonPath("$[1].comments", is("wow"))); +// verify(userService, times(1)).getAllUsers(); +// verifyNoMoreInteractions(userService); +// } + + /*@Test + public void test_delete_user_success() throws Exception { + User user = new User(); + user.setUsername("mahe12"); + user.setPassword("blowin in the wind"); + user.setGender("Nice song"); + user.setLastName("mahe12"); + user.setFirstName("blowin in the wind"); + user.setEmailId("Nice song"); + user.setCourse("mahe12"); + user.setDiscipline("blowin in the wind"); + user.setCollege("Nice song"); + user.setAge(25); + user.setInterest("blowin in the wind"); + user.setCompany("Nice song"); + + doNothing().when(userService).deleteUser(user.getEmailId()); + + mockMvc.perform( + delete("/api/v1/users/{id}", user.getEmailId())) + .andExpect(status().isOk()); + + + verify(userService, times(1)).deleteUser(user.getEmailId()); + verifyNoMoreInteractions(userService); + } +*/ +} diff --git a/registration-service/src/test/java/com/stackroute/Repository/RegistrationRepositoryTest.java b/registration-service/src/test/java/com/stackroute/Repository/RegistrationRepositoryTest.java new file mode 100644 index 00000000..4a89b053 --- /dev/null +++ b/registration-service/src/test/java/com/stackroute/Repository/RegistrationRepositoryTest.java @@ -0,0 +1,50 @@ +//package com.stackroute.Repository; +// +//import com.stackroute.domain.User; +//import com.stackroute.repository.UserRepository; +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +//import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +//import org.springframework.test.context.junit4.SpringRunner; +// +//import java.util.Optional; +// +//import static org.assertj.core.api.Assertions.assertThat; +// +//@RunWith(SpringRunner.class) +//@DataJpaTest +//@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +//public class RegistrationRepositoryTest { +// +// @Autowired +// private UserRepository userRepository; +// +// private User user; +// +// @Before +// public void setUp() throws Exception { +// +// user = new User(); +// } +// +// @Test +// public void testRegisterUserSuccess() { +// +// userRepository.save(user); +// Optional object = userRepository.findById(user.getEmailId()); +// assertThat(object.equals(user)); +// } +// +//// @Test +//// public void testFindByNameSuccess() { +//// userRepository.findByName("john"); +//// Optional object=muzixRepository.findById(muzix.getId()); +//// assertThat(object.equals(muzix)); +//// } +// +// +// +//} diff --git a/registration-service/src/test/java/com/stackroute/Service/RegistrationServiceTest.java b/registration-service/src/test/java/com/stackroute/Service/RegistrationServiceTest.java new file mode 100644 index 00000000..d276fd49 --- /dev/null +++ b/registration-service/src/test/java/com/stackroute/Service/RegistrationServiceTest.java @@ -0,0 +1,134 @@ +//package com.stackroute.Service; +// +// +//import com.stackroute.domain.User; +//import com.stackroute.exception.UserAlreadyExistsException; +//import com.stackroute.exception.UserNotFoundException; +//import com.stackroute.repository.UserRepository; +//import com.stackroute.service.UserServiceImpl; +//import org.junit.Before; +//import org.junit.Test; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.Mockito; +//import org.mockito.MockitoAnnotations; +// +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.List; +//import java.util.NoSuchElementException; +// +//import static org.junit.Assert.*; +//import static org.mockito.Mockito.*; +// +//public class RegistrationServiceTest { +// +// @Mock +// UserRepository userRepository; +// +// @InjectMocks +// UserServiceImpl serviceImpl; +// +// private User user; +// List userList; +// +// @Before +// public void setUp(){ +// MockitoAnnotations.initMocks(this); +// user=new User(); +// user.setUsername("mahe12"); +// user.setPassword("blowin in the wind"); +// user.setGender("Nice song"); +// user.setLastName("mahe12"); +// user.setFirstName("blowin in the wind"); +// user.setEmailId("Nice song"); +// user.setCourse("mahe12"); +// user.setDiscipline("blowin in the wind"); +// user.setCollege("Nice song"); +// user.setAge(25); +// user.setInterest("blowin in the wind"); +// user.setCompany("Nice song"); +// } +// +// @Test +// public void testSaveByName() throws UserAlreadyExistsException { +// +// Mockito.when(userRepository.save(user)).thenReturn(user); +// User expectedList=serviceImpl.saveUser(user); +// assertEquals(user,expectedList); +// } +// +// @Test +// public void getAllTrackTest() +// { +// List list = new ArrayList(); +// User empOne = new User(); +// empOne.setUsername("mahe12"); +// empOne.setPassword("blowin in the wind"); +// empOne.setGender("Nice song"); +// empOne.setLastName("mahe12"); +// empOne.setFirstName("blowin in the wind"); +// empOne.setEmailId("Nice song"); +// empOne.setCourse("mahe12"); +// empOne.setDiscipline("blowin in the wind"); +// empOne.setCollege("Nice song"); +// empOne.setAge(25); +// empOne.setInterest("blowin in the wind"); +// empOne.setCompany("Nice song"); +// User empTwo = new User(); +// empTwo.setUsername("mahe123"); +// empTwo.setPassword("blowin in the wind12"); +// empTwo.setGender("Nice song"); +// empTwo.setLastName("mahe12"); +// empTwo.setFirstName("blowin in the wind"); +// empTwo.setEmailId("Nice song1"); +// empTwo.setCourse("mahe12"); +// empTwo.setDiscipline("blowin in the wind"); +// empTwo.setCollege("Nice song"); +// empTwo.setAge(26); +// empTwo.setInterest("blowin in the wind1"); +// empTwo.setCompany("Nice song"); +// User empThree = new User(); +// user.setUsername("mahe1234"); +// user.setPassword("blowin in the wind3"); +// user.setGender("Nice song3"); +// user.setLastName("mahe12"); +// user.setFirstName("blowin in the wind"); +// user.setEmailId("Nice song8"); +// user.setCourse("mahe12"); +// user.setDiscipline("blowin in the wind"); +// user.setCollege("Nice song"); +// user.setAge(25); +// user.setInterest("blowin in the wind9"); +// user.setCompany("Nice song"); +// +// list.add(empOne); +// list.add(empTwo); +// list.add(empThree); +// +// when(userRepository.findAll()).thenReturn(list); +// +// //test +// List userList = serviceImpl.getAllUsers(); +// +// // assertEquals(3, trackList.size()); +// assertEquals(list,userList); +// } +// +// +//// @Test +//// public void testRemoveTrack() { +//// //Muzix muzix = new Muzix(1, "hey jude","yeah"); +//// +//// List userli = Arrays.asList( +//// new User(1, "dont let me down","nice")); +//// when(userRepository.deleteById(8);).thenReturn(userli); +//// +////// doNothing().when(muzixRepository.findById(anyInt())); +////// doNothing().when(muzixRepository.deleteById(anyInt())); +//// +//// verify(userRepository, times(0)).deleteById(user.getEmailId()); +//// +//// } +// +//} diff --git a/registration-service/src/test/java/com/stackroute/UserserviceApplicationTests.java b/registration-service/src/test/java/com/stackroute/UserserviceApplicationTests.java new file mode 100644 index 00000000..46993ace --- /dev/null +++ b/registration-service/src/test/java/com/stackroute/UserserviceApplicationTests.java @@ -0,0 +1,90 @@ +package com.stackroute; + +import com.stackroute.domain.User; +import com.stackroute.exception.UserAlreadyExistsException; +import com.stackroute.repository.UserRepository; +import com.stackroute.service.UserServiceImpl; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + + +public class UserserviceApplicationTests { + + @InjectMocks + private UserServiceImpl service; + + @Mock + private UserRepository repos; + + @Mock + private PasswordEncoder encoder; + + + User user; + List userList; + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + + user = new User(); + user.setUsername("mahe12"); + user.setPassword("blowin in the wind"); + user.setGender("Nice song"); + user.setLastName("mahe12"); + user.setFirstName("blowin in the wind"); + user.setEmailId("Nice song"); + user.setCourse("mahe12"); + user.setDiscipline("blowin in the wind"); + user.setCollege("Nice song"); + user.setAge(25); + user.setInterest("blowin in the wind"); + user.setCompany("Nice song"); + + userList = new ArrayList(); + userList.add(user); + + } + +// @Test +// public void saveuser_success() throws UserAlreadyExistsException { +// Mockito.when(repos.existsByEmailId(user.getEmailId())).thenReturn(false); +// //Mockito.when(encoder.encode("blowin in the wind")).thenReturn("AXY"); +// Mockito.when(repos.save(user)).thenReturn(user); +// User result = service.saveUser(user); +// Mockito.verify(repos).existsByEmailId(user.getEmailId()); +// Mockito.verify(repos).save(user); +// //Mockito.verify(encoder).encode("blowin in the wind"); +// Assert.assertEquals(user.getAge(),result.getAge()); +// } + + @Test + public void getAllUsers_success(){ + Mockito.when(repos.findAll()).thenReturn(userList); + List result = service.getAllUsers(); + Mockito.verify(repos).findAll(); + Assert.assertEquals(1,result.size()); + } + +// @Test +// public void deleteUser_success(){ +// Mockito.when(repos.findAllById("User")).thenReturn(Optional.of(user)); +// +// } + +} + diff --git a/zuul-gatewayservice/Dockerfile b/zuul-gatewayservice/Dockerfile index 402ae5a3..43f8ccb9 100644 --- a/zuul-gatewayservice/Dockerfile +++ b/zuul-gatewayservice/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM openjdk:10 ADD ./target/zuul-gatewayservice-0.0.1-SNAPSHOT.jar /event/src/zuul-gatewayservice-0.0.1-SNAPSHOT.jar EXPOSE 8092 diff --git a/zuul-gatewayservice/pom.xml b/zuul-gatewayservice/pom.xml index 0f7a49fa..1c407648 100644 --- a/zuul-gatewayservice/pom.xml +++ b/zuul-gatewayservice/pom.xml @@ -21,7 +21,7 @@ UTF-8 UTF-8 - 1.8 + 10 ${java.version} ${java.version} Greenwich.RELEASE diff --git a/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/SimpleCORSFilter.java b/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/SimpleCORSFilter.java new file mode 100644 index 00000000..dbbb4280 --- /dev/null +++ b/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/SimpleCORSFilter.java @@ -0,0 +1,41 @@ +//package com.stackroute.zuulgatewayservice; +// +//import org.springframework.stereotype.Component; +// +//import javax.servlet.*; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.IOException; +// +//@Component +//public class SimpleCORSFilter implements Filter { +// +// +// public SimpleCORSFilter() { +// System.out.println("SimpleCORSFilter init"); +// } +// +// @Override +// public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { +// +// HttpServletRequest request = (HttpServletRequest) req; +// HttpServletResponse response = (HttpServletResponse) res; +// +// response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); +// response.setHeader("Access-Control-Allow-Credentials", "true"); +// response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); +// response.setHeader("Access-Control-Max-Age", "3600"); +// response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me"); +// +// chain.doFilter(req, res); +// } +// +// @Override +// public void init(FilterConfig filterConfig) { +// } +// +// @Override +// public void destroy() { +// } +// +//} \ No newline at end of file diff --git a/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/ZuulGatewayserviceApplication.java b/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/ZuulGatewayserviceApplication.java index 42e1ca6a..a35ae966 100644 --- a/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/ZuulGatewayserviceApplication.java +++ b/zuul-gatewayservice/src/main/java/com/stackroute/zuulgatewayservice/ZuulGatewayserviceApplication.java @@ -5,8 +5,9 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; +import org.springframework.web.bind.annotation.CrossOrigin; - +@CrossOrigin("http://localhost:4200") @EnableDiscoveryClient @EnableZuulProxy @SpringBootApplication diff --git a/zuul-gatewayservice/src/main/resources/application.properties b/zuul-gatewayservice/src/main/resources/application.properties index 367ac77e..288c447b 100644 --- a/zuul-gatewayservice/src/main/resources/application.properties +++ b/zuul-gatewayservice/src/main/resources/application.properties @@ -1,9 +1,13 @@ server.port=8092 +zuul.routes.registration-service.url=http://localhost:8020 +zuul.routes.authentication-service.url=http://localhost:8021 +zuul.routes.question-service.url=http://localhost:8022 +zuul.routes.recommendation-service.url=http://localhost:8023 zuul.routes.event-service.url=http://localhost:8082 #ribbon.eureka.enabled=false spring.application.name=api-gateway -eureka.client.serviceUrl.defaultZone=http://localhost:9091/eureka/ +eureka.client.serviceUrl.defaultZone=http://localhost:8093/eureka/ eureka.client.register-with-eureka=true eureka.client.fetch-registry=true