Skip to content

Ghidra is a software reverse engineering (SRE) framework

Added Json support to SaveState. Also added support for all the types used by options (File, Font, Keystroke, Date, Color). Also added support for values to be SaveStates so that values can be nested.

ghidravore5d592090144f
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java
index 400d48fdd0..a807afe6bb 100644
--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java
+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java
@@ -13,15 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-/*
- * (c) Copyright 2001 MyCorporation.
- * All Rights Reserved.
- */
package ghidra.framework.options;
import static org.junit.Assert.*;
+import java.awt.Color;
+import java.awt.Font;
import java.io.*;
+import java.util.Arrays;
+import java.util.Date;
+
+import javax.swing.KeyStroke;
import org.jdom.Document;
import org.jdom.Element;
@@ -30,30 +32,21 @@ import org.jdom.output.XMLOutputter;
import org.junit.Before;
import org.junit.Test;
+import com.google.gson.JsonObject;
+
import generic.test.AbstractGenericTest;
+import ghidra.app.plugin.core.overview.addresstype.AddressType;
+import ghidra.program.model.lang.Endian;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
-/**
- * @version 1.0
- *
- */
public class SaveStateTest extends AbstractGenericTest {
private SaveState ss;
- /**
- * Constructor for SaveStateTest.
- *
- * @param arg0
- */
- public SaveStateTest() {
- super();
- }
-
@Before
public void setUp() {
- ss = new SaveState();
+ ss = new SaveState("foo");
}
@Test
@@ -67,6 +60,103 @@ public class SaveStateTest extends AbstractGenericTest {
s = ss.getString(validKey, null);
assertNotNull(s);
+ SaveState restoredState = saveAndRestoreToXml();
+
+ String value = restoredState.getString(validKey, null);
+ assertNotNull(value);
+ }
+
+ @Test
+ public void testColor() throws Exception {
+ ss.putColor("TEST", Color.RED);
+ Color c = ss.getColor("TEST", null);
+ assertEquals(Color.RED, c);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ c = restoredState.getColor("TEST", null);
+ assertEquals(Color.RED, c);
+ }
+
+ @Test
+ public void testDate() throws Exception {
+ Date date = SaveState.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");
+ ss.putDate("TEST", date);
+ Date d = ss.getDate("TEST", null);
+ assertEquals(date, d);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ d = restoredState.getDate("TEST", null);
+ assertEquals(date, d);
+ }
+
+ @Test
+ public void testFile() throws Exception {
+ File file = createTempFile("myFile", "txt");
+ file.deleteOnExit();
+ ss.putFile("TEST", file);
+ File f = ss.getFile("TEST", null);
+ assertEquals(file, f);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ f = restoredState.getFile("TEST", null);
+ assertEquals(file, f);
+ }
+
+ @Test
+ public void testKeyStroke() throws Exception {
+ KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");
+ assertNotNull(keyStroke);
+
+ ss.putKeyStroke("TEST", keyStroke);
+ KeyStroke k = ss.getKeyStroke("TEST", null);
+ assertEquals(keyStroke, k);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ k = restoredState.getKeyStroke("TEST", null);
+ assertEquals(keyStroke, k);
+ }
+
+ @Test
+ public void testFont() throws Exception {
+ Font font = new Font("Times New Roman", Font.BOLD, 12);
+ ss.putFont("TEST", font);
+ Font f = ss.getFont("TEST", null);
+ assertEquals(font, f);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ f = restoredState.getFont("TEST", null);
+ assertEquals(font, f);
+ }
+
+ @Test
+ public void testSubSaveState() throws Exception {
+ SaveState subState = new SaveState("sub");
+ subState.putInt("a", 5);
+ subState.putString("foo", "bar");
+
+ ss.putSaveState("TEST", subState);
+ ss.putString("xxx", "zzzz");
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ assertEquals("zzzz", restoredState.getString("xxx", null));
+ SaveState restoredSub = restoredState.getSaveState("TEST");
+ assertEquals(2, restoredSub.getNames().length);
+ assertEquals(5, restoredSub.getInt("a", 0));
+ assertEquals("bar", restoredSub.getString("foo", ""));
+ }
+
+ private SaveState saveAndRestoreToXml() throws Exception {
// persist the state
File saveFileTemp = createTempFile("xmlTest");
Element element = ss.saveToXml();
@@ -76,13 +166,9 @@ public class SaveStateTest extends AbstractGenericTest {
InputStream is = new FileInputStream(saveFileTemp);
SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
Element root = sax.build(is).getRootElement();
-
- // make sure our value is inside
SaveState loadedState = new SaveState(root);
- String value = loadedState.getString(validKey, null);
- assertNotNull(value);
-
saveFileTemp.deleteOnExit();
+ return loadedState;
}
private void saveElement(Element element, File saveFile) throws Exception {
@@ -102,88 +188,118 @@ public class SaveStateTest extends AbstractGenericTest {
}
@Test
- public void testStringArray() {
+ public void testStringArray() throws Exception {
String[] array1 =
new String[] { "Dennis", "Bill", "Brian", "Mike", null, "Ellen", "Steve" };
+ String[] after =
+ new String[] { "Dennis", "Bill", "Brian", "Mike", "Ellen", "Steve" };
+
ss.putStrings("ARRAY", array1);
String[] array2 = ss.getStrings("ARRAY", null);
- for (int i = 0; i < array1.length; ++i) {
- assertEquals(array1[i], array2[i]);
- }
+
+ assertArrayEquals(array1, array2);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ assertArrayEquals(after, restoredState.getStrings("ARRAY", null));
}
@Test
- public void testByte() {
+ public void testByte() throws Exception {
ss.putByte("FOURTYTWO", (byte) 42);
assertTrue(ss.hasValue("FOURTYTWO"));
assertEquals((byte) 42, ss.getByte("FOURTYTWO", (byte) 0));
assertTrue(!ss.hasValue("XXX"));
assertEquals((byte) 5, ss.getByte("XXX", (byte) 5));
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals((byte) 42, restoredState.getByte(("FOURTYTWO"), (byte) 0));
}
@Test
- public void testByteArray() {
+ public void testByteArray() throws Exception {
byte[] array1 = new byte[] { (byte) 0, (byte) 5, (byte) 9, (byte) 42, (byte) 77 };
ss.putBytes("ARRAY", array1);
byte[] array2 = ss.getBytes("ARRAY", null);
- for (int i = 0; i < array1.length; ++i) {
- assertEquals(array1[i], array2[i]);
- }
+ assertArrayEquals(array1, array2);
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertArrayEquals(array1, restoredState.getBytes("ARRAY", null));
+
}
@Test
- public void testShort() {
+ public void testShort() throws Exception {
ss.putShort("FOURTYTWO", (short) 42);
assertTrue(ss.hasValue("FOURTYTWO"));
assertEquals((short) 42, ss.getShort("FOURTYTWO", (short) 0));
assertTrue(!ss.hasValue("XXX"));
assertEquals((short) 5, ss.getShort("XXX", (short) 5));
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals((short) 42, restoredState.getShort(("FOURTYTWO"), (short) 0));
}
@Test
- public void testInt() {
+ public void testInt() throws Exception {
ss.putInt("FOURTYTWO", 42);
assertTrue(ss.hasValue("FOURTYTWO"));
assertEquals(42, ss.getInt("FOURTYTWO", 0));
assertTrue(!ss.hasValue("XXX"));
assertEquals(5, ss.getInt("XXX", 5));
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals(42, restoredState.getInt(("FOURTYTWO"), 0));
}
@Test
- public void testIntArray() {
+ public void testIntArray() throws Exception {
int[] array1 = new int[] { 0, 5, 9, 42, 77 };
ss.putInts("ARRAY", array1);
int[] array2 = ss.getInts("ARRAY", null);
- for (int i = 0; i < array1.length; ++i) {
- assertEquals(array1[i], array2[i]);
- }
+ Arrays.equals(array1, array2);
+
+ SaveState restoredState = saveAndRestoreToXml();
+
+ // make sure our value is inside
+ int[] restoredArray = restoredState.getInts("ARRAY", null);
+ Arrays.equals(array1, restoredArray);
}
@Test
- public void testLong() {
+ public void testLong() throws Exception {
ss.putLong("FOURTYTWO", 42);
assertTrue(ss.hasValue("FOURTYTWO"));
assertEquals(42, ss.getLong("FOURTYTWO", 0));
assertTrue(!ss.hasValue("XXX"));
assertEquals(5, ss.getLong("XXX", 5));
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals(42L, restoredState.getLong(("FOURTYTWO"), 0));
}
@Test
- public void testFloat() {
+ public void testFloat() throws Exception {
ss.putFloat("PI", (float) 3.14159);
assertTrue(ss.hasValue("PI"));
assertEquals((float) 3.14159, ss.getFloat("PI", (float) 0.0), (float) 0.01);
assertTrue(!ss.hasValue("XXX"));
assertEquals(5, ss.getFloat("XXX", 5), (float) 0.01);
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals(3.14159, restoredState.getFloat(("PI"), 0), 0.001f);
}
@Test
- public void testDouble() {
+ public void testDouble() throws Exception {
ss.putDouble("PI", 3.14159);
assertTrue(ss.hasValue("PI"));
assertEquals(3.14159, ss.getDouble("PI", 0.0), 0.01);
assertTrue(!ss.hasValue("XXX"));
assertEquals(5, ss.getDouble("XXX", 5), 0.01);
+
+ SaveState restoredState = saveAndRestoreToXml();
+ assertEquals(3.14159, restoredState.getDouble(("PI"), 0), 0.000001);
}
@Test
@@ -295,4 +411,237 @@ public class SaveStateTest extends AbstractGenericTest {
assertEquals("Hey There", ss2.getString("S1", ""));
file.delete();
}
+
+ @Test
+ public void testJsonStringRoundTrip() {
+ ss.putString("foo", "Hey");
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals("Hey", restored.getString("foo", "there"));
+ }
+
+ @Test
+ public void testJsonColorRoundTrip() {
+ ss.putColor("foo", Color.BLUE);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(Color.BLUE, restored.getColor("foo", null));
+ }
+
+ @Test
+ public void testJsonDatRoundTrip() throws Exception {
+ Date date = SaveState.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");
+ ss.putDate("foo", date);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(date, restored.getDate("foo", null));
+ }
+
+ @Test
+ public void testJsonFileRoundTrip() throws IOException {
+ File file = createTempFile("myFile", "txt");
+ ss.putFile("foo", file);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(file, restored.getFile("foo", null));
+ file.deleteOnExit();
+ }
+
+ @Test
+ public void testJsonKeyStrokRoundTrip() {
+ KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");
+ assertNotNull(keyStroke);
+
+ ss.putKeyStroke("foo", keyStroke);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(keyStroke, restored.getKeyStroke("foo", null));
+ }
+
+ @Test
+ public void testJsonFontRoundTrip() {
+ Font font = new Font("Times New Roman", Font.BOLD, 12);
+ ss.putFont("foo", font);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(font, restored.getFont("foo", null));
+ }
+
+ @Test
+ public void testJsonSubSaveStateRoundTrip() {
+ SaveState subState = new SaveState("sub");
+ subState.putInt("a", 5);
+ subState.putString("foo", "bar");
+ ss.putSaveState("foo", subState);
+ ss.putString("bar", "xyz");
+
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals("xyz", restored.getString("bar", null));
+ SaveState restoredSub = restored.getSaveState("foo");
+ assertEquals(2, restoredSub.getNames().length);
+ assertEquals(5, restoredSub.getInt("a", 0));
+ assertEquals("bar", restoredSub.getString("foo", ""));
+ }
+
+ @Test
+ public void testJsonByteRoundTrip() {
+ ss.putByte("foo", (byte) 42);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals((byte) 42, restored.getByte("foo", (byte) 0));
+ }
+
+ @Test
+ public void testJsonShortRoundTrip() {
+ ss.putShort("foo", (short) 42);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals((short) 42, restored.getShort("foo", (short) 0));
+ }
+
+ @Test
+ public void testJsonIntRoundTrip() {
+ ss.putInt("foo", 123456789);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(123456789, restored.getInt("foo", 0));
+ }
+
+ @Test
+ public void testJsonLongRoundTrip() {
+ ss.putLong("foo", 12345678901234L);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(12345678901234L, restored.getLong("foo", 0));
+ }
+
+ @Test
+ public void testJsonFloatRoundTrip() {
+ ss.putFloat("foo", 12.123f);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(12.123f, restored.getFloat("foo", 0), 0.0001f);
+ }
+
+ @Test
+ public void testJsonDoubleRoundTrip() {
+ ss.putDouble("foo", 12.123456);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(12.123456, restored.getDouble("foo", 0), 0.00000001);
+ }
+
+ @Test
+ public void testJsonBooleanRoundTrip() {
+ ss.putBoolean("foo", true);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(true, restored.getBoolean("foo", false));
+ }
+
+ @Test
+ public void testJsonStringArrayRoundTrip() {
+ String[] strings = new String[] { "aaa", "bbb", null, "ccc" };
+ String[] after = new String[] { "aaa", "bbb", "ccc" };
+ ss.putStrings("foo", strings);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(after, restored.getStrings("foo", null));
+ }
+
+ @Test
+ public void testJsonByteArrayRoundTrip() {
+ byte[] bytes = new byte[] { (byte) 1, (byte) 2, (byte) 3 };
+ ss.putBytes("foo", bytes);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(bytes, restored.getBytes("foo", null));
+ }
+
+ @Test
+ public void testJsonShortArrayRoundTrip() {
+ short[] shorts = new short[] { (short) 1, (short) 2, (short) 3 };
+ ss.putShorts("foo", shorts);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(shorts, restored.getShorts("foo", null));
+ }
+
+ @Test
+ public void testJsonIntArrayRoundTrip() {
+ int[] ints = new int[] { 1, 2, 3, 4, 5 };
+ ss.putInts("foo", ints);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(ints, restored.getInts("foo", null));
+ }
+
+ @Test
+ public void testJsonLongArrayRoundTrip() {
+ long[] longs = new long[] { 1, 2, 3, 4, 5 };
+ ss.putLongs("foo", longs);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(longs, restored.getLongs("foo", null));
+ }
+
+ @Test
+ public void testJsonFloatArrayRoundTrip() {
+ float[] floats = new float[] { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f };
+ ss.putFloats("foo", floats);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(floats, restored.getFloats("foo", null), .1f);
+ }
+
+ @Test
+ public void testJsonDoubleArrayRoundTrip() {
+ double[] doubles = new double[] { 1.1, 2.2, 3.3, 4.4, 5.5 };
+ ss.putDoubles("foo", doubles);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(doubles, restored.getDoubles("foo", null), .1);
+ }
+
+ @Test
+ public void testJsonBooleanArrayRoundTrip() {
+ boolean[] booleans = new boolean[] { true, false, true, true, false };
+ ss.putBooleans("foo", booleans);
+ SaveState restored = jsonRoundTrip(ss);
+ assertArrayEquals(booleans, restored.getBooleans("foo", null));
+ }
+
+ @Test
+ public void testJsonEnumRoundTrip() {
+ ss.putEnum("foo", AddressType.FUNCTION);
+ SaveState restored = jsonRoundTrip(ss);
+ assertEquals(AddressType.FUNCTION, restored.getEnum("foo", null));
+ }
+
+ @Test
+ public void testJsonXmlRoundTrip() {
+ Element element = new Element("ABC");
+ element.setAttribute("AAA", "aaa");
+ element.setAttribute("BBB", "bbb");
+ element.setAttribute("CCC", "ccc");
+ ss.putXmlElement("Foo", element);
+ SaveState restored = jsonRoundTrip(ss);
+ Element restoredElement = restored.getXmlElement("Foo");
+ assertEquals("aaa", restoredElement.getAttributeValue("AAA"));
+ assertEquals("bbb", restoredElement.getAttributeValue("BBB"));
+ assertEquals("ccc", restoredElement.getAttributeValue("CCC"));
+ }
+
+ private SaveState jsonRoundTrip(SaveState saveState) {
+ JsonObject saveToJason = saveState.saveToJson();
+ return new SaveState(saveToJason);
+ }
+
+// private void printJson(SaveState saveState) {
+// JsonObject saveToJson = saveState.saveToJson();
+// Gson gson = new GsonBuilder().setPrettyPrinting().create();
+// System.out.println(gson.toJson(saveToJson));
+// }
+
+ @Test
+ public void testJsonFullRountTripThoughFile() throws IOException {
+ ss.putString("Name", "Bob");
+ ss.putBoolean("Retired", true);
+ ss.putInt("Age", 65);
+ ss.putEnum("Endian", Endian.BIG);
+ int[] ints = new int[] { 90, 95, 82, 93 };
+ ss.putInts("grades", ints);
+
+ File file = createTempFile("SaveStateTest", "json");
+ ss.saveToJsonFile(file);
+ SaveState restoredSaveState = SaveState.readJsonFile(file);
+
+ assertEquals("Bob", restoredSaveState.getString("Name", ""));
+ assertEquals(true, restoredSaveState.getBoolean("Retired", false));
+ assertEquals(65, restoredSaveState.getInt("Age", 0));
+ assertEquals(Endian.BIG, restoredSaveState.getEnum("Endian", Endian.LITTLE));
+ assertArrayEquals(ints, restoredSaveState.getInts("grades", null));
+
+ }
+
}
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java
index 0653810a2c..6abf44cc7f 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java
@@ -15,26 +15,35 @@
*/
package ghidra.framework.options;
+import java.awt.Color;
+import java.awt.Font;
import java.io.*;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
+import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
+import java.text.*;
import java.util.*;
+import javax.swing.KeyStroke;
+
import org.jdom.Element;
+import org.jdom.JDOMException;
+import org.jdom.output.XMLOutputter;
+
+import com.google.gson.*;
import ghidra.util.Msg;
import ghidra.util.NumericUtilities;
+import ghidra.util.exception.AssertException;
import ghidra.util.xml.XmlUtilities;
import utilities.util.FileUtilities;
/**
- * Class for saving values in "serializable safe" way. Classes that want to be
+ * Class for saving name/value pairs as XML or Json. Classes that want to be
* able to save their state can do so using the SaveState object.
* The idea is that each state variable in the class
* is first saved into a SaveState object via a String key. Then the SaveState
- * object is written out to an XML element. When the save state object is
- * to be restored, the saveState object is constructed with an XML Element
+ * object is written out as XML or Json. When the save state object is
+ * restored, the SaveState object is constructed with an XML Element or JsonObject
* that contains all of the name/value pairs. Since the "get" methods require
* a default value, the object that is recovering its state variables
* will be successfully initialized even if
@@ -42,14 +51,52 @@ import utilities.util.FileUtilities;
* <p> <i>Note: Names for options are assumed to be unique. When a putXXX()
* method is called, if a value already exists for a name, it will
* be overwritten.</i>
+ * <P>
+ * The SaveState supports the following types:
+ * <pre>
+ * java primitives
+ * arrays of java primitives
+ * String
+ * Color
+ * Font
+ * KeyStroke
+ * File
+ * Date
+ * Enum
+ * SaveState (values can be nested SaveStates)
+ * </pre>
*/
public class SaveState {
+ private static final String STATE = "STATE";
+ private static final String TYPE = "TYPE";
+ private static final String NAME = "NAME";
+ private static final String VALUE = "VALUE";
+ private static final String SAVE_STATE = "SAVE_STATE";
+ public static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
+ private static final String ARRAY_ELEMENT_NAME = "A";
private HashMap<String, Object> map;
private String saveStateName;
/**
- * Creates a new saveState object.
+ * Creates a SaveState object and populates its values from the given file. The file must
+ * conform to the format that is created with {@link #saveToJson()}
+ *
+ * @param file the file to load values from
+ * @return a new SaveState object loaded with values from the given file.
+ * @throws IOException if an error occurs reading the given file.
+ */
+ public static SaveState readJsonFile(File file) throws IOException {
+ try (Reader reader = new FileReader(file)) {
+ JsonElement element = JsonParser.parseReader(reader);
+ return new SaveState((JsonObject) element);
+ }
+ }
+
+ /**
+ * Creates a new SaveState object with a non-default name. The name serves no real purpose
+ * other than as a hint as to what the SaveState represents
+ *
* @param name of the state
*/
public SaveState(String name) {
@@ -63,7 +110,7 @@ public class SaveState {
* @see java.lang.Object#Object()
*/
public SaveState() {
- this("SAVE_STATE");
+ this(SAVE_STATE);
}
/**
@@ -86,9 +133,9 @@ public class SaveState {
while (iter.hasNext()) {
Element elem = (Element) iter.next();
String tag = elem.getName();
- String name = elem.getAttributeValue("NAME");
- String type = elem.getAttributeValue("TYPE");
- String value = elem.getAttributeValue("VALUE");
+ String name = elem.getAttributeValue(NAME);
+ String type = elem.getAttributeValue(TYPE);
+ String value = elem.getAttributeValue(VALUE);
if (tag.equals("XML")) {
map.put(name, elem.getChildren().get(0));
}
@@ -97,7 +144,7 @@ public class SaveState {
map.put(name, NumericUtilities.convertStringToBytes(value));
}
}
- else if (tag.equals("STATE")) {
+ else if (tag.equals(STATE)) {
try {
if (type == null) {
// skip this element
@@ -131,6 +178,21 @@ public class SaveState {
}
map.put(name, value);
}
+ else if (type.equals("Color")) {
+ map.put(name, new Color(Integer.valueOf(value)));
+ }
+ else if (type.equals("Date")) {
+ map.put(name, DATE_FORMAT.parse(value));
+ }
+ else if (type.equals("File")) {
+ map.put(name, new File(value));
+ }
+ else if (type.equals("KeyStroke")) {
+ map.put(name, KeyStroke.getKeyStroke(value));
+ }
+ else if (type.equals("Font")) {
+ map.put(name, Font.decode(value));
+ }
}
catch (Exception e) {
Msg.warn(this, "Error processing primitive value in saveState", e);
@@ -142,14 +204,14 @@ public class SaveState {
}
try {
- List<?> list = elem.getChildren("A");
+ List<?> list = elem.getChildren(ARRAY_ELEMENT_NAME);
Iterator<?> it = list.iterator();
int i = 0;
if (type.equals("short")) {
short[] vals = new short[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = Short.parseShort(e.getAttributeValue("VALUE"));
+ vals[i++] = Short.parseShort(e.getAttributeValue(VALUE));
}
map.put(name, vals);
}
@@ -157,7 +219,7 @@ public class SaveState {
int[] vals = new int[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = Integer.parseInt(e.getAttributeValue("VALUE"));
+ vals[i++] = Integer.parseInt(e.getAttributeValue(VALUE));
}
map.put(name, vals);
}
@@ -165,7 +227,7 @@ public class SaveState {
long[] vals = new long[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = Long.parseLong(e.getAttributeValue("VALUE"));
+ vals[i++] = Long.parseLong(e.getAttributeValue(VALUE));
}
map.put(name, vals);
}
@@ -173,7 +235,7 @@ public class SaveState {
float[] vals = new float[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = Float.parseFloat(e.getAttributeValue("VALUE"));
+ vals[i++] = Float.parseFloat(e.getAttributeValue(VALUE));
}
map.put(name, vals);
}
@@ -181,7 +243,7 @@ public class SaveState {
double[] vals = new double[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = Double.parseDouble(e.getAttributeValue("VALUE"));
+ vals[i++] = Double.parseDouble(e.getAttributeValue(VALUE));
}
map.put(name, vals);
}
@@ -190,7 +252,7 @@ public class SaveState {
while (it.hasNext()) {
Element e = (Element) it.next();
vals[i++] =
- Boolean.valueOf(e.getAttributeValue("VALUE")).booleanValue();
+ Boolean.valueOf(e.getAttributeValue(VALUE)).booleanValue();
}
map.put(name, vals);
}
@@ -198,7 +260,7 @@ public class SaveState {
String[] vals = new String[list.size()];
while (it.hasNext()) {
Element e = (Element) it.next();
- vals[i++] = e.getAttributeValue("VALUE");
+ vals[i++] = e.getAttributeValue(VALUE);
}
map.put(name, vals);
}
@@ -217,34 +279,173 @@ public class SaveState {
}
if (type.equals("enum")) {
String className = elem.getAttributeValue("CLASS");
- try {
- Class<?> enumClass = Class.forName(className).asSubclass(Enum.class);
-
- Method m = enumClass.getMethod("valueOf", new Class[] { String.class });
- if (m != null) {
- Enum<?> e = (Enum<?>) m.invoke(null, new Object[] { value });
- if (e != null) {
- map.put(name, e);
- }
- }
- }
- catch (Exception e) {
- Msg.warn(this, "Error processing enum class " + className, e);
+ Enum<?> e = getEnumValue(className, value);
+ if (e != null) {
+ map.put(name, e);
}
}
}
+ else if (tag.equals(SAVE_STATE)) {
+ Element element = (Element) elem.getChildren().get(0);
+ if (element != null) {
+ map.put(name, new SaveState(element));
+ }
+ }
else if (tag.equals("NULL")) {
map.put(name, null);
}
}
}
- /**
- * Save this object to an XML element.
- * @return Element XML element containing the state
- */
- public Element saveToXml() {
- return saveToXml(null);
+ protected SaveState(JsonObject root) {
+ map = new HashMap<>();
+ saveStateName = root.get("SAVE_STATE_NAME").getAsString();
+ JsonObject values = root.get("VALUES").getAsJsonObject();
+ JsonObject types = root.get("TYPES").getAsJsonObject();
+ JsonObject enumClasses = root.get("ENUM_CLASSES").getAsJsonObject();
+
+ for (String name : values.keySet()) {
+ String type = types.get(name).getAsString();
+ JsonElement valueElement = values.get(name);
+ JsonElement enumClass = enumClasses.get(name);
+ Object value = getObjectFromJson(type, valueElement, enumClass);
+ if (value != null) {
+ map.put(name, value);
+ }
+ }
+ }
+
+ private Object getObjectFromJson(String type, JsonElement value, JsonElement enumClass) {
+
+ switch (type) {
+ case "null":
+ return null;
+ case "String":
+ return value.getAsString();
+ case "Color":
+ return new Color(value.getAsInt());
+ case "Date":
+ return parseDate(value.getAsString());
+ case "File":
+ return new File(value.getAsString());
+ case "KeyStroke":
+ return KeyStroke.getKeyStroke(value.getAsString());
+ case "Font":
+ return Font.decode(value.getAsString());
+ case "byte":
+ return value.getAsByte();
+ case "short":
+ return value.getAsShort();
+ case "int":
+ return value.getAsInt();
+ case "long":
+ return value.getAsLong();
+ case "float":
+ return value.getAsFloat();
+ case "double":
+ return value.getAsDouble();
+ case "boolean":
+ return value.getAsBoolean();
+ case "byte[]":
+ JsonArray byteArray = value.getAsJsonArray();
+ byte[] bytes = new byte[byteArray.size()];
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = byteArray.get(i).getAsByte();
+ }
+ return bytes;
+ case "short[]":
+ JsonArray shortArray = value.getAsJsonArray();
+ short[] shorts = new short[shortArray.size()];
+ for (int i = 0; i < shorts.length; i++) {
+ shorts[i] = shortArray.get(i).getAsShort();
+ }
+ return shorts;
+ case "int[]":
+ JsonArray intArray = value.getAsJsonArray();
+ int[] ints = new int[intArray.size()];
+ for (int i = 0; i < ints.length; i++) {
+ ints[i] = intArray.get(i).getAsInt();
+ }
+ return ints;
+ case "long[]":
+ JsonArray longArray = value.getAsJsonArray();
+ long[] longs = new long[longArray.size()];
+ for (int i = 0; i < longs.length; i++) {
+ longs[i] = longArray.get(i).getAsLong();
+ }
+ return longs;
+ case "float[]":
+ JsonArray floatArray = value.getAsJsonArray();
+ float[] floats = new float[floatArray.size()];
+ for (int i = 0; i < floats.length; i++) {
+ floats[i] = floatArray.get(i).getAsFloat();
+ }
+ return floats;
+ case "double[]":
+ JsonArray doubleArray = value.getAsJsonArray();
+ double[] doubles = new double[doubleArray.size()];
+ for (int i = 0; i < doubles.length; i++) {
+ doubles[i] = doubleArray.get(i).getAsDouble();
+ }
+ return doubles;
+ case "boolean[]":
+ JsonArray boolArray = value.getAsJsonArray();
+ boolean[] booleans = new boolean[boolArray.size()];
+ for (int i = 0; i < booleans.length; i++) {
+ booleans[i] = boolArray.get(i).getAsBoolean();
+ }
+ return booleans;
+ case "String[]":
+ JsonArray stringArray = value.getAsJsonArray();
+ String[] strings = new String[stringArray.size()];
+ for (int i = 0; i < strings.length; i++) {
+ strings[i] = stringArray.get(i).getAsString();
+ }
+ return strings;
+ case "xml":
+ try {
+ return XmlUtilities.fromString(value.getAsString());
+ }
+ catch (JDOMException | IOException e) {
+ throw new AssertException("Error processing embedded XML");
+ }
+
+ case "enum":
+ String enumClassName = enumClass.getAsString();
+ String enumValue = value.getAsString();
+ return getEnumValue(enumClassName, enumValue);
+
+ case "SaveState":
+ JsonObject json = (JsonObject) value;
+ return new SaveState(json);
+
+ default:
+ throw new AssertException("Unknown type: " + type);
+ }
+ }
+
+ private Date parseDate(String dateString) {
+ try {
+ return DATE_FORMAT.parse(dateString);
+ }
+ catch (ParseException e) {
+ throw new AssertException("Can't parse date string: " + dateString);
+ }
+ }
+
+ Enum<?> getEnumValue(String enumClassName, String value) {
+ try {
+ Class<?> enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
+
+ Method m = enumClass.getMethod("valueOf", new Class[] { String.class });
+ if (m != null) {
+ return (Enum<?>) m.invoke(null, new Object[] { value });
+ }
+ }
+ catch (Exception e) {
+ Msg.warn(this, "Can't find field " + value + " in enum class " + enumClassName, e);
+ }
+ return null;
}
private static Element getXmlElementFromFile(File file) throws IOException {
@@ -259,188 +460,358 @@ public class SaveState {
* @throws IOException if the file could not be written
*/
public void saveToFile(File file) throws FileNotFoundException, IOException {
- Element saveToXml = saveToXml(null);
+ Element saveToXml = saveToXml();
byte[] bytes = XmlUtilities.xmlToByteArray(saveToXml);
FileUtilities.writeBytes(file, bytes);
}
+ /**
+ * Outputs this SaveState to a file using Json
+ * <P>
+ * For example, a SaveState that is created with:
+ * <pre>
+ * ss = new SaveState("foo")
+ * ss.putString("Name", "Bob");
+ * ss.putBoolean("Retired", true);
+ * ss.putInt("Age", 65);
+ * ss.putEnum("Endian", Endian.BIG);
+ *
+ * would produce a Json file with the following text
+ *
+ * {
+ * "SAVE STATE NAME": "foo",
+ * "VALUES": {
+ * "Name": "Bob"
+ * "Retired": true,
+ * "Age": 65,
+ * "Endian": "BIG",
+ * },
+ * "TYPES": {
+ * "Name": "String"
+ * "Retired": "boolean",
+ * "Age": "int",
+ * "Endian": "enum",
+ * },
+ * "ENUM CLASSES": {
+ * "Endian": "ghidra.program.model.lang.Endian"
+ * }
+ *}
+ * </pre>
+ *
+ * @param file the file to save to
+ * @throws IOException if an error occurs writing to the given file
+ */
+ public void saveToJsonFile(File file) throws IOException {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ JsonObject saveToJson = saveToJson();
+ try (FileWriter writer = new FileWriter(file)) {
+ writer.write(gson.toJson(saveToJson));
+ }
+ }
+
/**
* Save this object to an XML element.
- * Restrict child elements to the set specified.
- * @param restrictedSet restricted set of element names or null for all names
* @return Element XML element containing the state
*/
- public Element saveToXml(Set<String> restrictedSet) {
+ public Element saveToXml() {
Element root = new Element(saveStateName);
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
- if (restrictedSet != null && !restrictedSet.contains(key)) {
- continue;
- }
Object value = map.get(key);
Element elem = null;
if (value instanceof Element) {
elem = createElementFromElement(key, (Element) value);
}
else if (value instanceof Byte) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "byte");
- elem.setAttribute("VALUE", ((Byte) value).toString());
+ elem = setAttributes(key, "byte", ((Byte) value).toString());
}
else if (value instanceof Short) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "short");
- elem.setAttribute("VALUE", ((Short) value).toString());
+ elem = setAttributes(key, "short", ((Short) value).toString());
}
else if (value instanceof Integer) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "int");
- elem.setAttribute("VALUE", ((Integer) value).toString());
+ elem = setAttributes(key, "int", ((Integer) value).toString());
}
else if (value instanceof Long) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "long");
- elem.setAttribute("VALUE", ((Long) value).toString());
+ elem = setAttributes(key, "long", ((Long) value).toString());
}
else if (value instanceof Float) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "float");
- elem.setAttribute("VALUE", ((Float) value).toString());
+ elem = setAttributes(key, "float", ((Float) value).toString());
}
else if (value instanceof Double) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "double");
- elem.setAttribute("VALUE", ((Double) value).toString());
+ elem = setAttributes(key, "double", ((Double) value).toString());
}
else if (value instanceof Boolean) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "boolean");
- elem.setAttribute("VALUE", ((Boolean) value).toString());
+ elem = setAttributes(key, "boolean", ((Boolean) value).toString());
}
else if (value instanceof String) {
- elem = new Element("STATE");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "string");
+ elem = new Element(STATE);
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(TYPE, "string");
if (XmlUtilities.hasInvalidXMLCharacters((String) value)) {
elem.setAttribute("ENCODED_VALUE", NumericUtilities.convertBytesToString(
((String) value).getBytes(StandardCharsets.UTF_8)));
}
else {
- elem.setAttribute("VALUE", (String) value);
+ elem.setAttribute(VALUE, (String) value);
}
}
+ else if (value instanceof Color) {
+ elem = setAttributes(key, "Color", Integer.toString(((Color) value).getRGB()));
+ }
+ else if (value instanceof Date) {
+ elem = setAttributes(key, "Date", DATE_FORMAT.format((Date) value));
+ }
+ else if (value instanceof File) {
+ elem = setAttributes(key, "File", ((File) value).getAbsolutePath());
+ }
+ else if (value instanceof KeyStroke) {
+ elem = setAttributes(key, "KeyStroke", value.toString());
+ }
+ else if (value instanceof Font) {
+ elem =
+ setAttributes(key, "Font", OptionType.FONT_TYPE.convertObjectToString(value));
+ }
else if (value instanceof byte[]) {
elem = new Element("BYTES");
- elem.setAttribute("NAME", key);
- elem.setAttribute("VALUE", NumericUtilities.convertBytesToString((byte[]) value));
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(VALUE, NumericUtilities.convertBytesToString((byte[]) value));
+ }
+ else if (value instanceof short[]) {
+ elem = setArrayAttributes(key, "short", value);
+ }
+ else if (value instanceof int[]) {
+ elem = setArrayAttributes(key, "int", value);
+ }
+ else if (value instanceof long[]) {
+ elem = setArrayAttributes(key, "long", value);
+ }
+ else if (value instanceof float[]) {
+ elem = setArrayAttributes(key, "float", value);
+ }
+ else if (value instanceof double[]) {
+ elem = setArrayAttributes(key, "double", value);
+ }
+ else if (value instanceof boolean[]) {
+ elem = setArrayAttributes(key, "boolean", value);
+ }
+ else if (value instanceof String[]) {
+ elem = setArrayAttributes(key, "string", value);
+ }
+ else if (value instanceof Enum) {
+ Enum<?> e = (Enum<?>) value;
+ elem = new Element("ENUM");
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(TYPE, "enum");
+ elem.setAttribute("CLASS", e.getClass().getName());
+ elem.setAttribute(VALUE, e.name());
+ }
+ else if (value instanceof SaveState) {
+ Element element = ((SaveState) value).saveToXml();
+ elem = new Element(SAVE_STATE);
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(TYPE, "SaveState");
+ elem.addContent(element);
+ }
+ else {
+ elem = new Element("NULL");
+ elem.setAttribute(NAME, key);
+ }
+ root.addContent(elem);
+ }
+ return root;
+ }
+
+ private <T> Element setArrayAttributes(String key, String type, Object values) {
+ Element elem = new Element("ARRAY");
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(TYPE, type);
+ for (int i = 0; i < Array.getLength(values); i++) {
+ Object value = Array.get(values, i);
+ if (value != null) {
+ Element arrElem = new Element(ARRAY_ELEMENT_NAME);
+ arrElem.setAttribute(VALUE, value.toString());
+ elem.addContent(arrElem);
+ }
+ }
+ return elem;
+ }
+
+ private Element setAttributes(String key, String type, String value) {
+ Element elem;
+ elem = new Element(STATE);
+ elem.setAttribute(NAME, key);
+ elem.setAttribute(TYPE, type);
+ elem.setAttribute(VALUE, value);
+ return elem;
+ }
+
+ /**
+ * Save this object to an JsonObject
+ *
+ * @return JsonObject containing the state
+ */
+ public JsonObject saveToJson() {
+ JsonObject types = new JsonObject();
+ JsonObject values = new JsonObject();
+ JsonObject enumClasses = new JsonObject();
+ Iterator<String> iter = map.keySet().iterator();
+ while (iter.hasNext()) {
+ String key = iter.next();
+ Object value = map.get(key);
+ if (value == null) {
+ types.addProperty(key, "null");
+ values.addProperty(key, "null");
+ }
+ else if (value instanceof Element) {
+ types.addProperty(key, "xml");
+ String outputString = new XMLOutputter().outputString((Element) value);
+ values.addProperty(key, outputString);
+ }
+ else if (value instanceof Color) {
+ types.addProperty(key, "Color");
+ values.addProperty(key, ((Color) value).getRGB());
+ }
+ else if (value instanceof Date) {
+ types.addProperty(key, "Date");
+ values.addProperty(key, DATE_FORMAT.format((Date) value));
+ }
+ else if (value instanceof File) {
+ types.addProperty(key, "File");
+ values.addProperty(key, ((File) value).getAbsolutePath());
+ }
+ else if (value instanceof KeyStroke) {
+ types.addProperty(key, "KeyStroke");
+ values.addProperty(key, value.toString());
+ }
+ else if (value instanceof Font) {
+ types.addProperty(key, "Font");
+ values.addProperty(key, OptionType.FONT_TYPE.convertObjectToString(value));
+ }
+ else if (value instanceof Byte) {
+ types.addProperty(key, "byte");
+ values.addProperty(key, (Byte) value);
+ }
+ else if (value instanceof Short) {
+ types.addProperty(key, "short");
+ values.addProperty(key, (Short) value);
+ }
+ else if (value instanceof Integer) {
+ types.addProperty(key, "int");
+ values.addProperty(key, (Integer) value);
+ }
+ else if (value instanceof Long) {
+ types.addProperty(key, "long");
+ values.addProperty(key, (Long) value);
+ }
+ else if (value instanceof Float) {
+ types.addProperty(key, "float");
+ values.addProperty(key, (Float) value);
+ }
+ else if (value instanceof Double) {
+ types.addProperty(key, "double");
+ values.addProperty(key, (Double) value);
+ }
+ else if (value instanceof Boolean) {
+ types.addProperty(key, "boolean");
+ values.addProperty(key, (Boolean) value);
+ }
+ else if (value instanceof String) {
+ types.addProperty(key, "String");
+ values.addProperty(key, (String) value);
+ }
+ else if (value instanceof byte[]) {
+ JsonArray ja = new JsonArray();
+ for (byte b : (byte[]) value) {
+ ja.add(b);
+ }
+ types.addProperty(key, "byte[]");
+ values.add(key, ja);
}
else if (value instanceof short[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "short");
- short[] arr = (short[]) value;
- for (short element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (short s : (short[]) value) {
+ ja.add(s);
}
+ types.addProperty(key, "short[]");
+ values.add(key, ja);
}
else if (value instanceof int[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "int");
- int[] arr = (int[]) value;
- for (int element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (int i : (int[]) value) {
+ ja.add(i);
}
+ types.addProperty(key, "int[]");
+ values.add(key, ja);
}
else if (value instanceof long[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "long");
- long[] arr = (long[]) value;
- for (long element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (long i : (long[]) value) {
+ ja.add(i);
}
+ types.addProperty(key, "long[]");
+ values.add(key, ja);
}
else if (value instanceof float[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "float");
- float[] arr = (float[]) value;
- for (float element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (float f : (float[]) value) {
+ ja.add(f);
}
+ types.addProperty(key, "float[]");
+ values.add(key, ja);
}
else if (value instanceof double[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "double");
- double[] arr = (double[]) value;
- for (double element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (double f : (double[]) value) {
+ ja.add(f);
}
+ types.addProperty(key, "double[]");
+ values.add(key, ja);
}
else if (value instanceof boolean[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "boolean");
- boolean[] arr = (boolean[]) value;
- for (boolean element : arr) {
- Element arrElem = new Element("A");
- arrElem.setAttribute("VALUE", "" + element);
- elem.addContent(arrElem);
+ JsonArray ja = new JsonArray();
+ for (boolean b : (boolean[]) value) {
+ ja.add(b);
}
+ types.addProperty(key, "boolean[]");
+ values.add(key, ja);
}
else if (value instanceof String[]) {
- elem = new Element("ARRAY");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "string");
- String[] arr = (String[]) value;
- for (String element : arr) {
- Element arrElem = new Element("A");
- if (element != null) {
- arrElem.setAttribute("VALUE", element);
+ JsonArray ja = new JsonArray();
+ for (String s : (String[]) value) {
+ if (s != null) {
+ ja.add(s);
}
- elem.addContent(arrElem);
}
+ types.addProperty(key, "String[]");
+ values.add(key, ja);
}
else if (value instanceof Enum) {
Enum<?> e = (Enum<?>) value;
- elem = new Element("ENUM");
- elem.setAttribute("NAME", key);
- elem.setAttribute("TYPE", "enum");
- elem.setAttribute("CLASS", e.getClass().getName());
- elem.setAttribute("VALUE", e.name());
+ types.addProperty(key, "enum");
+ enumClasses.addProperty(key, e.getClass().getName());
+ values.addProperty(key, e.name());
+ }
+ else if (value instanceof SaveState) {
+ types.addProperty(key, "SaveState");
+ JsonObject json = ((SaveState) value).saveToJson();
+ values.add(key, json);
}
else {
- elem = new Element("NULL");
- elem.setAttribute("NAME", key);
+ throw new AssertException("found unsupported object type: " + value.getClass());
}
- root.addContent(elem);
}
- return root;
+ JsonObject jsonObject = new JsonObject();
+ jsonObject.addProperty("SAVE_STATE_NAME", saveStateName);
+ jsonObject.add("VALUES", values);
+ jsonObject.add("TYPES", types);
+ jsonObject.add("ENUM_CLASSES", enumClasses);
+ return jsonObject;
}
protected Element createElementFromElement(String internalKey, Element internalElement) {
Element newElement = new Element("XML");
- newElement.setAttribute("NAME", internalKey);
+ newElement.setAttribute(NAME, internalKey);
Element internalElementClone = (Element) internalElement.clone();
newElement.addContent(internalElementClone);
@@ -449,14 +820,17 @@ public class SaveState {
}
/**
- * Return whether anything was added to this save state.
+ * Returns true if this list contains no elements
+ * @return true if there are no properties in this save state
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
- * Remove the object identified by the given name.
+ * Remove the object identified by the given name
+ *
+ * @param name the name of the property to remove
*/
public void remove(String name) {
map.remove(name);
@@ -470,7 +844,8 @@ public class SaveState {
}
/**
- * Return the number of objects in the save state.
+ * Return the number of properties in the save state
+ * @return The number of properties in the save state
*/
public int size() {
return map.size();
@@ -510,7 +885,7 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putInt(String name, int value) {
- map.put(name, new Integer(value));
+ map.put(name, Integer.valueOf(value));
}
/**
@@ -519,7 +894,7 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putByte(String name, byte value) {
- map.put(name, new Byte(value));
+ map.put(name, Byte.valueOf(value));
}
/**
@@ -528,7 +903,7 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putShort(String name, short value) {
- map.put(name, new Short(value));
+ map.put(name, Short.valueOf(value));
}
/**
@@ -537,7 +912,7 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putLong(String name, long value) {
- map.put(name, new Long(value));
+ map.put(name, Long.valueOf(value));
}
/**
@@ -549,13 +924,58 @@ public class SaveState {
map.put(name, value);
}
+ /**
+ * Associates a Color value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putColor(String name, Color value) {
+ map.put(name, value);
+ }
+
+ /**
+ * Associates a Date value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putDate(String name, Date value) {
+ map.put(name, value);
+ }
+
+ /**
+ * Associates a File value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putFile(String name, File value) {
+ map.put(name, value);
+ }
+
+ /**
+ * Associates a KeyStroke value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putKeyStroke(String name, KeyStroke value) {
+ map.put(name, value);
+ }
+
+ /**
+ * Associates a Font value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putFont(String name, Font value) {
+ map.put(name, value);
+ }
+
/**
* Associates a boolean value with the given name.
* @param name The name in the name,value pair.
* @param value The value in the name,value pair.
*/
public void putBoolean(String name, boolean value) {
- map.put(name, new Boolean(value));
+ map.put(name, Boolean.valueOf(value));
}
/**
@@ -564,7 +984,7 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putFloat(String name, float value) {
- map.put(name, new Float(value));
+ map.put(name, Float.valueOf(value));
}
/**
@@ -573,7 +993,16 @@ public class SaveState {
* @param value The value in the name,value pair.
*/
public void putDouble(String name, double value) {
- map.put(name, new Double(value));
+ map.put(name, Double.valueOf(value));
+ }
+
+ /**
+ * Associates a sub SaveState value with the given name.
+ * @param name The name in the name,value pair.
+ * @param value The value in the name,value pair.
+ */
+ public void putSaveState(String name, SaveState value) {
+ map.put(name, value);
}
/**
@@ -585,16 +1014,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public int getInt(String name, int defaultValue) {
- try {
- Integer val = (Integer) map.get(name);
- if (val != null) {
- return val.intValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Integer.class);
}
/**
@@ -606,16 +1026,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public byte getByte(String name, byte defaultValue) {
- try {
- Byte val = (Byte) map.get(name);
- if (val != null) {
- return val.byteValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Byte.class);
}
/**
@@ -627,16 +1038,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public short getShort(String name, short defaultValue) {
- try {
- Short val = (Short) map.get(name);
- if (val != null) {
- return val.shortValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Short.class);
}
/**
@@ -648,16 +1050,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public long getLong(String name, long defaultValue) {
- try {
- Long val = (Long) map.get(name);
- if (val != null) {
- return val.longValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Long.class);
}
/**
@@ -669,16 +1062,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public boolean getBoolean(String name, boolean defaultValue) {
- try {
- Boolean val = (Boolean) map.get(name);
- if (val != null) {
- return val.booleanValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Boolean.class);
}
/**
@@ -690,13 +1074,67 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public String getString(String name, String defaultValue) {
- try {
- return map.containsKey(name) ? (String) map.get(name) : defaultValue;
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- return defaultValue;
- }
+ return getAsType(name, defaultValue, String.class);
+ }
+
+ /**
+ * Gets the Color value for the given name.
+ * @param name the name of the pair.
+ * @param defaultValue the default value to be returned if the name does
+ * not exist in the map, or it does not contain the proper object type.
+ * @return the Color value associated with the given name or the defaultValue
+ * passed in if the name doesn't exist or is the wrong type.
+ */
+ public Color getColor(String name, Color defaultValue) {
+ return getAsType(name, defaultValue, Color.class);
+ }
+
+ /**
+ * Gets the Date value for the given name.
+ * @param name the name of the pair.
+ * @param defaultValue the default value to be returned if the name does
+ * not exist in the map, or it does not contain the proper object type.
+ * @return the Date value associated with the given name or the defaultValue
+ * passed in if the name doesn't exist or is the wrong type.
+ */
+ public Date getDate(String name, Date defaultValue) {
+ return getAsType(name, defaultValue, Date.class);
+ }
+
+ /**
+ * Gets the File value for the given name.
+ * @param name the name of the pair.
+ * @param defaultValue the default value to be returned if the name does
+ * not exist in the map, or it does not contain the proper object type.
+ * @return the File value associated with the given name or the defaultValue
+ * passed in if the name doesn't exist or is the wrong type.
+ */
+ public File getFile(String name, File defaultValue) {
+ return getAsType(name, defaultValue, File.class);
+ }
+
+ /**
+ * Gets the KeyStroke value for the given name.
+ * @param name the name of the pair.
+ * @param defaultValue the default value to be returned if the name does
+ * not exist in the map, or it does not contain the proper object type.
+ * @return the KeyStroke value associated with the given name or the defaultValue
+ * passed in if the name doesn't exist or is the wrong type.
+ */
+ public KeyStroke getKeyStroke(String name, KeyStroke defaultValue) {
+ return getAsType(name, defaultValue, KeyStroke.class);
+ }
+
+ /**
+ * Gets the Font value for the given name.
+ * @param name the name of the pair.
+ * @param defaultValue the default value to be returned if the name does
+ * not exist in the map, or it does not contain the proper object type.
+ * @return the Font value associated with the given name or the defaultValue
+ * passed in if the name doesn't exist or is the wrong type.
+ */
+ public Font getFont(String name, Font defaultValue) {
+ return getAsType(name, defaultValue, Font.class);
}
/**
@@ -708,16 +1146,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public float getFloat(String name, float defaultValue) {
- try {
- Float val = (Float) map.get(name);
- if (val != null) {
- return val.floatValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Float.class);
}
/**
@@ -729,16 +1158,7 @@ public class SaveState {
* passed in if the name doesn't exist or is the wrong type.
*/
public double getDouble(String name, double defaultValue) {
- try {
- Double val = (Double) map.get(name);
- if (val != null) {
- return val.doubleValue();
- }
- }
- catch (Exception e) {
- Msg.debug(this, "Two different types for option name: " + name);
- }
- return defaultValue;
+ return getAsType(name, defaultValue, Double.class);
}
/**
@@ -948,7 +1368,10 @@ public class SaveState {
}
/**
- * Returns true if the SaveState object has a value for the given name.
+ * Returns true if there is a value for the given name
+ *
+ * @param name true the name of the property to check for a value
+ * @return true if the SaveState object has a value for the given name
*/
public boolean hasValue(String name) {
return map.containsKey(name);
@@ -974,12 +1397,40 @@ public class SaveState {
* given name.
*/
public Element getXmlElement(String name) {
- try {
- return (Element) map.get(name);
+ return getAsType(name, null, Element.class);
+ }
+
+ /**
+ * Returns the sub SaveState associated with the
+ * given name.
+ * @param name The name associated with the desired Element.
+ * @return The SaveState object associated with the
+ * given name.
+ */
+ public SaveState getSaveState(String name) {
+ return getAsType(name, null, SaveState.class);
+ }
+
+ private <T> T getAsType(String name, T defaultValue, Class<T> clazz) {
+ if (map.containsKey(name)) {
+ Object value = map.get(name);
+ if (isExpectedType(name, value, clazz)) {
+ return clazz.cast(value);
+ }
}
- catch (Exception exc) {
- Msg.debug(this, "Two different types for option name: " + name);
+ return defaultValue;
+
+ }
+
+ private boolean isExpectedType(String name, Object value, Class<?> expectedType) {
+ if (value != null && !expectedType.isInstance(value)) {
+ Msg.debug(this,
+ "Type mismatch on saveState property \"" + name +
+ "\". Attempted to retrieve value as a " + expectedType.getName() +
+ " but was of type " + value.getClass().getName());
+ return false;
}
- return null;
+ return true;
}
+
}