100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Forked elemental JSON, now custom value model
Christian Bauerd70cf02c5637
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex 618f4b897..04a9e5499 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import org.openremote.container.json.ElementalJsonModule;import org.openremote.container.concurrent.ContainerThreads;+import org.openremote.container.json.ModelValueModule;import org.openremote.container.util.LogUtil;import java.util.*;@@ -68,6 +69,7 @@ public class Container {.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE)+ .registerModule(new ModelValueModule()).registerModule(new ElementalJsonModule());protected final Map<String, String> config = new HashMap<>();diff --git a/container/src/main/java/org/openremote/container/json/ModelValueModule.java b/container/src/main/java/org/openremote/container/json/ModelValueModule.javanew file mode 100644index 000000000..8c2ee491c--- /dev/null+++ b/container/src/main/java/org/openremote/container/json/ModelValueModule.java@@ -0,0 +1,75 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.container.json;++import com.fasterxml.jackson.core.JsonGenerator;+import com.fasterxml.jackson.core.JsonParser;+import com.fasterxml.jackson.core.Version;+import com.fasterxml.jackson.databind.DeserializationContext;+import com.fasterxml.jackson.databind.JsonSerializer;+import com.fasterxml.jackson.databind.SerializerProvider;+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;+import com.fasterxml.jackson.databind.module.SimpleModule;+import org.openremote.model.value.*;++import java.io.IOException;++public class ModelValueModule extends SimpleModule {++ private static class ValueJsonDeserializer<T extends Value> extends StdDeserializer<T> {++ public ValueJsonDeserializer() {+ super(Value.class);+ }++ @SuppressWarnings("unchecked")+ @Override+ public T deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {+ return (T) Values.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString());+ }+ }++ private static class ValueJsonSerializer extends JsonSerializer<Value> {+ @Override+ public void serialize(Value value, JsonGenerator gen, SerializerProvider serializers) throws IOException {+ if (value == null)+ return;+ if (value instanceof Null) {+ gen.writeNull();+ } else {+ gen.writeRawValue(value.toJson());+ }+ }+ }++ @SuppressWarnings("unchecked")+ public ModelValueModule() {+ super("ModelValueModule", new Version(1, 0, 0, "latest", null, null));+ ValueJsonSerializer serializer = new ValueJsonSerializer();+ ValueJsonDeserializer deserializer = new ValueJsonDeserializer();+ this.addSerializer(Value.class, serializer);+ this.addDeserializer(ObjectValue.class, deserializer);+ this.addDeserializer(ArrayValue.class, deserializer);+ this.addDeserializer(Null.class, deserializer);+ this.addDeserializer(StringValue.class, deserializer);+ this.addDeserializer(NumberValue.class, deserializer);+ this.addDeserializer(BooleanValue.class, deserializer);+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueDeserializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueDeserializer.javanew file mode 100644index 000000000..8560d01e6--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueDeserializer.java@@ -0,0 +1,43 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.client.interop.jackson;++import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;+import com.github.nmorel.gwtjackson.client.JsonDeserializer;+import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;+import com.github.nmorel.gwtjackson.client.stream.JsonReader;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueException;+import org.openremote.model.value.Values;++public class ModelValueDeserializer extends JsonDeserializer<Value> {++ @Override+ protected Value doDeserialize(JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params) {+ if (reader.hasNext()) {+ try {+ return Values.parse(reader.nextValue());+ } catch (ValueException ex) {+ throw new RuntimeException(ex);+ }+ }+ return null;+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueSerializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueSerializer.javanew file mode 100644index 000000000..fbe5793f0--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ModelValueSerializer.java@@ -0,0 +1,40 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.client.interop.jackson;++import com.github.nmorel.gwtjackson.client.JsonSerializationContext;+import com.github.nmorel.gwtjackson.client.JsonSerializer;+import com.github.nmorel.gwtjackson.client.JsonSerializerParameters;+import com.github.nmorel.gwtjackson.client.stream.JsonWriter;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueException;++public class ModelValueSerializer extends JsonSerializer<Value> {++ @Override+ protected void doSerialize(JsonWriter writer, Value value, JsonSerializationContext ctx, JsonSerializerParameters params) {+ try {+ writer.rawValue(value.toJson());+ } catch (ValueException ex) {+ throw new RuntimeException(ex);+ }+ }++}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.javaindex 40c99be30..59d80548b 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java@@ -22,7 +22,11 @@ package org.openremote.manager.client.interop.jackson;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.github.nmorel.gwtjackson.client.AbstractConfiguration;import elemental.json.*;+import org.openremote.model.value.*;+/**+ * Restart super-dev server after modifying this class!+ */public class SerializationConfiguration extends AbstractConfiguration {@Override@@ -32,6 +36,15 @@ public class SerializationConfiguration extends AbstractConfiguration {setterVisibility(JsonAutoDetect.Visibility.NONE);isGetterVisibility(JsonAutoDetect.Visibility.NONE);creatorVisibility(JsonAutoDetect.Visibility.NONE);+ type(Value.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(ObjectValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(ArrayValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(Null.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(NumberValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(StringValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);+ type(BooleanValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);++ // TODO remove elemental jsontype(JsonObject.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);type(JsonArray.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);type(JsonValue.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);@@ -39,5 +52,6 @@ public class SerializationConfiguration extends AbstractConfiguration {type(JsonNumber.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);type(JsonString.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);type(JsonBoolean.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);+}}diff --git a/manager/test/src/test/groovy/org/openremote/test/model/ModelValueTest.groovy b/manager/test/src/test/groovy/org/openremote/test/model/ModelValueTest.groovynew file mode 100644index 000000000..5451c2e43--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/model/ModelValueTest.groovy@@ -0,0 +1,172 @@+package org.openremote.test.model++import org.openremote.model.value.ArrayValue+import org.openremote.model.value.ObjectValue+import org.openremote.model.value.Values+import spock.lang.Specification++class ModelValueTest extends Specification {++ def "Read and write JSON"() {+ expect:+ ObjectValue sampleObject1 = Values.createObject()+ sampleObject1.put("object1A", "O1-AAA")+ sampleObject1.put("object1B", 456)++ ArrayValue sampleArray1 = Values.createArray()+ sampleArray1.set(0, "A0")+ sampleArray1.set(1, "A1")+ sampleArray1.set(2, true)+ sampleArray1.set(3, 123.45)+ sampleArray1.set(4, sampleObject1)++ String json = sampleArray1.toJson()+ ArrayValue value = Values.parse(json)+ value == sampleArray1+ }++ def "Compare scalar values"() {+ expect:+ Values.create(true) == Values.create(true)+ Values.create(true).hashCode() == Values.create(true).hashCode()++ Values.create(false) != Values.create(true)+ Values.create(false).hashCode() != Values.create(true).hashCode()++ Values.create(true) != Values.create(false)+ Values.create(true).hashCode() != Values.create(false).hashCode()++ Values.create(123) != Values.create(false)+ Values.create(123).hashCode() != Values.create(false).hashCode()++ Values.create(0) != Values.create(false)+ Values.create(0).hashCode() != Values.create(false).hashCode()++ Values.create(1) != Values.create(true)+ Values.create(1).hashCode() != Values.create(true).hashCode()++ Values.createNull() == Values.createNull()+ Values.createNull().hashCode() == Values.createNull().hashCode()++ Values.createNull() != Values.create(123)+ Values.createNull().hashCode() != Values.create(123).hashCode()++ Values.createNull() != Values.create(false)+ Values.createNull().hashCode() != Values.create(false).hashCode()++ Values.createNull() != Values.create(true)+ Values.createNull().hashCode() != Values.create(true).hashCode()++ Values.createNull() != Values.create("abc")+ Values.createNull().hashCode() != Values.create("abc").hashCode()++ Values.create(123) == Values.create(123)+ Values.create(123).hashCode() == Values.create(123).hashCode()++ Values.create(123) != Values.create(456)+ Values.create(123).hashCode() != Values.create(456).hashCode()++ Values.create(456) != Values.create(123)+ Values.create(456).hashCode() != Values.create(123).hashCode()++ Values.create(0) != Values.create("")+ Values.create(0).hashCode() != Values.create("").hashCode()++ Values.create("abc") == Values.create("abc")+ Values.create("abc").hashCode() == Values.create("abc").hashCode()++ Values.create("abcd") != Values.create("abc")+ Values.create("abcd").hashCode() != Values.create("abc").hashCode()++ Values.create("abc") != Values.create("abcd")+ Values.create("abc").hashCode() != Values.create("abcd").hashCode()++ Values.create("abc") != Values.createNull()+ Values.create("abc").hashCode() != Values.createNull().hashCode()++ Values.create("abc") != Values.create(123)+ Values.create("abc").hashCode() != Values.create(123).hashCode()++ Values.create("") != Values.create(0)+ Values.create("").hashCode() != Values.create(0).hashCode()+ }++ def "Compare non-scalar Json values"() {++ given:+ ObjectValue sampleObject1 = Values.createObject()+ sampleObject1.put("object1A", "O1-AAA")+ sampleObject1.put("object1B", 456)++ ObjectValue sampleObject2 = Values.createObject()+ sampleObject2.put("object2A", "O2-AAA")+ sampleObject2.put("object2B", 789)++ ArrayValue sampleArray1 = Values.createArray()+ sampleArray1.set(0, "A0")+ sampleArray1.set(1, "A1")+ sampleArray1.set(2, sampleObject1)++ ArrayValue sampleArray2 = Values.createArray()+ sampleArray1.set(0, sampleObject1)+ sampleArray1.set(1, "A1")+ sampleArray1.set(2, "A0")++ expect: "Array equality comparisons to be correct"+ Values.createArray() == Values.createArray()+ Values.createArray().hashCode() == Values.createArray().hashCode()++ Values.createArray() != Values.createNull()+ Values.createArray().hashCode() != Values.createNull().hashCode()++ sampleArray1 == sampleArray1+ sampleArray1.hashCode() == sampleArray1.hashCode()++ sampleArray2 != sampleArray1+ sampleArray2.hashCode() != sampleArray1.hashCode()++ sampleArray1 != sampleArray2+ sampleArray1.hashCode() != sampleArray2.hashCode()++ and: "Objects with no fields to be equal"+ Values.createObject() == Values.createObject()+ Values.createObject().hashCode() == Values.createObject().hashCode()++ Values.createNull() != Values.createObject()+ Values.createNull().hashCode() != Values.createObject().hashCode()++ Values.createArray() != Values.createObject()+ Values.createArray().hashCode() != Values.createObject().hashCode()++ and: "Objects with the same fields to be equal"+ ObjectValue sameFields1 = Values.createObject()+ sameFields1.put("fieldA", "AAA")+ sameFields1.put("fieldB", 123)+ sameFields1.put("fieldC", true)+ sameFields1.put("fieldD", sampleArray1)+ ObjectValue sameFields2 = Values.createObject()+ sameFields2.put("fieldD", sampleArray1)+ sameFields2.put("fieldC", true)+ sameFields2.put("fieldB", 123)+ sameFields2.put("fieldA", "AAA")+ sameFields1 == sameFields2+ sameFields1.hashCode() == sameFields2.hashCode()++ and: "Objects with the different fields to be not equal"+ ObjectValue otherFields1 = Values.createObject()+ otherFields1.put("fieldA", "AAA")+ ObjectValue otherFields2 = Values.createObject()+ otherFields2.put("fieldB", 123)+ otherFields1 != otherFields2+ otherFields1.hashCode() != otherFields2.hashCode()++ and: "Objects with the different field values to be not equal"+ ObjectValue differentValues1 = Values.createObject()+ differentValues1.put("fieldA", "AAA")+ ObjectValue differentValues2 = Values.createObject()+ differentValues2.put("fieldA", "AAAAA")+ differentValues1 != differentValues2+ differentValues1.hashCode() != differentValues2.hashCode()+ }++}diff --git a/model/src/main/java/org/openremote/model/value/ArrayValue.java b/model/src/main/java/org/openremote/model/value/ArrayValue.javanew file mode 100644index 000000000..33ad405f9--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ArrayValue.java@@ -0,0 +1,84 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++public interface ArrayValue extends Value {++ /**+ * Return the ith element of the array.+ */+ <T extends Value> T get(int index);++ /**+ * Return the ith element of the array (uncoerced). If the type is not an array,+ * this can result in runtime errors.+ */+ ArrayValue getArray(int index);++ /**+ * Return the ith element of the array (uncoerced). If the type is not a boolean,+ * this can result in runtime errors.+ */+ boolean getBoolean(int index);++ /**+ * Return the ith element of the array (uncoerced). If the type is not a number, this+ * can result in runtime errors.+ */+ double getNumber(int index);++ /**+ * Return the ith element of the array (uncoerced). If the type is not an object,,+ * this can result in runtime errors.+ */+ ObjectValue getObject(int index);++ /**+ * Return the ith element of the array (uncoerced). If the type is not a String, this+ * can result in runtime errors.+ */+ String getString(int index);++ /**+ * Length of the array.+ */+ int length();++ /**+ * Remove an element of the array at a particular index.+ */+ void remove(int index);++ /**+ * Set the value at index to be a given value.+ */+ void set(int index, Value value);++ /**+ * Set the value at index to be a String value.+ */+ void set(int index, String string);++ /**+ * Set the value at index to be a number value.+ */+ void set(int index, double number);++ /**+ * Set the value at index to be a boolean value.+ */+ void set(int index, boolean bool);+}diff --git a/model/src/main/java/org/openremote/model/value/BooleanValue.java b/model/src/main/java/org/openremote/model/value/BooleanValue.javanew file mode 100644index 000000000..a65fa8ba5--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/BooleanValue.java@@ -0,0 +1,21 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++public interface BooleanValue extends Value {++ boolean getBoolean();+}diff --git a/model/src/main/java/org/openremote/model/value/Null.java b/model/src/main/java/org/openremote/model/value/Null.javanew file mode 100644index 000000000..2b146d6c9--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/Null.java@@ -0,0 +1,19 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++public interface Null extends Value {+}diff --git a/model/src/main/java/org/openremote/model/value/NumberValue.java b/model/src/main/java/org/openremote/model/value/NumberValue.javanew file mode 100644index 000000000..ac6ea4931--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/NumberValue.java@@ -0,0 +1,21 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++public interface NumberValue extends Value {++ double getNumber();+}diff --git a/model/src/main/java/org/openremote/model/value/ObjectValue.java b/model/src/main/java/org/openremote/model/value/ObjectValue.javanew file mode 100644index 000000000..1dee7d2da--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ObjectValue.java@@ -0,0 +1,96 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++/**+ * Object values can not have duplicate keys. For equality operations, objects+ * are equal if their key sets are equal and each key has the same value in both+ * instances.+ */+public interface ObjectValue extends Value {++ /**+ * Return the element (uncoerced).+ */+ <T extends Value> T get(String key);++ /**+ * Return the element (uncoerced) as a JsonArray. If the type is not an array,+ * this can result in runtime errors.+ */+ ArrayValue getArray(String key);++ /**+ * Return the element (uncoerced) as a boolean. If the type is not a boolean,+ * this can result in runtime errors.+ */+ boolean getBoolean(String key);++ /**+ * Return the element (uncoerced) as a number. If the type is not a number, this+ * can result in runtime errors.+ */+ double getNumber(String key);++ /**+ * Return the element (uncoerced) as a JsonObject If the type is not an object,,+ * this can result in runtime errors.+ */+ ObjectValue getObject(String key);++ /**+ * Return the element (uncoerced) as a String. If the type is not a String, this+ * can result in runtime errors.+ */+ String getString(String key);++ /**+ * All keys of the object.+ */+ String[] keys();++ /**+ * Set a given key to the given value.+ */+ void put(String key, Value value);++ /**+ * Set a given key to the given String value.+ */+ void put(String key, String value);++ /**+ * Set a given key to the given double value.+ */+ void put(String key, double value);++ /**+ * Set a given key to the given boolean value.+ */+ void put(String key, boolean bool);++ /**+ * Test whether a given key has present.+ */+ boolean hasKey(String key);++ /**+ * Remove a given key and associated value from the object.+ *+ * @param key+ */+ void remove(String key);+}diff --git a/model/src/main/java/org/openremote/model/value/StringValue.java b/model/src/main/java/org/openremote/model/value/StringValue.javanew file mode 100644index 000000000..2bc065794--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/StringValue.java@@ -0,0 +1,21 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++public interface StringValue extends Value {++ String getString();+}diff --git a/model/src/main/java/org/openremote/model/value/Value.java b/model/src/main/java/org/openremote/model/value/Value.javanew file mode 100644index 000000000..cf81a68c1--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/Value.java@@ -0,0 +1,57 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++/**+ * Base interface for all values. This is a Java API for a JSON model and instances+ * may be serialized into JSON text with {@link #toJson()} or parsed from JSON text+ * with {@link Values#parse(String)}.+ */+public interface Value {++ /**+ * Coerces underlying value to boolean according to the rules of Javascript coercion.+ */+ boolean asBoolean();++ /**+ * Coerces the underlying value to a number according to the rules of Javascript coercion.+ */+ double asNumber();++ /**+ * Coerces the underlying value to a String according to the rules of JavaScript coercion.+ */+ String asString();++ /**+ * Returns an enumeration representing the fundamental type.+ */+ ValueType getType();++ /**+ * Returns a serialized JSON string representing this value.+ */+ String toJson() throws ValueException;++ /**+ * If used in a GWT context, converts the object to a native+ * {@link com.google.gwt.core.client.JavaScriptObject} suitable for passing to+ * native and {@link jsinterop.annotations.JsType} methods. Otherwise, returns+ * the current object in other contexts, such as server-side use.+ */+ Object toNative() throws ValueException;+}diff --git a/model/src/main/java/org/openremote/model/value/ValueException.java b/model/src/main/java/org/openremote/model/value/ValueException.javanew file mode 100644index 000000000..ec409533c--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ValueException.java@@ -0,0 +1,31 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++import java.io.IOException;++/**+ * A exception representing an error in parsing or serializing values to/from JSON.+ */+public class ValueException extends IOException {++ public ValueException() {+ }++ public ValueException(String s) {+ super(s);+ }+}diff --git a/model/src/main/java/org/openremote/model/value/ValueFactory.java b/model/src/main/java/org/openremote/model/value/ValueFactory.javanew file mode 100644index 000000000..201564123--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ValueFactory.java@@ -0,0 +1,36 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++/**+ * Factory interface for parsing and creating values.+ */+public interface ValueFactory {++ StringValue create(String string);++ NumberValue create(double number);++ BooleanValue create(boolean bool);++ ArrayValue createArray();++ ObjectValue createObject();++ Null createNull();++ <T extends Value> T parse(String jsonString) throws ValueException;+}diff --git a/model/src/main/java/org/openremote/model/value/ValueType.java b/model/src/main/java/org/openremote/model/value/ValueType.javanew file mode 100644index 000000000..addbfdbe0--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ValueType.java@@ -0,0 +1,23 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++/**+ * Represents the type of the underlying value, the same as in JSON.+ */+public enum ValueType {+ OBJECT, ARRAY, STRING, NUMBER, BOOLEAN, NULL;+}diff --git a/model/src/main/java/org/openremote/model/value/Values.java b/model/src/main/java/org/openremote/model/value/Values.javanew file mode 100644index 000000000..0c3891d0f--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/Values.java@@ -0,0 +1,56 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value;++import org.openremote.model.value.impl.ValueFactoryImpl;++/**+ * Vends out implementations of {@link Value} and {@link ValueFactory}.+ */+public class Values {++ public static StringValue create(String string) {+ return instance().create(string);+ }++ public static BooleanValue create(boolean bool) {+ return instance().create(bool);+ }++ public static ArrayValue createArray() {+ return instance().createArray();+ }++ public static Null createNull() {+ return instance().createNull();+ }++ public static NumberValue create(double number) {+ return instance().create(number);+ }++ public static ObjectValue createObject() {+ return instance().createObject();+ }++ public static ValueFactory instance() {+ return ValueFactoryImpl.INSTANCE;+ }++ public static <T extends Value> T parse(String jsonString) throws ValueException {+ return instance().parse(jsonString);+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ArrayValueContext.java b/model/src/main/java/org/openremote/model/value/impl/ArrayValueContext.javanew file mode 100644index 000000000..ef885eae1--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ArrayValueContext.java@@ -0,0 +1,68 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Value;++/**+ * A {@link ValueContext} with integer based location context.+ */+class ArrayValueContext extends ValueContext {++ int currentIndex = 0;++ public ArrayValueContext(ArrayValue array) {+ super(array);+ }++ public ArrayValue array() {+ return (ArrayValue) getValue();+ }++ public int getCurrentIndex() {+ return currentIndex;+ }++ @Override+ public void removeMe() {+ array().remove(getCurrentIndex());+ }++ @Override+ public void replaceMe(double d) {+ array().set(getCurrentIndex(), d);+ }++ @Override+ public void replaceMe(String d) {+ array().set(getCurrentIndex(), d);+ }++ @Override+ public void replaceMe(boolean d) {+ array().set(getCurrentIndex(), d);+ }++ @Override+ public void replaceMe(Value value) {+ array().set(getCurrentIndex(), value);+ }++ public void setCurrentIndex(int currentIndex) {+ this.currentIndex = currentIndex;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.javanew file mode 100644index 000000000..05d5fcae1--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java@@ -0,0 +1,190 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.*;++import java.util.ArrayList;+import java.util.List;++public class ArrayValueImpl extends ValueImpl implements ArrayValue {++ final private transient ValueFactory factory;+ private transient ArrayList<Value> values = new ArrayList<>();++ public ArrayValueImpl(ValueFactory factory) {+ this.factory = factory;+ }++ @Override+ public boolean asBoolean() {+ return true;+ }++ @Override+ public double asNumber() {+ switch (length()) {+ case 0:+ return 0;+ case 1:+ return get(0).asNumber();+ default:+ return Double.NaN;+ }+ }++ @Override+ public String asString() {+ StringBuilder toReturn = new StringBuilder();+ for (int i = 0; i < length(); i++) {+ if (i > 0) {+ toReturn.append(", ");+ }+ toReturn.append(get(i).asString());+ }+ return toReturn.toString();+ }++ @SuppressWarnings("unchecked")+ @Override+ public Value get(int index) {+ return values.get(index);+ }++ @Override+ public ArrayValue getArray(int index) {+ return (ArrayValue) get(index);+ }++ @Override+ public boolean getBoolean(int index) {+ return ((BooleanValue) get(index)).getBoolean();+ }++ @Override+ public double getNumber(int index) {+ return ((NumberValue) get(index)).getNumber();+ }++ @Override+ public ObjectValue getObject(int index) {+ return (ObjectValue) get(index);+ }++ @Override+ public List<Object> getObject() {+ List<Object> objs = new ArrayList<>();+ for (Value val : values) {+ objs.add(((ValueImpl) val).getObject());+ }+ return objs;+ }++ @Override+ public String getString(int index) {+ return ((StringValue) get(index)).getString();+ }++ @Override+ public ValueType getType() {+ return ValueType.ARRAY;+ }++ @Override+ public int length() {+ return values.size();+ }++ @Override+ public void remove(int index) {+ values.remove(index);+ }++ @Override+ public void set(int index, Value value) {+ if (value == null) {+ value = factory.createNull();+ }+ if (index == values.size()) {+ values.add(index, value);+ } else {+ values.set(index, value);+ }+ }++ @Override+ public void set(int index, String string) {+ set(index, factory.create(string));+ }++ @Override+ public void set(int index, double number) {+ set(index, factory.create(number));+ }++ @Override+ public void set(int index, boolean bool) {+ set(index, factory.create(bool));+ }++ @Override+ public String toJson() throws ValueException {+ return ValueUtil.stringify(this);+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) throws ValueException {+ if (visitor.visit(this, ctx)) {+ ArrayValueContext arrayCtx = new ArrayValueContext(this);+ for (int i = 0; i < length(); i++) {+ arrayCtx.setCurrentIndex(i);+ if (visitor.visitIndex(arrayCtx.getCurrentIndex(), arrayCtx)) {+ visitor.accept(get(i), arrayCtx);+ arrayCtx.setFirst(false);+ }+ }+ }+ visitor.endVisit(this, ctx);+ }++ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;+ if (!(o instanceof ArrayValueImpl))+ return false;+ ArrayValueImpl that = (ArrayValueImpl) o;++ if (length() != that.length())+ return false;+ for (int i = 0; i < length(); i++) {+ if (!get(i).equals(that.get(i)))+ return false;+ }+ return true;+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 5;+ for (int i = 0; i < length(); i++) {+ result = result * 5 + (i + get(i).hashCode());+ }+ return result;+ }++}diff --git a/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.javanew file mode 100644index 000000000..0d5996aea--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java@@ -0,0 +1,85 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.BooleanValue;+import org.openremote.model.value.ValueType;++public class BooleanValueImpl extends ValueImpl implements BooleanValue {++ private transient boolean bool;++ public BooleanValueImpl(boolean bool) {+ this.bool = bool;+ }++ @Override+ public boolean asBoolean() {+ return getBoolean();+ }++ @Override+ public double asNumber() {+ return getBoolean() ? 1 : 0;+ }++ @Override+ public String asString() {+ return Boolean.toString(getBoolean());+ }++ @Override+ public boolean getBoolean() {+ return bool;+ }++ @Override+ public Boolean getObject() {+ return getBoolean();+ }++ @Override+ public ValueType getType() {+ return ValueType.BOOLEAN;+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) {+ visitor.visit(getBoolean(), ctx);+ }++ @Override+ public String toJson() {+ return String.valueOf(bool);+ }++ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;+ if (!(o instanceof BooleanValueImpl))+ return false;+ BooleanValueImpl that = (BooleanValueImpl) o;+ return getBoolean() == that.getBoolean();+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 7 + (getBoolean() ? 1 : 0);+ return result;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/NullImpl.java b/model/src/main/java/org/openremote/model/value/impl/NullImpl.javanew file mode 100644index 000000000..409b75547--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/NullImpl.java@@ -0,0 +1,66 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.Null;+import org.openremote.model.value.ValueType;++public class NullImpl extends ValueImpl implements Null {++ public static final Null NULL_INSTANCE = new NullImpl();++ @Override+ public double asNumber() {+ return 0;+ }++ @Override+ public boolean asBoolean() {+ return false;+ }++ @Override+ public String asString() {+ return "null";+ }++ public Null getObject() {+ return NULL_INSTANCE;+ }++ public ValueType getType() {+ return ValueType.NULL;+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) {+ visitor.visitNull(ctx);+ }++ public String toJson() {+ return "null";+ }++ @Override+ public boolean equals(Object o) {+ return o != null && o instanceof NullImpl;+ }++ @Override+ public int hashCode() {+ return 31 * 31;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.javanew file mode 100644index 000000000..05d2fba81--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java@@ -0,0 +1,92 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.NumberValue;+import org.openremote.model.value.ValueType;++public class NumberValueImpl extends ValueImpl implements NumberValue {++ private transient double number;++ public NumberValueImpl(double number) {+ this.number = number;+ }++ @Override+ public boolean asBoolean() {+ return !(Double.isNaN(getNumber()) || Math.abs(getNumber()) == 0.0);+ }++ @Override+ public double asNumber() {+ return getNumber();+ }++ @Override+ public String asString() {+ return toJson();+ }++ @Override+ public double getNumber() {+ return number;+ }++ @Override+ public Double getObject() {+ return getNumber();+ }++ @Override+ public ValueType getType() {+ return ValueType.NUMBER;+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) {+ visitor.visit(getNumber(), ctx);+ }++ @Override+ public String toJson() {+ if (Double.isInfinite(number) || Double.isNaN(number)) {+ return "null";+ }+ String toReturn = String.valueOf(number);+ if (toReturn.endsWith(".0")) {+ toReturn = toReturn.substring(0, toReturn.length() - 2);+ }+ return toReturn;+ }++ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;+ if (!(o instanceof NumberValueImpl))+ return false;+ NumberValueImpl that = (NumberValueImpl) o;+ return getNumber() == that.getNumber();+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 11 + Double.hashCode(getNumber());+ return result;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ObjectValueContext.java b/model/src/main/java/org/openremote/model/value/impl/ObjectValueContext.javanew file mode 100644index 000000000..450f032c7--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ObjectValueContext.java@@ -0,0 +1,68 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;++/**+ * A {@link ValueContext} with String based location index.+ */+class ObjectValueContext extends ValueContext {++ String currentKey;++ public ObjectValueContext(ObjectValue value) {+ super(value);+ }++ private ObjectValue object() {+ return (ObjectValue) getValue();+ }++ public String getCurrentKey() {+ return currentKey;+ }++ @Override+ public void removeMe() {+ object().remove(getCurrentKey());+ }++ @Override+ public void replaceMe(double d) {+ object().put(getCurrentKey(), d);+ }++ @Override+ public void replaceMe(String d) {+ object().put(getCurrentKey(), d);+ }++ @Override+ public void replaceMe(boolean d) {+ object().put(getCurrentKey(), d);+ }++ @Override+ public void replaceMe(Value value) {+ object().put(getCurrentKey(), value);+ }++ public void setCurrentKey(String currentKey) {+ this.currentKey = currentKey;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.javanew file mode 100644index 000000000..c6564b06b--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java@@ -0,0 +1,199 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.*;++import java.util.*;++public class ObjectValueImpl extends ValueImpl implements ObjectValue {++ private static List<String> stringifyOrder(String[] keys) {+ List<String> toReturn = new ArrayList<>();+ List<String> nonNumeric = new ArrayList<>();+ for (String key : keys) {+ if (key.matches("\\d+")) {+ toReturn.add(key);+ } else {+ nonNumeric.add(key);+ }+ }+ Collections.sort(toReturn);+ toReturn.addAll(nonNumeric);+ return toReturn;+ }++ private transient ValueFactory factory;+ private transient Map<String, Value> map = new LinkedHashMap<>();++ public ObjectValueImpl(ValueFactory factory) {+ this.factory = factory;+ }++ @Override+ public boolean asBoolean() {+ return true;+ }++ @Override+ public double asNumber() {+ return Double.NaN;+ }++ @Override+ public String asString() {+ return "[object Object]";+ }++ @SuppressWarnings("unchecked")+ public <T extends Value> T get(String key) {+ return (T) map.get(key);+ }++ @Override+ public ArrayValue getArray(String key) {+ return (ArrayValue) get(key);+ }++ @Override+ public boolean getBoolean(String key) {+ return ((BooleanValue) get(key)).getBoolean();+ }++ @Override+ public double getNumber(String key) {+ return ((NumberValue) get(key)).getNumber();+ }++ @Override+ public ObjectValue getObject(String key) {+ return (ObjectValue) get(key);+ }++ @Override+ public Map<String, Object> getObject() {+ Map<String, Object> obj = new HashMap<>();+ for (Map.Entry<String, Value> e : map.entrySet()) {+ obj.put(e.getKey(), ((ValueImpl) e.getValue()).getObject());+ }+ return obj;+ }++ @Override+ public String getString(String key) {+ return ((StringValue) get(key)).getString();+ }++ @Override+ public ValueType getType() {+ return ValueType.OBJECT;+ }++ @Override+ public boolean hasKey(String key) {+ return map.containsKey(key);+ }++ @Override+ public String[] keys() {+ return map.keySet().toArray(new String[map.size()]);+ }++ @Override+ public void put(String key, Value value) {+ if (value == null) {+ value = factory.createNull();+ }+ map.put(key, value);+ }++ @Override+ public void put(String key, String value) {+ put(key, factory.create(value));+ }++ @Override+ public void put(String key, double value) {+ put(key, factory.create(value));+ }++ @Override+ public void put(String key, boolean bool) {+ put(key, factory.create(bool));+ }++ @Override+ public void remove(String key) {+ map.remove(key);+ }++ public void set(String key, Value value) {+ put(key, value);+ }++ @Override+ public String toJson() throws ValueException {+ return ValueUtil.stringify(this);+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) throws ValueException {+ if (visitor.visit(this, ctx)) {+ ObjectValueContext objCtx = new ObjectValueContext(this);+ for (String key : stringifyOrder(keys())) {+ objCtx.setCurrentKey(key);+ if (visitor.visitKey(objCtx.getCurrentKey(), objCtx)) {+ visitor.accept(get(key), objCtx);+ objCtx.setFirst(false);+ }+ }+ }+ visitor.endVisit(this, ctx);+ }++ /**+ * Compare two {@link ObjectValue} instances by actual value.+ */+ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;+ if (!(o instanceof ObjectValueImpl))+ return false;+ ObjectValueImpl that = (ObjectValueImpl) o;++ if (!this.map.keySet().equals(that.map.keySet()))+ return false;++ for (Map.Entry<String, Value> entry : this.map.entrySet()) {+ Value mapAValue = entry.getValue();+ Value mapBValue = that.map.get(entry.getKey());+ if (!mapAValue.equals(mapBValue)) {+ return false;+ }+ }+ return true;+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 3;+ result = result * getObject().hashCode();+ return result;+ }++}diff --git a/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.javanew file mode 100644index 000000000..2ba374968--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java@@ -0,0 +1,93 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.StringValue;+import org.openremote.model.value.ValueException;+import org.openremote.model.value.ValueType;++public class StringValueImpl extends ValueImpl implements StringValue {++ private transient String string;++ public StringValueImpl(String string) {+ this.string = string;+ }++ @Override+ public boolean asBoolean() {+ return !getString().isEmpty();+ }++ @Override+ public double asNumber() {+ try {+ if (asString().isEmpty()) {+ return 0.0;+ } else {+ return Double.parseDouble(asString());+ }+ } catch (NumberFormatException nfe) {+ return Double.NaN;+ }+ }++ @Override+ public String asString() {+ return getString();+ }++ @Override+ public String getObject() {+ return getString();+ }++ @Override+ public String getString() {+ return string;+ }++ @Override+ public ValueType getType() {+ return ValueType.STRING;+ }++ @Override+ public void traverse(ValueVisitor visitor, ValueContext ctx) {+ visitor.visit(getString(), ctx);+ }++ public String toJson() throws ValueException {+ return ValueUtil.quote(getString());+ }++ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;+ if (!(o instanceof StringValueImpl))+ return false;+ StringValueImpl that = (StringValueImpl) o;+ return getString().equals(that.getString());+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 13 + getString().hashCode();+ return result;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueContext.java b/model/src/main/java/org/openremote/model/value/impl/ValueContext.javanew file mode 100644index 000000000..8fdc37be8--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueContext.java@@ -0,0 +1,82 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.Value;++/**+ * Represents the current location where a value is stored, and allows+ * the value's replacement or deletion.+ */+abstract class ValueContext {++ private Value value;++ private boolean isFirst = true;++ ValueContext(Value value) {+ this.value = value;+ }++ /**+ * Return the underlying Value (Array or Object) that backs the+ * context.+ */+ public Value getValue() {+ return value;+ }++ /**+ * Whether or not the current context location within the value is the first+ * key or array index.+ */+ public boolean isFirst() {+ return isFirst;+ }++ /**+ * Remove the current array index or key.+ */+ public abstract void removeMe();++ /**+ * Replace the current location's value with a double.+ */+ public abstract void replaceMe(double d);++ /**+ * Replace the current location's value with a String.+ */+ public abstract void replaceMe(String d);++ /**+ * Replace the current location's value with a boolean.+ */+ public abstract void replaceMe(boolean d);++ /**+ * Replace the current location's value with a value.+ */+ public abstract void replaceMe(Value value);++ public void setFirst(boolean first) {+ isFirst = first;+ }++ void setValue(Value value) {+ this.value = value;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueFactoryImpl.java b/model/src/main/java/org/openremote/model/value/impl/ValueFactoryImpl.javanew file mode 100644index 000000000..1c0bae702--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueFactoryImpl.java@@ -0,0 +1,63 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.*;++public class ValueFactoryImpl implements ValueFactory {++ public static final ValueFactoryImpl INSTANCE = new ValueFactoryImpl();++ @Override+ public StringValue create(String string) {+ assert string != null;+ return new StringValueImpl(string);+ }++ @Override+ public NumberValue create(double number) {+ return new NumberValueImpl(number);+ }++ @Override+ public BooleanValue create(boolean bool) {+ return new BooleanValueImpl(bool);+ }++ @Override+ public ArrayValue createArray() {+ return new ArrayValueImpl(this);+ }++ @Override+ public Null createNull() {+ return NullImpl.NULL_INSTANCE;+ }++ @Override+ public ObjectValue createObject() {+ return new ObjectValueImpl(this);+ }++ @Override+ public <T extends Value> T parse(String jsonString) throws ValueException {+ if (jsonString.startsWith("(") && jsonString.endsWith(")")) {+ // some clients send in (json) expecting an eval is required+ jsonString = jsonString.substring(1, jsonString.length() - 1);+ }+ return new ValueTokenizer(this, jsonString).nextValue();+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ValueImpl.javanew file mode 100644index 000000000..c759c008d--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueImpl.java@@ -0,0 +1,43 @@+/*+ * Copyright 2011 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import com.google.gwt.core.client.GWT;+import com.google.gwt.core.client.JsonUtils;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueException;++public abstract class ValueImpl implements Value {++ @Override+ public Object toNative() throws ValueException {+ if (GWT.isClient())+ return JsonUtils.safeEval(this.toJson());+ else+ return this;+ }++ @Override+ public String toString() {+ Object o = getObject();+ return o != null ? o.toString() : "null";+ }++ public abstract Object getObject();++ public abstract void traverse(ValueVisitor visitor, ValueContext ctx) throws ValueException;++}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueTokenizer.java b/model/src/main/java/org/openremote/model/value/impl/ValueTokenizer.javanew file mode 100644index 000000000..df5089d0a--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueTokenizer.java@@ -0,0 +1,312 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.*;++/**+ * Implementation of parsing a JSON string into instances+ * of {@link org.openremote.model.value.Value}.+ */+class ValueTokenizer {++ private static final int INVALID_CHAR = -1;++ private static final String STOPCHARS = ",:]}/\\\"[{;=#";++ private ValueFactory valueFactory;++ private boolean lenient = true;++ private int pushBackBuffer = INVALID_CHAR;++ private final String json;+ private int position = 0;++ ValueTokenizer(ValueFactoryImpl valueFactory, String json) {+ this.valueFactory = valueFactory;+ this.json = json;+ }++ void back(char c) {+ assert pushBackBuffer == INVALID_CHAR;+ pushBackBuffer = c;+ }++ void back(int c) {+ back((char) c);+ }++ int next() {+ if (pushBackBuffer != INVALID_CHAR) {+ final int c = pushBackBuffer;+ pushBackBuffer = INVALID_CHAR;+ return c;+ }++ return position < json.length() ? json.charAt(position++) : INVALID_CHAR;+ }++ String next(int n) throws ValueException {+ if (n == 0) {+ return "";+ }++ char[] buffer = new char[n];+ int pos = 0;++ if (pushBackBuffer != INVALID_CHAR) {+ buffer[0] = (char) pushBackBuffer;+ pos = 1;+ pushBackBuffer = INVALID_CHAR;+ }++ int len;+ while ((pos < n) && ((len = read(buffer, pos, n - pos)) != -1)) {+ pos += len;+ }++ if (pos < n) {+ throw new ValueException("TODO"/* TODO(knorton): Add message. */);+ }++ return String.valueOf(buffer);+ }++ int nextNonWhitespace() {+ while (true) {+ final int c = next();+ if (!Character.isWhitespace((char) c)) {+ return c;+ }+ }+ }++ String nextString(int startChar) throws ValueException {+ final StringBuilder buffer = new StringBuilder();+ int c = next();+ assert c == '"' || (lenient && c == '\'');+ while (true) {+ c = next();+ switch (c) {+ case '\r':+ case '\n':+ throw new ValueException("");+ case INVALID_CHAR:+ throw new ValueException("Invalid string: closing " + startChar + " is not found");+ case '\\':+ c = next();+ switch (c) {+ case 'b':+ buffer.append('\b');+ break;+ case 't':+ buffer.append('\t');+ break;+ case 'n':+ buffer.append('\n');+ break;+ case 'f':+ buffer.append('\f');+ break;+ case 'r':+ buffer.append('\r');+ break;+ // TODO(knorton): I'm not sure I should even support this escaping+ // mode since JSON is always UTF-8.+ case 'u':+ buffer.append((char) Integer.parseInt(next(4), 16));+ break;+ default:+ buffer.append((char) c);+ }+ break;+ default:+ if (c == startChar) {+ return buffer.toString();+ }+ buffer.append((char) c);+ }+ }+ }++ String nextUntilOneOf(String chars) {+ final StringBuilder buffer = new StringBuilder();+ int c = next();+ while (c != INVALID_CHAR) {+ if (Character.isWhitespace((char) c) || chars.indexOf((char) c) >= 0) {+ back(c);+ break;+ }+ buffer.append((char) c);+ c = next();+ }+ return buffer.toString();+ }++ @SuppressWarnings("unchecked")+ <T extends Value> T nextValue() throws ValueException {+ final int c = nextNonWhitespace();+ back(c);+ switch (c) {+ case '"':+ case '\'':+ return (T) valueFactory.create(nextString(c));+ case '{':+ return (T) parseObject();+ case '[':+ return (T) parseArray();+ default:+ return (T) getValueForLiteral(nextUntilOneOf(STOPCHARS));+ }+ }++ ArrayValue parseArray() throws ValueException {+ final ArrayValue array = valueFactory.createArray();+ int c = nextNonWhitespace();+ assert c == '[';+ while (true) {+ c = nextNonWhitespace();+ switch (c) {+ case ']':+ return array;+ default:+ back(c);+ array.set(array.length(), (Value) nextValue());+ final int d = nextNonWhitespace();+ switch (d) {+ case ']':+ return array;+ case ',':+ break;+ default:+ throw new ValueException("Invalid array: expected , or ]");+ }+ }+ }+ }++ ObjectValue parseObject() throws ValueException {+ final ObjectValue object = valueFactory.createObject();+ int c = nextNonWhitespace();+ if (c != '{') {+ throw new ValueException("Payload does not begin with '{'. Got " + c + "(" + (char) c + ")");+ }++ while (true) {+ c = nextNonWhitespace();+ switch (c) {+ case '}':+ // We're done.+ return object;+ case '"':+ case '\'':+ back(c);+ // Ready to start a key.+ final String key = nextString(c);+ if (nextNonWhitespace() != ':') {+ throw new ValueException("Invalid object: expecting \":\"");+ }+ // TODO(knorton): Make sure this key is not already set.+ object.put(key, (Value) nextValue());+ switch (nextNonWhitespace()) {+ case ',':+ break;+ case '}':+ return object;+ default:+ throw new ValueException("Invalid object: expecting } or ,");+ }+ break;+ case ',':+ break;+ default:+ if (lenient && (Character.isDigit((char) c) || Character.isLetterOrDigit((char) c))) {+ StringBuilder keyBuffer = new StringBuilder();+ keyBuffer.append(c);+ while (true) {+ c = next();+ if (Character.isDigit((char) c) || Character.isLetterOrDigit((char) c)) {+ keyBuffer.append(c);+ } else {+ back(c);+ break;+ }+ }+ if (nextNonWhitespace() != ':') {+ throw new ValueException("Invalid object: expecting \":\"");+ }+ // TODO(knorton): Make sure this key is not already set.+ object.put(keyBuffer.toString(), (Value) nextValue());+ switch (nextNonWhitespace()) {+ case ',':+ break;+ case '}':+ return object;+ default:+ throw new ValueException("Invalid object: expecting } or ,");+ }++ } else {+ throw new ValueException("Invalid object: ");+ }+ }+ }+ }++ private NumberValue getNumberForLiteral(String literal)+ throws ValueException {+ try {+ return valueFactory.create(Double.parseDouble(literal));+ } catch (NumberFormatException e) {+ throw new ValueException("Invalid number literal: " + literal);+ }+ }++ private Value getValueForLiteral(String literal) throws ValueException {+ if ("".equals(literal)) {+ throw new ValueException("Missing value");+ }++ if ("null".equals(literal) || "undefined".equals(literal)) {+ return valueFactory.createNull();+ }++ if ("true".equals(literal)) {+ return valueFactory.create(true);+ }++ if ("false".equals(literal)) {+ return valueFactory.create(false);+ }++ final char c = literal.charAt(0);+ if (c == '-' || Character.isDigit(c)) {+ return getNumberForLiteral(literal);+ }++ throw new ValueException("Invalid literal: \"" + literal + "\"");+ }++ private int read(char[] buffer, int pos, int len) {+ int maxLen = Math.min(json.length() - position, len);+ String src = json.substring(position, position + maxLen);+ char result[] = src.toCharArray();+ System.arraycopy(result, 0, buffer, pos, maxLen);+ position += maxLen;+ return maxLen;+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueUtil.java b/model/src/main/java/org/openremote/model/value/impl/ValueUtil.javanew file mode 100644index 000000000..86c05d681--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueUtil.java@@ -0,0 +1,303 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.*;++import java.util.Collections;+import java.util.HashSet;+import java.util.Set;++/**+ * Direct port of json2.js at http://www.json.org/json2.js to GWT.+ */+public class ValueUtil {++ private static class StringifyValueVisitor extends ValueVisitor {++ private static final Set<String> skipKeys;++ static {+ Set<String> toSkip = new HashSet<>();+ toSkip.add("$H");+ toSkip.add("__gwt_ObjectId");+ skipKeys = Collections.unmodifiableSet(toSkip);+ }++ private String indentLevel;++ private Set<Value> visited;++ private final String indent;++ private final StringBuilder sb;++ private final boolean pretty;++ public StringifyValueVisitor(String indent, StringBuilder sb,+ boolean pretty) {+ this.indent = indent;+ this.sb = sb;+ this.pretty = pretty;+ indentLevel = "";+ visited = new HashSet<>();+ }++ @Override+ public void endVisit(ArrayValue array, ValueContext ctx) {+ if (pretty) {+ indentLevel = indentLevel+ .substring(0, indentLevel.length() - indent.length());+ sb.append('\n');+ sb.append(indentLevel);+ }+ sb.append("]");+ visited.remove(array);+ }++ @Override+ public void endVisit(ObjectValue object, ValueContext ctx) {+ if (pretty) {+ indentLevel = indentLevel+ .substring(0, indentLevel.length() - indent.length());+ sb.append('\n');+ sb.append(indentLevel);+ }+ sb.append("}");+ visited.remove(object);+ assert !visited.contains(object);+ }++ @Override+ public void visit(double number, ValueContext ctx) {+ sb.append(Double.isInfinite(number) || Double.isNaN(number) ? "null" : format(number));+ }++ @Override+ public void visit(String string, ValueContext ctx) {+ sb.append(quote(string));+ }++ @Override+ public void visit(boolean bool, ValueContext ctx) {+ sb.append(bool);+ }++ @Override+ public boolean visit(ArrayValue array, ValueContext ctx) throws ValueException {+ checkCycle(array);+ sb.append("[");+ if (pretty) {+ sb.append('\n');+ indentLevel += indent;+ sb.append(indentLevel);+ }+ return true;+ }++ @Override+ public boolean visit(ObjectValue object, ValueContext ctx) throws ValueException {+ checkCycle(object);+ sb.append("{");+ if (pretty) {+ sb.append('\n');+ indentLevel += indent;+ sb.append(indentLevel);+ }+ return true;+ }++ @Override+ public boolean visitIndex(int index, ValueContext ctx) {+ commaIfNotFirst(ctx);+ return true;+ }++ @Override+ public boolean visitKey(String key, ValueContext ctx) {+ if ("".equals(key)) {+ return true;+ }+ // skip properties injected by GWT runtime on JSOs+ if (skipKeys.contains(key)) {+ return false;+ }+ commaIfNotFirst(ctx);+ sb.append(quote(key)).append(":");+ if (pretty) {+ sb.append(' ');+ }+ return true;+ }++ @Override+ public void visitNull(ValueContext ctx) {+ sb.append("null");+ }++ private void checkCycle(Value value) throws ValueException {+ if (visited.contains(value)) {+ throw new ValueException("Cycled detected during stringify");+ } else {+ visited.add(value);+ }+ }++ private void commaIfNotFirst(ValueContext ctx) {+ if (!ctx.isFirst()) {+ sb.append(",");+ if (pretty) {+ sb.append('\n');+ sb.append(indentLevel);+ }+ }+ }++ private String format(double number) {+ String n = String.valueOf(number);+ if (n.endsWith(".0")) {+ n = n.substring(0, n.length() - 2);+ }+ return n;+ }+ }++ /**+ * Convert special control characters into unicode escape format.+ */+ public static String escapeControlChars(String text) {+ StringBuilder toReturn = new StringBuilder();+ for (int i = 0; i < text.length(); i++) {+ char c = text.charAt(i);+ if (isControlChar(c)) {+ toReturn.append(escapeCharAsUnicode(c));+ } else {+ toReturn.append(c);+ }+ }+ return toReturn.toString();+ }++ public static <T extends Value> T parse(String json) throws ValueException {+ return Values.instance().parse(json);+ }++ /**+ * Safely escape an arbitrary string as a JSON string literal.+ */+ public static String quote(String value) {+ StringBuilder toReturn = new StringBuilder("\"");+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);++ String toAppend = String.valueOf(c);+ switch (c) {+ case '\b':+ toAppend = "\\b";+ break;+ case '\t':+ toAppend = "\\t";+ break;+ case '\n':+ toAppend = "\\n";+ break;+ case '\f':+ toAppend = "\\f";+ break;+ case '\r':+ toAppend = "\\r";+ break;+ case '"':+ toAppend = "\\\"";+ break;+ case '\\':+ toAppend = "\\\\";+ break;+ default:+ if (isControlChar(c)) {+ toAppend = escapeCharAsUnicode(c);+ }+ }+ toReturn.append(toAppend);+ }+ toReturn.append("\"");+ return toReturn.toString();+ }++ /**+ * Converts an Object to Json format.+ *+ * @param jsonValue object to stringify+ * @return json formatted string+ * @throws ValueException when a cycle is detected+ */+ public static String stringify(Value jsonValue) throws ValueException {+ return stringify(jsonValue, 0);+ }++ /**+ * Converts an Object to Json format.+ *+ * @param value object to stringify+ * @param spaces number of spaces to indent in pretty print mode+ * @return json formatted string+ * @throws ValueException when a cycle is detected+ */+ public static String stringify(Value value, int spaces) throws ValueException {+ StringBuilder sb = new StringBuilder();+ for (int i = 0; i < spaces; i++) {+ sb.append(' ');+ }+ return stringify(value, sb.toString());+ }++ /**+ * Converts a Json object to Json formatted String.+ *+ * @param value object to stringify+ * @param indent optional indention prefix for pretty printing+ * @return json formatted string+ * @throws ValueException when a cycle is detected+ */+ public static String stringify(Value value, final String indent) throws ValueException {+ final StringBuilder sb = new StringBuilder();+ final boolean isPretty = indent != null && !"".equals(indent);++ new StringifyValueVisitor(indent, sb, isPretty).accept(value);+ return sb.toString();+ }++ /**+ * Turn a single unicode character into a 32-bit unicode hex literal.+ */+ private static String escapeCharAsUnicode(char toEscape) {+ String hexValue = Integer.toString(toEscape, 16);+ int padding = 4 - hexValue.length();+ return "\\u" + ("0000".substring(0, padding)) + hexValue;+ }++ private static boolean isControlChar(char c) {+ return (c >= 0x00 && c <= 0x1f)+ || (c >= 0x7f && c <= 0x9f)+ || c == '\u00ad' || c == '\u070f' || c == '\u17b4' || c == '\u17b5'+ || c == '\ufeff'+ || (c >= '\u0600' && c <= '\u0604')+ || (c >= '\u200c' && c <= '\u200f')+ || (c >= '\u2028' && c <= '\u202f')+ || (c >= '\u2060' && c <= '\u206f')+ || (c >= '\ufff0' && c <= '\uffff');+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueVisitor.java b/model/src/main/java/org/openremote/model/value/impl/ValueVisitor.javanew file mode 100644index 000000000..cdea3b0a2--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/impl/ValueVisitor.java@@ -0,0 +1,171 @@+/*+ * Copyright 2010 Google Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not+ * use this file except in compliance with the License. You may obtain a copy of+ * the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+package org.openremote.model.value.impl;++import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueException;++/**+ * A visitor for {@link Value} objects. For each unique value type, a callback is+ * invoked with a {@link ValueContext} that can be used to replace a value+ * or remove it.+ * <p>+ * For {@link ObjectValue} and {@link ArrayValue} types, the {@link #visitKey}+ * and {@link #visitIndex} methods are invoked respectively for each contained+ * value to determine if they should be processed or not.+ * <p>+ * Finally, the visit methods for Object and Array types returns a boolean that+ * determines whether or not to process its contained values.+ */+class ValueVisitor {++ private class ImmutableValueContext extends ValueContext {++ public ImmutableValueContext(Value node) {+ super(node);+ }++ @Override+ public void removeMe() {+ immutableError();+ }++ @Override+ public void replaceMe(double d) {+ immutableError();+ }++ @Override+ public void replaceMe(String d) {+ immutableError();+ }++ @Override+ public void replaceMe(boolean d) {+ immutableError();+ }++ @Override+ public void replaceMe(Value value) {+ immutableError();+ }++ private void immutableError() {+ throw new UnsupportedOperationException("Immutable context");+ }+ }++ public void accept(Value node) throws ValueException {+ accept(node, new ImmutableValueContext(node));+ }++ /**+ * Accept array or object type and visit its members.+ */+ public void accept(Value node, ValueContext ctx) throws ValueException {+ if (node == null) {+ return;+ }+ ((ValueImpl) node).traverse(this, ctx);+ }++ /**+ * Called after every element of array has been visited.+ */+ public void endVisit(ArrayValue array, ValueContext ctx) {+ }++ /**+ * Called after every field of an object has been visited.+ *+ * @param object+ * @param ctx+ */+ public void endVisit(ObjectValue object, ValueContext ctx) {+ }++ /**+ * Called for numbers present in an object.+ */+ public void visit(double number, ValueContext ctx) {+ }++ /**+ * Called for strings present in an object.+ */+ public void visit(String string, ValueContext ctx) {+ }++ /**+ * Called for boolean present in an object.+ */+ public void visit(boolean bool, ValueContext ctx) {+ }++ /**+ * Called for arrays present in an object. Return true if array+ * elements should be visited.+ *+ * @param array an array+ * @param ctx a context to replace or delete the array+ * @return true if the array elements should be visited+ */+ public boolean visit(ArrayValue array, ValueContext ctx) throws ValueException {+ return true;+ }++ /**+ * Called for objects present in an object. Return true if object+ * fields should be visited.+ *+ * @param object an object+ * @param ctx a context to replace or delete the object+ * @return true if object fields should be visited+ */+ public boolean visit(ObjectValue object, ValueContext ctx) throws ValueException {+ return true;+ }++ /**+ * Return true if the value for a given array index should be visited.+ *+ * @param index an index in an array+ * @param ctx a context object used to delete or replace values+ * @return true if the value associated with the index should be visited+ */+ public boolean visitIndex(int index, ValueContext ctx) {+ return true;+ }++ /**+ * Return true if the value for a given object key should be visited.+ *+ * @param key a key in an object+ * @param ctx a context object used to delete or replace values+ * @return true if the value associated with the key should be visited+ */+ public boolean visitKey(String key, ValueContext ctx) {+ return true;+ }++ /**+ * Called for nulls present in an object.+ */+ public void visitNull(ValueContext ctx) {+ }+}