Skip to content

Commit

Permalink
Žože shenanigans somehow fixed..
Browse files Browse the repository at this point in the history
  • Loading branch information
Firestone82 committed Apr 29, 2024
1 parent e7dcbe6 commit 4836aac
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
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.*;
import cz.trailsthroughshadows.api.table.schematic.location.model.dto.LocationPathDTO;
import cz.trailsthroughshadows.api.table.campaign.model.Campaign;
import cz.trailsthroughshadows.api.table.campaign.model.CampaignAchievements;
import cz.trailsthroughshadows.api.table.campaign.model.CampaignDTO;
import cz.trailsthroughshadows.api.table.campaign.model.CampaignLocation;
import cz.trailsthroughshadows.api.util.Pair;
import cz.trailsthroughshadows.api.util.reflect.Filtering;
import cz.trailsthroughshadows.api.util.reflect.Initialization;
import cz.trailsthroughshadows.api.util.reflect.Sorting;
Expand All @@ -15,12 +18,12 @@
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand All @@ -30,13 +33,18 @@
@RequestMapping("/campaigns")
public class CampaignController {
private static final Logger log = LoggerFactory.getLogger(CampaignController.class);

@Autowired
private CampaignRepo campaignRepo;

@Autowired
private CampaignLocationRepo campaignLocationRepo;

@Autowired
private ValidationService validation;

@GetMapping("")
@Cacheable(value = "campaign")
public ResponseEntity<RestPaginatedResult<CampaignDTO>> findAllEntities(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "100") int limit,
Expand Down Expand Up @@ -69,6 +77,7 @@ public ResponseEntity<RestPaginatedResult<CampaignDTO>> findAllEntities(
}

@GetMapping("/{id}")
@Cacheable(value = "campaign")
public CampaignDTO findById(
@PathVariable int id,
@RequestParam(required = false, defaultValue = "") List<String> include,
Expand All @@ -87,6 +96,7 @@ public CampaignDTO findById(

}

@Cacheable(value = "campaign")
@GetMapping("/{id}/location/{idLocation}")
public CampaignLocation findById2(
@PathVariable int id,
Expand Down Expand Up @@ -115,18 +125,69 @@ public CampaignLocation findById2(
@Transactional(rollbackOn = Exception.class)
@CacheEvict(value = "campaign", allEntries = true)
public ResponseEntity<MessageResponse> update(@PathVariable int id, @RequestBody CampaignDTO campaign) {
log.debug("Updating campaign with id '{}': {}", id, campaign);

// Validate campaign
validation.validate(campaign);

CampaignDTO campaignToUpdate = campaignRepo
.findById(id)
.orElseThrow(() -> RestException.of(HttpStatus.NOT_FOUND, "Campaign with id '{}' not found!", id));

validation.validate(campaign);
// Remove relations and save them for later
List<CampaignAchievements> achievements = new ArrayList<>();
if (campaign.getAchievements() != null) {
achievements.addAll(campaign.getAchievements());
campaign.getAchievements().clear();
}

List<CampaignLocation> locations = new ArrayList<>();
if (campaign.getLocations() != null) {
locations.addAll(campaign.getLocations());
campaign.getLocations().clear();
}

// Update campaign
campaignToUpdate.setTitle(campaign.getTitle());
campaignToUpdate.setDescription(campaign.getDescription());
campaignToUpdate.setAchievements(campaign.getAchievements());
campaignToUpdate.setLocations(campaign.getLocations());
campaignToUpdate = campaignRepo.save(campaignToUpdate);

// Post load relations
if (campaignToUpdate.getAchievements() != null) {
campaignToUpdate.getAchievements().clear();
campaignToUpdate.getAchievements().addAll(achievements);
}

if (campaignToUpdate.getLocations() != null) {
for (CampaignLocation cl : locations) {
cl.setIdCampaign(campaign.getId());
cl.getStories().forEach(story -> {
if (story.getId() == 0) {
story.setId(null);
}

story.setIdCampaignLocation(cl.getId());
});
cl.getPaths().forEach(path -> {
path.setIdCampaign(campaign.getId());
});

StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(cl.getConditions().stream().map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
sb.append("]");
cl.setConditionString(sb.toString());

campaignToUpdate.getLocations().clear();
campaignToUpdate.getLocations().addAll(locations);
}
}

return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaign updated successfully!"), HttpStatus.OK);
if (!achievements.isEmpty() || !locations.isEmpty()) {
campaignToUpdate = campaignRepo.save(campaignToUpdate);
}

return new ResponseEntity<>(MessageResponse.of(HttpStatus.OK, "Campaign with id '{}' updated!", id), HttpStatus.OK);
}

@DeleteMapping("/{id}")
Expand All @@ -142,35 +203,68 @@ public ResponseEntity<MessageResponse> delete(@PathVariable int id) {
}


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

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

// Remove ids to prevent conflicts
campaigns.forEach(e -> e.setId(null));

// save relations
Map<String, List<CampaignAchievements>> achievementsRelations = new HashMap<>();
Map<String, List<CampaignLocation>> locationsRelations = new HashMap<>();
Map<String, List<LocationPathDTO>> pathsRelations = new HashMap<>();
// Remove relations and save them for later
Map<String, Pair<List<CampaignAchievements>, List<CampaignLocation>>> achievementsAndLocations = new HashMap<>();

// remove relations
campaigns.forEach(campaign -> {
campaign.setAchievements(new ArrayList<>());
campaign.setLocations(new ArrayList<>());
achievementsAndLocations.put(campaign.getTitle(), new Pair<>(new ArrayList<>(campaign.getAchievements()), new ArrayList<>(campaign.getLocations())));
campaign.setAchievements(null);
campaign.setLocations(null);
});

// todo zoze glhf
// Save all campaigns
campaigns = campaignRepo.saveAll(campaigns);

campaignRepo.save(campaign);
// Load relations
campaigns.forEach(campaign -> {
Pair<List<CampaignAchievements>, List<CampaignLocation>> pair = achievementsAndLocations.get(campaign.getTitle());
campaign.setAchievements(new ArrayList<>(pair.first()));
campaign.getAchievements().forEach(achievement -> achievement.getKey().setIdCampaign(campaign.getId()));

List<CampaignLocation> campLoc = pair.second();
for (CampaignLocation cl : campLoc) {
cl.setId(null);
cl.setIdCampaign(campaign.getId());
cl.getStories().forEach(story -> {
story.setId(null);
story.setIdCampaignLocation(cl.getId());
});
cl.getPaths().forEach(path -> {
path.setIdCampaign(campaign.getId());
});

StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(cl.getConditions().stream().map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
sb.append("]");
cl.setConditionString(sb.toString());
}

// Save middle entities
campLoc = campaignLocationRepo.saveAll(campLoc);
campaign.setLocations(campLoc);
});

String ids = campaigns.stream().map(CampaignDTO::getId).map(String::valueOf).reduce((a, b) -> a + ", " + b).orElse("");
// Save all relations
campaigns = campaignRepo.saveAll(campaigns);

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: " + ids), HttpStatus.OK);
}

@Cacheable(value = "campaignTree", key = "#id")
@GetMapping(value = "/{id}/tree", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getTree(@PathVariable int id) {
Campaign campaign = Campaign.fromDTO(campaignRepo
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package cz.trailsthroughshadows.api.table.campaign;

import cz.trailsthroughshadows.api.table.campaign.model.CampaignLocation;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CampaignLocationRepo extends JpaRepository<CampaignLocation, Integer> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package cz.trailsthroughshadows.api.table.campaign;

import cz.trailsthroughshadows.api.table.campaign.model.CampaignLocation;
import cz.trailsthroughshadows.api.table.schematic.location.model.dto.LocationPathDTO;
import org.springframework.data.jpa.repository.JpaRepository;

public interface LocationPath extends JpaRepository<LocationPathDTO, Integer> {

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

Expand All @@ -40,11 +39,11 @@ public class CampaignDTO extends Validable {

@OneToMany(fetch = FetchType.LAZY, mappedBy = "key.idCampaign", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonSerialize(using = LazyFieldsSerializer.class)
private List<CampaignAchievements> achievements = new ArrayList<>();
private List<CampaignAchievements> achievements;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "idCampaign", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonSerialize(using = LazyFieldsSerializer.class)
private List<CampaignLocation> locations = new ArrayList<>();
private List<CampaignLocation> locations ;

@JsonIgnore
public Collection<AchievementDTO> getMappedAchievements() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@
public class CampaignLocation extends Validable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne(fetch = FetchType.LAZY)
@JsonSerialize(using = LazyFieldsSerializer.class)
@JoinColumn(name = "idLocation", insertable = false, updatable = false)
@JoinColumn(name = "idLocation")
private LocationDTO location;

@Column(nullable = false, insertable = false, updatable = false)
@Column(nullable = false)
private Integer idCampaign;

@OneToMany(mappedBy = "idCampaignLocation", fetch = FetchType.LAZY)
Expand Down Expand Up @@ -70,6 +71,11 @@ private void postLoad() {
}
}

public List<LocationPathDTO> getPaths() {
// Zoze pice, jak to kurva funguje
return paths.stream().filter(path -> path.getIdCampaign().equals(idCampaign)).toList();
}

@JsonIgnore
public String getConditionString() {
return conditionString;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
Expand All @@ -44,6 +45,7 @@ public class LocationController {
private CampaignRepo campaignRepo;

@GetMapping("/locations")
@Cacheable(value = "location")
public ResponseEntity<RestPaginatedResult<Location>> getLocations(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "100") int limit,
Expand Down Expand Up @@ -85,6 +87,7 @@ public ResponseEntity<RestPaginatedResult<Location>> getLocations(
}

@GetMapping("/locations/{id}")
@Cacheable(value = "location", key = "#id")
public ResponseEntity<Location> getLocationById(
@PathVariable int id,
@RequestParam(required = false, defaultValue = "") List<String> include,
Expand All @@ -105,6 +108,7 @@ public ResponseEntity<Location> getLocationById(
}

@GetMapping("/locations/{idLocation}/parts/{idPart}")
@Cacheable(value = "location")
public ResponseEntity<Part> getPartByLocationId(@PathVariable int idLocation, @PathVariable int idPart) {

LocationDTO locationDTO = locationRepo
Expand Down

0 comments on commit 4836aac

Please sign in to comment.