Skip to content

Commit

Permalink
Basic campaign validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kkobarii committed Apr 29, 2024
1 parent af26dfd commit 48aceae
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
package cz.trailsthroughshadows.api.table.campaign;

import cz.trailsthroughshadows.algorithm.validation.ValidationService;
import cz.trailsthroughshadows.api.rest.exception.RestException;
import cz.trailsthroughshadows.api.rest.model.pagination.Pagination;
import cz.trailsthroughshadows.api.rest.model.pagination.RestPaginatedResult;
import cz.trailsthroughshadows.api.rest.model.response.MessageResponse;
import cz.trailsthroughshadows.api.table.campaign.model.Campaign;
import cz.trailsthroughshadows.api.table.campaign.model.CampaignDTO;
import cz.trailsthroughshadows.api.table.campaign.model.CampaignLocation;
import cz.trailsthroughshadows.api.table.campaign.model.*;
import cz.trailsthroughshadows.api.util.reflect.Filtering;
import cz.trailsthroughshadows.api.util.reflect.Initialization;
import cz.trailsthroughshadows.api.util.reflect.Sorting;
import jakarta.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/campaigns")
public class CampaignController {
private static final Logger log = LoggerFactory.getLogger(CampaignController.class);
@Autowired
private CampaignRepo campaignRepo;

@Autowired
private ValidationService validation;

@GetMapping("")
public ResponseEntity<RestPaginatedResult<CampaignDTO>> findAllEntities(
@RequestParam(defaultValue = "0") int page,
Expand Down Expand Up @@ -99,16 +109,79 @@ public CampaignLocation findById2(
return location;
}

@PutMapping("/{id}")
@Transactional(rollbackOn = Exception.class)
@CacheEvict(value = "campaign", allEntries = true)
public ResponseEntity<MessageResponse> update(@PathVariable int id, @RequestBody CampaignDTO campaign) {
CampaignDTO campaignToUpdate = campaignRepo
.findById(id)
.orElseThrow(() -> RestException.of(HttpStatus.NOT_FOUND, "Campaign with id '{}' not found!", id));

validation.validate(campaign);

campaignToUpdate.setTitle(campaign.getTitle());
campaignToUpdate.setDescription(campaign.getDescription());
campaignToUpdate.setAchievements(campaign.getAchievements());
campaignToUpdate.setLocations(campaign.getLocations());

return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaign updated successfully!"), HttpStatus.OK);
}

@DeleteMapping("/{id}")
@Transactional(rollbackOn = Exception.class)
@CacheEvict(value = "campaign", allEntries = true)
public ResponseEntity<MessageResponse> delete(@PathVariable int id) {
CampaignDTO campaign = campaignRepo
.findById(id)
.orElseThrow(() -> RestException.of(HttpStatus.NOT_FOUND, "Campaign with id '{}' not found!", id));

campaignRepo.delete(campaign);
return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaign deleted successfully!"), HttpStatus.OK);
}


@PostMapping("")
//@CacheEvict(value = "campaign", allEntries = true)
public ResponseEntity<MessageResponse> create(@RequestBody List<CampaignDTO> campaigns) {
log.info("Creating campaigns: {}", campaigns);

//TODO validation of the input

// validate all and set ids to null
campaigns.forEach(validation::validate);
campaigns.forEach(e -> e.setId(null));

// save relations
Map<String, List<CampaignAchievements>> achievementsRelations = new HashMap<>();
Map<String, List<CampaignLocation>> locationsRelations = new HashMap<>();

// remove relations
campaigns.forEach(campaign -> {
achievementsRelations.put(campaign.getTitle(), new ArrayList<>(campaign.getAchievements()));
campaign.setAchievements(null);

locationsRelations.put(campaign.getTitle(), new ArrayList<>(campaign.getLocations()));
campaign.setLocations(null);
});

// save campaigns
campaignRepo.saveAll(campaigns);

// post load relations
campaigns.forEach(campaign -> {
List<CampaignAchievements> achievements = achievementsRelations.get(campaign.getTitle());
List<CampaignLocation> locations = locationsRelations.get(campaign.getTitle());

campaign.setAchievements(achievements);
campaign.getAchievements().forEach(e -> e.setKey(new CampaignAchievements.CampaignAchievementsId(campaign.getId(), e.getAchievement().getId())));

campaign.setLocations(locations);
campaign.getLocations().forEach(e -> e.setIdCampaign(campaign.getId()));

campaignRepo.save(campaign);
});

String ids = campaigns.stream().map(CampaignDTO::getId).map(String::valueOf).reduce((a, b) -> a + ", " + b).orElse("");

return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaigns created successfully!"), HttpStatus.OK);
return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaigns created: " + ids), HttpStatus.OK);
}

@GetMapping(value = "/{id}/tree", produces = MediaType.APPLICATION_JSON_VALUE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import cz.trailsthroughshadows.algorithm.validation.Validable;
import cz.trailsthroughshadows.algorithm.validation.ValidationConfig;
import cz.trailsthroughshadows.api.rest.json.LazyFieldsSerializer;
import cz.trailsthroughshadows.api.table.playerdata.adventure.achievement.AchievementDTO;
import jakarta.annotation.Nullable;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
Expand All @@ -17,7 +20,7 @@
@Entity
@Table(name = "CampaignAchievements")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CampaignAchievements {
public class CampaignAchievements extends Validable {

@EmbeddedId
private CampaignAchievementsId key;
Expand All @@ -27,8 +30,37 @@ public class CampaignAchievements {
@JoinColumn(name = "idAchievement", insertable = false, updatable = false)
private AchievementDTO achievement;

@Override
protected void validateInner(@Nullable ValidationConfig validationConfig) {
if (key == null) {
errors.add(new cz.trailsthroughshadows.api.rest.model.error.type.ValidationError("CampaignAchievements", "key", null, "Key must not be null."));
}
if (!errors.isEmpty()) { return; }
if (key.idAchievement == null) {
errors.add(new cz.trailsthroughshadows.api.rest.model.error.type.ValidationError("CampaignAchievements", "key.idAchievement", null, "Achievement ID must not be null."));
}
if (key.idCampaign == null) {
errors.add(new cz.trailsthroughshadows.api.rest.model.error.type.ValidationError("CampaignAchievements", "key.idCampaign", null, "Campaign ID must not be null."));
}
if (achievement == null) {
errors.add(new cz.trailsthroughshadows.api.rest.model.error.type.ValidationError("CampaignAchievements", "achievement", null, "Achievement must not be null."));
}
validateChild(achievement, validationConfig);
if (!errors.isEmpty()) { return; }
if (achievement.getId() == null) {
errors.add(new cz.trailsthroughshadows.api.rest.model.error.type.ValidationError("CampaignAchievements", "achievement.id", null, "Achievement ID must not be null."));
}
}

@Override
public String getValidableValue() {
return null;
}

@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class CampaignAchievementsId implements Serializable {
@Column(nullable = false)
private Integer idCampaign;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,8 @@ protected void validateInner(@Nullable ValidationConfig validationConfig) {
validateChild(new Title(title), validationConfig);
validateChild(new Description(description), validationConfig);

for (CampaignLocation location : locations) {
validateChild(location, validationConfig);
}

for (CampaignAchievements achievement : achievements) {
validateChild(achievement.getAchievement(), validationConfig);
}
locations.forEach(location -> validateChild(location, validationConfig));
achievements.forEach(achievement -> validateChild(achievement, validationConfig));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,9 @@ protected void validateInner(@Nullable ValidationConfig validationConfig) {

if (!errors.isEmpty()) return;

for (Story story : stories) {
validateChild(story, validationConfig);
}

for (Condition condition : conditions) {
validateChild(condition, validationConfig);
}
stories.forEach(story -> validateChild(story, validationConfig));
conditions.forEach(condition -> validateChild(condition, validationConfig));
validateChild(location, validationConfig);
}

@Override
Expand Down

0 comments on commit 48aceae

Please sign in to comment.