Coder Social home page Coder Social logo

plopezgit / sprint5_t1_springboot_dice_roller_microservices Goto Github PK

View Code? Open in Web Editor NEW
5.0 1.0 0.0 27.82 MB

Dice Roller microservice proposal.

Java 100.00%
auth config-server eureka-server gateway-services jwt microservice rest-template zipkin mongodb mysql

sprint5_t1_springboot_dice_roller_microservices's Introduction

Dice roller microservices

Current trace

04/02/2024 current trace

01/02/2024 current trace

29/01/2024 current trace

26/01/2024 current trace

23/01/2024 current trace

Requirement

Level 1
  • The dice game is played with two dice. If the result of the sum of the two dice is 7, the game is won, otherwise it is lost. A player can see a list of all the rolls he/she has made and the success percentage.

  • In order to play the game and make a roll, a user must register with a non-repeating name. Upon creation, it is assigned a unique numeric identifier and a registration date. If the user so wishes, you can not add any name, and it will be called "ANONYMOUS". There can be more than one "ANONYMOUS" player.

  • Each player can see a list of all the rolls they have made, with the value of each die and whether they won the game. In addition, you can know your success percentage for all the rolls you have made.

  • You cannot delete a specific game, but you can delete the entire list of rolls for a player.

  • The software must be able to list all the players in the system, the success percentage of each player and the average success percentage of all the players in the system.

  • The software must respect the main design patterns.

  • You must take into account the following construction details:

URLs
  • URLs: • POST: /players: Create a player.

  • PUT /players: modify the player's name.

  • POST /players/{id}/games/ : A specific player rolls the dice.

  • GET /players/: returns the list of all the players in the system with their average success rate.

  • GET /players/{id}/games: returns the list of games played by a player. Ok

  • DELETE /players/{id}/games: deletes the player's rolls.

  • GET /players/ranking: returns the average ranking of all the players in the system. That is, the average percentage of successes.

  • GET /players/ranking/loser: returns the player with the worst hit percentage.

  • GET /players/ranking/winner: Returns the player with the worst hit percentage.

  • Phase 1 • Persistence: Use MySQL as the database.

  • Phase 2 • Change everything you need and use MongodbDBDB to persist data.

  • Phase 3 • Add security: Include JWT authentication on all accesses to microservice URLs.

Level 2
  • Add unit, component and integration tests to the project with jUnit, AssertJ or Hamcrest libraries.
  • Add Mocks to project testing (Mockito)
  • and Contract Tests (https://docs.pact.io/)
Level 3
  • Design and modify the project by diversifying persistence to use two database schemas at the same time, MySQL and Mongodb.

Feedback and results

Feedback soon...

sprint5_t1_springboot_dice_roller_microservices's People

Contributors

plopezgit avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

sprint5_t1_springboot_dice_roller_microservices's Issues

[Checklist] Security to access API JWT & Spring Security

  • Add dependencies: stater-security (spring), and Json Web Token

  • Security package

  • -- Clase WebSecurityConfig or similar(@ ) // https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter/

  • --- SecurityFilterChain method return (@ Bean) ==== Secuencia de seguridad

  • --- UserDetailsService method return (@ Bean) ==== Cargar de usuario en memoria (InMemoryUserDetailsManage)

  • --- PasswordEncoder method returning a type of encoder ex. new BCryptPasswordEncoder (@ Bean)

  • Auth db persistance

  • -- Clase TokenHelper or similar

  • Clase AuthCredentials

  • Clase UserDetailsServiceImpl implements UserDetailsService

  • Clase UserDetailImpl implements UserDetails

  • Clase JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter

  • Clase JWTAuthorizationFilter

implement @ CircuitBreaker and fallbackMethod call for createGame (rest template method)

Player controller method:

public ResponseEntity<?> createGame(@PathVariable("playerId") int playerId, @requestbody GameDTO gameDTO)

new lines, something like:

@CircuitBreaker(name="gamesCB", fallbackMethod ="fallbackCreateGame")
   public ResponseEntity<?> fallbackCreateGame(@PathVariable("playerId") int playerId, @RequestBody GameDTO gameDTO, RuntimeException e) {
        return new ResponseEntity<>("The player: " + playerId + " can not play now. Try later", HttpStatus.OK);
    }

uses javax.validation.constraints.NotNull for auth-service entity persistence

  • Dependencies check
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>8.0.1.Final</version>
</dependency>



    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
  • Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class Configuration {
    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }
}
  • uses not null on entities
  • use valid on AuthUserController

