Add metadata processing.
LocationBasedServices/mowesta/pipeline/head This commit looks good

This commit is contained in:
2021-05-19 14:42:09 +02:00
parent 66550094c8
commit e338fd6c47
32 changed files with 2688 additions and 304 deletions
+4 -2
View File
@@ -58,7 +58,9 @@ allprojects {
versionAndroidXRoom = '2.2.6'
versionAndroidXPreference = '1.1.1'
versionRobolectric = '4.5'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
}
@@ -178,4 +180,4 @@ gradle.taskGraph.afterTask {
available.signal()
lock.unlock()
}
}
}
@@ -1,12 +1,8 @@
package com.mowesta.api.measurement;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mowesta.api.Coordinate;
import com.mowesta.api.Entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashMap;
import java.util.Map;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
@@ -14,8 +10,12 @@ import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mowesta.api.Coordinate;
import com.mowesta.api.Entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Represents a measurement of a device.
@@ -25,7 +25,7 @@ import java.util.Map;
@XmlRootElement
@ApiModel(description = "Represents a measurement of a device at a particular point in time.", parent = Entity.class)
public class Measurement extends Entity {
/**
* The coordinate of the device, if it can be determined. Note that it
* also makes sense to allow the capturing of data for unknown locations
@@ -37,19 +37,19 @@ public class Measurement extends Entity {
private Coordinate coordinate;
/**
* The time stamp assigned by the device when the measurement was created.
* The time stamp assigned by the device when the measurement was created.
*/
@XmlAttribute(required = true)
@ApiModelProperty(value = "The timestamp of the measurement in Epoch milliseconds.", required = true)
private long time;
/**
* The device id of the device that created the measurement.
*/
@XmlAttribute(required = true)
@ApiModelProperty(value = "The device id of the measurement.", required = true)
private long device;
/**
* The version of the application that captured the measurement.
*/
@@ -57,7 +57,7 @@ public class Measurement extends Entity {
@XmlAttribute(required = true)
@ApiModelProperty(value = "The app version (version code on Android or build code on IOS).", required = true)
private long version;
/**
* The actual raw data captured by the device.
*/
@@ -66,22 +66,26 @@ public class Measurement extends Entity {
@JsonProperty(value = "data")
@ApiModelProperty(value = "The raw data captured by the device.")
private Map<MeasurementType, String> data = new HashMap<>();
/**
* The temperature calculated by the server.
*/
@XmlAttribute
@ApiModelProperty(value = "The calculated air temperature (estimated by the service), may be null.")
@ApiModelProperty(value = "The calculated air temperature (estimated by the service) in centigrade, may be null.")
private Double temperature;
@XmlAttribute
@ApiModelProperty(value = "The calculated air pressure (estimated by the service), may be null.")
@ApiModelProperty(value = "The calculated air pressure (estimated by the service) in hPA, may be null.")
private Double pressure;
@XmlAttribute
@ApiModelProperty(value = "The calculated relative humidity (estimated by the service), may be null.")
@ApiModelProperty(value = "The calculated relative humidity (estimated by the service) in percent, may be null.")
private Double humidity;
@XmlAttribute
@ApiModelProperty(value = "The calculated measurement rating (estimated by the service) from 0 (low quality) to 1 (high quality), may be null.")
private Double rating;
/**
* The default constructor for serialization.
*/
@@ -232,7 +236,21 @@ public class Measurement extends Entity {
public void setHumidity(Double humidity) {
this.humidity = humidity;
}
/**
* Returns the rating.
* @return The rating.
*/
public Double getRating() {
return rating;
}
/**
* Sets the rating.
*
* @param rating The rating to set.
*/
public void setRating(Double rating) {
this.rating = rating;
}
}
@@ -8,7 +8,7 @@ import com.fasterxml.jackson.annotation.JsonValue;
/**
* The types of measurement context.
*
*
* @author Sebastian
*/
public enum MeasurementType {
@@ -18,87 +18,127 @@ public enum MeasurementType {
* e.g. true false
*/
BATTERY_CHARGING(Boolean.class),
/**
* The temperature reading of the battery (double value in centigrade, can be read through ACTION_BATTERY_CHANGED).
* e.g. 37.1, -1.3
*/
BATTERY_TEMPERATURE(Double.class),
/**
* A temperature reading of a temperature sensor (double value in centigrade, TYPE_TEMERATURE on Android).
* e.g. 37.1, -1.3
*/
SENSOR_TEMPERATURE(Double.class),
/**
* A pressure reading of a barometer sensor (double value in hPa, TYPE_BAROMETER on Android).
* e.g. 1000.0, 998.26127
*/
SENSOR_PRESSURE(Double.class),
/**
* A humidity reading of a humidity sensor (double value as relative humidity in %, TYPE_RELATIVE_HUMIDITY on Android).
* range: 0-1 (0->0%, 1->100%, 0.5->50%)
*/
SENSOR_HUMIDITY(Double.class),
/**
* The temperature of the cpu (double value in centigrade, can be read by analyzing the proc file system).
* e.g. 37.1 -1.3
*/
CPU_TEMPERATURE(Double.class),
/**
* The current frequency of the cpu (double value in mhz, can be read by analyzing the proc file system).
*/
CPU_FREQUENCY(Double.class),
/**
* A boolean to determine whether the screen is on (true) or off (false).
*/
SCREEN_ENABLED(Boolean.class),
/**
* The voltage of the battery (used to monitor the battery of the weather station).
* e.g. 3.77 -> 3.77 Volt
*/
BATTERY_VOLTAGE(Double.class),
/**
* The voltage of the solar panel (used to estimate whether the weather station is located in the sun).
* e.g. 3.77 -> 3.77 Volt
* e.g. 3.77 -> 3.77 Volt
*/
SOLAR_VOLTAGE(Double.class);
SOLAR_VOLTAGE(Double.class),
/**
* The distance from the next building.
*/
BUILDING_DISTANCE(Double.class),
/**
* The distance from the previous measurement in meters.
*/
MOVEMENT_DISTANCE(Double.class),
/**
* The time difference between the current and the previous measurement.
*/
TIME_DIFFERENCE(Double.class),
/**
* The difference between the current temperature and the previous temperature.
*/
TEMPERATURE_DIFFERENCE(Double.class),
/**
* A flag to determine whether we are outside (true) or inside (false).
*/
OUTSIDE_INDICATOR(Boolean.class),
/**
* The length of time that the device was outside.
*/
OUTSIDE_DURATION(Double.class),
/**
* The temperature of the nearest station.
*/
STATION_TEMPERATURE(Double.class),
/**
* The air pressure of the nearest station.
*/
STATION_PRESSURE(Double.class);
/**
* The data type.
*/
private Class<?> type;
/**
* Creates a measurement type with the specified data type.
*
*
* @param type The data type expected for the measurement.
*/
private MeasurementType(Class<?> type) {
this.type = type;
}
/**
* Returns the data type.
*
*
* @return The data type.
*/
public Class<?> getType() {
return type;
}
/**
* Parses the data and returns a java array with the type
* represented by this constant or an empty array, if the
* represented by this constant or an empty array, if the
* data cannot be parsed.
*
*
* @param value The value to parse.
* @return The java object.
*/
@@ -108,26 +148,69 @@ public enum MeasurementType {
String[] substrings = value.split(",");
if (type == Boolean.class) {
for (String s: substrings) {
Boolean b = (Boolean)parseValue(s);
Boolean b = (Boolean)readValue(s);
if (b != null) result.add(b);
}
} else if (type == Double.class) {
for (String s: substrings) {
Double d = (Double)parseValue(s);
Double d = (Double)readValue(s);
if (d != null) result.add(d);
}
}
}
}
}
return result.toArray(new Object[result.size()]);
}
/**
* Returns the string version of the values
* for the type represented by this constant or
* null, if there is nothing to write.
*
* @param values The values.
* @return The string value for the values.
*/
public String setValues(Object[] values) {
List<String> list = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
String s = writeValue(values[i]);
if (s != null) list.add(s);
}
if (list.size() == 0) {
return null;
} else {
StringBuilder b = new StringBuilder();
b.append(list.get(0));
for (int i = 1; i < list.size(); i++) {
b.append(",");
b.append(list.get(i));
}
return b.toString();
}
}
/**
* Returns the string value of the object.
*
* @param value The value to serialize.
* @return The string value.
*/
private String writeValue(Object value) {
if (type == Double.class && value instanceof Number) {
return Double.toString(((Number)value).doubleValue());
} else if (type == Boolean.class && value instanceof Boolean) {
return Boolean.toString((Boolean)value);
} else {
return null;
}
}
/**
* Parses a single value.
*
*
* @param value The string value.
* @return The parsed value.
*/
private Object parseValue(String value) {
private Object readValue(String value) {
if (value == null) return null;
value = value.trim();
if (type == Boolean.class) {
@@ -143,13 +226,11 @@ public enum MeasurementType {
} else {
return null;
}
}
/**
* Returns the value for the json representation.
*
*
* @param json The json string.
* @return The measurement_context type.
*/
@@ -162,7 +243,7 @@ public enum MeasurementType {
/**
* Returns the json representation.
*
*
* @return The json representation.
*/
@JsonValue
@@ -36,8 +36,8 @@ extension DataManager {
let _ = CDevice(context: mockCtx, device: Device(_id: 2, creationTime: 0, modificationTime: 0, deleted: false, user: 123, os: .ios, manufacturer: "Apple Inc.", device: "iPad", model: "iPad8,1"))
let _ = CDevice(context: mockCtx, device: Device(_id: 123456, creationTime: 0, modificationTime: 0, deleted: false, user: 123, os: .ios, manufacturer: "Apple Inc.", device: "iPhone", model: "iPhone8,2"))
let _ = CDMeasurement(context: mockCtx, measurement: MowestaApi.Measurement(_id: 1, creationTime: 10, modificationTime: 10, deleted: false, coordinate: .essen, time: 9, device: 1, version: 1, temperature: 10.2, pressure: 1001.34, humidity: 45, data: ["SENSOR_HUMIDITY":"12.32", "SENSOR_PRESSURE":"999.738212"]))
let _ = CDMeasurement(context: mockCtx, measurement: MowestaApi.Measurement(_id: 2, creationTime: 4000, modificationTime: 4000, deleted: false, coordinate: .applePark, time: 1020, device: 1, version: 1, temperature: 22.872, pressure: 999.010922, humidity: 50.21, data: ["SENSOR_HUMIDITY":"45", "SENSOR_PRESSURE":"1003"]))
let _ = CDMeasurement(context: mockCtx, measurement: MowestaApi.Measurement(_id: 1, creationTime: 10, modificationTime: 10, deleted: false, coordinate: .essen, time: 9, device: 1, version: 1, temperature: 10.2, predictionVersion: 0, pressure: 1001.34, humidity: 45, rating: 0.5, data: ["SENSOR_HUMIDITY":"12.32", "SENSOR_PRESSURE":"999.738212"]))
let _ = CDMeasurement(context: mockCtx, measurement: MowestaApi.Measurement(_id: 2, creationTime: 4000, modificationTime: 4000, deleted: false, coordinate: .applePark, time: 1020, device: 1, version: 1, temperature: 22.872, predictionVersion: 0, pressure: 999.010922, humidity: 50.21, rating: 0.5, data: ["SENSOR_HUMIDITY":"45", "SENSOR_PRESSURE":"1003"]))
return mockCtx
}
}
@@ -11,6 +11,6 @@ import MowestaApi
extension MowestaApi.Measurement {
init(coordinate: Coordinate, time date: Date, measurements data: [String:String], deviceId: Int64) {
self.init(_id: nil, creationTime: nil, modificationTime: nil, deleted: false, coordinate: coordinate, time: date.millisecondsSince1970, device: deviceId, version: 1, temperature: nil, pressure: nil, humidity: nil, data: data)
self.init(_id: nil, creationTime: nil, modificationTime: nil, deleted: false, coordinate: coordinate, time: date.millisecondsSince1970, device: deviceId, version: 1, temperature: nil, predictionVersion: nil, pressure: nil, humidity: nil, rating: 0.5, data: data)
}
}
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<web-app xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd "
version = "4.0">
<display-name>alexaservlet</display-name>
<servlet>
<servlet-name>alexaservlet</servlet-name>
@@ -0,0 +1,163 @@
package com.mowesta.data.process.algorithm;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Implements linear regression as in the example code given here:
* https://introcs.cs.princeton.edu/java/97data/LinearRegression.java
*
* @author Marcus
*/
public class LinearRegression {
/**
* A builder for the linear regression.
*
* @author Marcus
* @param <T> The type of number to store.
*/
public static class Builder<T extends Number> {
/**
* The x values.
*/
private List<T> x = new LinkedList<>();
/**
* The y values.
*/
private List<T> y = new LinkedList<>();
/**
* Adds a point to the builder.
*
* @param x The x value.
* @param y The y value.
*/
public void add(T x, T y) {
this.x.add(x);
this.y.add(y);
}
/**
* Performs the linear regression and returns it.
*
* @return The linear regression.
*/
public LinearRegression build() {
return new LinearRegression(x, y);
}
}
/**
* The intersection with the y-axis.
*/
private double intercept;
/**
* The slope of the straight.
*/
private double slope;
/**
* The r² value.
*/
private double rSquared;
/**
* The standard error.
*/
private double error;
/**
* Performs linear regression on the given values. Of course,
* we need at least 2 values at different x positions for this
* to work.
*
* @param x The x values.
* @param y The y values.
*/
public LinearRegression(List<? extends Number> x, List<? extends Number> y) {
int n = Math.min(x.size(), y.size());
// first pass: read in data, compute xbar and ybar
double sumx = 0.0, sumy = 0.0;
Iterator<? extends Number> itx = x.iterator();
Iterator<? extends Number> ity = y.iterator();
for (int i = 0; i < n; i++) {
double vx = itx.next().doubleValue();
double vy = ity.next().doubleValue();
sumx += vx;
sumy += vy;
}
double xbar = sumx / n;
double ybar = sumy / n;
// second pass: compute summary statistics
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
itx = x.iterator();
ity = y.iterator();
for (int i = 0; i < n; i++) {
double vx = itx.next().doubleValue();
double vy = ity.next().doubleValue();
xxbar += (vx - xbar) * (vx - xbar);
yybar += (vy - ybar) * (vy - ybar);
xybar += (vx - xbar) * (vy - ybar);
}
slope = xybar / xxbar;
intercept = ybar - slope * xbar;
// analyze results
double rss = 0.0; // residual sum of squares
double ssr = 0.0; // regression sum of squares
itx = x.iterator();
ity = y.iterator();
for (int i = 0; i < n; i++) {
double vx = itx.next().doubleValue();
double vy = ity.next().doubleValue();
double fit = slope*vx + intercept;
rss += (fit - vy) * (fit - vy);
ssr += (fit - ybar) * (fit - ybar);
}
rSquared = ssr / yybar;
error = Math.sqrt(rss / (n - 2));
}
/**
* Returns the R² value.
*
* @return The r squared value.
*/
public double getRSquared() {
return rSquared;
}
/**
* Returns the remaining error.
*
* @return The remaining error.
*/
public double getError() {
return error;
}
/**
* Returns the intersection with y.
*
* @return The intersection with y.
*/
public double getIntercept() {
return intercept;
}
/**
* Returns the slope of the curve.
*
* @return The slope of the curve.
*/
public double getSlope() {
return slope;
}
}
+12
View File
@@ -11,6 +11,12 @@ dependencies {
compile project(':service-data')
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
compile "org.infinispan:infinispan-query:${versionInfinispan}"
compile "com.locoslab.library.geometry:geometry-wgs:${versionGeometry}"
compile "com.locoslab.service.carta:carta-api:${versionCarta}"
compile "org.jboss.resteasy:resteasy-client:${versionResteasy}"
compile "org.jboss.resteasy:resteasy-jackson2-provider:${versionResteasy}"
compileOnly "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
compileOnly "org.hibernate:hibernate-search-orm:${versionHibernateSearch}"
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
@@ -33,6 +39,12 @@ dependencies {
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
testBundle "org.infinispan:infinispan-query:${versionInfinispan}"
testBundle "com.locoslab.library.geometry:geometry-wgs:${versionGeometry}"
testBundle "com.locoslab.service.carta:carta-api:${versionCarta}"
testBundle "org.jboss.resteasy:resteasy-client:${versionResteasy}"
testBundle "org.jboss.resteasy:resteasy-jackson2-provider:${versionResteasy}"
}
// copy the jars required for testing into an output folder
@@ -15,6 +15,7 @@ import org.hibernate.search.annotations.SortableField;
import org.hibernate.search.annotations.Spatial;
import org.hibernate.search.annotations.SpatialMode;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.hibernate.search.query.dsl.Unit;
@@ -24,7 +25,7 @@ import com.mowesta.api.Coordinate;
/**
* Base class for entities with coordinate.
*
*
* @author Jan
*/
@Entity
@@ -40,7 +41,7 @@ public abstract class AbstractSpatialEntity extends AbstractEntity {
@Spatial(spatialMode = SpatialMode.HASH)
@SortableField
private EmbeddedCoordinate coordinate;
/**
* Returns the coordiante.
*
@@ -49,7 +50,7 @@ public abstract class AbstractSpatialEntity extends AbstractEntity {
public EmbeddedCoordinate getCoordinate() {
return coordinate;
}
/**
* Sets the coordiante.
*
@@ -58,17 +59,17 @@ public abstract class AbstractSpatialEntity extends AbstractEntity {
public void setCoordinate(EmbeddedCoordinate coordiante) {
this.coordinate = coordiante;
}
/**
* Finds the entities within the specified range and returns them.
*
*
* @param em The entity manager.
* @param <E> The type to search.
* @param type The type to search.
* @param location The location.
* @param range The maximum search range in km.
* @param limit The maximum number to return.
* @return The nearest (limit) forecasts from the coordinate that are at most (range) away.
* @param limit The maximum number to return or -1 to return all.
* @return The nearest (limit) forecasts from the coordinate that are at most (range) away.
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractSpatialEntity> List<E> findByLocation(EntityManager em, Class<E> type, Coordinate location, int range, int limit) {
@@ -79,12 +80,14 @@ public abstract class AbstractSpatialEntity extends AbstractEntity {
.createQuery();
Sort order = new Sort(new DistanceSortField(location.getLatitude(), location.getLongitude(), "coordinate"));
List<E> result = new ArrayList<>();
for (Object o: manager.createFullTextQuery(query, type).setMaxResults(limit).setSort(order).getResultList()) {
FullTextQuery q = manager.createFullTextQuery(query, type).setSort(order);
if (limit >= 0) q = q.setMaxResults(limit);
for (Object o: q.getResultList()) {
if (type.isAssignableFrom(o.getClass())) {
result.add((E)o);
result.add((E)o);
}
}
return result;
}
}
@@ -0,0 +1,74 @@
package com.mowesta.service.entity;
/**
* Represents a range of entities from a particular
* id to a particular id.
*
* @author Marcus
*
*/
public class EntityRange {
/**
* The first id of the measurement range.
*/
private long start;
/**
* The last id of the measurement range.
*/
private long end;
/**
* Create a range of entities from a particular
* id to a particular id.
*
* @param start The first id of the range.
* @param end The last id of the range.
*/
public EntityRange(long start, long end) {
this.start = start;
this.end = end;
}
/**
* The id of the end of the range.
*
* @return The id of the end.
*/
public long getEnd() {
return end;
}
/**
* The id of the start of the range.
*
* @return The id of the start.
*/
public long getStart() {
return start;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (end ^ (end >>> 32));
result = prime * result + (int) (start ^ (start >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EntityRange other = (EntityRange) obj;
return (end == other.end && start == other.start);
}
@Override
public String toString() {
return "Start(" + start + ") End(" + end + ")";
}
}
@@ -0,0 +1,298 @@
package com.mowesta.service.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.mowesta.api.TimeRange;
/**
* This entity is used to store the two linear temperature models that
* constitute the heat transfer model explained in "Crowd-sourcing
* urban air temperatures from smartphone battery temperatures"
* which can be found at https://doi.org/10.1002/grl.50786
*
* @author Johannes Jahn
*/
@Entity
@Table(name = "temperature_model", indexes = {
@Index(columnList = "type,start,duration", unique = false),
})
public class LinearModelEntity extends AbstractEntity {
/**
* The model type represented by the entry.
*
* @author Marcus
*/
public enum ModelType {
/**
* Represents the linear model used to compute
* an equilibrium value. This model is a linear
* fit over a long period of measurements.
*/
TEMPERATURE_EQUILIBRIUM,
/**
* Represents the linear model to compute the
* heat transfer. This model applies a short-term
* scaling.
*/
TEMPERATURE_PREDICTION;
}
/**
* The serialization version.
*/
private static final long serialVersionUID = 8039668173139778735L;
/**
* The type of the model.
*/
@Column
@Enumerated(EnumType.ORDINAL)
private ModelType type;
/**
* The timestamp of the first measurement included in the model.
*/
@Column
private long start;
/**
* The duration of the timestamps considered in the model.
*/
@Column
private long duration;
/**
* The maximum measurement id considered in the run which can be
* used to detect whether the model should be recomputed. If
* there are measurements which fall into the time range that
* have a higher id than this, we know the model is outdated.
*/
@Column
private long measurement;
/**
* The slope of the linear model.
*/
@Column
private double slope;
/**
* The intercept of the linear model.
*/
@Column
private double intercept;
/**
* The base model used to compute the model. For temperature
* prediction models, this will point to the equilibrium model
* used to derive the prediction.
*/
@ManyToOne
@JoinColumn(name="basis")
private LinearModelEntity basis;
/**
* Returns the begin time of the training data the model was trained on.
*
* @return The begin time.
*/
public long getStart() {
return start;
}
/**
* Sets the start time.
*
* @param start The start time to set.
*/
public void setStart(long start) {
this.start = start;
}
/**
* Returns the duration of measurements considered in this mode.
*
* @return The duration of the model.
*/
public long getDuration() {
return duration;
}
/**
* Sets the end time.
*
* @param endTime The end time to set.
*/
public void setDuration(long endTime) {
this.duration = endTime;
}
/**
* Returns the slope.
*
* @return The slope.
*/
public double getSlope() {
return slope;
}
/**
* Sets the slope.
*
* @param slope The slope.
*/
public void setSlope(double slope) {
this.slope = slope;
}
/**
* Returns the intercept.
*
* @return The intercept.
*/
public double getIntercept() {
return intercept;
}
/**
* Sets the intercept.
*
* @param intercept The intercept.
*/
public void setIntercept(double intercept) {
this.intercept = intercept;
}
/**
* Returns the type.
*
* @return The type.
*/
public ModelType getType() {
return type;
}
/**
* Sets the type.
*
* @param type The type to set.
*/
public void setType(ModelType type) {
this.type = type;
}
/**
* Returns the measurement.
*
* @return The measurement.
*/
public long getMeasurement() {
return measurement;
}
/**
* Sets the measurement.
*
* @param measurement The measurement to set.
*/
public void setMeasurement(long measurement) {
this.measurement = measurement;
}
/**
* Returns the base.
*
* @return The base.
*/
public LinearModelEntity getBasis() {
return basis;
}
/**
* Sets the base.
*
* @param base The base to set.
*/
public void setBasis(LinearModelEntity base) {
this.basis = base;
}
/**
* Predicts a value using the model.
*
* @param value The value.
* @return The predicted value.
*/
public Double predict(double value) {
double result = value * slope + intercept;
if (Double.isNaN(result) || Double.isInfinite(result)) return null;
return result;
}
/**
* Finds the most recent model entity of the specified type.
*
* @param em The entity manager.
* @param type The model type.
* @return The model entity or null, if no such model exists.
*/
public static LinearModelEntity findLatest(EntityManager em, ModelType type) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<LinearModelEntity> cq = cb.createQuery(LinearModelEntity.class);
Root<LinearModelEntity> r = cq.from(LinearModelEntity.class);
cq.select(r);
cq.where(cb.equal(r.get("type"), type));
cq.orderBy(cb.desc(r.get("creationTime")));
TypedQuery<LinearModelEntity> q = em.createQuery(cq);
q.setMaxResults(1);
List<LinearModelEntity> results = q.getResultList();
if (results.size() == 0) return null;
else return results.get(0);
}
/**
* Finds the most recent model entity that reflects the specified time
* range.
*
* @param em The entity manager.
* @param type The model type.
* @param range The time range.
* @return The linear model entity or null, if no such model exists.
*/
public static LinearModelEntity findLatestWithRange(EntityManager em, ModelType type, TimeRange range) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<LinearModelEntity> cq = cb.createQuery(LinearModelEntity.class);
Root<LinearModelEntity> r = cq.from(LinearModelEntity.class);
cq.select(r);
cq.where(cb.and(
cb.equal(r.get("type"), type),
cb.equal(r.get("start"), range.getStart()),
cb.equal(r.get("duration"), range.getDuration())
));
cq.orderBy(cb.desc(r.get("creationTime")));
TypedQuery<LinearModelEntity> q = em.createQuery(cq);
q.setMaxResults(1);
List<LinearModelEntity> results = q.getResultList();
if (results.size() == 0) return null;
else return results.get(0);
}
}
@@ -29,13 +29,15 @@ import com.mowesta.api.measurement.MeasurementType;
/**
* The entity to store measurements.
*
*
* @author Sebastian
*/
@Entity
@Table(name = "measurement", indexes = {
@Table(name = "measurement", indexes = {
@Index(columnList = "device_id,modificationTime", unique = false) ,
@Index(columnList = "device_id,time,deleted", unique = false)
@Index(columnList = "device_id,time,deleted", unique = false) ,
@Index(columnList = "device_id,time,data_version", unique = false),
@Index(columnList = "device_id,time,rating_version", unique = false)
})
public class MeasurementEntity extends AbstractSpatialEntity {
@@ -81,18 +83,48 @@ public class MeasurementEntity extends AbstractSpatialEntity {
/**
* The temperature in centigrade.
*/
@Column
private Double temperature;
/**
* The pressure in hPA.
*/
@Column
private Double pressure;
/**
* The relative humidity in %.
*/
@Column
private Double humidity;
/**
* The rating of the measurement.
*/
private Double rating;
/**
* The temperature model used to compute the predicted
* temperature.
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="temperature_model")
private LinearModelEntity temperatureModel;
/**
* The version of the metadata processing applied to
* this measurement.
*/
@Column(name = "data_version")
private Integer dataVersion;
/**
* The version of the rating processing applied to this
* measurement.
*/
@Column(name = "rating_version")
private Integer ratingVersion;
/**
* Returns the timestamp.
*
@@ -218,10 +250,83 @@ public class MeasurementEntity extends AbstractSpatialEntity {
public void setHumidity(Double humidity) {
this.humidity = humidity;
}
/**
* Returns the rating.
*
* @return The rating.
*/
public Double getRating() {
return rating;
}
/**
* Sets the rating.
*
* @param rating The rating to set.
*/
public void setRating(Double rating) {
this.rating = rating;
}
/**
* Returns the rating version.
*
* @return The rating version.
*/
public Integer getRatingVersion() {
return ratingVersion;
}
/**
* Sets the rating version.
*
* @param ratingVersion The rating version to set.
*/
public void setRatingVersion(Integer ratingVersion) {
this.ratingVersion = ratingVersion;
}
/**
* Returns the temperatureModel.
*
* @return The temperatureModel.
*/
public LinearModelEntity getTemperatureModel() {
return temperatureModel;
}
/**
* Sets the temperatureModel.
*
* @param temperatureModel The temperatureModel to set.
*/
public void setTemperatureModel(LinearModelEntity temperatureModel) {
this.temperatureModel = temperatureModel;
}
/**
* Returns the dataVersion.
*
* @return The dataVersion.
*/
public Integer getDataVersion() {
return dataVersion;
}
/**
* Sets the dataVersion.
*
* @param dataVersion The dataVersion to set.
*/
public void setDataVersion(Integer dataVersion) {
this.dataVersion = dataVersion;
}
/**
* Returns the (first) measurement entity of the specified device with the specified timestamp.
*
*
* @param em The entity manager.
* @param device The device.
* @param time The time stamp.
@@ -239,12 +344,12 @@ public class MeasurementEntity extends AbstractSpatialEntity {
if (results.size() == 0) return null;
else return results.get(0);
}
/**
* Returns the maximum modification time stamp for a particular device.
* If device is null the maximum modification time stamp for all measurements
* of all devices is returned.
*
*
* @param em The entity manager.
* @param device The device to search.
* @return The maximum modification time stamp.
@@ -292,7 +397,7 @@ public class MeasurementEntity extends AbstractSpatialEntity {
/**
* Counts the number of measurement whose start and duration time matches.
* If device is not null it only filters for the specified device.
*
*
* @param em The entity manager.
* @param device The device to search measurements for or null.
* @param timeRange The time range.
@@ -317,10 +422,23 @@ public class MeasurementEntity extends AbstractSpatialEntity {
return getSingleResultOrZero(q).intValue();
}
// public static List<MeasurementEntity> getMeasurementsWithoutRatingInTimeRange(EntityManager em, PageConfig config, TimeRange timeRange) {
// CriteriaBuilder cb = em.getCriteriaBuilder();
// CriteriaQuery<MeasurementEntity> cq = cb.createQuery(MeasurementEntity.class);
// Root<MeasurementEntity> r = cq.from(MeasurementEntity.class);
// cq.where(cb.isNull(r.get("ratingVersion")));
// cq.where(cb.between(r.get("time"), timeRange.getStart(), timeRange.getEnd()));
//
// TypedQuery<MeasurementEntity> q = em.createQuery(cq);
// q.setFirstResult(config.getOffset());
// q.setMaxResults(config.getSize());
// return q.getResultList();
// }
/**
* Finds all measurement by start and duration time.
* If device is not null it only filters for the specified device.
*
*
* @param em The entity manager.
* @param device The device to search measurements for or null.
* @param config The page configuration.
@@ -351,4 +469,112 @@ public class MeasurementEntity extends AbstractSpatialEntity {
q.setMaxResults(config.getSize());
return q.getResultList();
}
/**
* Returns the range of measurements of a particular device whose metadata must be updated.
*
* @param em The entity manager.
* @param deviceId The device id.
* @param time The time to limit responses to values below the time.
* @param dataVersion The metadata version.
* @return The entity range.
*/
public static EntityRange findMetadataEntityRange(EntityManager em, long deviceId, long time, long dataVersion) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<EntityRange> cq = cb.createQuery(EntityRange.class);
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class);
cq.multiselect(cb.min(r.get("id")), cb.max(r.get("id")));
Predicate dev = cb.equal(r.get("device").get("id"), deviceId);
Predicate ver = cb.not(cb.equal(r.get("dataVersion"), dataVersion));
Predicate non = cb.isNull(r.get("dataVersion"));
Predicate t = cb.lessThan(r.get("time"), time);
cq.where(cb.and(dev, t, cb.or(ver, non)));
TypedQuery<EntityRange> q = em.createQuery(cq);
List<EntityRange> result = q.getResultList();
if (result.isEmpty()) return null;
else return result.get(0);
}
/**
* Returns the previous measurement of a device for a given measurement id, if it exists.
*
* @param em The entity manager.
* @param deviceId The device id.
* @param measurementId The measurement id.
* @return The measurement that has been made directly before the specified measurement id.
*/
public static MeasurementEntity findPrevious(EntityManager em, long deviceId, long measurementId) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MeasurementEntity> cq = cb.createQuery(MeasurementEntity.class);
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class);
cq.select(r);
cq.where(cb.and(cb.equal(r.get("device").get("id"), deviceId), cb.lessThan(r.get("id"), measurementId)));
cq.orderBy(cb.desc(r.get("id")));
TypedQuery<MeasurementEntity> q = em.createQuery(cq);
q.setFirstResult(0);
q.setMaxResults(1);
List<MeasurementEntity> result = q.getResultList();
if (result.size() == 0) return null;
else return result.get(0);
}
/**
* Finds the device whose metadata can be updated with the lowest measurement id.
*
* @param em The entity manager.
* @param time The time to limit responses to values below the time.
* @param dataVersion The metadata version.
* @return The device id or null, if no device can be updated.
*/
public static Long findMetadataDevice(EntityManager em, long time, long dataVersion) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class);
cq.multiselect(r.get("device").get("id"), cb.min(r.get("id")));
cq.distinct(true);
cq.groupBy(r.get("device").get("id"));
Predicate ver = cb.not(cb.equal(r.get("dataVersion"), dataVersion));
Predicate non = cb.isNull(r.get("dataVersion"));
Predicate t = cb.lessThan(r.get("time"), time);
cq.where(cb.and(t, cb.or(ver, non)));
cq.orderBy(cb.asc(cb.min(r.get("id"))));
TypedQuery<Object[]> q = em.createQuery(cq);
q.setMaxResults(1);
List<Object[]> result = q.getResultList();
if (result.isEmpty()) return null;
else return (Long)result.get(0)[0];
}
/**
* Finds all measurements of a device or all devices that reside within a
* specified range and returns them ordered by id.
*
* @param em The entity manager.
* @param config The page configuration.
* @param deviceId The device id (for one device) or null (for all devices).
* @param range The range.
* @return The list of measurements.
*/
public static List<MeasurementEntity> findAllByEntityRange(EntityManager em, PageConfig config, Long deviceId, EntityRange range) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MeasurementEntity> cq = cb.createQuery(MeasurementEntity.class);
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class);
cq.select(r);
Predicate predicate = cb.between(r.get("id"), range.getStart(), range.getEnd());
if (deviceId != null) {
Predicate dev = cb.equal(r.get("device").get("id"), deviceId);
predicate = cb.and(predicate, dev);
}
cq.where(predicate);
cq.orderBy(cb.asc(r.get("id")));
TypedQuery<MeasurementEntity> q = em.createQuery(cq);
q.setFirstResult(config.getOffset());
q.setMaxResults(config.getSize());
return q.getResultList();
}
}
@@ -27,7 +27,7 @@ import com.mowesta.api.TimeRange;
/**
* Represents a weather report from a station.
*
*
* @author Marcus
*/
@Entity
@@ -41,12 +41,12 @@ indexes = {
})
@Indexed
public class WeatherReportEntity extends AbstractEntity {
/**
* The serialization id.
*/
private static final long serialVersionUID = 5443960038620074108L;
/**
* The station that created the report.
*/
@@ -62,21 +62,21 @@ public class WeatherReportEntity extends AbstractEntity {
@Field
@SortableField
private long time;
/**
* The temperature in 2m above the ground in degree Celsius.
*/
@Column
@Field
private Double temperature;
/**
* The air pressure in hPa at the station's altitude.
*/
@Column
@Field
private Double pressure;
/**
* The relative humidity measured at two meters above the ground.
*/
@@ -173,15 +173,33 @@ public class WeatherReportEntity extends AbstractEntity {
public void setHumidity(Double humidity) {
this.humidity = humidity;
}
/**
* Returns the maximum time that we have available for any station.
*
* @param em The entity manager.
* @param filtered True to filter deleted reports and stations.
* @return The maximum time we have available.
*/
public static long getMaxTime(EntityManager em, boolean filtered) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<WeatherReportEntity> r = cq.from(WeatherReportEntity.class);
cq.select(cb.max(r.get("time")));
if (filtered) {
cq.where(cb.equal(r.get("deleted"), false));
}
TypedQuery<Long> q = em.createQuery(cq);
return getSingleResultOrZero(q).longValue();
}
/**
* Finds the latest report time of a station.
*
*
* @param em The entity manager.
* @param station The station to lookup.
* @param filtered True to filter deleted.
* @return The maximum time of the station.
* @return The maximum time of the station.
*/
public static long getMaxTime(EntityManager em, WeatherStationEntity station, boolean filtered) {
CriteriaBuilder cb = em.getCriteriaBuilder();
@@ -197,11 +215,11 @@ public class WeatherReportEntity extends AbstractEntity {
TypedQuery<Long> q = em.createQuery(cq);
return getSingleResultOrZero(q).longValue();
}
/**
* Finds a weather report of a station with a particular time stamp.
*
*
* @param em The entity manager.
* @param station The station.
* @param time The time stamp.
@@ -222,7 +240,7 @@ public class WeatherReportEntity extends AbstractEntity {
/**
* Finds all reports by start and duration time belonging to a particular station.
*
*
* @param em The entity manager.
* @param station The station to search for.
* @param config The page configuration.
@@ -252,7 +270,7 @@ public class WeatherReportEntity extends AbstractEntity {
/**
* Counts the number of reports for a page of a station in a time range.
*
*
* @param em The entity manager.
* @param station The station to search reports for.
* @param timeRange The time range.
@@ -274,10 +292,10 @@ public class WeatherReportEntity extends AbstractEntity {
TypedQuery<Long> q = em.createQuery(cq);
return getSingleResultOrZero(q).intValue();
}
/**
* Returns the maximum modification time stamp for a particular station.
*
*
* @param em The entity manager.
* @param station The station to search.
* @return The maximum modification time stamp.
@@ -293,5 +311,5 @@ public class WeatherReportEntity extends AbstractEntity {
}
}
@@ -26,6 +26,7 @@ import com.mowesta.service.entity.EmbeddedCoordinate;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.MeasurementEntity;
import com.mowesta.service.session.util.Measurements;
/**
* A stateful session bean to manage measurements.
@@ -41,7 +42,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
/**
* Adds a list of measurements for the current device.
*
*
* @param measurements The measurements to add.
* @return The measurements that have been added or the existing measurement, if they have been ignored.
* @throws EntityForbiddenException Thrown if the device is not authorized.
@@ -70,10 +71,10 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
em.flush();
return Convert.with(MeasurementConverter.class).apply(result, true);
}
/**
* Adds a single measurement, if the measurement has not been added already.
*
*
* @param m The measurement to add.
* @return The added measurement or the existing measurement, if the measurement was present already.
* @throws EntityForbiddenException Thrown if the device is not authorized.
@@ -94,10 +95,10 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
return Convert.with(MeasurementConverter.class).apply(existing, true);
}
}
/**
* Creates a measurement for the device.
*
*
* @param device The device.
* @param m The measurement to copy.
* @return The measurement entity.
@@ -108,23 +109,23 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
e.setVersion(m.getVersion());
e.setTime(m.getTime());
if (m.getHumidity() != null) {
e.setHumidity(getValidDouble("Humidity", m.getHumidity()));
e.setHumidity(Measurements.getValid("Humidity", m.getHumidity()));
} else {
e.setHumidity(getMeasurementAverage(m, MeasurementType.SENSOR_HUMIDITY));
e.setHumidity(Measurements.getAverage(MeasurementType.SENSOR_HUMIDITY, m.getData()));
}
if (m.getPressure() != null) {
e.setPressure(getValidDouble("Pressure", m.getPressure()));
e.setPressure(Measurements.getValid("Pressure", m.getPressure()));
} else {
e.setPressure(getMeasurementAverage(m, MeasurementType.SENSOR_PRESSURE));
e.setPressure(Measurements.getAverage(MeasurementType.SENSOR_PRESSURE, m.getData()));
}
if (m.getTemperature() != null) {
e.setTemperature(getValidDouble("Temperature", m.getTemperature()));
e.setTemperature(Measurements.getValid("Temperature", m.getTemperature()));
} else {
e.setTemperature(getMeasurementAverage(m, MeasurementType.SENSOR_TEMPERATURE));
e.setTemperature(Measurements.getAverage(MeasurementType.SENSOR_TEMPERATURE, m.getData()));
}
if (m.getCoordinate() != null) {
Double longitude = getValidDouble("Longitude", m.getCoordinate().getLongitude());
Double latitude = getValidDouble("Latitude", m.getCoordinate().getLatitude());
Double longitude = Measurements.getValid("Longitude", m.getCoordinate().getLongitude());
Double latitude = Measurements.getValid("Latitude", m.getCoordinate().getLatitude());
if (longitude != null && latitude != null) {
e.setCoordinate(new EmbeddedCoordinate(longitude, latitude));
}
@@ -156,48 +157,10 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
return e;
}
/**
* Returns a valid (non-nan and non-infinite) double or null.
*
* @param name The name to log.
* @param value The value to check.
* @return Null or a valid double.
*/
protected Double getValidDouble(String name, Double value) {
if (value == null) return null;
if (value.isNaN()) {
log.log(Level.INFO, "Ignoring NaN in field " + name + ".");
return null;
} else if (value.isInfinite()) {
log.log(Level.INFO, "Ignoring infinite value in field " + name + ".");
return null;
} else {
return value;
}
}
/**
* Computes the average value of the data specified by the
* measurement type.
*
* @param m The measurement.
* @param t The measurement type.
* @return The average value or null, if the data is not available.
*/
protected Double getMeasurementAverage(Measurement m, MeasurementType t) {
if (t.getType() != Double.class || m.getData() == null) return null;
Object[] data = t.getValues(m.getData().get(t));
if (data.length == 0) return null;
double result = 0;
for (Object o: data) {
result += (Double)o;
}
return getValidDouble(t.name(), Double.valueOf(result / data.length));
}
/**
* Returns a measurement page for the current device over a time range.
*
*
* @param range The time range.
* @param config The page configuration.
* @param filtered True to filter deleted, false otherwise.
@@ -213,7 +176,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
/**
* Returns a measurement page for the specified device over a time range.
*
*
* @param id The id of the device.
* @param range The time range.
* @param config The page configuration.
@@ -231,7 +194,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
/**
* Returns the last modification timestamp of the measurements
* for the current device.
*
*
* @return The last modification time stamp.
* @throws EntityNotFoundException Thrown if there is no caller principal.
*/
@@ -241,7 +204,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
if (principal == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot access principal device.");
return MeasurementEntity.getLastModifiedForDevice(em, principal);
}
/**
* Returns the time stamp of the last modification to the set of measurements.
*
@@ -286,7 +249,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
/**
* Returns a measurement page for a specific device and time range.
*
*
* @param device The device.
* @param range The time range.
* @param config The page configuration.
@@ -309,8 +272,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
* @param findAll Retrieves the actual measurements and adds it to the given page.
* @return The measurement page.
*/
private MeasurementPage createMeasurementPage(PageConfig config, IntSupplier measurementCount,
Consumer<MeasurementPage> findAll) {
private MeasurementPage createMeasurementPage(PageConfig config, IntSupplier measurementCount, Consumer<MeasurementPage> findAll) {
MeasurementPage page = new MeasurementPage();
page.setOffset(config.getOffset());
page.setSize(config.getSize());
@@ -322,10 +284,10 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
if (page.getElements() != null) {
for (Measurement m: page.getElements()) {
if (m.getTemperature() == null) {
m.setTemperature(getMeasurementAverage(m, MeasurementType.SENSOR_TEMPERATURE));
m.setTemperature(Measurements.getAverage(MeasurementType.SENSOR_TEMPERATURE, m.getData()));
}
if (m.getTemperature() == null) {
m.setTemperature(getMeasurementAverage(m, MeasurementType.BATTERY_TEMPERATURE));
m.setTemperature(Measurements.getAverage(MeasurementType.BATTERY_TEMPERATURE, m.getData()));
}
}
}
@@ -268,7 +268,8 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
*/
@PermitAll
public WeatherStation getStation(Coordinate coordinate, boolean filtered) {
return Convert.with(WeatherStationConverter.class).apply(getStationEntity(coordinate, filtered), filtered);
return Convert.with(WeatherStationConverter.class)
.apply(getStationEntity(coordinate, filtered, 100), filtered);
}
/**
@@ -276,10 +277,12 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
*
* @param coordinate The coordinate.
* @param filtered True to filter deleted.
* @param range Max Filter range in km.
* @return The station entity.
*/
protected WeatherStationEntity getStationEntity(Coordinate coordinate, boolean filtered) {
List<WeatherStationEntity> result = WeatherStationEntity.findByLocation(em, WeatherStationEntity.class, coordinate, 100, 5);
@PermitAll
public WeatherStationEntity getStationEntity(Coordinate coordinate, boolean filtered, int range) {
List<WeatherStationEntity> result = WeatherStationEntity.findByLocation(em, WeatherStationEntity.class, coordinate, range, 5);
for (WeatherStationEntity e: result) {
if (! filtered || !e.isDeleted()) return e;
}
@@ -307,7 +310,7 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
}
if (result == null) return null;
// find the weather station nearby
WeatherStationEntity station = getStationEntity(coordinate, true);
WeatherStationEntity station = getStationEntity(coordinate, true, 100);
if (station != null) {
WeatherReportEntity report = getLatestReportEntity(station, true);
if (report != null && report.getTime() > System.currentTimeMillis() - MAX_REPORT_AGE) {
@@ -0,0 +1,653 @@
package com.mowesta.service.session.measure;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import org.geojson.Feature;
import org.geojson.FeatureCollection;
import org.geojson.LngLatAlt;
import org.geojson.Polygon;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.locoslab.library.geometry.wgs.Box;
import com.locoslab.library.geometry.wgs.Coordinate;
import com.locoslab.library.geometry.wgs.Coordinates;
import com.locoslab.library.geometry.wgs.HaversineDistance;
import com.locoslab.library.geometry.wgs.MapTile;
import com.locoslab.library.geometry.wgs.Surface;
import com.locoslab.service.carta.api.vector.geojson.IVectorServiceGeojson;
import com.mowesta.api.PageConfig;
import com.mowesta.api.TimeRange;
import com.mowesta.api.measurement.MeasurementType;
import com.mowesta.service.entity.EntityRange;
import com.mowesta.service.entity.MeasurementEntity;
import com.mowesta.service.entity.WeatherReportEntity;
import com.mowesta.service.entity.WeatherStationEntity;
import com.mowesta.service.session.AbstractSessionBean;
import com.mowesta.service.session.ShutdownSessionBean;
import com.mowesta.service.session.util.Buildings;
import com.mowesta.service.session.util.Measurements;
/**
* The metadata session bean is used to enrich the measurements
* with additional data that is derived from individual as well
* as consecutive measurements.
*
* @author Marcus
*/
@Stateless
public class MetadataSessionBean extends AbstractSessionBean {
/**
* The base url for carta to load vector map tiles.
*/
public static final String URL_CARTA = "https://www.mowesta.com/carta";
/**
* The current version of the meta data processing.
*/
public static final int VERSION_CURRENT = 1;
/**
* The number of measurements to process per transaction.
*/
public static final int BATCH_SIZE = 20;
/**
* The delay that we are lagging behind the highest report.
*/
public static final int REPORT_DELAY = 3 * 60 * 60 * 1000;
/**
* The search range for buildings in meters.
*/
public static final double BUILDING_RANGE = 300;
/**
* The zoom level for building resolution.
*/
public static final int BUILDING_ZOOM = 15;
/**
* The range to search for stations in meters given as target
* range (used for resolution) and query range (used to limit db queries).
*/
public static final int[] STATION_RANGE = new int[] { 80000, 100000 };
/**
* The page size used to load measurements for a station.
*/
public static final int STATION_PAGE = 100;
/**
* The time to allow between device and station measurement.
*/
public static final long STATION_TIME = 30 * 60 * 1000;
/**
* The distance at which we consider someone to be outside of a building.
*/
public static final double OUTSIDE_BUILDING = 20;
/**
* The speed at which we consider someone to be moving outside in m/s
* defined as minimum, maximum.
*/
public static final double[] OUTSIDE_SPEED = new double[] { 1, 10 };
/**
* The maximum time between consecutive measurements to keep considering
* the measurements to be outside.
*/
public static final double OUTSIDE_TIME = 10 * 60 * 1000;
/**
* The session context to access the principal.
*/
@Resource
protected SessionContext sessionContext;
/**
* The session bean to detect applicatin shutdowns.
*/
@Inject
protected ShutdownSessionBean shutdownSession;
/**
* Updates the metadata of all devices that require
* an update.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.NEVER)
public void updateMetadata() {
MetadataSessionBean self = sessionContext.getBusinessObject(MetadataSessionBean.class);
long time = self.getLatestWeatherReportTime() - REPORT_DELAY;
log.log(Level.INFO, String.format("Starting metadata processing for measurements before time %d.", time));
MetadataContext context;
try {
while ((context = self.createContext(time)) != null) {
while (!shutdownSession.isShuttingDown() && self.updateMetadata(context));
}
log.log(Level.INFO, String.format("Finishing metadata processing for measurements before time %d.", time));
} catch (IOException e) {
log.log(Level.SEVERE, "Failure during metadata processing.", e);
}
}
/**
* Returns the time of the latest weather report of any station.
*
* @return The time of the latest weather report.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public long getLatestWeatherReportTime() {
return WeatherReportEntity.getMaxTime(em, true);
}
/**
* Finds the device with the oldest measurement that needs to be processed until
* the specified time and create a context for it.
*
* @param time The time limit to search for measurements of devices to process.
* @return The context or null, if all devices have been processed.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public MetadataContext createContext(long time) {
Long deviceId = MeasurementEntity.findMetadataDevice(em, time, VERSION_CURRENT);
if (deviceId == null) {
// this is part of the normal processing
log.log(Level.INFO, "No device found for metadata processing.");
return null;
} else {
log.log(Level.INFO, String.format("Using device %d for metadata processing.", deviceId));
EntityRange range = MeasurementEntity.findMetadataEntityRange(em, deviceId, time, VERSION_CURRENT);
if (range == null) {
// this should not happen
log.log(Level.WARNING, String.format("Skipping device %d for metadata processing due to null range.", deviceId));
return null;
} else {
MetadataContext context = new MetadataContext();
context.device = deviceId;
context.range = range;
context.previous = MeasurementEntity.findPrevious(em, deviceId, range.getStart());
// eager load previous data
if (context.previous != null) context.previous.getData().size();
return context;
}
}
}
/**
* Updates the metadata of the context.
*
* @param context The context.
* @return True if there is more to do.
* @throws IOException Thrown if the interaction with carta fails.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean updateMetadata(MetadataContext context) throws IOException{
log.log(Level.INFO, String.format("Continue metadata processing for device %d at offset %d.", context.device, context.offset));
PageConfig config = new PageConfig(context.offset, BATCH_SIZE);
List<MeasurementEntity> update = MeasurementEntity.findAllByEntityRange(em, config, context.device, context.range);
for (MeasurementEntity current: update) {
if (shutdownSession.isShuttingDown()) return false;
// note that the order is important since the computations refer to each other (outside_* requires distances, etc.)
setMetadata(current, MeasurementType.TIME_DIFFERENCE, getTimeDifference(current, context));
setMetadata(current, MeasurementType.MOVEMENT_DISTANCE, getMovementDistance(current, context));
setMetadata(current, MeasurementType.TEMPERATURE_DIFFERENCE, getTemperatureDifference(current, context));
setMetadata(current, MeasurementType.STATION_TEMPERATURE, getStationTemperature(current, context));
setMetadata(current, MeasurementType.STATION_PRESSURE, getStationPressure(current, context));
setMetadata(current, MeasurementType.BUILDING_DISTANCE, getBuildingDistance(current, context));
setMetadata(current, MeasurementType.OUTSIDE_INDICATOR, getOutsideIndicator(current, context));
setMetadata(current, MeasurementType.OUTSIDE_DURATION, getOutsideDuration(current, context));
log.log(Level.INFO, "Metadata is: " + current.getData());
current.setDataVersion(VERSION_CURRENT);
context.previous = current;
context.offset += 1;
}
return update.size() != 0;
}
/**
* Sets the metadata value. If the value is null, the key will be removed.
*
* @param measurement The measurement.
* @param key The key.
* @param value The value.
*/
private void setMetadata(MeasurementEntity measurement, MeasurementType key, Object value) {
String s = key.setValues(new Object[] { value });
if (s == null) {
measurement.getData().remove(key);
} else {
measurement.getData().put(key, s);
}
}
/**
* Computes the time difference between the current measurement and the measurement in the context.
*
* @param current The current measurement.
* @param context The context with the previous reading.
* @return The difference or null, if the previous reading does not exist.
*/
private Long getTimeDifference(MeasurementEntity current, MetadataContext context) {
if (context.previous == null) return null;
return current.getTime() - context.previous.getTime();
}
/**
* Computes the movement distance between the current measurement and the measurement in the context.
*
* @param current The current measurement.
* @param context The context with the previous reading.
* @return The distance or null, if the previous reading does not exist.
*/
private Double getMovementDistance(MeasurementEntity current, MetadataContext context) {
if (context.previous == null) return null;
return HaversineDistance.getDistance(current.getCoordinate().getLongitude(), current.getCoordinate().getLatitude(),
context.previous.getCoordinate().getLongitude(), context.previous.getCoordinate().getLatitude());
}
/**
* Computes the temperature distance between the current measurement and the measurement in the context.
*
* @param current The current measurement.
* @param context The context with the previous reading.
* @return The distance or null, if the previous reading does not exist.
*/
private Double getTemperatureDifference(MeasurementEntity current, MetadataContext context) {
if (context.previous == null) return null;
Double c = Measurements.getAverage(MeasurementType.BATTERY_TEMPERATURE, current.getData());
Double p = Measurements.getAverage(MeasurementType.BATTERY_TEMPERATURE, context.previous.getData());
if (c == null || p == null) return null;
else return c - p;
}
/**
* Computes the distance to the nearest building.
*
* @param current The current measurement.
* @param context The context.
* @return The distance to the nearest building in meters.
* @throws IOException Thrown if a tile cannot be loaded.
*/
private Double getBuildingDistance(MeasurementEntity current, MetadataContext context) throws IOException {
Coordinate c = new Coordinate(current.getCoordinate().getLongitude(), current.getCoordinate().getLatitude());
// compute the tiles that we have to search for buildings based on
// the range that the user specified
Box box = Buildings.getBounds(c, BUILDING_RANGE);
MapTile topLeft = Buildings.getTopLeftTile(box, BUILDING_ZOOM);
MapTile bottomRight = Buildings.getBottomRightTile(box, BUILDING_ZOOM);
int total = (bottomRight.getX() - topLeft.getX() + 1) * (bottomRight.getY() - topLeft.getY() + 1);
log.log(Level.INFO, String.format("Tiles are X: %d-%d Y: %d-%d Total: %d", topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(), total));
// iterate over the tiles and find the closest building
Surface minimum = null;
double distance = 0;
for (int x = topLeft.getX(); x <= bottomRight.getX(); x++) {
for (int y = topLeft.getY(); y <= bottomRight.getY(); y++) {
List<Surface> buildings = getBuildings(new MapTile(x, y, BUILDING_ZOOM), context);
for (Surface building: buildings) {
double d = Buildings.computeDistance(c, building);
if (minimum == null || d < distance) {
distance = d;
minimum = building;
}
}
}
}
if (minimum == null) return null;
else if (minimum.contains(c)) return 0d;
else return distance;
}
/**
* Returns an indicator that signals whether the measurement was likely taken outside.
*
* @param current The current measurement.
* @param context The context.
* @return The boolean.
*/
private boolean getOutsideIndicator(MeasurementEntity current, MetadataContext context) {
Double building = Measurements.getAverage(MeasurementType.BUILDING_DISTANCE, current.getData());
Double movement = Measurements.getAverage(MeasurementType.MOVEMENT_DISTANCE, current.getData());
Double difference = Measurements.getAverage(MeasurementType.TIME_DIFFERENCE, current.getData());
if (building == null || building > OUTSIDE_BUILDING) return true;
if (movement != null && difference != null && difference > 0) {
double speed = movement / (difference / 1000d);
return speed >= OUTSIDE_SPEED[0] && speed <= OUTSIDE_SPEED[1];
} else {
return false;
}
}
/**
* Computes the time that the device was outside based on the outside indicators and the timing
* between the measurements.
*
* @param current The current measurement.
* @param context The context.
* @return The duration that the device was outside without interruption.
*/
private double getOutsideDuration(MeasurementEntity current, MetadataContext context) {
if (context.previous == null) return 0d;
boolean wasOutside = Measurements.getValue(MeasurementType.OUTSIDE_INDICATOR, context.previous.getData(), false);
if (!wasOutside) return 0d;
boolean isOutside = Measurements.getValue(MeasurementType.OUTSIDE_INDICATOR, current.getData(), false);
if (!isOutside) return 0d;
Double difference = Measurements.getAverage(MeasurementType.TIME_DIFFERENCE, current.getData());
if (difference == null || difference > OUTSIDE_TIME) return 0d;
Double period = Measurements.getAverage(MeasurementType.OUTSIDE_DURATION, context.previous.getData());
if (period == null) return 0d;
return difference + period;
}
/**
* Loads the station temperature for the current measurement.
*
* @param current The current measurement.
* @param context The context.
* @return The temperature of the nearest station that has a temperature reading.
*/
private Double getStationTemperature(MeasurementEntity current, MetadataContext context) {
List<WeatherStationEntity> stations = getWeatherStations(new Coordinate(current.getCoordinate().getLongitude(), current.getCoordinate().getLatitude()), context);
for (WeatherStationEntity s: stations) {
WeatherReportEntity e = getWeatherReport(s,current.getTime());
if (e != null && e.getTemperature() != null) {
return e.getTemperature();
}
}
return null;
}
/**
* Loads the station pressure for the current measurement.
*
* @param current The current measurement.
* @param context The context.
* @return The pressure of the nearest station that has a pressure reading.
*/
private Double getStationPressure(MeasurementEntity current, MetadataContext context) {
List<WeatherStationEntity> stations = getWeatherStations(new Coordinate(current.getCoordinate().getLongitude(), current.getCoordinate().getLatitude()), context);
for (WeatherStationEntity s: stations) {
WeatherReportEntity e = getWeatherReport(s,current.getTime());
if (e != null && e.getPressure() != null) {
return e.getPressure();
}
}
return null;
}
/**
* Returns the weather report for the station and time.
*
* @param s The station.
* @param time The time to search.
* @return The best matching weather report.
*/
private WeatherReportEntity getWeatherReport(WeatherStationEntity s, long time) {
TimeRange range = new TimeRange(time - STATION_TIME, 2 * STATION_TIME);
PageConfig config = new PageConfig(0, STATION_PAGE);
List<WeatherReportEntity> reports = WeatherReportEntity.findAllByStationAndTimeRange(em, config, s, range, true);
if (reports.size() == 0) return null;
WeatherReportEntity best = reports.get(0);
long minimum = Math.abs(time - best.getTime());
for (int i = 1; i < reports.size(); i++) {
WeatherReportEntity next = reports.get(i);
long delta = Math.abs(time - next.getTime());
if (delta < minimum) {
minimum = delta;
best = next;
}
}
return best;
}
/**
* Returns the weather stations for a particular coordinate sorted by distance.
*
* @param c The coordinate.
* @param context The context.
* @return The weather station.
*/
private List<WeatherStationEntity> getWeatherStations(Coordinate c, MetadataContext context) {
if (context.center == null || Coordinates.DISTANCE.getDistance(c, context.center) > STATION_RANGE[1] - STATION_RANGE[0]) {
context.stations = WeatherStationEntity.findByLocation(em, WeatherStationEntity.class, new com.mowesta.api.Coordinate(c.getLongitude(), c.getLatitude()), STATION_RANGE[1] / 1000, -1);
context.center = c;
}
Map<WeatherStationEntity, Double> distances = new HashMap<>();
List<WeatherStationEntity> result = new ArrayList<>();
for (WeatherStationEntity s: context.stations) {
double distance = HaversineDistance.getDistance(s.getCoordinate().getLongitude(), s.getCoordinate().getLatitude(), c.getLongitude(), c.getLatitude());
if (distance <= STATION_RANGE[0]) {
distances.put(s, distance);
result.add(s);
}
}
result.sort((a, b) -> Double.compare(distances.get(a), distances.get(b)));
return result;
}
/**
* Returns the buildings that are located on a particular map tile.
*
* @param tile The tile.
* @param context The context to load.
* @return The surroundings of the building
* @throws IOException Thrown if the data cannot be loaded.
*/
private List<Surface> getBuildings(MapTile tile, MetadataContext context) throws IOException {
List<Surface> buildings = context.buildings.get(tile);
if (buildings == null) {
log.log(Level.INFO, String.format("Downloading tile for %d/%d at zoom %d.", tile.getX(), tile.getY(), tile.getZ()));
buildings = loadBuildings(tile);
context.buildings.put(tile, buildings);
} else {
log.log(Level.INFO, String.format("Using cached tile for %d/%d at zoom %d.", tile.getX(), tile.getY(), tile.getZ()));
}
return buildings;
}
/**
* Loads the buildings that intersect with a particular map tile from carta.
*
* @param tile The tile to load.
* @return The buildings on the tile.
* @throws IOException Thrown if something fails.
*/
private List<Surface> loadBuildings(MapTile tile) throws IOException {
Response response = getCartaService().getFeatures(tile.getX(), tile.getY(), tile.getZ(), -1, true, null);
if (response.getStatus() / 100 != 2)
throw new IOException(String.format("Failed to download geojson tile %d/%d at zoom %d.", tile.getX(), tile.getY(), tile.getZ()));
List<Surface> result = new ArrayList<>();
InputStream stream = response.readEntity(InputStream.class);
ObjectMapper mapper = new ObjectMapper();
FeatureCollection collection = mapper.readValue(stream, FeatureCollection.class);
for (Feature feature: collection.getFeatures()) {
if (feature.getProperties().containsKey("building") &&
feature.getGeometry() instanceof Polygon) {
Polygon p = (Polygon)feature.getGeometry();
if (p.getExteriorRing().size() > 3) {
List<Coordinate> coordinates = new ArrayList<>();
for (LngLatAlt c: p.getExteriorRing()) {
coordinates.add(new Coordinate(c.getLongitude(), c.getLatitude()));
}
result.add(new Surface(coordinates));
}
}
}
return result;
}
/**
* Returns a proxy to access the geojson vector service of carta.
*
* @return The proxy to access carta.
*/
protected IVectorServiceGeojson getCartaService() {
ResteasyClientBuilder builder = new ResteasyClientBuilder();
builder.httpEngine(new URLConnectionEngine());
ResteasyClient client = builder.build();
return client.target(URL_CARTA)
.proxy(IVectorServiceGeojson.class);
}
/**
* The metadata context which stores the state during
* batch processing and also holds cached data.
*
* @author Marcus
*/
private static class MetadataContext {
/** The buildings for a particular map tile. */
LimitedMap<MapTile, List<Surface>> buildings = new LimitedMap<>(100);
/** The nearby stations around the center. */
List<WeatherStationEntity> stations = new ArrayList<>();
/** The center where we asked for stations. */
Coordinate center;
/** The previous measurement. */
MeasurementEntity previous;
/** The measurement range. */
EntityRange range;
/** The current page offset. */
int offset;
/** The device. */
long device;
}
/**
* A map that has a limited number of entries that are replaced by
* a simple LRU scheme.
*
* @author Marcus
*
* @param <K> The type of the key.
* @param <V> The type of the value.
*/
private static class LimitedMap<K, V> {
/**
* The storage of the map.
*/
private Map<K, V> map = new HashMap<>();
/**
* The usage list that reflects the age of the map.
*/
private List<K> usage = new LinkedList<>();
/**
* The maximum number of elements (>=1)
*/
private int limit;
/**
* Creates a new map with the specified limit.
*
* @param limit The maximum number of elements.
*/
public LimitedMap(int limit) {
if (limit < 1)
throw new IllegalArgumentException("Limit must be at least 1.");
this.limit = limit;
}
/**
* The current number of elements.
*
* @return The size.
*/
public int getSize() {
return map.size();
}
/**
* The maximum number of elements.
*
* @return The maximum number of elements.
*/
public int getLimit() {
return limit;
}
/**
* Returns true if the map contains the key.
*
* @param key the key.
* @return True if the map contins the key, false otherwise.
*/
public boolean contains(K key) {
return map.containsKey(key);
}
/**
* Returns the value for the key, thereby marking the key as used.
*
* @param key The key.
* @return The value for the key or null, if not present.
*/
public V get(K key) {
if (map.containsKey(key)) {
use(key);
return map.get(key);
} else {
return null;
}
}
/**
* Saves the value for the key, thereby marking they key as used.
* If the limit of the map
*
* @param key The key.
* @param value The value to store.
*/
public void put(K key, V value) {
if (! map.containsKey(key)) {
usage.add(0, key);
if (usage.size() > limit) {
K oldest = usage.remove(usage.size() - 1);
map.remove(oldest);
}
} else {
use(key);
}
map.put(key, value);
}
/**
* Marks the key as used.
*
* @param key The key.
*/
private void use(K key) {
if (usage.remove(key)) usage.add(0, key);
}
}
}
@@ -0,0 +1,5 @@
package com.mowesta.service.session.measure;
public class PredictionSessionBean {
}
@@ -0,0 +1,518 @@
package com.mowesta.service.session.measure;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import com.mowesta.api.access.Roles;
import com.mowesta.service.session.sync.AbstractSyncSessionBean;
/**
* A stateless session bean that calculates the rating for given measurements
*/
@Stateless
@RolesAllowed({Roles.ADMIN})
public class RatingSessionBean extends AbstractSyncSessionBean {
//
// static final int BATCH_SIZE = 100;
//
// public static final int RATING_VERSION = 0;
// public static final int PREDICTION_VERSION = 0;
//
// static final double CHARGING_WEIGHT = 1;
// static final double TEMPERATURE_WEIGHT = 2;
// static final double WEIGHT_SUM = CHARGING_WEIGHT + TEMPERATURE_WEIGHT;
//
// @EJB
// WeatherSessionBean weatherSession;
//
// @Inject
// protected ShutdownSessionBean shutdownSession;
//
// @Inject
// protected EntityManager em;
//
// /**
// * Calculates and persists the equilibrium value on basis of all given measurements.
// *
// * @return The equilibrium entity.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.NEVER)
// public TemperatureEquilibriumEntity calculateEquilibriumValue() {
// RatingSessionBean proxy = sessionContext.getBusinessObject(getClass());
// LinearRegression.Builder<Double> yearModel = new LinearRegression.Builder<>();
// int offset = 0;
// boolean resultWasEmpty;
// do {
// resultWasEmpty = proxy.addValuesToGivenModel(offset, yearModel);
// offset += BATCH_SIZE;
// } while (!resultWasEmpty);
//
// return proxy.createAndPersistEquilibriumEntity(yearModel.build());
// }
//
// /**
// * Adds battery and station temperatures to a given model for all measurements with a given
// * offset
// *
// * @param offset The offset.
// * @param model The model,
// * @return true if the database does not provide any more data for a given offset
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public boolean addValuesToGivenModel(int offset, LinearRegression.Builder<Double> model) {
//
// List<MeasurementEntity> relevantMeasurements = MeasurementEntity.findAllByTimeRange(em,
// new PageConfig(offset, BATCH_SIZE),
// new TimeRange(0, Long.MAX_VALUE),
// false);
//
// for (int i = 0; i < relevantMeasurements.size(); i++) {
// if (relevantMeasurements.get(i).getDevice().getOs() != OperatingSystem.ANDROID) {
// continue;
// }
//
// Double deviceBatteryTemperature = getMeanBatteryTemperatureFromMeasurement(
// relevantMeasurements.get(i));
// if (deviceBatteryTemperature == null) {
// continue;
// }
//
// Double stationTemperature = getNearestStationTemperatureForMeasurement(
// relevantMeasurements.get(i));
// if (stationTemperature == null || Double.isNaN(stationTemperature)) {
// continue;
// }
//
// relevantMeasurements.get(i).setStationTemperature(stationTemperature);
//
// model.add(deviceBatteryTemperature, stationTemperature);
// }
//
// return relevantMeasurements.isEmpty();
// }
//
// /**
// * Creates and persists an EquilibriumEntity for a given Linear Regression Model
// *
// * @param model The model
// * @return The resulting EquilibriumEntity
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public TemperatureEquilibriumEntity createAndPersistEquilibriumEntity(LinearRegression model) {
// double m = model.getSlope();
// double c = model.getIntercept();
//
// // Heat Transfer formula resolved for equilibrium (assuming x = y)
// //
// // https://doi.org/10.1002/grl.50786
// double equilibriumValue = c / (1 - m);
// TemperatureEquilibriumEntity equilibriumEntity = new TemperatureEquilibriumEntity();
//
// equilibriumEntity.setValue(equilibriumValue);
// equilibriumEntity.setTime(System.currentTimeMillis());
//
// em.persist(equilibriumEntity);
//
// return equilibriumEntity;
// }
//
// /**
// * Creates and persists ratings for a day in shards.
// *
// * @param date The date
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.NEVER)
// public void createRatingsForADay(LocalDate date) {
// RatingSessionBean proxy = sessionContext.getBusinessObject(getClass());
// LinearModelEntity model = proxy.readOrCalculateHeatTransferModelForDate(date);
//
// int counter = 0;
// MeasurementEntity measurementEntity;
//
// do {
// if (shutdownSession.isShuttingDown()) {
// return;
// }
// measurementEntity = proxy.createRatingForMeasurementCounter(counter, model, date);
// counter++;
// } while (measurementEntity != null);
// }
//
// /**
// * Predict a temperature for a given measurement entity. If the measurement has no temperature
// * reading or no fitting heat transfer model was created, the prediction temperature is not set.
// * If a temperature is already present, the measurement is just returned.
// *
// * @param measurement The measurement that should get an prediction.
// * @return The measurement with a predicted temperature, if the prediction process was
// * successful.
// */
// @RolesAllowed({Roles.ADMIN})
// public MeasurementEntity predictTemperature(MeasurementEntity measurement) {
//
// // check if temperature has already been predicted with the current method
// if (measurement == null || measurement.getPredictionVersion() == PREDICTION_VERSION)
// return measurement;
//
// // Can only predict measurements with battery measurements
// Double batteryTemperature = getMeanBatteryTemperatureFromMeasurement(measurement);
// if (batteryTemperature == null) return measurement;
//
// LocalDate date = Instant.ofEpochMilli(measurement.getTime())
// .atZone(ZoneId.of("CET")).minusDays(1).toLocalDate();
//
// // get fitting heat transfer model
// LinearModelEntity heatTransferModel = readHeatTransferModelEntityFromDB(
// date.toEpochDay() * TimeUnit.DAYS.toMillis(1),
// date.plusDays(1).toEpochDay() * TimeUnit.DAYS.toMillis(1));
//
// // Can not predict without heat transfer model
// if (heatTransferModel == null) return measurement;
//
// measurement.setTemperature(heatTransferModel.predict(batteryTemperature));
// measurement.setPredictionVersion(PREDICTION_VERSION);
//
// return measurement;
// }
//
// /**
// * Creates and persists ratings of a measurement for a given day with a given offset.
// *
// * @param offset The offset.
// * @param model The model with which the temperature should be predicted.
// * @param date The date of the temperatures.
// * @return The modified MeasurementEntity or null if no MeasurementEntity is found.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public MeasurementEntity createRatingForMeasurementCounter(int offset,
// LinearModelEntity model, LocalDate date) {
//
// List<MeasurementEntity> measurementEntities = MeasurementEntity
// .getMeasurementsWithoutRatingInTimeRange(em,
// new PageConfig(offset, 1), // TODO check batch size (increase)
// new TimeRange(date.toEpochDay() * TimeUnit.DAYS.toMillis(1),
// TimeUnit.DAYS.toMillis(1)));
// if (measurementEntities.isEmpty()) {
// return null;
// }
// MeasurementEntity measurement = measurementEntities.get(0);
//
// // Check if rating has already been set
// if (measurement.getRatingVersion() != null
// && measurement.getRatingVersion() == RATING_VERSION) {
// return measurement;
// }
//
// if (measurement.getData().get(MeasurementType.BATTERY_TEMPERATURE) == null) {
// measurement.setRatingVersion(0);
// return measurement;
// }
//
// Double meanSensorTemperature = getMeanBatteryTemperatureFromMeasurement(measurement);
// if (meanSensorTemperature == null) {
// measurement.setRatingVersion(0);
// return measurement;
// }
//
// if (measurement.getStationTemperature() == null) {
// // Get closest weather station
// Double stationTemperature = getNearestStationTemperatureForMeasurement(measurement);
// if (stationTemperature == null || Double.isNaN(stationTemperature)) {
// measurement.setRatingVersion(RATING_VERSION);
// measurement.setPredictionVersion(PREDICTION_VERSION);
// return measurement; // No station temperature found
// }
// measurement.setStationTemperature(stationTemperature);
// }
//
// Double prediction = model.predict(meanSensorTemperature);
// if (prediction != null) {
// double rating = calculateRatingForMeasurement(
// Boolean.parseBoolean(measurement.getData().get(MeasurementType.BATTERY_CHARGING)),
// prediction, measurement.getStationTemperature());
// measurement.setTemperature(prediction);
// measurement.setPredictionVersion(PREDICTION_VERSION);
// measurement.setRating(rating);
// measurement.setRatingVersion(RATING_VERSION);
// }
// return measurement;
// }
//
// /**
// * Gets the temperature measured from the nearest station to a given measurement
// *
// * @param measurement The measurement from the mobile sensor.
// * @return The measurement from the station.
// */
// private Double getNearestStationTemperatureForMeasurement(MeasurementEntity measurement) {
// List<WeatherStationEntity> weatherStationEntities = WeatherStationEntity
// .findByLocation(em, WeatherStationEntity.class, new Coordinate(
// measurement.getCoordinate().getLongitude(),
// measurement.getCoordinate().getLatitude()
// ), 100, 20);
// if (weatherStationEntities.isEmpty()) {
// return null;
// }
// try {
// // Set station time that is measured in a time window of 10 minutes
// for (int i = 0; i < weatherStationEntities.size(); i++) {
// WeatherReportPage reportPage = weatherSession
// .getReports(weatherStationEntities.get(i).getId(),
// new TimeRange(measurement.getTime() - TimeUnit.MINUTES.toMillis(10)
// , TimeUnit.MINUTES.toMillis(20)),
// new PageConfig(0, 100), false);
// Optional<WeatherReport> closestReport = reportPage.getElements().stream()
// .min((a, b) -> (int) (Math.abs(a.getTime() - measurement.getTime()) - Math
// .abs(b.getTime() - measurement.getTime())));
//
// if (!closestReport.isPresent() || closestReport.get().getTemperature() == null) {
// continue;
// }
//
// return closestReport.map(WeatherReport::getTemperature).orElse(null);
// }
// } catch (EntityNotFoundException e) {
// return null;
// }
// return null;
// }
//
// /**
// * Reads or creates the heat transfer model for a given day, if the result is null, no model
// * can be generated from the given data. If a model can get created, the result is stored in the
// * database.
// *
// * @param date The date for the given model.
// * @return The Heat Transfer model.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.NEVER)
// public LinearModelEntity readOrCalculateHeatTransferModelForDate(LocalDate date) {
//
// RatingSessionBean proxy = sessionContext.getBusinessObject(getClass());
//
// long start = date.minusDays(1).toEpochDay() * TimeUnit.DAYS.toMillis(1);
// long end = date.toEpochDay() * TimeUnit.DAYS.toMillis(1);
//
// // If Model is already calculated;
// LinearModelEntity result = proxy.readHeatTransferModelEntityFromDB(start, end);
// if (result != null) {
// return result;
// }
//
// double equilibriumValue;
// TemperatureEquilibriumEntity equilibriumEntity = proxy.readMostRecentEquilibriumEntityFromDB();
// if (equilibriumEntity == null) {
// equilibriumValue = proxy.calculateEquilibriumValue().getValue();
// } else {
// equilibriumValue = equilibriumEntity.getValue();
// }
//
// MeanCalculatorResponse meanCalculatorResponse;
// int offset = 0;
// Double yMean = null;
// Double xMean = null;
// int currentNumberOfItems = 0;
//
// do {
// meanCalculatorResponse = proxy
// .calculateMeanTemperaturesForStartDateAndOffset(start, offset);
//
// if (meanCalculatorResponse.numberOfItems != 0) {
//
// if (xMean == null) {
// xMean = meanCalculatorResponse.meanX;
// yMean = meanCalculatorResponse.meanY;
// } else {
// // combined means
// xMean = (meanCalculatorResponse.meanX * meanCalculatorResponse.numberOfItems
// + xMean * currentNumberOfItems) / (meanCalculatorResponse.numberOfItems
// + currentNumberOfItems);
// yMean = (meanCalculatorResponse.meanY * meanCalculatorResponse.numberOfItems
// + yMean * currentNumberOfItems) / (meanCalculatorResponse.numberOfItems
// + currentNumberOfItems);
// }
//
// currentNumberOfItems += meanCalculatorResponse.numberOfItems;
// }
//
// offset += BATCH_SIZE;
//
// } while (meanCalculatorResponse.hasMoreData);
//
// if (xMean == null) {
// return null;
// }
//
// double slope = (yMean - equilibriumValue) /
// (xMean - equilibriumValue);
//
// if (Double.isNaN(slope) || Double.isInfinite(slope)) {
// return null;
// }
//
// double intersect = equilibriumValue - (slope * equilibriumValue);
//
// if (Double.isNaN(intersect) || Double.isInfinite(slope)) {
// return null;
// }
//
// result = new LinearModelEntity();
// result.setStart(start);
// result.setDuration(end);
// result.setSlope(slope);
// result.setIntercept(intersect);
//
// proxy.persistNewHeatTransferModelEntity(result);
//
// return result;
// }
//
// /**
// * Reads a Heat TransferModelEntity from the database that corresponds to the given start and
// * end timestamp with a new transaction to enable sharding.
// *
// * @param start The begin timestamp.
// * @param end The end timestamp.
// * @return The corresponding HeatTransferModelEntity or null.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public LinearModelEntity readHeatTransferModelEntityFromDB(long start, long end) {
// return LinearModelEntity.findForTimestamp(em, start, end);
// }
//
// /**
// * Reads the most recent equilibrium entity from the database with a new transaction, to enable
// * sharding.
// *
// * @return The EquilibriumEntity or null.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public TemperatureEquilibriumEntity readMostRecentEquilibriumEntityFromDB() {
// return TemperatureEquilibriumEntity.findMostRecent(em);
// }
//
// /**
// * Calculates mean temperatures for a given date with an offset with a new transaction to enable
// * sharding.
// *
// * @param start The start timestamp.
// * @param offset The offset.
// * @return The MeanCalculatorResponse including the means, number of results and if the query
// * was empty to indicate no more results.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public MeanCalculatorResponse calculateMeanTemperaturesForStartDateAndOffset(long start,
// int offset) {
// List<MeasurementEntity> relevantMeasurements = MeasurementEntity.findAllByTimeRange(em,
// new PageConfig(offset, BATCH_SIZE),
// new TimeRange(start, TimeUnit.DAYS.toMillis(1)), false);
//
// double currentSumX = 0D;
// double currentSumY = 0D;
// int numberOfItems = 0;
//
// for (int i = 0; i < relevantMeasurements.size(); i++) {
//
// Double stationTemperature = getNearestStationTemperatureForMeasurement(
// relevantMeasurements.get(i));
// if (stationTemperature == null || Double.isNaN(stationTemperature)) {
// continue;
// }
// Double batteryTemperature = getMeanBatteryTemperatureFromMeasurement(
// relevantMeasurements.get(i));
// if (batteryTemperature == null) {
// continue;
// }
//
// currentSumX += batteryTemperature;
// currentSumY += stationTemperature;
// numberOfItems++;
// }
//
// double meanX = currentSumX / numberOfItems;
// double meanY = currentSumY / numberOfItems;
//
// return new MeanCalculatorResponse(meanX, meanY, numberOfItems,
// !relevantMeasurements.isEmpty());
// }
//
// /**
// * A response for the sharded mean calculation
// */
// static class MeanCalculatorResponse {
//
// double meanX;
// double meanY;
// int numberOfItems;
// boolean hasMoreData;
//
// public MeanCalculatorResponse(double meanX, double meanY, int numberOfItems,
// boolean hasMoreData) {
// this.meanX = meanX;
// this.meanY = meanY;
// this.numberOfItems = numberOfItems;
// this.hasMoreData = hasMoreData;
// }
// }
//
// /**
// * Persists a new Heat Transfer Model with a new transaction
// *
// * @param heatTransferModelEntity The Heat Transfer Model.
// */
// @RolesAllowed({Roles.ADMIN})
// @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// public void persistNewHeatTransferModelEntity(LinearModelEntity heatTransferModelEntity) {
// em.persist(heatTransferModelEntity);
// }
//
// /**
// * Returns a measurement rating for a given measurement.
// *
// * @param charging The charging status of the measurement.
// * @param predictionTemperature The measurement temperature.
// * @param stationTemperature The station temperature.
// * @return The rating for the given data.
// */
// @RolesAllowed({Roles.ADMIN})
// public Double calculateRatingForMeasurement(boolean charging, double predictionTemperature,
// double stationTemperature) {
// double rating = 0D;
// rating += getChargingRating(charging) * CHARGING_WEIGHT;
// rating += getTemperatureRating(predictionTemperature, stationTemperature);
// double result = rating / WEIGHT_SUM;
// if (Double.isNaN(result) || Double.isInfinite(result)) {
// return null;
// }
// return result;
// }
//
// private Double getMeanBatteryTemperatureFromMeasurement(MeasurementEntity measurementEntity) {
// String[] measurements = measurementEntity.getData().get(MeasurementType.BATTERY_TEMPERATURE)
// .split(",");
// if (measurements.length < 1) {
// return null;
// }
// return Arrays.stream(measurements)
// .map(Double::parseDouble)
// .reduce(Double::sum).get() / measurements.length;
// }
//
// private Double getChargingRating(boolean charging) {
// return charging ? 0D : 1D;
// }
//
// private Double getTemperatureRating(double measurementTemperature, double stationTemperature) {
// double delta = Math.abs(measurementTemperature - stationTemperature);
// return delta > 5 ? 0 : 1 - (delta / 5);
// }
}
@@ -22,18 +22,20 @@ import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import com.mowesta.service.session.measure.MetadataSessionBean;
/**
* The session bean that controls the background synchronization tasks.
*
*
* @author Jan
*/
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class PeriodicSyncSessionBean {
/**
* Constants with the task.
*
*
* @author Marcus
*/
public enum JobType {
@@ -52,19 +54,23 @@ public class PeriodicSyncSessionBean {
/**
* The task that generates weather videos.
*/
VIDEO;
VIDEO,
/**
* The task that adds metadata to the measurements.
*/
METADATA;
};
@Inject
protected Logger log;
@Resource
protected TimerService timerService;
@Inject
@Inject
protected LocationSyncSessionBean locationSyncSession;
@Inject
protected WeatherReportSyncSessionBean reportSyncSession;
@@ -73,13 +79,17 @@ public class PeriodicSyncSessionBean {
@Inject
protected WeatherVideoSyncSessionBean videoSyncSession;
@Inject
protected MetadataSessionBean metadataSession;
@Resource
protected SessionContext context;
protected Job[] jobs = new Job[JobType.values().length];
@PostConstruct
protected void createTasks() {
jobs[JobType.FORECAST.ordinal()] = new Job("ForecastSync", (first) -> {
@@ -94,9 +104,12 @@ public class PeriodicSyncSessionBean {
jobs[JobType.VIDEO.ordinal()] = new Job("VideoSync", (first)-> {
videoSyncSession.syncVideos(first);
});
jobs[JobType.METADATA.ordinal()] = new Job("MeasurementSync", (first -> {
metadataSession.updateMetadata();
}));
}
/**
* Uses a {@link TimerService} to start the {@link Timer}
*/
@@ -111,27 +124,29 @@ public class PeriodicSyncSessionBean {
timerService.createIntervalTimer(TimeUnit.MINUTES.toMillis(3), TimeUnit.HOURS.toMillis(1), forecastConfig);
final TimerConfig locationConfig = new TimerConfig(JobType.LOCATION, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(5), locationConfig);
final TimerConfig metadataConfig = new TimerConfig(JobType.METADATA, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(5), metadataConfig);
}
/**
* Called when a timer expires.
*
*
* @param timer The timer.
*/
@Timeout
@TransactionAttribute(TransactionAttributeType.NEVER)
@TransactionAttribute(TransactionAttributeType.NEVER)
public void onTimeout(Timer timer) {
if (timer.getInfo() != null && timer.getInfo() instanceof JobType) {
JobType type = (JobType)timer.getInfo();
PeriodicSyncSessionBean proxy = context.getBusinessObject(getClass());
proxy.executeAsync(type);
}
}
/**
* Executes the specified job asynchronously.
*
*
* @param type The job to execute.
*/
@Asynchronous
@@ -141,23 +156,23 @@ public class PeriodicSyncSessionBean {
Job job = jobs[type.ordinal()];
if (job != null) job.execute();
}
/**
* Executes the specified job synchronously.
*
*
* @param type The job to execute.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.NEVER)
public void executeSync(JobType type) {
Job job = jobs[type.ordinal()];
if (job != null) job.execute();
}
if (job != null) job.execute();
}
/**
* An abstract base class for jobs that are synchronizing data
* periodically.
*
*
* @author Marcus
*/
private class Job {
@@ -166,25 +181,25 @@ public class PeriodicSyncSessionBean {
* The name of the task for logging.
*/
protected final String name;
/**
* A lock to avoid duplicate execution.
*/
protected final Lock running = new ReentrantLock();
/**
* A flag to determine whether this is the first execution.
*/
protected boolean firstExecution = true;
/**
* The job function to execute.
*/
protected final JobFunction function;
/**
* Creates a new job with the specified name.
*
*
* @param name The name.
* @param function The function;
*/
@@ -192,7 +207,7 @@ public class PeriodicSyncSessionBean {
this.name = name;
this.function = function;
}
/**
* Called when the job shall be executed. This implementation
* ensures that only one job is executing at a time.
@@ -213,20 +228,20 @@ public class PeriodicSyncSessionBean {
}
else {
log.log(Level.WARNING, "Ignoring scheduled job " + name + " since it is still running.");
}
}
}
}
}
/**
* An interface for job functions.
*
*
* @author Marcus
*/
private interface JobFunction {
/**
* Performs the actual work.
*
* Performs the actual work.
*
* @param first A flag to indicate whether this is the first run.
* @throws Exception Thrown if something fails.
*/
@@ -1,6 +1,7 @@
package com.mowesta.service.session.test;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.security.PermitAll;
@@ -14,6 +15,8 @@ import com.mowesta.service.crypto.SecureToken;
import com.mowesta.service.crypto.TokenType;
import com.mowesta.service.entity.DeviceEntity;
import com.mowesta.service.entity.EmbeddedCoordinate;
import com.mowesta.service.entity.LinearModelEntity;
import com.mowesta.service.entity.LinearModelEntity.ModelType;
import com.mowesta.service.entity.MeasurementEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.session.DataSessionBean;
@@ -29,9 +32,8 @@ import com.mowesta.service.session.DataSessionBean;
@Alternative
@Stateless
public class DataTestBean extends DataSessionBean {
private static final long ONE_WEEK = 604_800_000;
private static final long ONE_DAY = 86_400_000;
private static final long ONE_WEEK = TimeUnit.DAYS.convert(7, TimeUnit.MILLISECONDS);
private static final long ONE_DAY = TimeUnit.DAYS.convert(1, TimeUnit.MILLISECONDS);
/** Approximation of one degree of latitude in kilometers. */
private static final double LAT_ONE_DEGREE_IN_KM = 111.32d;
@@ -81,6 +83,13 @@ public class DataTestBean extends DataSessionBean {
createBatchTestMeasurements(device, geoCenter, 200, time, 7);
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_DAY, 34);
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_WEEK, 57);
// Create Test Measurements for Rating
final EmbeddedCoordinate geoWeatherStation = new EmbeddedCoordinate(8.9, 48.2); // TestWeatherStation
long stationTestTime = 1_577_750_400_000L;
createNonRandomBatchTestMeasurements(device, geoWeatherStation, stationTestTime, 10);
createNonRandomBatchTestMeasurements(device, geoWeatherStation, stationTestTime - ONE_DAY, 10);
createTestEquilibriumTemperature();
}
/**
@@ -128,7 +137,18 @@ public class DataTestBean extends DataSessionBean {
final double lngDegreeRange = range / lngOneDegreeInKM;
final double randomLngOffset = (Math.random() * lngDegreeRange) - (lngDegreeRange / 2d);
final double longitude = geoCenter.getLongitude() + randomLngOffset;
createTestMeasurements(device, new EmbeddedCoordinate(longitude, latitude), timestamp + count);
final double temperature = randomLatOffset % 30;
createTestMeasurements(device, new EmbeddedCoordinate(longitude, latitude),
timestamp + count, temperature);
}
}
private void createNonRandomBatchTestMeasurements(DeviceEntity device, EmbeddedCoordinate geoCenter,
long timestamp, int count) {
for (int i = 0; i < count; i++) {
final double temperature = (geoCenter.getLatitude() * geoCenter.getLongitude() * i + 3) % 30;
createTestMeasurements(device, new EmbeddedCoordinate(geoCenter.getLongitude(),
geoCenter.getLatitude()), timestamp + (i / count) * ONE_DAY, temperature);
}
}
@@ -139,7 +159,8 @@ public class DataTestBean extends DataSessionBean {
* @param coords The coordinates.
* @param timestamp The timestamp.
*/
private void createTestMeasurements(DeviceEntity device, EmbeddedCoordinate coords, long timestamp) {
private void createTestMeasurements(DeviceEntity device, EmbeddedCoordinate coords,
long timestamp, double temperature) {
MeasurementEntity measurement = new MeasurementEntity();
measurement.setDevice(device);
measurement.setVersion(1);
@@ -148,11 +169,14 @@ public class DataTestBean extends DataSessionBean {
} else {
measurement.setCoordinate(coords);
}
measurement.setTemperature(temperature);
measurement.setTime(timestamp);
measurement.setData(new HashMap<>());
for (MeasurementType t : MeasurementType.values()) {
if (t.getType() == Boolean.class) {
measurement.getData().put(t, Boolean.TRUE.toString());
} else if (t == MeasurementType.BATTERY_TEMPERATURE) {
measurement.getData().put(t, Double.valueOf(temperature).toString());
} else if (t.getType() == Double.class) {
measurement.getData().put(t, Double.valueOf(1.1).toString());
}
@@ -160,4 +184,15 @@ public class DataTestBean extends DataSessionBean {
em.persist(measurement);
em.flush();
}
private void createTestEquilibriumTemperature() {
LinearModelEntity equilibrium = new LinearModelEntity();
equilibrium.setType(ModelType.TEMPERATURE_EQUILIBRIUM);
equilibrium.setSlope(1);
equilibrium.setIntercept(37d);
long now = System.currentTimeMillis();
equilibrium.setStart(now - 1000);
em.persist(equilibrium);
em.flush();
}
}
@@ -0,0 +1,79 @@
package com.mowesta.service.session.util;
import java.util.List;
import com.locoslab.library.geometry.wgs.Box;
import com.locoslab.library.geometry.wgs.Coordinate;
import com.locoslab.library.geometry.wgs.Coordinates;
import com.locoslab.library.geometry.wgs.MapTile;
import com.locoslab.library.geometry.wgs.Surface;
/**
* A utility class to support the search for the nearest building.
*
* @author Marcus
*/
public class Buildings {
/**
* Computes the minimum distance to a building.
*
* @param surface The surface denoting the building.
* @param c The coordinate to compute the distance.
* @return The minimum distance.
*/
public static double computeDistance(Coordinate c, Surface surface) {
double distance = 0;
Coordinate minimum = null;
// handle cases where polygon is not closed
List<Coordinate> coordinates = surface.getPoints();
for (int i = 1; i < coordinates.size(); i++) {
Coordinate closest = Coordinates.ALGORITHMS.getClosestPointOnLine(coordinates.get(i - 1), coordinates.get(i), c);
double d = Coordinates.DISTANCE.getDistance(closest, c);
if (minimum == null || d < distance) {
distance = d;
minimum = closest;
}
}
return distance;
}
/**
* Returns the top left tile of the box at the zoom level.
*
* @param box The box.
* @param zoom The zoom level.
* @return The top left tile.
*/
public static MapTile getTopLeftTile(Box box, int zoom) {
return MapTile.getMapTile(box.getMin().getLongitude(), box.getMax().getLatitude(), zoom);
}
/**
* Returns the bottom right tile of the box at the zoom level.
*
* @param box The box.
* @param zoom The zoom level.
* @return The bottom right tile.
*/
public static MapTile getBottomRightTile(Box box, int zoom) {
return MapTile.getMapTile(box.getMax().getLongitude(), box.getMin().getLatitude(), zoom);
}
/**
* Computes a (crude) estimate for a bounding box that spans around the
* given point.
*
* @param c The coordiante.
* @param range The range.
* @return The bounding box with the range.
*/
public static Box getBounds(Coordinate c, double range) {
double longitude = c.getLongitude();
double latitude = c.getLatitude();
double dx = range / Coordinates.DISTANCE.getDistance(c, new Coordinate(longitude + 1, latitude));
double dy = range / Coordinates.DISTANCE.getDistance(c, new Coordinate(longitude, latitude + 1));
return new Box(longitude - dx, latitude - dy, longitude + dx, latitude + dy);
}
}
@@ -0,0 +1,76 @@
package com.mowesta.service.session.util;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mowesta.api.measurement.MeasurementType;
/**
* A utility class to process measurements.
*
* @author Marcus
*/
public class Measurements {
/**
* The logger to produce debug output.
*/
public static Logger log = Logger.getLogger(Measurements.class.getName());
/**
* Returns a boolean value from the data for the type.
*
* @param t The type.
* @param d The data.
* @param defaultValue The default value, if the data is empty or invalid.
* @return The boolean.
*/
public static boolean getValue(MeasurementType t, Map<MeasurementType, String> d, boolean defaultValue) {
if (t.getType() != Boolean.class || d == null) return defaultValue;
Object[] data = t.getValues(d.get(t));
if (data.length != 1) return defaultValue;
return (Boolean)data[0];
}
/**
* Returns a valid (non-nan and non-infinite) double or null.
*
* @param name The name to log.
* @param value The value to check.
* @return Null or a valid double.
*/
public static Double getValid(String name, Double value) {
if (value == null) return null;
if (value.isNaN()) {
log.log(Level.INFO, "Ignoring NaN in field " + name + ".");
return null;
} else if (value.isInfinite()) {
log.log(Level.INFO, "Ignoring infinite value in field " + name + ".");
return null;
} else {
return value;
}
}
/**
* Computes the average value of the data specified by the
* measurement type.
*
* @param d The measurement data.
* @param t The measurement type.
* @return The average value or null, if the data is not available.
*/
public static Double getAverage(MeasurementType t, Map<MeasurementType, String> d) {
if (t.getType() != Double.class || d == null) return null;
Object[] data = t.getValues(d.get(t));
if (data.length == 0) return null;
double result = 0;
for (Object o: data) {
result += (Double)o;
}
return getValid(t.name(), Double.valueOf(result / data.length));
}
}
@@ -25,6 +25,7 @@
<class>com.mowesta.service.entity.UserEntity</class>
<class>com.mowesta.service.entity.WeatherReportEntity</class>
<class>com.mowesta.service.entity.WeatherStationEntity</class>
<class>com.mowesta.service.entity.LinearModelEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="jboss.as.jpa.providerModule" value="application"></property>
@@ -1,35 +1,35 @@
package com.mowesta.service.test;
import java.io.File;
import org.jboss.shrinkwrap.api.Filters;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import java.io.File;
/**
* The class that defines the deployment that will be used for
* all tests. While this might be less flexible, it will be a lot
* faster if there are a lot of test classes. Take a look at
* https://github.com/ingwarsw/arquillian-suite-extension on
* github for more details.
*
*
* @author Marcus
*/
public class EjbDeployment {
/**
* Creates an ejb jar that contains all data for testing.
*
*
* @return The ejb jar.
*/
public static JavaArchive createEjb() {
JavaArchive r = ShrinkWrap.create(JavaArchive.class);
mergeLibraries(r)
.addAsManifestResource(new StringAsset(getManifest()), "MANIFEST.MF")
.addPackages(true, "org.apache.commons.compress", "org.geojson", "org.mapstruct", "org.apache.commons")
.addPackages(true, "org.apache.commons.compress", "org.geojson", "org.mapstruct", "org.apache.commons", "com.locoslab")
.addPackages(true, Filters.exclude("com.mowesta.service.test.*"), "com.mowesta.api", "com.mowesta.service", "com.mowesta.data")
.addAsManifestResource(new File("src/test/resources/META-INF/beans.xml"), "beans.xml")
.addAsManifestResource(new File("src/test/resources/META-INF/persistence.xml"), "persistence.xml")
@@ -40,24 +40,24 @@ public class EjbDeployment {
.addAsResource(new File("src/test/resources/nominatim/"), "/nominatim/");
return r;
}
/**
* Merges the libraries copied by gradle into the jar.
*
*
* @param r The java archive to merge the libraries into.
* @return A java archive.
*/
public static JavaArchive mergeLibraries(JavaArchive r) {
File[] files = new File("build/test-libraries").listFiles();
File[] files = new File("build/test-libraries").listFiles();
for (File a: files) {
r.merge(ShrinkWrap.createFromZipFile(JavaArchive.class, a));
}
return r;
}
/**
* Returns a default manifest for testing.
*
*
* @return The manifest.
*/
private static String getManifest() {
@@ -68,6 +68,6 @@ public class EjbDeployment {
b.append("Dependencies: jdk.unsupported\n");
b.append("Built-By: creator\n\n");
return b.toString();
}
}
}
@@ -0,0 +1,109 @@
package com.mowesta.service.test.session;
//@RunWith(Arquillian.class)
public class MeasurementRatingSessionTest extends AbstractSessionTest {
//
// @EJB
// RatingSessionBean measurementRatingSession;
//
// @EJB
// PeriodicSyncSessionBean periodicSyncSession;
//
// @Inject
// WeatherReportSyncSessionBean reportSyncSession;
//
// @Inject
// EntityManager em;
//
// @Before
// public void setUp() throws Exception {
// tearDown();
// final VirtualFile virtualParent = VFS.getChild(getClass().getResource("/temp").toURI());
// File tempParent = reportSyncSession.getTempFolder();
// for (VirtualFile virtualFile : virtualParent.getChildrenRecursively()) {
// File target = new File(tempParent, virtualFile.getPathNameRelativeTo(virtualParent));
// System.out.println(virtualFile.getName() + "->" + target.getAbsolutePath());
// if (virtualFile.isDirectory()) {
// target.mkdirs();
// } else {
// try (InputStream is = virtualFile.openStream()) {
// Files.copy(is, target.toPath());
// }
// }
// }
// periodicSyncSession.executeSync(PeriodicSyncSessionBean.JobType.REPORT);
// }
//
// /**
// * Deletes the files from the temp folder.
// *
// * @throws IOException Should not be thrown.
// */
// @After
// public void tearDown() throws IOException {
// final File tempFolder = reportSyncSession.getTempFolder();
// if (tempFolder.exists()) {
// Files.walk(tempFolder.toPath())
// .map(Path::toFile)
// .sorted((o1, o2) -> -o1.compareTo(o2))
// .forEach(File::delete);
// tempFolder.delete();
// }
// }
//
// @Test
// public void testEquilibrium() {
//
// executeAs("admin", () -> {
// TemperatureEquilibriumEntity result = measurementRatingSession.calculateEquilibriumValue();
// assertNotNull(result);
// });
// }
//
// @Test
// public void testSetMeasurementRatingForAllNonSet() {
//
// executeAs("admin", () -> {
//
// LocalDate testDate = Instant.ofEpochMilli(1_577_754_000_000L).atZone(ZoneId.systemDefault()).toLocalDate();
//
// measurementRatingSession.createRatingsForADay(testDate);
//
// List<MeasurementEntity> data = MeasurementEntity.findAllByTimeRange(em,
// new PageConfig(0, Integer.MAX_VALUE),
// new TimeRange(testDate.toEpochDay() * TimeUnit.DAYS.toMillis(1), TimeUnit.DAYS.toMillis(1)),
// false);
//
// assertEquals("Number of results should be equal to the number of samples created in DataTestBean"
// , data.size(), 10);
// data.forEach(measurementEntity -> {
// assertEquals("All rated stations should have rating version 0 for now",(Integer) 0, measurementEntity.getRatingVersion());
//
// assertNotEquals("All station temperatures should be set", null, measurementEntity.getStationTemperature());
// assertNotEquals("All station temperatures should be set", Double.NaN, measurementEntity.getStationTemperature());
//
// assertNotEquals("All ratings should be set", null, measurementEntity.getRating());
// assertNotEquals("All ratings should be set", Double.NaN, measurementEntity.getRating());
//
// assertThat(measurementEntity.getRating(), isBetween(0.0, 1.0));
//
// });
//
// });
// }
//
// static Matcher<Double> isBetween(final Double lowerBound, final Double upperBound) {
// return new BaseMatcher<Double>() {
// @Override
// public boolean matches(Object item) {
// if (!(item instanceof Double)) return false;
// Double actual = (Double) item;
// return actual >= lowerBound && actual <= upperBound;
// }
//
// @Override
// public void describeTo(Description description) {
// }
// };
// }
}
@@ -1,25 +1,5 @@
package com.mowesta.service.test.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.ejb.EJB;
import javax.ejb.EJBAccessException;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.mowesta.api.Coordinate;
import com.mowesta.api.PageConfig;
import com.mowesta.api.TimeRange;
@@ -32,6 +12,26 @@ import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.session.DeviceSessionBean;
import com.mowesta.service.session.MeasurementSessionBean;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.ejb.EJB;
import javax.ejb.EJBAccessException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Runs tests on the measurement session.
*
@@ -289,4 +289,31 @@ public class MeasurementSessionTest extends AbstractSessionTest {
}
});
}
@Test
public void testMeasurementRatings() {
final long time = System.currentTimeMillis();
final DeviceHandle deviceHandle =
DeviceSessionTest.createDevice(this, deviceSession, "handte");
executeAs("handte", deviceHandle.getToken(), () -> {
try {
Measurement measurement = createMeasurement(time);
measurement.setRating(1337D);
measurementSession.addCurrentDeviceMeasurement(measurement);
MeasurementPage result = measurementSession
.getCurrentDeviceMeasurements(new TimeRange(time, time + 1),
new PageConfig(0, 10), false);
assertEquals(1, result.getTotal());
assertNull(result.getElements().get(0).getRating()); // The client should not be able to set MeasurementsRatings
} catch (EntityForbiddenException e) {
fail("Failed due to: " + e.getMessage());
}
});
}
}
@@ -104,8 +104,10 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
Assert.assertEquals("Should have 6 stations.", 6, stations.getTotal());
Assert.assertEquals("Should retrieve 6 stations.", 6, stations.getElements().size());
for (WeatherStation s: stations.getElements()) {
System.out.println(s.getName());
int expect = s.getName().startsWith("Aldersbach")?78:96;
WeatherReportPage reports = weatherSession.getReports(s.getId(), new TimeRange(0, Long.MAX_VALUE), new PageConfig(0, 100), false);
if (s.getName().startsWith("Albstadt-Badkap")) expect = 384;
WeatherReportPage reports = weatherSession.getReports(s.getId(), new TimeRange(0, Long.MAX_VALUE), new PageConfig(0, 400), false);
Assert.assertEquals("Should have " + expect + " reports.", expect, reports.getTotal());
Assert.assertEquals("Should retrieve " + expect + " reports.", expect, reports.getElements().size());
}
+2 -2
View File
@@ -15,8 +15,8 @@ dependencies {
// dependencies required for analysis tools
compile 'commons-cli:commons-cli:1.4'
compile 'com.locoslab.library.geometry:geometry-wgs:1.1.4'
compile 'com.locoslab.service.carta:carta-api:1.1.4'
compile "com.locoslab.library.geometry:geometry-wgs:${versionGeometry}"
compile "com.locoslab.service.carta:carta-api:${versionCarta}"
compileOnly "io.swagger:swagger-annotations:${versionSwagger}"
@@ -26,6 +26,7 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.locoslab.library.geometry.wgs.HaversineDistance;
import com.mowesta.api.PageConfig;
import com.mowesta.api.TimeRange;
import com.mowesta.api.measurement.IMeasurementService;
@@ -34,52 +35,52 @@ import com.mowesta.api.measurement.MeasurementPage;
/**
* A tool to download the measurements of a number of devices.
*
*
* @author Marcus
*
*/
public class MeasurementDownloader {
// 1161281,9569042,9660419,9732599,9870388,9934728,9939081,10108047,10108047,10312353,10381889,10880985
/**
* The url of the MoWeSta api.
*/
public static final String API_URL = "https://www.mowesta.com/api";
/**
* The page size used for downloads.
*/
private static final int PAGE_SIZE = 500;
/**
* The default output directory of the tool.
*/
private static final String DEFAULT_OUTPUT_DIRECTORY = "data";
/**
* The logger used to generate the output.
*/
private static Logger log = Logger.getLogger(MeasurementDownloader.class.getName());
/**
* The output folder.
*/
private File outputFolder;
/**
* The devices.
*/
private List<Long> devices;
/**
* The measurement service.
*/
private IMeasurementService service;
/**
* Creates a new downloader.
*
*
* @param username The user name.
* @param password The password.
* @param outputFolder The output folder.
@@ -94,11 +95,11 @@ public class MeasurementDownloader {
target.register(new BasicAuthentication(username, password));
service = target.proxy(IMeasurementService.class);
}
/**
* Downloads all device data in the time range.
*
*
* @param range The time range.
* @throws Exception Thrown if the download fails.
*/
@@ -107,10 +108,10 @@ public class MeasurementDownloader {
download(range, device, getOutputFile(device));
}
}
/**
* Returns the output file for the device.
*
*
* @param device The device id.
* @return The output file.
*/
@@ -120,7 +121,7 @@ public class MeasurementDownloader {
/**
* Downloads the data for a single device.
*
*
* @param range The time range.
* @param device The device id.
* @param outputFile The target file.
@@ -137,25 +138,27 @@ public class MeasurementDownloader {
MeasurementPage page = response.readEntity(MeasurementPage.class);
if (page.getElements().size() > 0) {
for (Measurement m : page.getElements()) {
writer.write(mapper.writeValueAsString(m));
writer.newLine();
measurementCount += 1;
if (HaversineDistance.getDistance(m.getCoordinate().getLongitude(), m.getCoordinate().getLatitude(), 7.086776428171052d, 50.774159544034596d) < 40) {
writer.write(mapper.writeValueAsString(m));
writer.newLine();
measurementCount += 1;
}
}
config.setOffset(config.getOffset() + page.getSize());
} else {
break;
}
}
}
writer.close();
writer.close();
}
log.log(Level.INFO, String.format("Wrote %d measurements to %s.", measurementCount, outputFile.getAbsolutePath()));
}
/**
* The main method that runs the downloader with command line parameters.
*
*
* @param args The arguments.
*/
public static void main(String[] args) {
@@ -169,19 +172,19 @@ public class MeasurementDownloader {
Option passwordOption = new Option("p", "password", true, "The password of the MoWeSta user.");
passwordOption.setRequired(true);
options.addOption(passwordOption);
Option outputOption = new Option("o", "output", true, "The destination folder to store the downloaded data.");
options.addOption(outputOption);
Option devicesOption = new Option("d", "devices", true, "The device id(s) to download, separated by a comma or given as multiple arguments.");
devicesOption.setRequired(true);
options.addOption(devicesOption);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
MeasurementDownloader downloader;
try {
CommandLine cmd = parser.parse(options, args);
String username = cmd.getOptionValue(usernameOption.getOpt());
@@ -212,15 +215,15 @@ public class MeasurementDownloader {
System.exit(1);
return;
}
try {
downloader.download(new TimeRange(0, System.currentTimeMillis()));
downloader.download(new TimeRange(0, System.currentTimeMillis()));
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to download data.", e);
System.exit(1);
}
}
}
@@ -1,5 +1,5 @@
/**
*
*
*/
package com.mowesta.service.rest;
@@ -30,7 +30,7 @@ import com.mowesta.service.session.WeatherSessionBean;
/**
* Implements the weather service.
*
*
* @author Marcus
*/
@RequestScoped
@@ -41,13 +41,13 @@ public class WeatherResource implements IWeatherService {
*/
@Inject
protected WeatherSessionBean weatherSession;
/**
* The location session to resolve cities.
*/
@Inject
protected LocationSessionBean locationSession;
/**
* The request that will be injected by the jax-rs runtime.
*/
@@ -59,7 +59,7 @@ public class WeatherResource implements IWeatherService {
*/
@Inject
Logger log;
@Override
public Response getCityForecast(long id) {
try {
@@ -71,10 +71,10 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(forecast);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
}
@Override
@@ -88,7 +88,7 @@ public class WeatherResource implements IWeatherService {
}
return builder.tag(tag).build();
}
@Override
public Response getForecast(long id) {
WeatherForecast forecast = weatherSession.getForecast(id);
@@ -98,7 +98,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(forecast);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
}
@Override
@@ -112,7 +112,7 @@ public class WeatherResource implements IWeatherService {
return r.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
}
@Override
@@ -138,10 +138,10 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(station);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
}
@Override
@@ -152,7 +152,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(weatherSession.getStations(term, pageConfig, true));
}
return builder.tag(tag).build();
return builder.tag(tag).build();
}
@Override
@@ -164,7 +164,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(station);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -181,7 +181,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(condition);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -197,7 +197,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(report);
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -210,7 +210,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(weatherSession.getVideos(pageConfig));
}
return builder.tag(tag).build();
return builder.tag(tag).build();
}
@Override
@@ -228,7 +228,7 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(weatherSession.getVideos(city.getCoordinate(), pageConfig));
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -243,12 +243,12 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(weatherSession.getLatestVideos(city.getCoordinate()).toArray(new WeatherVideo[0]));
}
return builder.tag(tag).build();
return builder.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
@Override
public Response searchVideos(double longitude, double latitude, PageConfig pageConfig) {
EntityTag tag = new EntityTag(Long.toString(weatherSession.getLastModifiedVideo()));
@@ -256,8 +256,8 @@ public class WeatherResource implements IWeatherService {
if (builder == null) {
builder = Response.ok(weatherSession.getVideos(new Coordinate(longitude, latitude), pageConfig));
}
return builder.tag(tag).build();
return builder.tag(tag).build();
}
}
+6 -5
View File
@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>resteasy.media.type.mappings</param-name>
<param-value>html : text/html, json : application/json, xml : application/xml</param-value>
</context-param>
</context-param>
<!-- run resteasy as filter to support coexistence with static content -->
<filter>
<filter-name>Resteasy</filter-name>