Skip to content

Commit

Permalink
Added value coercion methods
Browse files Browse the repository at this point in the history
  • Loading branch information
richturner committed Jun 25, 2017
1 parent 44f25e4 commit 92f108f
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions model/src/main/java/org/openremote/model/value/Values.java
Expand Up @@ -71,6 +71,59 @@ public static Optional<Boolean> getBoolean(Value value) {
return cast(BooleanValue.class, value).map(BooleanValue::getBoolean);
}

/**
* Will attempt to coerce the value into a boolean (where it makes sense)
*/
public static Optional<Boolean> getBooleanCoerced(Value value) {
if (value == null) {
return Optional.empty();
}

switch (value.getType()) {
case OBJECT:
return Optional.empty();
case ARRAY:
return Optional.empty();
case STRING:
return Optional.of(Boolean.parseBoolean(value.toString().toLowerCase()));
case NUMBER:
int number = Values.getNumber(value).map(Double::intValue).orElse(2);
return number == 0 ? Optional.of(false) : number == 1 ? Optional.of(true) : Optional.empty();
case BOOLEAN:
return Values.getBoolean(value);
}

return Optional.empty();
}

/**
* Attempts to coerce the value into an integer (where it makes sense)
*/
public static Optional<Integer> getIntegerCoerced(Value value) {
if (value == null) {
return Optional.empty();
}

switch (value.getType()) {
case OBJECT:
return Optional.empty();
case ARRAY:
return Optional.empty();
case STRING:
try {
Optional.of(Integer.parseInt(value.toString()));
} catch (NumberFormatException e) {
return Optional.empty();
}
case NUMBER:
return Values.getNumber(value).map(Double::intValue);
case BOOLEAN:
return Values.getBoolean(value).map(b -> b ? 1 : 0);
}

return Optional.empty();
}

public static Optional<ObjectValue> getObject(Value value) {
return cast(ObjectValue.class, value);
}
Expand Down

0 comments on commit 92f108f

Please sign in to comment.