[LIB-10] SerialVersionUID for Serializable classes
[snooker-score-api.git] / src / main / java / org / hedgecode / snooker / json / JsonCollectionEntity.java
1 /*
2  * Copyright (c) 2017-2020. 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.io.Serializable;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.Iterator;
23 import java.util.LinkedHashMap;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.hedgecode.snooker.api.CollectionEntity;
29 import org.hedgecode.snooker.api.IdEntity;
30
31 /**
32  * Abstract Collection Entity to JSON deserialize.
33  *
34  * @author Dmitry Samoshin aka gotty
35  */
36 public abstract class JsonCollectionEntity<E extends IdEntity>
37         implements CollectionEntity<E>, Serializable
38 {
39     private static final long serialVersionUID = 6302642716627217361L;
40
41     private final Map<Integer, E> entities = new LinkedHashMap<>();
42
43     JsonCollectionEntity(E[] entities) {
44         for (E entity : entities) {
45             if (entity != null)
46                 this.entities.put(
47                         entity.getId(), entity
48                 );
49         }
50     }
51
52     JsonCollectionEntity(List<E> entities) {
53         for (E entity : entities) {
54             this.entities.put(
55                     entity.getId(), entity
56             );
57         }
58     }
59
60     @Override
61     public int size() {
62         return entities.size();
63     }
64
65     @Override
66     public boolean isEmpty() {
67         return entities.isEmpty();
68     }
69
70     @Override
71     public Iterator<E> iterator() {
72         return entities.values().iterator();
73     }
74
75     @Override
76     public E byId(int id) {
77         return entities.get(id);
78     }
79
80     protected void sort(Comparator<E> comparator) {
81         List<E> entityList = new LinkedList<>(entities.values());
82         Collections.sort(
83                 entityList, comparator
84         );
85         entities.clear();
86         for (E entity : entityList) {
87             entities.put(entity.getId(), entity);
88         }
89     }
90
91     @Override
92     public void sortById() {
93         sort(
94                 (entity1, entity2) -> entity1.getId() - entity2.getId()
95         );
96     }
97
98 }