Add in-memory implementation of Sone database.
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemorySoneDatabase.java
1 /*
2  * Sone - MemorySoneDatabase.java - Copyright © 2011 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.database.memory;
19
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import net.pterodactylus.sone.core.Core;
24 import net.pterodactylus.sone.data.Sone;
25 import net.pterodactylus.sone.database.DatabaseException;
26 import net.pterodactylus.sone.database.SoneDatabase;
27 import net.pterodactylus.util.validation.Validation;
28
29 /**
30  * In-memory implementation of {@link SoneDatabase} that stores all its data in
31  * a {@link Map}. This is roughly equivalent to what {@link Core} does today and
32  * is mainly used while Sone is transitioning to using a real database.
33  *
34  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
35  */
36 public class MemorySoneDatabase implements SoneDatabase {
37
38         /** The Sones. */
39         private final Map<String, Sone> sones = new HashMap<String, Sone>();
40
41         /**
42          * {@inheritDoc}
43          */
44         @Override
45         public Sone getSone(String id, boolean create) throws DatabaseException {
46                 Validation.begin().isNotNull("Sone ID", id).check();
47                 synchronized (sones) {
48                         if (!sones.containsKey(id)) {
49                                 sones.put(id, new Sone(id));
50                         }
51                         return sones.get(id);
52                 }
53         }
54
55         /**
56          * {@inheritDoc}
57          */
58         @Override
59         public void saveSone(Sone sone) throws DatabaseException {
60                 synchronized (sones) {
61                         Validation.begin().isNotNull("Sone", sone).check().is("Sone is an in-memory Sone", sones.containsKey(sone.getId())).check();
62                 }
63                 /* this is a no-op. */
64         }
65
66 }