feature/measurement_rating #159
+4
-3
@@ -58,7 +58,8 @@ allprojects {
|
||||
versionAndroidXRoom = '2.2.6'
|
||||
versionAndroidXPreference = '1.1.1'
|
||||
versionRobolectric = '4.5'
|
||||
|
||||
// apache math dependencies
|
||||
versionApacheMath = '3.6.1'
|
||||
}
|
||||
|
||||
|
||||
@@ -131,8 +132,8 @@ subprojects {
|
||||
publishing {
|
||||
repositories {
|
||||
maven {
|
||||
url = version.endsWith('SNAPSHOT') ?
|
||||
"https://project.nes.uni-due.de/nexus/repository/maven-snapshots" :
|
||||
url = version.endsWith('SNAPSHOT') ?
|
||||
"https://project.nes.uni-due.de/nexus/repository/maven-snapshots" :
|
||||
"https://project.nes.uni-due.de/nexus/repository/maven-releases"
|
||||
credentials { username = 'jenkins'; password = System.properties['jenkins.nexus.password'] }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
|
||||
@@ -81,6 +81,10 @@ public class Measurement extends Entity {
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The calculated relative humidity (estimated by the service), may be null.")
|
||||
private Double humidity;
|
||||
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The calculated measurement rating (null if not set by the backend)")
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,10 +29,12 @@ dependencies {
|
||||
testCompile "org.picketbox:picketbox:${versionPicketbox}"
|
||||
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
|
||||
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
|
||||
compile "org.apache.commons:commons-math3:${versionApacheMath}"
|
||||
|
||||
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
|
||||
|
||||
testBundle "org.infinispan:infinispan-query:${versionInfinispan}"
|
||||
testBundle "org.apache.commons:commons-math3:${versionApacheMath}"
|
||||
}
|
||||
|
||||
// copy the jars required for testing into an output folder
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
@Entity
|
||||
@Table(name = "equilibrium", indexes = {
|
||||
@Index(columnList = "time"),
|
||||
})
|
||||
public class EquilibriumEntity extends AbstractEntity {
|
||||
|
||||
/**
|
||||
* The serialization version.
|
||||
*/
|
||||
private static final long serialVersionUID = 8039663673139778735L;
|
||||
|
||||
/**
|
||||
* The timestamp form which the model training was started.
|
||||
*/
|
||||
private long time;
|
||||
|
||||
/**
|
||||
* The equilibrium value.
|
||||
*/
|
||||
private double value;
|
||||
|
||||
public long getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(long time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public double getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(double value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public static EquilibriumEntity findForTimestamp(EntityManager em, long time) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<EquilibriumEntity> cq = cb.createQuery(EquilibriumEntity.class);
|
||||
Root<EquilibriumEntity> r = cq.from(EquilibriumEntity.class);
|
||||
cq.select(r);
|
||||
cq.where(cb.equal(r.get("time"), time));
|
||||
TypedQuery<EquilibriumEntity> q = em.createQuery(cq);
|
||||
List<EquilibriumEntity> results = q.getResultList();
|
||||
if (results.size() == 0) return null;
|
||||
else return results.get(0);
|
||||
}
|
||||
|
||||
public static EquilibriumEntity findMostRecent(EntityManager em) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<EquilibriumEntity> cq = cb.createQuery(EquilibriumEntity.class);
|
||||
Root<EquilibriumEntity> r = cq.from(EquilibriumEntity.class);
|
||||
cq.select(r);
|
||||
cq.orderBy(cb.desc(r.get("time")));
|
||||
TypedQuery<EquilibriumEntity> q = em.createQuery(cq);
|
||||
List<EquilibriumEntity> results = q.getResultList();
|
||||
if (results.size() == 0) return null;
|
||||
else return results.get(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
@Entity
|
||||
@Table(name = "heatTransferModel", indexes = {
|
||||
@Index(columnList = "beginTime", unique = false),
|
||||
})
|
||||
public class HeatTransferModelEntity extends AbstractEntity {
|
||||
|
||||
/**
|
||||
* The serialization version.
|
||||
*/
|
||||
private static final long serialVersionUID = 8039668173139778735L;
|
||||
|
||||
/**
|
||||
* The timestamp form which the model training was started.
|
||||
*/
|
||||
private long beginTime;
|
||||
|
||||
/**
|
||||
* The timestamp where the model training ended.
|
||||
*/
|
||||
private long endTime;
|
||||
|
||||
/**
|
||||
* The slope of the Linear Model.
|
||||
*/
|
||||
private double slope;
|
||||
|
||||
/**
|
||||
* The intercept of the Linear Model.
|
||||
*/
|
||||
private double intercept;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the begin time of the training data the model was trained on.
|
||||
*
|
||||
* @return The begin time.
|
||||
*/
|
||||
public long getBeginTime() {
|
||||
return beginTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the begin time.
|
||||
*
|
||||
* @param beginTime The begin time to set.
|
||||
*/
|
||||
public void setBeginTime(long beginTime) {
|
||||
this.beginTime = beginTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the end time of the training data the model was trained on.
|
||||
*
|
||||
* @return The end time.
|
||||
*/
|
||||
public long getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the end time.
|
||||
*
|
||||
* @param endTime The end time to set.
|
||||
*/
|
||||
public void setEndTime(long endTime) {
|
||||
this.endTime = 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;
|
||||
}
|
||||
|
||||
public Double predict(double value) {
|
||||
double result = value * slope + intercept;
|
||||
if (Double.isNaN(result) || Double.isInfinite(result)) return null;
|
||||
return result;
|
||||
}
|
||||
|
||||
public static HeatTransferModelEntity findForTimestamp(EntityManager em, long beginTime, long endTime) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<HeatTransferModelEntity> cq = cb.createQuery(HeatTransferModelEntity.class);
|
||||
Root<HeatTransferModelEntity> r = cq.from(HeatTransferModelEntity.class);
|
||||
cq.select(r);
|
||||
cq.where(cb.equal(r.get("beginTime"), beginTime));
|
||||
cq.where(cb.equal(r.get("endTime"), endTime));
|
||||
TypedQuery<HeatTransferModelEntity> q = em.createQuery(cq);
|
||||
List<HeatTransferModelEntity> results = q.getResultList();
|
||||
if (results.size() == 0) return null;
|
||||
else return results.get(0);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -23,19 +27,16 @@ import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
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,ratingVersion")
|
||||
})
|
||||
public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
|
||||
@@ -83,6 +84,11 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
*/
|
||||
private Double temperature;
|
||||
|
||||
/**
|
||||
* The version of the prediction method that was used to create the temperature.
|
||||
*/
|
||||
private Integer predictionVersion;
|
||||
|
||||
/**
|
||||
* The pressure in hPA.
|
||||
*/
|
||||
@@ -92,7 +98,22 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
* The relative humidity in %.
|
||||
*/
|
||||
private Double humidity;
|
||||
|
||||
|
||||
/**
|
||||
* The rating of the measurement.
|
||||
*/
|
||||
private Double rating;
|
||||
|
||||
/**
|
||||
* The version of the rating.
|
||||
*/
|
||||
private Integer ratingVersion;
|
||||
|
||||
/**
|
||||
* The measured temperature of the next station.
|
||||
*/
|
||||
private Double stationTemperature;
|
||||
|
||||
/**
|
||||
* Returns the timestamp.
|
||||
*
|
||||
@@ -218,10 +239,82 @@ 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 nearest station temperature.
|
||||
*
|
||||
* @return The temperature.
|
||||
*/
|
||||
public Double getStationTemperature() {
|
||||
return stationTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the station temperature.
|
||||
*
|
||||
* @param stationTemperature The station temperature.
|
||||
*/
|
||||
public void setStationTemperature(Double stationTemperature) {
|
||||
this.stationTemperature = stationTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the prediction version.
|
||||
* @return The version.
|
||||
*/
|
||||
public Integer getPredictionVersion() {
|
||||
return predictionVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the prediction version.
|
||||
*
|
||||
* @param predictionVersion The version.
|
||||
*/
|
||||
public void setPredictionVersion(Integer predictionVersion) {
|
||||
this.predictionVersion = predictionVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +332,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 +385,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 +410,25 @@ 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.
|
||||
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
package com.mowesta.service.session;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.api.weather.WeatherReport;
|
||||
import com.mowesta.api.weather.WeatherReportPage;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.EquilibriumEntity;
|
||||
import com.mowesta.service.entity.HeatTransferModelEntity;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
import com.mowesta.service.entity.WeatherStationEntity;
|
||||
import com.mowesta.service.session.sync.AbstractSyncSessionBean;
|
||||
|
||||
import org.apache.commons.math3.stat.regression.SimpleRegression;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ejb.EJB;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
/**
|
||||
* A stateless session bean that calculates the rating for given measurements
|
||||
*/
|
||||
@Stateless
|
||||
@RolesAllowed({Roles.ADMIN})
|
||||
public class MeasurementRatingSessionBean 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 EquilibriumEntity calculateEquilibriumValue() {
|
||||
|
||||
MeasurementRatingSessionBean proxy = sessionContext.getBusinessObject(getClass());
|
||||
SimpleRegression yearModel = new SimpleRegression(true);
|
||||
int offset = 0;
|
||||
boolean resultWasEmpty;
|
||||
|
||||
do {
|
||||
resultWasEmpty = proxy.addValuesToGivenModel(offset, yearModel);
|
||||
offset += BATCH_SIZE;
|
||||
} while (!resultWasEmpty);
|
||||
|
||||
return proxy.createAndPersistEquilibriumEntity(yearModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, SimpleRegression 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.addData(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 EquilibriumEntity createAndPersistEquilibriumEntity(SimpleRegression 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 / (m - 1);
|
||||
EquilibriumEntity equilibriumEntity = new EquilibriumEntity();
|
||||
|
||||
equilibriumEntity.setValue(equilibriumValue);
|
||||
equilibriumEntity.setTime(System.currentTimeMillis());
|
||||
|
||||
em.persist(equilibriumEntity);
|
||||
|
||||
return equilibriumEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only for beta environment
|
||||
* @param date
|
||||
*/
|
||||
@RolesAllowed({Roles.ADMIN})
|
||||
@TransactionAttribute(TransactionAttributeType.NEVER)
|
||||
public void createRatingsForYear(LocalDate date) {
|
||||
for (int i = 0; i < 356; i++) {
|
||||
createRatingsForADay(date.minusDays(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and persists ratings for a day in shards.
|
||||
*
|
||||
* @param date The date
|
||||
*/
|
||||
@RolesAllowed({Roles.ADMIN})
|
||||
@TransactionAttribute(TransactionAttributeType.NEVER)
|
||||
public void createRatingsForADay(LocalDate date) {
|
||||
MeasurementRatingSessionBean proxy = sessionContext.getBusinessObject(getClass());
|
||||
HeatTransferModelEntity 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
|
||||
HeatTransferModelEntity 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,
|
||||
HeatTransferModelEntity 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 HeatTransferModelEntity readOrCalculateHeatTransferModelForDate(LocalDate date) {
|
||||
|
||||
MeasurementRatingSessionBean 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;
|
||||
HeatTransferModelEntity result = proxy.readHeatTransferModelEntityFromDB(start, end);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
double equilibriumValue;
|
||||
EquilibriumEntity 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 HeatTransferModelEntity();
|
||||
result.setBeginTime(start);
|
||||
result.setEndTime(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 HeatTransferModelEntity readHeatTransferModelEntityFromDB(long start, long end) {
|
||||
return HeatTransferModelEntity.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 EquilibriumEntity readMostRecentEquilibriumEntityFromDB() {
|
||||
return EquilibriumEntity.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(HeatTransferModelEntity 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() / (double) 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);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,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 +70,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 +94,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.
|
||||
@@ -175,11 +175,11 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
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.
|
||||
@@ -197,7 +197,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
|
||||
/**
|
||||
* 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 +213,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 +231,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 +241,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 +286,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.
|
||||
|
||||
@@ -267,8 +267,9 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
* @return The weather station.
|
||||
*/
|
||||
@PermitAll
|
||||
public WeatherStation getStation(Coordinate coordinate, boolean filtered) {
|
||||
return Convert.with(WeatherStationConverter.class).apply(getStationEntity(coordinate, filtered), filtered);
|
||||
public WeatherStation getStation(Coordinate coordinate, boolean filtered, int range) {
|
||||
return Convert.with(WeatherStationConverter.class)
|
||||
.apply(getStationEntity(coordinate, filtered, range), 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) {
|
||||
|
||||
+1
-1
@@ -229,7 +229,7 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
|
||||
batch.add(data);
|
||||
if (batch.size() >= BATCH_SIZE_CITY) {
|
||||
if (shutdownSession.isShuttingDown())
|
||||
throw new RuntimeException("Stopping sync since application is shuttng down.");
|
||||
throw new RuntimeException("Stopping sync since application is shutting down.");
|
||||
syncSession.addCities(batch, duplicates);
|
||||
batch.clear();
|
||||
}
|
||||
|
||||
+70
-39
@@ -1,5 +1,10 @@
|
||||
package com.mowesta.service.session.sync;
|
||||
|
||||
import com.mowesta.service.session.MeasurementRatingSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
@@ -12,6 +17,7 @@ import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Asynchronous;
|
||||
import javax.ejb.ConcurrencyManagement;
|
||||
import javax.ejb.ConcurrencyManagementType;
|
||||
import javax.ejb.ScheduleExpression;
|
||||
import javax.ejb.SessionContext;
|
||||
import javax.ejb.Singleton;
|
||||
import javax.ejb.Timeout;
|
||||
@@ -24,16 +30,16 @@ import javax.inject.Inject;
|
||||
|
||||
/**
|
||||
* 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 +58,24 @@ public class PeriodicSyncSessionBean {
|
||||
/**
|
||||
* The task that generates weather videos.
|
||||
*/
|
||||
VIDEO;
|
||||
VIDEO,
|
||||
/**
|
||||
* The task that creates ratings for measurements with no rating.
|
||||
*/
|
||||
RATINGS,
|
||||
YEAR_RATINGS;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
@Inject
|
||||
protected Logger log;
|
||||
|
||||
@Resource
|
||||
protected TimerService timerService;
|
||||
|
||||
@Inject
|
||||
|
||||
@Inject
|
||||
protected LocationSyncSessionBean locationSyncSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected WeatherReportSyncSessionBean reportSyncSession;
|
||||
|
||||
@@ -73,13 +84,19 @@ public class PeriodicSyncSessionBean {
|
||||
|
||||
@Inject
|
||||
protected WeatherVideoSyncSessionBean videoSyncSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected MeasurementSessionBean measurementSession;
|
||||
|
||||
@Inject
|
||||
protected MeasurementRatingSessionBean measurementRatingSession;
|
||||
|
||||
@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 +111,15 @@ public class PeriodicSyncSessionBean {
|
||||
jobs[JobType.VIDEO.ordinal()] = new Job("VideoSync", (first)-> {
|
||||
videoSyncSession.syncVideos(first);
|
||||
});
|
||||
jobs[JobType.RATINGS.ordinal()] = new Job("MeasurementSync", (first -> {
|
||||
measurementRatingSession.createRatingsForADay(LocalDate.now(ZoneId.of("ECT")).minusDays(1));
|
||||
}));
|
||||
jobs[JobType.YEAR_RATINGS.ordinal()] = new Job("MeasurementYearSync", (first) -> {
|
||||
measurementRatingSession.createRatingsForYear(LocalDate.now(ZoneId.of("ECT")).minusDays(1));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Uses a {@link TimerService} to start the {@link Timer}
|
||||
*/
|
||||
@@ -111,27 +134,35 @@ 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 ratingConfig = new TimerConfig(JobType.RATINGS, false);
|
||||
final ScheduleExpression ratingSchedule = new ScheduleExpression();
|
||||
ratingSchedule.hour(3);
|
||||
timerService.createCalendarTimer(ratingSchedule, ratingConfig);
|
||||
final TimerConfig yearRatingConfig = new TimerConfig(JobType.YEAR_RATINGS, false);
|
||||
final ScheduleExpression yearRatingSchedule = new ScheduleExpression();
|
||||
ratingSchedule.hour(4);
|
||||
timerService.createCalendarTimer(yearRatingSchedule, yearRatingConfig);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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 +172,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 +197,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 +223,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 +244,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.
|
||||
*/
|
||||
|
||||
@@ -6,17 +6,22 @@ import java.util.logging.Level;
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.enterprise.inject.Alternative;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.api.weather.StationOperator;
|
||||
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.EquilibriumEntity;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.entity.WeatherStationEntity;
|
||||
import com.mowesta.service.session.DataSessionBean;
|
||||
import com.mowesta.service.session.InfinispanSessionBean;
|
||||
|
||||
|
||||
/**
|
||||
@@ -81,6 +86,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 +140,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 +162,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 +172,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 +187,12 @@ public class DataTestBean extends DataSessionBean {
|
||||
em.persist(measurement);
|
||||
em.flush();
|
||||
}
|
||||
|
||||
private void createTestEquilibriumTemperature() {
|
||||
EquilibriumEntity equilibriumEntity = new EquilibriumEntity();
|
||||
equilibriumEntity.setTime(System.currentTimeMillis());
|
||||
equilibriumEntity.setValue(37D);
|
||||
em.persist(equilibriumEntity);
|
||||
em.flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
<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.HeatTransferModelEntity</class>
|
||||
<class>com.mowesta.service.entity.EquilibriumEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="jboss.as.jpa.providerModule" value="application"></property>
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.mowesta.service.test.session;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.service.entity.EquilibriumEntity;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
import com.mowesta.service.session.MeasurementRatingSessionBean;
|
||||
import com.mowesta.service.session.sync.PeriodicSyncSessionBean;
|
||||
import com.mowesta.service.session.sync.WeatherReportSyncSessionBean;
|
||||
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.jboss.vfs.VFS;
|
||||
import org.jboss.vfs.VirtualFile;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class MeasurementRatingSessionTest extends AbstractSessionTest {
|
||||
|
||||
@EJB
|
||||
MeasurementRatingSessionBean 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", () -> {
|
||||
EquilibriumEntity 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) {
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+47
-20
@@ -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());
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -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());
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -117,7 +117,7 @@ public class WeatherResource implements IWeatherService {
|
||||
|
||||
@Override
|
||||
public Response searchStation(double longitude, double latitude) {
|
||||
WeatherStation station = weatherSession.getStation(new Coordinate(longitude, latitude), true);
|
||||
WeatherStation station = weatherSession.getStation(new Coordinate(longitude, latitude), true, 100);
|
||||
if (station == null) return Response.noContent().build();
|
||||
EntityTag tag = new EntityTag(Long.toString(station.getId()) + "-" + Long.toString(station.getModificationTime()));
|
||||
ResponseBuilder builder = request.evaluatePreconditions(tag);
|
||||
@@ -131,7 +131,7 @@ public class WeatherResource implements IWeatherService {
|
||||
public Response getCityStation(long id) {
|
||||
try {
|
||||
City city = locationSession.getCity(id, true);
|
||||
WeatherStation station = weatherSession.getStation(city.getCoordinate(), true);
|
||||
WeatherStation station = weatherSession.getStation(city.getCoordinate(), true, 100);
|
||||
if (station == null) return Response.noContent().build();
|
||||
EntityTag tag = new EntityTag(Long.toString(station.getModificationTime()));
|
||||
ResponseBuilder builder = request.evaluatePreconditions(tag);
|
||||
|
||||
Reference in New Issue
Block a user