🛢️ 🚨 Implement bulk operations, lint the code

pull/5/head
Alexis Drai 2 years ago
parent 05e15ba5ba
commit 436ebc976b

1
.gitignore vendored

@ -85,3 +85,4 @@ gradle-app.setting
# Others # Others
docs/todos.md docs/todos.md
/src/test/resources/application.properties /src/test/resources/application.properties
/docs/sample-dataset/load_data.sh

@ -153,7 +153,7 @@
], ],
"body": { "body": {
"mode": "raw", "mode": "raw",
"raw": "{\r\n \"nickname\": \"Now with moves\",\r\n \"dob\": \"2023-05-07\",\r\n \"level\": 1,\r\n \"pokedexId\": 172,\r\n \"evoStage\": 1,\r\n \"evoTrack\": [\"PICHU\", \"PIKACHU\", \"RAICHU\"],\r\n \"types\": [\r\n {\r\n \"name\": \"ELECTRIC\",\r\n \"weakAgainst\": [\"GROUND\", \"ROCK\"],\r\n \"effectiveAgainst\": [\"WATER\", \"FLYING\"]\r\n }\r\n ],\r\n \"moveSet\": \r\n [\r\n {\r\n \"id\": \"60a64f7eae945a6e60b0e917\",\r\n \"name\": \"Ember\"\r\n }\r\n ],\r\n \"schemaVersion\": 1\r\n}" "raw": "{\r\n \"nickname\": \"Blappity-bloop\",\r\n \"dob\": \"2023-05-07\",\r\n \"level\": 1,\r\n \"pokedexId\": 172,\r\n \"evoStage\": 1,\r\n \"evoTrack\": [\"PICHU\", \"PIKACHU\", \"RAICHU\"],\r\n \"types\": [\r\n {\r\n \"name\": \"ELECTRIC\",\r\n \"weakAgainst\": [\"GROUND\", \"ROCK\"],\r\n \"effectiveAgainst\": [\"WATER\", \"FLYING\"]\r\n }\r\n ],\r\n \"moveSet\": \r\n [\r\n {\r\n \"id\": \"60a64f7eae945a6e60b0e917\",\r\n \"name\": \"Ember\"\r\n }\r\n ],\r\n \"schemaVersion\": 1\r\n}"
}, },
"url": { "url": {
"raw": "http://localhost:8080/pokemong", "raw": "http://localhost:8080/pokemong",
@ -243,7 +243,7 @@
"method": "DELETE", "method": "DELETE",
"header": [], "header": [],
"url": { "url": {
"raw": "http://localhost:8080/pokemong/60a64f7eae945a6e60b0e911", "raw": "http://localhost:8080/pokemong/60a64f7eae945a6e60b0e916",
"protocol": "http", "protocol": "http",
"host": [ "host": [
"localhost" "localhost"
@ -251,7 +251,7 @@
"port": "8080", "port": "8080",
"path": [ "path": [
"pokemong", "pokemong",
"60a64f7eae945a6e60b0e911" "60a64f7eae945a6e60b0e916"
] ]
} }
}, },

@ -29,6 +29,49 @@ public class TrainerCodec extends GenericCodec<Trainer> {
.get(Document.class); .get(Document.class);
} }
@NotNull
private static Trainer decodeV1(Document document) {
Trainer trainer = new Trainer();
trainer.setId(document.getObjectId("_id")
.toString());
trainer.setSchemaVersion(document.getInteger("schemaVersion"));
trainer.setName(document.getString("name"));
Date dob = document.getDate("dob");
if (dob != null) {
trainer.setDob(dob.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());
}
trainer.setWins(document.getInteger("wins"));
trainer.setLosses(document.getInteger("losses"));
List<String> pastOpponentsIds = document.getList("pastOpponents", ObjectId.class)
.stream()
.map(ObjectId::toString)
.collect(Collectors.toList());
trainer.setPastOpponents(pastOpponentsIds);
Set<TrainerPokemong> pokemongList = document
.getList("pokemongs", Document.class)
.stream()
.map(pokemongDoc -> {
TrainerPokemong pokemong = new TrainerPokemong();
pokemong.setId(((ObjectId) pokemongDoc.get("_id")).toString());
pokemong.setNickname(pokemongDoc.getString("nickname"));
pokemong.setSpecies(PokemongName.valueOf(pokemongDoc.getString("species")));
return pokemong;
})
.collect(Collectors.toSet());
trainer.setPokemongs(pokemongList);
return trainer;
}
@Override @Override
public void encode(BsonWriter writer, @NotNull Trainer trainer, EncoderContext encoderContext) { public void encode(BsonWriter writer, @NotNull Trainer trainer, EncoderContext encoderContext) {
Document doc = new Document(); Document doc = new Document();
@ -88,47 +131,4 @@ public class TrainerCodec extends GenericCodec<Trainer> {
default -> throw new IllegalArgumentException("Unsupported schema version: " + schemaVersion); default -> throw new IllegalArgumentException("Unsupported schema version: " + schemaVersion);
}; };
} }
@NotNull
private static Trainer decodeV1(Document document) {
Trainer trainer = new Trainer();
trainer.setId(document.getObjectId("_id")
.toString());
trainer.setSchemaVersion(document.getInteger("schemaVersion"));
trainer.setName(document.getString("name"));
Date dob = document.getDate("dob");
if (dob != null) {
trainer.setDob(dob.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());
}
trainer.setWins(document.getInteger("wins"));
trainer.setLosses(document.getInteger("losses"));
List<String> pastOpponentsIds = document.getList("pastOpponents", ObjectId.class)
.stream()
.map(ObjectId::toString)
.collect(Collectors.toList());
trainer.setPastOpponents(pastOpponentsIds);
Set<TrainerPokemong> pokemongList = document
.getList("pokemongs", Document.class)
.stream()
.map(pokemongDoc -> {
TrainerPokemong pokemong = new TrainerPokemong();
pokemong.setId(((ObjectId) pokemongDoc.get("_id")).toString());
pokemong.setNickname(pokemongDoc.getString("nickname"));
pokemong.setSpecies(PokemongName.valueOf(pokemongDoc.getString("species")));
return pokemong;
})
.collect(Collectors.toSet());
trainer.setPokemongs(pokemongList);
return trainer;
}
} }

