|
| 1 | +package io.meterian.samples.jackson; |
| 2 | + |
| 3 | +import java.util.Collection; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Random; |
| 8 | +import java.util.concurrent.atomic.AtomicInteger; |
| 9 | + |
| 10 | +public class ProductsDatabase { |
| 11 | + |
| 12 | + private Map<String, Product> products = new HashMap<>(); |
| 13 | + private AtomicInteger idGenerator = new AtomicInteger(0); |
| 14 | + |
| 15 | + public ProductsDatabase() { |
| 16 | + add(new Product(0,"apple", "Real apple from Italy", randomData())); |
| 17 | + add(new Product(0,"orange", "Real orange from Italy", randomData())); |
| 18 | + add(new Product(0,"kiwi", "Real kiwi from Italy", randomData())); |
| 19 | + } |
| 20 | + |
| 21 | + public Collection<Product> list() { |
| 22 | + return Collections.unmodifiableCollection(products.values()); |
| 23 | + } |
| 24 | + |
| 25 | + public Product findById(String id) { |
| 26 | + return products.get(id); |
| 27 | + } |
| 28 | + |
| 29 | + public Product add(Product newProduct) { |
| 30 | + Integer newId = idGenerator.incrementAndGet(); |
| 31 | + Product product = newProduct.duplicate(newId); |
| 32 | + products.put(newId.toString(), product); |
| 33 | + return product; |
| 34 | + } |
| 35 | + |
| 36 | + public Product update(String id, Product newProduct) { |
| 37 | + Product oldProduct = products.get(id); |
| 38 | + if (oldProduct == null) |
| 39 | + return null; |
| 40 | + |
| 41 | + products.put(id, newProduct); |
| 42 | + return newProduct; |
| 43 | + } |
| 44 | + |
| 45 | + public Product delete(String id) { |
| 46 | + return products.remove(id); |
| 47 | + } |
| 48 | + |
| 49 | + private Object randomData() { |
| 50 | + String[] colors = {"yellow", "red", "green"}; |
| 51 | + |
| 52 | + Map<String,Object> data = new HashMap<>(); |
| 53 | + data.put("cost", (int)(1+Math.random()*5)); |
| 54 | + data.put("color", colors[new Random().nextInt(colors.length)]); |
| 55 | + return data; |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +} |
0 commit comments