dice-n1exe1-3 (microservice version)

Process checklist:

  • project structure (basic) h2 persistence and secure, based on microservice system, config server, eureka, gateway for Game, Player and Auth microservices

  • auth roles implementation (24/01/2024)

  • traces (no priority)

  • cover requirement on the model and controller (27/01/2024)

  • --> business logic (dice roller quick analysis.txt in comments)

  • ---> model requirements (Rest template)

  • ----> New branch "model-requirements (merged with rest-template)"

  • ----> Player entity/DTO requires: registrationDate; games; addGames method, successRate method;

  • ------> creates this bug (pending to debug) @plopezgit #14

  • ----> Game entity/DTO requires: result is byte (1-0); rollDice method; result method;

  • ----> New branch "rest-template"

  • ----> Feign maven dependency on player-service

  • ----> creates GameClient interface on player-service model

  • ----> GameClient injection on PlayerService and its methods

  • ----> PlayerController methods

  • h2>mysql>mongo (29/01/2024) (finished 1 day before so an additional branch to review pattern were created for 29/01/2024)

  • ----> New branch "pattern-review"

  • ------> Games (29/01/2024)

  • ------> Player (29/01/2024)

  • ----> New branch "response-review"

  • ---> enhances responses and exception #48 #49 #50 #51 (30/01/2024)

  • -----> in addition : #58 #65 #66 (Done: 30/01/2024-31/01/2024)

  • DTO arguments validations #75 #73 among others (31/01/2024)

  • ----> New branch "tests"

  • basic repository test #85 (01/02/2024)

  • service test (02/02/2024) #88

  • controller test (03/02/2024) #96

  • adds games and auth service unit test #113 #114 #115 #116 #117 (date: to be defined)

  • ----> New branch "doc-openapi"

  • api documentation swagger #63 #101 #106 #107 #105 #104 (Done: 04/01/2024)

  • Bugs and improvements:
    #125
    #126
    #127
    #128

Extras:

  • android client test with (client android integrates to GET /games without auth filters)https://square.github.io/retrofit/ (09/02/2024)
  • traces Zipkin/Micrometer server alternative (24/01/2024)

Demo:

  • delivery demo brief: #118

Swagger configuration (openapi)

		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
			<version>2.2.0</version>
		</dependency>

changes path from /players/games/{id} to /players/{id}/games/ -- auth-path pattern alternative is required

Current validation logic:

  • a change on this logic is required? No need
private List<HttpRequestDTO> paths;


    public boolean isAdminPath(HttpRequestDTO httpRequestDTO) {
        return paths.stream().anyMatch(path ->
                Pattern.matches(path.getUri(), httpRequestDTO.getUri())
                && path.getMethod().equals(httpRequestDTO.getMethod()));
    }

Fed by:

  • change "/players/game/id" to "/players/id/game" or similar
  • change "/players/games/id" to "/players/id/games" or similar
  • regex adjustments
eureka:
  admin-paths:
    paths:
      - uri: "/players"
        method: "POST"
      - uri: "/players/game/{1}[1-9]+[0-9]*"
        method: "POST"
      - uri: "/players/update/{1}[1-9]+[0-9]*"
        method: "PUT"
      - uri: "/players/update/{1}[1-9]+[0-9]*"
        method: "POST"
      - uri: "/players/update/rate/{1}[1-9]+[0-9]*"
        method: "POST"
      - uri: "/players/games/{1}[1-9]+[0-9]*"
        method: "DELETE"

Through this Class:

  • stay as it is
public class HttpRequestDTO {
    private String uri;
    private String method;
}
  • Finally, adjust Service (rest template calls) and Controller method

How I can do to modify this to support the following path? Lets check

throwing exception with an empty message

given a game is creating
when player id does not exist
then an empty message exception is called

{
"responseCode": 404,
"message": null,
"messageDescription": "uri=/players/2/game",
"responseTimeStamp": "2024-01-31T12:29:40.619+00:00"
}

include a message a check if any other has the same issue

Player Anonymous records bug

given the third inserto on player db of a "" (Anonymous) player
the response is 500 and the error on console shows:
org.hibernate.NonUniqueResultException: Query did not return a unique result: 2 results were returned

Screen Shot 2024-01-25 at 7 19 41 PM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.