1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.millscript.millscript.datatypes;
23
24 import org.millscript.commons.util.IMap;
25 import org.millscript.commons.util.IMapDefault;
26 import org.millscript.commons.util.alerts.InvalidKeyForMapAlert;
27 import org.millscript.commons.util.map.EHashMap;
28 import org.millscript.millscript.alert.Alerts;
29
30 /**
31 * This class implements a database record, which is map with restrictions on
32 * the type of keys allowed.
33 *
34 * @since 9.6.4
35 */
36 public final class DatabaseRecord extends EHashMap< Object, Object > {
37
38 /**
39 * This class provides a default action for a database record.
40 */
41 static final class DatabaseRecordDefault implements IMapDefault< Object, Object > {
42
43 /**
44 * Static instance of the database record default action, for use in
45 * any database record instance.
46 */
47 static final DatabaseRecordDefault DATABASERECORD_DEFAULT = new DatabaseRecordDefault();
48
49 /**
50 * @see org.millscript.commons.util.IMapDefault#get(java.lang.Object)
51 */
52 public Object get( final IMap map, final Object key ) {
53 if ( key instanceof String ) {
54 throw new InvalidKeyForMapAlert(
55 "Trying to access non-existent field in database record"
56 ).culprit( "field", key ).culprit( "record", map ).mishap();
57 } else {
58 throw new InvalidKeyForMapAlert(
59 "Database records can only be indexed by strings"
60 ).culprit( "key", key ).culprit( "record", map ).mishap();
61 }
62 }
63
64 }
65
66 /**
67 * This is the ID from the release 10.2.0 for future compatibility.
68 */
69 private static final long serialVersionUID = 3689912864207287605L;
70
71 /**
72 * This flag indicates if the record is locked. A locked record can only
73 * have new keys defined if they begin with "!"
74 */
75 private boolean locked = true;
76
77 /**
78 * Construct a new database record.
79 */
80 public DatabaseRecord() {
81 super();
82 super.setDefault( DatabaseRecordDefault.DATABASERECORD_DEFAULT );
83 }
84
85 /**
86 * Locks this database record.
87 */
88 public void lock() {
89 locked = true;
90 }
91
92 /**
93 * Unlocks this database record
94 */
95 public void unlock() {
96 locked = false;
97 }
98
99 /**
100 * Associates the supplied value with the supplied key, in this map.
101 *
102 * @param key the key
103 * @param value the value
104 * @return the value associated with the supplied key
105 */
106 @Override
107 public void insert( final Object key, final Object value ) {
108 if ( key instanceof String ) {
109 if ( key.toString().startsWith( "!" ) || !locked ) {
110 super.insert( key, value );
111 } else {
112 throw(
113 Alerts.eval(
114 "Only mappings with keys beginning with the '!' character may be modified in a database record",
115 null
116 ).culprit( "key", key ).mishap()
117 );
118 }
119 } else {
120 throw(
121 Alerts.eval(
122 "Keys of a record map must be strings",
123 null
124 ).culprit( "key", key ).mishap()
125 );
126 }
127 }
128
129 }