Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Replaced Null with Optional value handling

Christian Bauerc3fb8fe70653
diff --git a/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java b/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java
index 4b0fc2faf..1dcc2504d 100644
--- a/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java
+++ b/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java
@@ -19,6 +19,7 @@
*/
package org.openremote.container.json;
+import elemental.json.impl.JsonUtil;
import org.jboss.resteasy.plugins.providers.ProviderHelper;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
@@ -46,7 +47,7 @@ public class ElementalMessageBodyConverter implements MessageBodyReader<Value>,
@Override
public Value readFrom(Class<Value> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
String str = ProviderHelper.readString(entityStream, mediaType);
- return Values.parse(str);
+ return Values.parse(str).orElseThrow(() -> new IOException("Empty JSON data"));
}
@Override
diff --git a/container/src/main/java/org/openremote/container/json/ModelValueModule.java b/container/src/main/java/org/openremote/container/json/ModelValueModule.java
index f3355eee3..282e7a705 100644
--- a/container/src/main/java/org/openremote/container/json/ModelValueModule.java
+++ b/container/src/main/java/org/openremote/container/json/ModelValueModule.java
@@ -43,7 +43,7 @@ public class ModelValueModule extends SimpleModule {
@Override
public T deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
try {
- return (T) Values.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString());
+ return (T) Values.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString()).orElse(null);
} catch (ValueException ex) {
throw new IOException(ex);
}
@@ -53,11 +53,7 @@ public class ModelValueModule extends SimpleModule {
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 {
+ if (value != null) {
try {
gen.writeRawValue(value.toJson());
} catch (ValueException ex) {
@@ -75,7 +71,6 @@ public class ModelValueModule extends SimpleModule {
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.java
index bd7212abb..75b977f04 100644
--- 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.java
@@ -26,12 +26,14 @@ import com.github.nmorel.gwtjackson.client.stream.JsonReader;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
+import java.io.IOException;
+
public class ModelValueDeserializer extends JsonDeserializer<Value> {
@Override
protected Value doDeserialize(JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params) {
if (reader.hasNext()) {
- return Values.parse(reader.nextValue());
+ return Values.parse(reader.nextValue()).orElseThrow(() -> new RuntimeException("Empty JSON data"));
}
return null;
}
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.java
index 59d80548b..a21796363 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
@@ -39,7 +39,6 @@ public class SerializationConfiguration extends AbstractConfiguration {
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);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/value/ObjectValueMapper.java b/manager/client/src/main/java/org/openremote/manager/client/interop/value/ObjectValueMapper.java
index 2e6960677..e6ad28cd0 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/interop/value/ObjectValueMapper.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/value/ObjectValueMapper.java
@@ -28,7 +28,7 @@ public class ObjectValueMapper implements EntityReader<ObjectValue>, EntityWrite
@Override
public ObjectValue read(String value) {
- return Values.parse(value);
+ return Values.<ObjectValue>parse(value).orElseThrow(() -> new RuntimeException("Empty JSON data"));
}
@Override
diff --git a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java
index 89eb80544..8a7e73fab 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java
@@ -26,6 +26,7 @@ import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.web.ManagerWebService;
import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.StringValue;
import org.openremote.model.value.Values;
import javax.ws.rs.core.UriBuilder;
@@ -38,6 +39,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
+import java.util.Optional;
import java.util.logging.Logger;
import static org.openremote.container.util.MapAccess.getString;
@@ -99,20 +101,29 @@ public class MapService implements ContainerService {
// Mix settings from file with database metadata, and some hardcoded magic
try {
String mapSettingsJson = new String(Files.readAllBytes(mapSettingsPath), "utf-8");
- mapSettings = Values.parse(mapSettingsJson);
+ mapSettings = Values.<ObjectValue>parse(mapSettingsJson).orElseThrow(() ->
+ new RuntimeException("Error parsing map settings: " + mapSettingsPath.toAbsolutePath())
+ );
} catch (Exception ex) {
throw new RuntimeException("Error parsing map settings: " + mapSettingsPath.toAbsolutePath(), ex);
}
- ObjectValue style = mapSettings.getObject("style");
+ ObjectValue style = mapSettings.<ObjectValue>get("style").orElseThrow(() ->
+ new RuntimeException("Missing 'style' field in map settings style: " + mapSettingsPath.toAbsolutePath())
+ );
style.put("version", 8);
if (style.hasKey("sprite")) {
+ // Rewrite path to sprite file to our external host
+ String spritePath =
+ style.<StringValue>get("sprite").orElseThrow(() ->
+ new RuntimeException("Missing 'sprite' field in map settings style: " + mapSettingsPath.toAbsolutePath())
+ ).getString();
String spriteUri =
baseUriBuilder.clone()
.replacePath(ManagerWebService.MANAGER_PATH)
- .path(style.getString("sprite"))
+ .path(spritePath)
.build().toString();
style.put("sprite", spriteUri);
}
@@ -131,6 +142,11 @@ public class MapService implements ContainerService {
vectorTiles.put("type", "vector");
+ ArrayValue tilesArray = Values.createArray();
+ String tileUrl = baseUriBuilder.clone().replacePath(realm).path("map/tile").build().toString() + "/{z}/{x}/{y}";
+ tilesArray.set(0, tileUrl);
+ vectorTiles.put("tiles", tilesArray);
+
PreparedStatement query = null;
ResultSet result = null;
try {
@@ -146,8 +162,13 @@ public class MapService implements ContainerService {
throw new RuntimeException("Missing JSON metadata in map database");
}
- ObjectValue metadataJson = Values.parse(resultMap.get("json"));
- vectorTiles.put("vector_layers", metadataJson.getArray("vector_layers"));
+ ObjectValue metadataJson = Values.<ObjectValue>parse(resultMap.get("json")).orElseThrow(() ->
+ new RuntimeException("Error parsing JSON metadata from map database")
+ );
+ ArrayValue vectorLayers = metadataJson.<ArrayValue>get("vector_layers").orElseThrow(() ->
+ new RuntimeException("Missing 'vector_layers' field in metadata from map database")
+ );
+ vectorTiles.put("vector_layers", vectorLayers);
vectorTiles.put("maxzoom", Integer.valueOf(resultMap.get("maxzoom")));
vectorTiles.put("minzoom", Integer.valueOf(resultMap.get("minzoom")));
vectorTiles.put("attribution", resultMap.get("attribution"));
@@ -157,11 +178,6 @@ public class MapService implements ContainerService {
closeQuietly(query, result);
}
- ArrayValue tilesArray = Values.createArray();
- String tileUrl = baseUriBuilder.clone().replacePath(realm).path("map/tile").build().toString() + "/{z}/{x}/{y}";
- tilesArray.set(0, tileUrl);
- mapSettings.getObject("style").getObject("sources").getObject("vector_tiles").put("tiles", tilesArray);
-
return mapSettings;
}
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.groovy
index 5451c2e43..43c387ca4 100644
--- a/manager/test/src/test/groovy/org/openremote/test/model/ModelValueTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/model/ModelValueTest.groovy
@@ -20,9 +20,10 @@ class ModelValueTest extends Specification {
sampleArray1.set(3, 123.45)
sampleArray1.set(4, sampleObject1)
- String json = sampleArray1.toJson()
- ArrayValue value = Values.parse(json)
- value == sampleArray1
+ String rawValue = sampleArray1.toJson()
+ println rawValue
+ ArrayValue parsedValue = Values.<ArrayValue>parse(rawValue).get()
+ parsedValue == sampleArray1
}
def "Compare scalar values"() {
@@ -45,21 +46,6 @@ class ModelValueTest extends Specification {
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()
@@ -81,9 +67,6 @@ class ModelValueTest extends Specification {
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()
@@ -116,9 +99,6 @@ class ModelValueTest extends Specification {
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()
@@ -132,9 +112,6 @@ class ModelValueTest extends Specification {
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()
diff --git a/model/src/main/java/org/openremote/model/value/ArrayValue.java b/model/src/main/java/org/openremote/model/value/ArrayValue.java
index 33ad405f9..4acec22bb 100644
--- a/model/src/main/java/org/openremote/model/value/ArrayValue.java
+++ b/model/src/main/java/org/openremote/model/value/ArrayValue.java
@@ -15,70 +15,21 @@
*/
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);
+import java.util.Optional;
- /**
- * 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);
+public interface ArrayValue extends Value {
- /**
- * 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);
+ <T extends Value> Optional<T> get(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/Null.java b/model/src/main/java/org/openremote/model/value/Null.java
deleted file mode 100644
index 2b146d6c9..000000000
--- a/model/src/main/java/org/openremote/model/value/Null.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * 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.java
index ac6ea4931..506ca18df 100644
--- a/model/src/main/java/org/openremote/model/value/NumberValue.java
+++ b/model/src/main/java/org/openremote/model/value/NumberValue.java
@@ -18,4 +18,15 @@ package org.openremote.model.value;
public interface NumberValue extends Value {
double getNumber();
+
+ // Convenience coercion method
+ default String asString() {
+ return toJson();
+ }
+
+ // Convenience coercion method
+ static NumberValue fromString(String s) {
+ return Values.create(Double.valueOf(s));
+ }
+
}
diff --git a/model/src/main/java/org/openremote/model/value/ObjectValue.java b/model/src/main/java/org/openremote/model/value/ObjectValue.java
index 1dee7d2da..f52b39367 100644
--- a/model/src/main/java/org/openremote/model/value/ObjectValue.java
+++ b/model/src/main/java/org/openremote/model/value/ObjectValue.java
@@ -15,6 +15,8 @@
*/
package org.openremote.model.value;
+import java.util.Optional;
+
/**
* 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
@@ -22,75 +24,19 @@ package org.openremote.model.value;
*/
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);
+ <T extends Value> Optional<T> get(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/Value.java b/model/src/main/java/org/openremote/model/value/Value.java
index cf81a68c1..8368ae2ba 100644
--- a/model/src/main/java/org/openremote/model/value/Value.java
+++ b/model/src/main/java/org/openremote/model/value/Value.java
@@ -22,21 +22,6 @@ package org.openremote.model.value;
*/
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.
*/
diff --git a/model/src/main/java/org/openremote/model/value/ValueFactory.java b/model/src/main/java/org/openremote/model/value/ValueFactory.java
index 201564123..e387b28c5 100644
--- a/model/src/main/java/org/openremote/model/value/ValueFactory.java
+++ b/model/src/main/java/org/openremote/model/value/ValueFactory.java
@@ -15,6 +15,8 @@
*/
package org.openremote.model.value;
+import java.util.Optional;
+
/**
* Factory interface for parsing and creating values.
*/
@@ -30,7 +32,5 @@ public interface ValueFactory {
ObjectValue createObject();
- Null createNull();
-
- <T extends Value> T parse(String jsonString) throws ValueException;
+ <T extends Value> Optional<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.java
index addbfdbe0..5b6e0767a 100644
--- a/model/src/main/java/org/openremote/model/value/ValueType.java
+++ b/model/src/main/java/org/openremote/model/value/ValueType.java
@@ -19,5 +19,5 @@ 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;
+ OBJECT, ARRAY, STRING, NUMBER, BOOLEAN;
}
diff --git a/model/src/main/java/org/openremote/model/value/Values.java b/model/src/main/java/org/openremote/model/value/Values.java
index 0c3891d0f..c3948e253 100644
--- a/model/src/main/java/org/openremote/model/value/Values.java
+++ b/model/src/main/java/org/openremote/model/value/Values.java
@@ -17,6 +17,8 @@ package org.openremote.model.value;
import org.openremote.model.value.impl.ValueFactoryImpl;
+import java.util.Optional;
+
/**
* Vends out implementations of {@link Value} and {@link ValueFactory}.
*/
@@ -34,10 +36,6 @@ public class Values {
return instance().createArray();
}
- public static Null createNull() {
- return instance().createNull();
- }
-
public static NumberValue create(double number) {
return instance().create(number);
}
@@ -50,7 +48,7 @@ public class Values {
return ValueFactoryImpl.INSTANCE;
}
- public static <T extends Value> T parse(String jsonString) throws ValueException {
+ public static <T extends Value> Optional<T> parse(String jsonString) throws ValueException {
return instance().parse(jsonString);
}
}
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.java
index 05d5fcae1..25afcd8b2 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java
@@ -19,6 +19,7 @@ import org.openremote.model.value.*;
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
public class ArrayValueImpl extends ValueImpl implements ArrayValue {
@@ -29,59 +30,10 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {
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);
+ public <T extends Value> Optional<T> get(int index) {
+ return index >= 0 && values.size() > index ? Optional.of((T) values.get(index)) : Optional.empty();
}
@Override
@@ -93,11 +45,6 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {
return objs;
}
- @Override
- public String getString(int index) {
- return ((StringValue) get(index)).getString();
- }
-
@Override
public ValueType getType() {
return ValueType.ARRAY;
@@ -115,10 +62,9 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {
@Override
public void set(int index, Value value) {
- if (value == null) {
- value = factory.createNull();
- }
- if (index == values.size()) {
+ if (value == null && index >= 0 && index < values.size()) {
+ values.remove(index);
+ } else if (index == values.size()) {
values.add(index, value);
} else {
values.set(index, value);
@@ -152,8 +98,11 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {
for (int i = 0; i < length(); i++) {
arrayCtx.setCurrentIndex(i);
if (visitor.visitIndex(arrayCtx.getCurrentIndex(), arrayCtx)) {
- visitor.accept(get(i), arrayCtx);
- arrayCtx.setFirst(false);
+ Optional<Value> value = get(i);
+ if (value.isPresent()) {
+ visitor.accept(value.get(), arrayCtx);
+ arrayCtx.setFirst(false);
+ }
}
}
}
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.java
index 0d5996aea..4c7de5678 100644
--- a/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java
@@ -26,21 +26,6 @@ public class BooleanValueImpl extends ValueImpl implements BooleanValue {
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;
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.java
deleted file mode 100644
index 409b75547..000000000
--- a/model/src/main/java/org/openremote/model/value/impl/NullImpl.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.java
index 05d2fba81..4c2a3244f 100644
--- a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java
@@ -26,21 +26,6 @@ public class NumberValueImpl extends ValueImpl implements NumberValue {
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;
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.java
index c6564b06b..aa654d007 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java
@@ -43,44 +43,10 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {
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);
+ public <T extends Value> Optional<T> get(String key) {
+ return map.containsKey(key) ? Optional.of((T) map.get(key)) : Optional.empty();
}
@Override
@@ -92,11 +58,6 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {
return obj;
}
- @Override
- public String getString(String key) {
- return ((StringValue) get(key)).getString();
- }
-
@Override
public ValueType getType() {
return ValueType.OBJECT;
@@ -115,14 +76,19 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {
@Override
public void put(String key, Value value) {
if (value == null) {
- value = factory.createNull();
+ map.remove(key);
+ } else {
+ map.put(key, value);
}
- map.put(key, value);
}
@Override
public void put(String key, String value) {
- put(key, factory.create(value));
+ if (value == null) {
+ remove(key);
+ } else {
+ put(key, factory.create(value));
+ }
}
@Override
@@ -140,10 +106,6 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {
map.remove(key);
}
- public void set(String key, Value value) {
- put(key, value);
- }
-
@Override
public String toJson() throws ValueException {
return ValueUtil.stringify(this);
@@ -156,8 +118,11 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {
for (String key : stringifyOrder(keys())) {
objCtx.setCurrentKey(key);
if (visitor.visitKey(objCtx.getCurrentKey(), objCtx)) {
- visitor.accept(get(key), objCtx);
- objCtx.setFirst(false);
+ Optional<Value> value = get(key);
+ if (value.isPresent()) {
+ visitor.accept(value.get(), objCtx);
+ objCtx.setFirst(false);
+ }
}
}
}
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.java
index 2ba374968..bc010fa36 100644
--- a/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java
@@ -27,29 +27,6 @@ public class StringValueImpl extends ValueImpl implements StringValue {
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();
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.java
index 1c0bae702..3a3352b08 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ValueFactoryImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ValueFactoryImpl.java
@@ -17,6 +17,8 @@ package org.openremote.model.value.impl;
import org.openremote.model.value.*;
+import java.util.Optional;
+
public class ValueFactoryImpl implements ValueFactory {
public static final ValueFactoryImpl INSTANCE = new ValueFactoryImpl();
@@ -42,18 +44,13 @@ public class ValueFactoryImpl implements ValueFactory {
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 {
+ public <T extends Value> Optional<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);
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.java
index df5089d0a..3123d5b0b 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ValueTokenizer.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ValueTokenizer.java
@@ -17,6 +17,8 @@ package org.openremote.model.value.impl;
import org.openremote.model.value.*;
+import java.util.Optional;
+
/**
* Implementation of parsing a JSON string into instances
* of {@link org.openremote.model.value.Value}.
@@ -125,8 +127,7 @@ class ValueTokenizer {
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.
+ // 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;
@@ -158,19 +159,20 @@ class ValueTokenizer {
}
@SuppressWarnings("unchecked")
- <T extends Value> T nextValue() throws ValueException {
+ <T extends Value> Optional<T> nextValue() throws ValueException {
final int c = nextNonWhitespace();
back(c);
switch (c) {
case '"':
case '\'':
- return (T) valueFactory.create(nextString(c));
+ String s = nextString(c);
+ return Optional.of((T)valueFactory.create(s));
case '{':
- return (T) parseObject();
+ return Optional.of( (T) parseObject());
case '[':
- return (T) parseArray();
+ return Optional.of((T) parseArray());
default:
- return (T) getValueForLiteral(nextUntilOneOf(STOPCHARS));
+ return (Optional<T>) getValueForLiteral(nextUntilOneOf(STOPCHARS));
}
}
@@ -185,7 +187,7 @@ class ValueTokenizer {
return array;
default:
back(c);
- array.set(array.length(), (Value) nextValue());
+ nextValue().ifPresent(v -> array.set(array.length(), v));
final int d = nextNonWhitespace();
switch (d) {
case ']':
@@ -220,8 +222,7 @@ class ValueTokenizer {
if (nextNonWhitespace() != ':') {
throw new ValueException("Invalid object: expecting \":\"");
}
- // TODO(knorton): Make sure this key is not already set.
- object.put(key, (Value) nextValue());
+ nextValue().ifPresent(v -> object.put(key, v));
switch (nextNonWhitespace()) {
case ',':
break;
@@ -249,8 +250,7 @@ class ValueTokenizer {
if (nextNonWhitespace() != ':') {
throw new ValueException("Invalid object: expecting \":\"");
}
- // TODO(knorton): Make sure this key is not already set.
- object.put(keyBuffer.toString(), (Value) nextValue());
+ nextValue().ifPresent(v -> object.put(keyBuffer.toString(), v));
switch (nextNonWhitespace()) {
case ',':
break;
@@ -276,26 +276,26 @@ class ValueTokenizer {
}
}
- private Value getValueForLiteral(String literal) throws ValueException {
+ private Optional<Value> getValueForLiteral(String literal) throws ValueException {
if ("".equals(literal)) {
throw new ValueException("Missing value");
}
if ("null".equals(literal) || "undefined".equals(literal)) {
- return valueFactory.createNull();
+ return Optional.empty();
}
if ("true".equals(literal)) {
- return valueFactory.create(true);
+ return Optional.of(valueFactory.create(true));
}
if ("false".equals(literal)) {
- return valueFactory.create(false);
+ return Optional.of(valueFactory.create(false));
}
final char c = literal.charAt(0);
if (c == '-' || Character.isDigit(c)) {
- return getNumberForLiteral(literal);
+ return Optional.of(getNumberForLiteral(literal));
}
throw new ValueException("Invalid literal: \"" + literal + "\"");
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.java
index 86c05d681..76cef0cbb 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ValueUtil.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ValueUtil.java
@@ -15,7 +15,10 @@
*/
package org.openremote.model.value.impl;
-import org.openremote.model.value.*;
+import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueException;
import java.util.Collections;
import java.util.HashSet;
@@ -143,11 +146,6 @@ public class ValueUtil {
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");
@@ -191,10 +189,6 @@ public class ValueUtil {
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.
*/
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.java
index cdea3b0a2..e81aeb3bd 100644
--- a/model/src/main/java/org/openremote/model/value/impl/ValueVisitor.java
+++ b/model/src/main/java/org/openremote/model/value/impl/ValueVisitor.java
@@ -163,9 +163,4 @@ class ValueVisitor {
return true;
}
- /**
- * Called for nulls present in an object.
- */
- public void visitNull(ValueContext ctx) {
- }
}