Advertisement
valchak

Edit Game

Nov 19th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1.  @Override
  2.     public String editGame(String[] tokens) {
  3.         StringBuilder sb = new StringBuilder();
  4.         String id = tokens[1];
  5.  
  6.         Game game = this.gameRepository.findById(Long.parseLong(id)).orElse(null);
  7.         if (game == null) {
  8.             return "Game not found!";
  9.         }
  10.  
  11.         GameEditDto gameToEdit = modelMapper.map(game, GameEditDto.class);
  12.         gameToEdit.setId(Long.parseLong(id));
  13.  
  14.         for (int i = 2; i < tokens.length; i++) {
  15.             String[] propertiesElements = tokens[i].split("=");
  16.             String propertyName = propertiesElements[0];
  17.             String propertyKey = propertiesElements[1];
  18.             switch (propertyName) {
  19.                 case "title":
  20.                     return "Title cannot be edited!";
  21.                 case "price":
  22.                     gameToEdit.setPrice(new BigDecimal(propertyKey));
  23.                     break;
  24.                 case "size":
  25.                     gameToEdit.setSize(new BigDecimal(propertyKey));
  26.                     break;
  27.                 case "trailer":
  28.                     gameToEdit.setTrailer(propertyKey);
  29.                     break;
  30.                 case "thumbnailUrl":
  31.                     gameToEdit.setThumbnailUrl(propertyKey);
  32.                     break;
  33.                 case "description":
  34.                     gameToEdit.setDescription(propertyKey);
  35.                     break;
  36.             }
  37.         }
  38.  
  39.         Set<ConstraintViolation<GameEditDto>> violations = this.validator.validate(gameToEdit);
  40.  
  41.         if (violations.size() > 0) {
  42.             for (ConstraintViolation<GameEditDto> violation : violations) {
  43.                 sb.append(violation.getMessage()).append(System.lineSeparator());
  44.  
  45.             }
  46.             return sb.toString().trim();
  47.         } else {
  48.             Game editedGame = this.modelMapper.map(gameToEdit, Game.class);
  49.             if (editedGame != null) {
  50.                 Game savedGame = this.gameRepository.saveAndFlush(editedGame);
  51.                 if (savedGame != null) {
  52.                     return String.format("Edited %s", savedGame.getTitle());
  53.                 }
  54.             }
  55.         }
  56.  
  57.         return null;
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement