-
Notifications
You must be signed in to change notification settings - Fork 84
/
InMemoryRepository.java
60 lines (43 loc) · 1.26 KB
/
InMemoryRepository.java
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
package com.dzone.albanoj2.example.rest.repository;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import com.dzone.albanoj2.example.rest.domain.Identifiable;
public abstract class InMemoryRepository<T extends Identifiable> {
@Autowired
private IdGenerator idGenerator;
private List<T> elements = Collections.synchronizedList(new ArrayList<>());
public T create(T element) {
elements.add(element);
element.setId(idGenerator.getNextId());
return element;
}
public boolean delete(Long id) {
return elements.removeIf(element -> element.getId().equals(id));
}
public List<T> findAll() {
return elements;
}
public Optional<T> findById(Long id) {
return elements.stream().filter(e -> e.getId().equals(id)).findFirst();
}
public int getCount() {
return elements.size();
}
public void clear() {
elements.clear();
}
public boolean update(Long id, T updated) {
if (updated == null) {
return false;
}
else {
Optional<T> element = findById(id);
element.ifPresent(original -> updateIfExists(original, updated));
return element.isPresent();
}
}
protected abstract void updateIfExists(T original, T desired);
}