-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrainService.java
More file actions
78 lines (64 loc) · 2.83 KB
/
Copy pathTrainService.java
File metadata and controls
78 lines (64 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ticket.booking.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import ticket.booking.entities.Train;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TrainService {
private List<Train> trainList;
private ObjectMapper objectMapper = new ObjectMapper();
private static final String TRAIN_DB_PATH = "../localDB/trains.json";
public TrainService() throws IOException {
File trains = new File(TRAIN_DB_PATH);
trainList = objectMapper.readValue(trains, new TypeReference<List<Train>>() {});
}
public List<Train> searchTrains(String source, String destination) {
return trainList.stream().filter(train -> validTrain(train, source, destination)).collect(Collectors.toList());
}
public void addTrain(Train newTrain) {
// Check if a train with the same trainId already exists
Optional<Train> existingTrain = trainList.stream()
.filter(train -> train.getTrainId().equalsIgnoreCase(newTrain.getTrainId()))
.findFirst();
if (existingTrain.isPresent()) {
// If a train with the same trainId exists, update it instead of adding a new one
updateTrain(newTrain);
} else {
// Otherwise, add the new train to the list
trainList.add(newTrain);
saveTrainListToFile();
}
}
public void updateTrain(Train updatedTrain) {
// Find the index of the train with the same trainId
OptionalInt index = IntStream.range(0, trainList.size())
.filter(i -> trainList.get(i).getTrainId().equalsIgnoreCase(updatedTrain.getTrainId()))
.findFirst();
if (index.isPresent()) {
// If found, replace the existing train with the updated one
trainList.set(index.getAsInt(), updatedTrain);
saveTrainListToFile();
} else {
// If not found, treat it as adding a new train
addTrain(updatedTrain);
}
}
private void saveTrainListToFile() {
try {
objectMapper.writeValue(new File(TRAIN_DB_PATH), trainList);
} catch (IOException e) {
e.printStackTrace(); // Handle the exception based on your application's requirements
}
}
private boolean validTrain(Train train, String source, String destination) {
List<String> stationOrder = train.getStations();
int sourceIndex = stationOrder.indexOf(source.toLowerCase());
int destinationIndex = stationOrder.indexOf(destination.toLowerCase());
return sourceIndex != -1 && destinationIndex != -1 && sourceIndex < destinationIndex;
}
}