[LIB-2] Add snooker-score-api source files
[snooker-score-api.git] / src / main / java / org / hedgecode / snooker / json / JsonCollectionEntity.java
1 /*
2  * Copyright (c) 2017. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.snooker.json;
18
19 import java.util.Collections;
20 import java.util.Comparator;
21 import java.util.Iterator;
22 import java.util.LinkedHashMap;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.hedgecode.snooker.api.CollectionEntity;
28 import org.hedgecode.snooker.api.IdEntity;
29
30 /**
31  * Abstract Collection Entity to JSON deserialize.
32  *
33  * @author Dmitry Samoshin aka gotty
34  */
35 public abstract class JsonCollectionEntity<E extends IdEntity>
36         implements CollectionEntity<E>, JsonSerializable
37 {
38     private final Map<Integer, E> entities = new LinkedHashMap<>();
39
40     protected JsonCollectionEntity(E[] entities) {
41         for (E entity : entities) {
42             if (entity != null)
43                 this.entities.put(entity.getId(), entity);
44         }
45     }
46
47     protected JsonCollectionEntity(List<E> entities) {
48         for (E entity : entities) {
49             this.entities.put(entity.getId(), entity);
50         }
51     }
52
53     @Override
54     public int size() {
55         return entities.size();
56     }
57
58     @Override
59     public boolean isEmpty() {
60         return entities.isEmpty();
61     }
62
63     @Override
64     public Iterator<E> iterator() {
65         return entities.values().iterator();
66     }
67
68     @Override
69     public E byId(int id) {
70         return entities.get(id);
71     }
72
73     protected void sort(Comparator<E> comparator) {
74         List<E> entityList = new LinkedList<>(entities.values());
75         Collections.sort(
76                 entityList, comparator
77         );
78         entities.clear();
79         for (E entity : entityList) {
80             entities.put(entity.getId(), entity);
81         }
82     }
83
84     @Override
85     public void sortById() {
86         sort(
87                 (entity1, entity2) -> entity1.getId() - entity2.getId()
88         );
89     }
90
91 }