@ -23,15 +23,14 @@ public abstract class GenericController<T extends GenericEntity> {
if (entity != null) { if (entity != null) {
return Response.ok(entity) return Response.ok(entity)
.build(); .build();
} } else {
else {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.NOT_FOUND)
.entity("Entity not found for id: " + id) .entity("Entity not found for id: " + id)
.build(); .build();
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity("Invalid id format: " + id) .entity(e.getMessage())
.build(); .build();
} }
} }
@ -72,17 +71,12 @@ public abstract class GenericController<T extends GenericEntity> {
return Response.status(Response.Status.OK) return Response.status(Response.Status.OK)
.entity(updatedEntity) .entity(updatedEntity)
.build(); .build();
} } else {
else {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.NOT_FOUND)
.entity("Entity not found for id: " + id) .entity("Entity not found for id: " + id)
.build(); .build();
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException | NonValidEntityException e) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Invalid id format: " + id)
.build();
} catch (NonValidEntityException e) {
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(e.getMessage()) .entity(e.getMessage())
.build(); .build();
@ -99,7 +93,7 @@ public abstract class GenericController<T extends GenericEntity> {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity("Invalid id format: " + id) .entity(e.getMessage())
.build(); .build();
} }
} }

@ -13,7 +13,8 @@ public class Move extends GenericVersionedEntity {
private Integer accuracy; private Integer accuracy;
private Type type; private Type type;
public Move() {} public Move() {
}
public String getName() { public String getName() {
return name; return name;

@ -31,7 +31,8 @@ public class Pokemong extends GenericVersionedEntity {
*/ */
private Set<PokemongMove> moveSet; private Set<PokemongMove> moveSet;
public Pokemong() {} public Pokemong() {
}
@Nullable @Nullable
public String getNickname() { public String getNickname() {
@ -100,8 +101,7 @@ public class Pokemong extends GenericVersionedEntity {
public void updateMove(String id, String name) { public void updateMove(String id, String name) {
for (PokemongMove move : moveSet) { for (PokemongMove move : moveSet) {
if (move.getId() if (move.getId()
.equals(id)) .equals(id)) {
{
move.setName(name); move.setName(name);
break; break;
} }
@ -116,6 +116,10 @@ public class Pokemong extends GenericVersionedEntity {
return Collections.unmodifiableList(evoTrack); return Collections.unmodifiableList(evoTrack);
} }
public void setEvoTrack(List<PokemongName> evoTrack) {
this.evoTrack = evoTrack;
}
public Integer getEvoStage() { public Integer getEvoStage() {
return evoStage; return evoStage;
} }
@ -123,9 +127,5 @@ public class Pokemong extends GenericVersionedEntity {
public void setEvoStage(Integer evoStage) { public void setEvoStage(Integer evoStage) {
this.evoStage = evoStage; this.evoStage = evoStage;
} }
public void setEvoTrack(List<PokemongName> evoTrack) {
this.evoTrack = evoTrack;
}
} }

@ -18,7 +18,8 @@ public class Trainer extends GenericVersionedEntity {
private List<String> pastOpponents; private List<String> pastOpponents;
private Set<TrainerPokemong> pokemongs; private Set<TrainerPokemong> pokemongs;
public Trainer() {} public Trainer() {
}
public String getName() { public String getName() {
return name; return name;
@ -72,7 +73,7 @@ public class Trainer extends GenericVersionedEntity {
pokemongs.add(trainerPokemong); pokemongs.add(trainerPokemong);
} }
public void removePokemong(TrainerPokemong trainerPokemong) { public void removePokemong(String id) {
pokemongs.remove(trainerPokemong); pokemongs.removeIf(trainerPokemong -> trainerPokemong.getId().equals(id));
} }
} }

@ -6,7 +6,8 @@ public class PokemongMove extends GenericEntity {
private String name; private String name;
public PokemongMove() {} public PokemongMove() {
}
public String getName() { public String getName() {
return name; return name;

@ -10,7 +10,8 @@ public class TrainerPokemong extends GenericEntity {
private PokemongName species; private PokemongName species;
public TrainerPokemong() {} public TrainerPokemong() {
}
@Nullable @Nullable
public String getNickname() { public String getNickname() {

@ -11,7 +11,8 @@ public class Type {
private List<TypeName> weakAgainst; private List<TypeName> weakAgainst;
private List<TypeName> effectiveAgainst; private List<TypeName> effectiveAgainst;
public Type() {} public Type() {
}
public TypeName getName() { public TypeName getName() {
return name; return name;

@ -2,7 +2,9 @@ package fr.uca.iut.repositories;
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.model.ReplaceOptions;
import com.mongodb.client.model.WriteModel;
import com.mongodb.lang.Nullable; import com.mongodb.lang.Nullable;
import fr.uca.iut.entities.GenericEntity; import fr.uca.iut.entities.GenericEntity;
import org.bson.Document; import org.bson.Document;
@ -49,6 +51,21 @@ public abstract class GenericRepository<T extends GenericEntity> {
); );
} }
public void updateAll(@NotNull List<T> entities) {
List<WriteModel<T>> updates = new ArrayList<>();
for (T entity : entities) {
updates.add(
new ReplaceOneModel<>(
eq("_id", new ObjectId(entity.getId())),
entity,
new ReplaceOptions().upsert(true)
)
);
}
getCollection().bulkWrite(updates);
}
public void delete(@NotNull T entity) { public void delete(@NotNull T entity) {
getCollection().deleteOne(eq("_id", new ObjectId(entity.getId()))); getCollection().deleteOne(eq("_id", new ObjectId(entity.getId())));
} }

@ -48,11 +48,20 @@ public abstract class GenericService<T extends GenericEntity> {
} }
/** /**
* Override me and start with `super.validateOne(entity);` * Override me
*/ */
@Nullable @Nullable
public T updateOne(@NotNull T entity) { public T updateOne(@NotNull T entity) {
validateOne(entity); validateOne(entity);
return entity; return entity;
} }
public void updateAll(List<T> entities) {
if (!entities.isEmpty()) {
for (T entity : entities) {
validateOne(entity);
}
repository.updateAll(entities);
}
}
} }

@ -82,10 +82,12 @@ public class MoveService extends GenericService<Move> {
@Override @Override
public void deleteOneById(String id) { public void deleteOneById(String id) {
List<Pokemong> pokemongs = pokemongService.findByMove(id); List<Pokemong> pokemongs = pokemongService.findByMove(id);
List<Pokemong> pokemongsToUpdate = new ArrayList<>();
for (Pokemong pokemong : pokemongs) { for (Pokemong pokemong : pokemongs) {
pokemong.removeMove(id); pokemong.removeMove(id);
pokemongService.updateOne(pokemong); pokemongsToUpdate.add(pokemong);
} }
pokemongService.updateAll(pokemongsToUpdate);
super.deleteOneById(id); super.deleteOneById(id);
} }
@ -95,15 +97,9 @@ public class MoveService extends GenericService<Move> {
super.updateOne(move); super.updateOne(move);
Move existingMove = moveRepository.findById(move.getId()); Move existingMove = moveRepository.findById(move.getId());
if (existingMove != null) { if (existingMove != null) {
if (!existingMove.getName() if (!existingMove.getName().equals(move.getName())) {
.equals(move.getName()))
{
existingMove.setName(move.getName()); existingMove.setName(move.getName());
List<Pokemong> pokemongs = pokemongService.findByMove(move.getId()); batchUpdatePokemongTrainers(move);
for (Pokemong pokemong : pokemongs) {
pokemong.updateMove(move.getId(), move.getName());
pokemongService.updateOne(pokemong);
}
} }
existingMove.setPower(move.getPower()); existingMove.setPower(move.getPower());
@ -115,6 +111,16 @@ public class MoveService extends GenericService<Move> {
return existingMove; return existingMove;
} }
private void batchUpdatePokemongTrainers(@NotNull Move move) {
List<Pokemong> pokemongs = pokemongService.findByMove(move.getId());
List<Pokemong> pokemongsToUpdate = new ArrayList<>();
for (Pokemong pokemong : pokemongs) {
pokemong.updateMove(move.getId(), move.getName());
pokemongsToUpdate.add(pokemong);
}
pokemongService.updateAll(pokemongsToUpdate);
}
/** /**
* We want to migrate the documents incrementally, so we upgrade the * We want to migrate the documents incrementally, so we upgrade the
* schema version if it is less than the current schema version, * schema version if it is less than the current schema version,

@ -85,16 +85,14 @@ public class PokemongService extends GenericService<Pokemong> {
Set<Type> types = pokemong.getTypes(); Set<Type> types = pokemong.getTypes();
if (types == null if (types == null
|| types.size() == 0 || types.size() == 0
|| types.size() > 2) || types.size() > 2) {
{
errors.add("pokemong types was null or empty or had more than 2 types"); errors.add("pokemong types was null or empty or had more than 2 types");
} }
Set<PokemongMove> moveSet = pokemong.getMoveSet(); Set<PokemongMove> moveSet = pokemong.getMoveSet();
if (moveSet == null) { if (moveSet == null) {
errors.add("pokemong move set was null"); errors.add("pokemong move set was null");
} } else {
else {
if (moveSet.size() == 0 || moveSet.size() > 4) { if (moveSet.size() == 0 || moveSet.size() > 4) {
errors.add("pokemong move set was empty or had more than 4 moves"); errors.add("pokemong move set was empty or had more than 4 moves");
} }
@ -114,8 +112,7 @@ public class PokemongService extends GenericService<Pokemong> {
} }
if (pokemong.getSchemaVersion() == null || if (pokemong.getSchemaVersion() == null ||
!Objects.equals(pokemong.getSchemaVersion(), Pokemong.LATEST_SCHEMA_VERSION)) !Objects.equals(pokemong.getSchemaVersion(), Pokemong.LATEST_SCHEMA_VERSION)) {
{
errors.add( errors.add(
"pokemong schema version was null or not the latest version: " + Pokemong.LATEST_SCHEMA_VERSION); "pokemong schema version was null or not the latest version: " + Pokemong.LATEST_SCHEMA_VERSION);
} }
@ -131,9 +128,7 @@ public class PokemongService extends GenericService<Pokemong> {
if (pokemong != null && pokemong.getTrainer() != null) { if (pokemong != null && pokemong.getTrainer() != null) {
Trainer trainer = trainerService.getOneById(pokemong.getTrainer()); Trainer trainer = trainerService.getOneById(pokemong.getTrainer());
if (trainer != null) { if (trainer != null) {
trainer.getPokemongs() trainer.removePokemong(id);
.removeIf(trainerPokemong -> trainerPokemong.getId()
.equals(id));
trainerService.updateOne(trainer); trainerService.updateOne(trainer);
} }
} }
@ -163,9 +158,22 @@ public class PokemongService extends GenericService<Pokemong> {
pokemongRepository.persistOrUpdate(existingPokemong); pokemongRepository.persistOrUpdate(existingPokemong);
if (nicknameChanged || evoStageChanged || evoTrackChanged) { if (nicknameChanged || evoStageChanged || evoTrackChanged) {
updateTrainerPokemong(existingPokemong, nicknameChanged, evoStageChanged, evoTrackChanged);
}
}
return existingPokemong;
}
private void updateTrainerPokemong(
@NotNull Pokemong existingPokemong,
boolean nicknameChanged,
boolean evoStageChanged,
boolean evoTrackChanged
) {
Trainer trainer = trainerService.getOneById(existingPokemong.getTrainer()); Trainer trainer = trainerService.getOneById(existingPokemong.getTrainer());
if (trainer != null) { if (trainer != null) {
TrainerPokemong trainerPokemong = trainer.getPokemongs() TrainerPokemong trainerPokemong =
trainer.getPokemongs()
.stream() .stream()
.filter(tp -> tp.getId() .filter(tp -> tp.getId()
.equals(existingPokemong.getId())) .equals(existingPokemong.getId()))
@ -180,14 +188,10 @@ public class PokemongService extends GenericService<Pokemong> {
if (evoStageChanged || evoTrackChanged) { if (evoStageChanged || evoTrackChanged) {
trainerPokemong.setSpecies(existingPokemong.getSpecies()); trainerPokemong.setSpecies(existingPokemong.getSpecies());
} }
trainerService.updateOne(trainer); trainerService.updateOne(trainer);
} }
} }
} }
}
return existingPokemong;
}
public List<Pokemong> findByMove(String id) { public List<Pokemong> findByMove(String id) {
return pokemongRepository.findByMove(id); return pokemongRepository.findByMove(id);
@ -204,14 +208,15 @@ public class PokemongService extends GenericService<Pokemong> {
} }
public void batchUpdatePokemongTrainers(@NotNull Set<TrainerPokemong> trainerPokemongs, public void batchUpdatePokemongTrainers(@NotNull Set<TrainerPokemong> trainerPokemongs,
@Nullable String trainerId) @Nullable String trainerId) {
{ List<Pokemong> pokemongsToUpdate = new ArrayList<>();
for (TrainerPokemong trainerPokemong : trainerPokemongs) { for (TrainerPokemong trainerPokemong : trainerPokemongs) {
Pokemong pokemong = getOneById(trainerPokemong.getId()); Pokemong pokemong = getOneById(trainerPokemong.getId());
if (pokemong != null && !Objects.equals(pokemong.getTrainer(), trainerId)) { if (pokemong != null && !Objects.equals(pokemong.getTrainer(), trainerId)) {
pokemong.setTrainer(trainerId); pokemong.setTrainer(trainerId);
updateOne(pokemong); pokemongsToUpdate.add(pokemong);
} }
} }
updateAll(pokemongsToUpdate);
} }
} }

@ -33,7 +33,7 @@ public class TrainerService extends GenericService<Trainer> {
public Trainer addOne(@NotNull Trainer trainer) { public Trainer addOne(@NotNull Trainer trainer) {
Trainer persistedTrainer = super.addOne(trainer); Trainer persistedTrainer = super.addOne(trainer);
// If this trainer gained pokemongs, that pokemong's ex-trainer if any needs to lose said pokemong // If this trainer gained pokemongs, that pokemong's ex-trainer if any needs to lose said pokemongs
transferNewlyArrivedTrainerPokemongs(new HashSet<>(), persistedTrainer.getPokemongs()); transferNewlyArrivedTrainerPokemongs(new HashSet<>(), persistedTrainer.getPokemongs());
// all owned pokemongs gain this trainer's reference // all owned pokemongs gain this trainer's reference
pokemongService.batchUpdatePokemongTrainers(trainer.getPokemongs(), trainer.getId()); pokemongService.batchUpdatePokemongTrainers(trainer.getPokemongs(), trainer.getId());
@ -68,8 +68,7 @@ public class TrainerService extends GenericService<Trainer> {
if (pastOpponents == null) { if (pastOpponents == null) {
errors.add("trainer past opponents collection was null"); errors.add("trainer past opponents collection was null");
} } else {
else {
for (String trainerId : pastOpponents) { for (String trainerId : pastOpponents) {
if (StringUtils.isBlankStringOrNull(trainerId)) { if (StringUtils.isBlankStringOrNull(trainerId)) {
errors.add("trainer past opponents collection contained an invalid id: " + trainerId); errors.add("trainer past opponents collection contained an invalid id: " + trainerId);
@ -81,14 +80,12 @@ public class TrainerService extends GenericService<Trainer> {
if (pokemongs == null) { if (pokemongs == null) {
errors.add("trainer pokemongs collection was null or invalid"); errors.add("trainer pokemongs collection was null or invalid");
} } else {
else {
for (TrainerPokemong pokemong : pokemongs) { for (TrainerPokemong pokemong : pokemongs) {
String pokemongId = pokemong.getId(); String pokemongId = pokemong.getId();
if (StringUtils.isBlankStringOrNull(pokemongId) || !pokemongService.existsById(pokemongId)) { if (StringUtils.isBlankStringOrNull(pokemongId) || !pokemongService.existsById(pokemongId)) {
errors.add("pokemong with id " + pokemongId + " does not exist"); errors.add("pokemong with id " + pokemongId + " does not exist");
} } else {
else {
if (!pokemongService.isEvoValid(pokemongId, pokemong.getSpecies())) { if (!pokemongService.isEvoValid(pokemongId, pokemong.getSpecies())) {
errors.add("pokemong with id " + pokemongId + " cannot be a " + errors.add("pokemong with id " + pokemongId + " cannot be a " +
pokemong.getSpecies()); pokemong.getSpecies());
@ -97,8 +94,7 @@ public class TrainerService extends GenericService<Trainer> {
if (pokemong.getNickname() != null if (pokemong.getNickname() != null
&& pokemongBehind != null && pokemongBehind != null
&& !pokemong.getNickname() && !pokemong.getNickname()
.equals(pokemongBehind.getNickname())) .equals(pokemongBehind.getNickname())) {
{
errors.add("pokemong with id " + pokemongId + " already has a nickname"); errors.add("pokemong with id " + pokemongId + " already has a nickname");
} }
} }
@ -106,8 +102,7 @@ public class TrainerService extends GenericService<Trainer> {
} }
if (trainer.getSchemaVersion() == null || if (trainer.getSchemaVersion() == null ||
!Objects.equals(trainer.getSchemaVersion(), Trainer.LATEST_SCHEMA_VERSION)) !Objects.equals(trainer.getSchemaVersion(), Trainer.LATEST_SCHEMA_VERSION)) {
{
errors.add("trainer schema version was null or not the latest version: " + Trainer.LATEST_SCHEMA_VERSION); errors.add("trainer schema version was null or not the latest version: " + Trainer.LATEST_SCHEMA_VERSION);
} }
@ -166,23 +161,25 @@ public class TrainerService extends GenericService<Trainer> {
private void transferNewlyArrivedTrainerPokemongs( private void transferNewlyArrivedTrainerPokemongs(
@NotNull Set<TrainerPokemong> oldPokemongs, @NotNull Set<TrainerPokemong> oldPokemongs,
@NotNull Set<TrainerPokemong> newPokemongs @NotNull Set<TrainerPokemong> newPokemongs
) ) {
{ List<Trainer> trainersToUpdate = new ArrayList<>();
for (TrainerPokemong tp : newPokemongs) {
if (oldPokemongs.isEmpty() || !oldPokemongs.contains(tp)) { for (TrainerPokemong newTrainerPokemong : newPokemongs) {
Pokemong pokemong = pokemongService.getOneById(tp.getId()); if (oldPokemongs.isEmpty() || !oldPokemongs.contains(newTrainerPokemong)) {
Pokemong pokemong = pokemongService.getOneById(newTrainerPokemong.getId());
if (pokemong != null) { if (pokemong != null) {
String oldTrainerId = pokemong.getTrainer(); String oldTrainerId = pokemong.getTrainer();
// If the pokemong already had a trainer, remove it from the old trainer's pokemongs list // If the pokemong already had a trainer, remove it from the old trainer's pokemongs list
if (oldTrainerId != null) { if (oldTrainerId != null) {
Trainer oldTrainer = getOneById(oldTrainerId); Trainer oldTrainer = getOneById(oldTrainerId);
if (oldTrainer != null) { if (oldTrainer != null) {
oldTrainer.removePokemong(tp); oldTrainer.removePokemong(newTrainerPokemong.getId());
updateOne(oldTrainer); trainersToUpdate.add(oldTrainer);
} }
} }
} }
} }
} }
updateAll(trainersToUpdate);
} }
} }

Loading…
Cancel
Save