feature/server/measurement #52
@@ -0,0 +1,83 @@
|
||||
package com.mowesta.api.measurement;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.BeanParam;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.Tags;
|
||||
import com.mowesta.api.access.Authorizations;
|
||||
import com.mowesta.api.access.Roles;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Authorization;
|
||||
|
||||
/**
|
||||
* A service to manage measurements.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@Api
|
||||
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
|
||||
@Path("/")
|
||||
public interface IMeasurementService {
|
||||
|
||||
/**
|
||||
* Adds a new measurement for device.
|
||||
*
|
||||
* @param measurement The measurement to add.
|
||||
* @return The measurement, if successful.
|
||||
*/
|
||||
@POST
|
||||
@Path("devices/current/measurements/")
|
||||
@ApiOperation(value = "Adds a measurement of current device.", authorizations = {
|
||||
@Authorization(Authorizations.DEVICE) }, tags = { Tags.DEFAULT, Tags.DEVICE })
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Measurement added successfully.", response = Measurement.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "No valid authorization found.") })
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
Response setCurrentDeviceMeasurement(
|
||||
@ApiParam(value = "The new measurement values to set.", required = true) @Valid Measurement measurement);
|
||||
|
||||
@GET
|
||||
@Path("devices/current/measurements/")
|
||||
@ApiOperation(value = "Returns the measurement for device with specified start and duration time.", authorizations = {
|
||||
@Authorization(Authorizations.DEVICE) }, tags = { Tags.DEFAULT, Tags.DEVICE, Tags.USER })
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Measurement retrieved successfully.", response = MeasurementPage.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges to retrieve the measurement.") })
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
Response getCurrentDeviceMeasurements(@BeanParam @Valid PageConfig pageConfig,
|
||||
@ApiParam(value = "The start time to retrieve measurement.", required = true) @QueryParam("start") long start,
|
||||
@ApiParam(value = "The duration time to retrieve measurement.") @QueryParam("duration") long duration);
|
||||
|
||||
@GET
|
||||
@Path("devices/{id}/measurements/")
|
||||
@ApiOperation(value = "Returns the measurement for a device with specified start and duration time.", authorizations = {
|
||||
@Authorization(Authorizations.USER) }, tags = { Tags.DEFAULT, Tags.USER })
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Measurements retrieved successfully.", response = MeasurementPage.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The measurements were not found."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges to retrieve the measurements.") })
|
||||
@RolesAllowed({ Roles.USER })
|
||||
Response getMeasurements(@BeanParam @Valid PageConfig pageConfig,
|
||||
@ApiParam(value = "The id of the device to retrieve measurement.", required = true) @PathParam("id") long id,
|
||||
@ApiParam(value = "The start time to retrieve measurement.", required = true) @QueryParam("start") long start,
|
||||
@ApiParam(value = "The duration time to retrieve measurement.") @QueryParam("duration") long duration);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.mowesta.api.measurement;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.mowesta.api.Entity;
|
||||
import com.mowesta.api.location.Coordinate;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Represents a measurement of a device.
|
||||
*
|
||||
* @author Sebastian, Tobias
|
||||
*/
|
||||
@XmlRootElement
|
||||
@ApiModel(description = "Represents a measurement of a device.", parent = Entity.class)
|
||||
public class Measurement extends Entity {
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value = "The coordinate of the measurement.", required = true)
|
||||
private Coordinate coordinate;
|
||||
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value = "The timestamp of the measurement.", required = true)
|
||||
private long timestamp;
|
||||
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value = "The device id of the measurement.", required = true)
|
||||
private long deviceId;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value = "The version of the app, that was used for creating the measurement.", required = true)
|
||||
private String appVersion;
|
||||
|
||||
@XmlElementWrapper
|
||||
@XmlElement(name = "contexts")
|
||||
@JsonProperty(value = "contexts")
|
||||
@ApiModelProperty(value = "The context of the measurement.")
|
||||
private Map<MeasurementContext, String> context;
|
||||
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The measured air temperature of the measurement.")
|
||||
private Long measuredTemperature;
|
||||
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The calculated air temperature for the measurement.")
|
||||
private Long calculatedTemperature;
|
||||
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The measured pressure of the measurement.")
|
||||
private Long pressure;
|
||||
|
||||
@XmlAttribute
|
||||
@ApiModelProperty(value = "The measured humidity ot the measurement.")
|
||||
private Long humidity;
|
||||
|
||||
/**
|
||||
* The default constructor for serialization.
|
||||
*/
|
||||
public Measurement() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
public Coordinate getCoordinate() {
|
||||
return coordinate;
|
||||
}
|
||||
|
||||
public void setCoordinate(Coordinate coordinate) {
|
||||
this.coordinate = coordinate;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public long getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public void setDeviceId(long deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public String getAppVersion() {
|
||||
return appVersion;
|
||||
}
|
||||
|
||||
public void setAppVersion(String appVersion) {
|
||||
this.appVersion = appVersion;
|
||||
}
|
||||
|
||||
public Map<MeasurementContext, String> getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public void setContext(Map<MeasurementContext, String> context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public Long getMeasuredTemperature() {
|
||||
return measuredTemperature;
|
||||
}
|
||||
|
||||
public void setMeasuredTemperature(Long measuredTemperature) {
|
||||
this.measuredTemperature = measuredTemperature;
|
||||
}
|
||||
|
||||
public Long getCalculatedTemperature() {
|
||||
return calculatedTemperature;
|
||||
}
|
||||
|
||||
public void setCalculatedTemperature(Long calculatedTemperature) {
|
||||
this.calculatedTemperature = calculatedTemperature;
|
||||
}
|
||||
|
||||
public Long getPressure() {
|
||||
return pressure;
|
||||
}
|
||||
|
||||
public void setPressure(Long pressure) {
|
||||
this.pressure = pressure;
|
||||
}
|
||||
|
||||
public Long getHumidity() {
|
||||
return humidity;
|
||||
}
|
||||
|
||||
public void setHumidity(Long humidity) {
|
||||
this.humidity = humidity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.mowesta.api.measurement;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
/**
|
||||
* The types of measurement context.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
public enum MeasurementContext {
|
||||
|
||||
/**
|
||||
* identifies weather battery is charging
|
||||
*/
|
||||
BATTERY_CHARGING;
|
||||
|
||||
/**
|
||||
* Returns the value for the json representation.
|
||||
*
|
||||
* @param json The json string.
|
||||
* @return The measurement_context type.
|
||||
*/
|
||||
@JsonCreator
|
||||
public static MeasurementContext fromString(String json) {
|
||||
if (json == null)
|
||||
return null;
|
||||
return valueOf(json.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the json representation.
|
||||
*
|
||||
* @return The json representation.
|
||||
*/
|
||||
@JsonValue
|
||||
public String toJson() {
|
||||
return name().toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.mowesta.api.measurement;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlSeeAlso;
|
||||
|
||||
import com.mowesta.api.Page;
|
||||
|
||||
/**
|
||||
* A page containing measurements.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@XmlRootElement
|
||||
@XmlSeeAlso(Measurement.class)
|
||||
@ApiModel(description = "Represents a page of measurements.", parent = Page.class)
|
||||
public class MeasurementPage extends Page<Measurement> {
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mowesta.service.conversion;
|
||||
|
||||
import com.mowesta.api.location.Coordinate;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.service.entity.EmbeddedCoordinate;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
import org.mapstruct.Context;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
/**
|
||||
* A converter for measurements.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@Mapper(config = AbstractConverter.class)
|
||||
public abstract class MeasurementConverter extends AbstractEntityConverter<MeasurementEntity, Measurement> {
|
||||
|
||||
@Override
|
||||
@Mapping(target = "deviceId", source = "device.id")
|
||||
public abstract Measurement convert(MeasurementEntity source, @Context boolean filtered);
|
||||
|
||||
abstract Coordinate mapCoordinate(EmbeddedCoordinate coordinate);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.hibernate.search.annotations.IndexedEmbedded;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.measurement.MeasurementContext;
|
||||
|
||||
/**
|
||||
* The entity to store measurements.
|
||||
*
|
||||
* @author Sebastian
|
||||
*
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "measurement", indexes = { @Index(columnList = "deleted,modificationTime", unique = false) })
|
||||
public class MeasurementEntity extends AbstractEntity {
|
||||
|
||||
private static final long serialVersionUID = 8039668173139778745L;
|
||||
|
||||
/**
|
||||
* The longitude and latitude of the center of the location.
|
||||
*/
|
||||
@NotNull
|
||||
@Embedded
|
||||
@IndexedEmbedded
|
||||
private EmbeddedCoordinate coordinate;
|
||||
|
||||
private long timestamp;
|
||||
|
||||
@NotNull
|
||||
@JoinColumn(name = "device_id")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
private DeviceEntity device;
|
||||
|
||||
@NotNull
|
||||
private String appVersion;
|
||||
|
||||
@ElementCollection
|
||||
@MapKeyColumn(name="contexttype")
|
||||
private Map<MeasurementContext, String> context;
|
||||
|
||||
private Long measuredTemperature;
|
||||
|
||||
private Long calculatedTemperature;
|
||||
|
||||
private Long pressure;
|
||||
|
||||
private Long humidity;
|
||||
|
||||
/**
|
||||
* @return the coordinate
|
||||
*/
|
||||
public EmbeddedCoordinate getCoordinate() {
|
||||
return coordinate;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param coordinate the coordinate to set
|
||||
*/
|
||||
public void setCoordinate(EmbeddedCoordinate coordinate) {
|
||||
this.coordinate = coordinate;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the timestamp
|
||||
*/
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param timestamp the timestamp to set
|
||||
*/
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the device
|
||||
*/
|
||||
public DeviceEntity getDevice() {
|
||||
return device;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param device the device to set
|
||||
*/
|
||||
public void setDevice(DeviceEntity device) {
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the appVersion
|
||||
*/
|
||||
public String getAppVersion() {
|
||||
return appVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param appVersion the appVersion to set
|
||||
*/
|
||||
public void setAppVersion(String appVersion) {
|
||||
this.appVersion = appVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the context
|
||||
*/
|
||||
public Map<MeasurementContext, String> getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param context the context to set
|
||||
*/
|
||||
public void setContext(Map<MeasurementContext, String> context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the measuredTemperature
|
||||
*/
|
||||
public Long getMeasuredTemperature() {
|
||||
return measuredTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param measuredTemperature the measuredTemperature to set
|
||||
*/
|
||||
public void setMeasuredTemperature(Long measuredTemperature) {
|
||||
this.measuredTemperature = measuredTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the calculatedTemperature
|
||||
*/
|
||||
public Long getCalculatedTemperature() {
|
||||
return calculatedTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param calculatedTemperature the calculatedTemperature to set
|
||||
*/
|
||||
public void setCalculatedTemperature(Long calculatedTemperature) {
|
||||
this.calculatedTemperature = calculatedTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pressure
|
||||
*/
|
||||
public Long getPressure() {
|
||||
return pressure;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pressure the pressure to set
|
||||
*/
|
||||
public void setPressure(Long pressure) {
|
||||
this.pressure = pressure;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the humidity
|
||||
*/
|
||||
public Long getHumidity() {
|
||||
return humidity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param humidity the humidity to set
|
||||
*/
|
||||
public void setHumidity(Long humidity) {
|
||||
this.humidity = humidity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the number of measurement whose start and duration time matches and
|
||||
* belongs to device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param device The device to search measurements for.
|
||||
* @param start The start timestamp to search for.
|
||||
* @param duration The duration time to search for.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The number of results.
|
||||
*/
|
||||
public static Integer countByDeviceAndTimestamp(EntityManager em, DeviceEntity device, long start, long duration,
|
||||
boolean filtered) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class); // from MeasurementEntity e
|
||||
cq.select(cb.count(r)); // select count(e)
|
||||
Predicate is = cb.and(cb.equal(r.get("device"), device.getId()), // e.device_id=:device_id
|
||||
cb.between(r.get("timestamp"), start, start + duration)); // and e.timestamp between start and
|
||||
// start+duration
|
||||
if (filtered) {
|
||||
cq.where(cb.and(cb.equal(r.get("deleted"), false), is)); // and not deleted
|
||||
} else {
|
||||
cq.where(is); // ignore deleted
|
||||
}
|
||||
try {
|
||||
TypedQuery<Long> q = em.createQuery(cq);
|
||||
return q.getSingleResult().intValue();
|
||||
} catch (NoResultException e) {
|
||||
return new Integer(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all measurement by start and duration time and belongs to device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param device The device to search measurements for.
|
||||
* @param start The start timestamp to search for.
|
||||
* @param duration The duration time to search for.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The list to fill the page.
|
||||
*/
|
||||
public static List<MeasurementEntity> findAllByDeviceAndTimestamp(EntityManager em, PageConfig config,
|
||||
DeviceEntity device, long start, long duration, boolean filtered) {
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<MeasurementEntity> cq = cb.createQuery(MeasurementEntity.class);
|
||||
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class); // from MeasuementEntity e
|
||||
cq.select(r); // select E
|
||||
Predicate is = cb.and(cb.equal(r.get("device"), device.getId()), // e.device=:device
|
||||
cb.between(r.get("timestamp"), start, start + duration)); // and e.timestamp between start and
|
||||
// start+duration
|
||||
if (filtered) {
|
||||
cq.where(cb.and(cb.equal(r.get("deleted"), false), is)); // and not deleted
|
||||
} else {
|
||||
cq.where(is); // ignore deleted
|
||||
}
|
||||
TypedQuery<MeasurementEntity> q = em.createQuery(cq);
|
||||
q.setFirstResult(config.getOffset());
|
||||
q.setMaxResults(config.getSize());
|
||||
return q.getResultList();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -29,200 +29,210 @@ import javax.enterprise.context.RequestScoped;
|
||||
@DeclareRoles({ Roles.ADMIN, Roles.USER, Roles.DEVICE })
|
||||
public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
|
||||
|
||||
/**
|
||||
* Adds a new device to the database.
|
||||
*
|
||||
* @param info The device info with meta data for the device.
|
||||
* @return The new device handle.
|
||||
*/
|
||||
@PermitAll
|
||||
public DeviceHandle addDevice(DeviceInfo info) {
|
||||
DeviceEntity entity = new DeviceEntity();
|
||||
entity.setUser(getPrincipalUser());
|
||||
entity.setDevice(info.getDevice());
|
||||
entity.setManufacturer(info.getManufacturer());
|
||||
entity.setModel(info.getModel());
|
||||
entity.setOs(info.getOs());
|
||||
entity.setToken(SecureToken.createToken(TokenType.INTERNAL));
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
return Convert.with(DeviceHandleConverter.class).apply(entity, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects a device that has been created without user account with
|
||||
* an existing user account.
|
||||
*
|
||||
* @return The device, if successful.
|
||||
* @throws EntityForbiddenException Thrown if the user or device is not valid.
|
||||
* @throws EntityConflictException Thrown if the device is already connected with
|
||||
* a user account.
|
||||
*/
|
||||
@RolesAllowed({Roles.DEVICE, Roles.USER})
|
||||
public Device setCurrentDeviceUser() throws EntityForbiddenException, EntityConflictException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (device == null) throw new EntityForbiddenException(DeviceEntity.class, null);
|
||||
if (user == null) throw new EntityForbiddenException(UserEntity.class, null);
|
||||
if (device.getUser() != null) throw new EntityConflictException(DeviceEntity.class, device.getId());
|
||||
device.setUser(user);
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(device, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the current device.
|
||||
*
|
||||
* @return The current device.
|
||||
* @throws EntityNotFoundException Thrown if the entity cannot be found.
|
||||
* @throws EntityForbiddenException Thrown if the entity is deleted.
|
||||
*/
|
||||
@RolesAllowed({Roles.DEVICE})
|
||||
public Device getCurrentDevice() throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity entity = getPrincipalDevice();
|
||||
if (entity == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device.");
|
||||
if (entity.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, entity.getId(), "Device is deleted.");
|
||||
return Convert.with(DeviceConverter.class).apply(entity, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the current device.
|
||||
*
|
||||
* @throws EntityNotFoundException Throw if the device is not found.
|
||||
* @throws EntityForbiddenException Thrown if the device is deleted already.
|
||||
*/
|
||||
@RolesAllowed({Roles.DEVICE})
|
||||
public void deleteCurrentDevice() throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device.");
|
||||
if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted.");
|
||||
device.setDeleted(true);
|
||||
}
|
||||
/**
|
||||
* Adds a new device to the database.
|
||||
*
|
||||
* @param info The device info with meta data for the device.
|
||||
* @return The new device handle.
|
||||
*/
|
||||
@PermitAll
|
||||
public DeviceHandle addDevice(DeviceInfo info) {
|
||||
DeviceEntity entity = new DeviceEntity();
|
||||
entity.setUser(getPrincipalUser());
|
||||
entity.setDevice(info.getDevice());
|
||||
entity.setManufacturer(info.getManufacturer());
|
||||
entity.setModel(info.getModel());
|
||||
entity.setOs(info.getOs());
|
||||
entity.setToken(SecureToken.createToken(TokenType.INTERNAL));
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
return Convert.with(DeviceHandleConverter.class).apply(entity, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a device page ordered by their inverse id.
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param filtered True to filter deleted objects.
|
||||
* @return The page of devices.
|
||||
*/
|
||||
@RolesAllowed({Roles.ADMIN})
|
||||
public DevicePage getAllDevices(PageConfig pageConfig, boolean filtered) {
|
||||
return getAll(DeviceEntity.class, pageConfig, new OrderCriterion("id", true), filtered, new DevicePage(), DeviceConverter.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a device page for the current user ordered by the creation time.
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param filtered True to filter.
|
||||
* @return The page of devices.
|
||||
* @throws EntityNotFoundException Thrown if the user cannot be found.
|
||||
*/
|
||||
@RolesAllowed({Roles.USER})
|
||||
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered) throws EntityNotFoundException {
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
|
||||
return getAllForUser(DeviceEntity.class, user, pageConfig, new OrderCriterion("id"), filtered, new DevicePage(), DeviceConverter.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last modification time for the devices of the current user.
|
||||
*
|
||||
* @return The last modification time for the devices of the current user or 0 if the user does not have any devices.
|
||||
* @throws EntityNotFoundException Thrown if the current user cannot be found.
|
||||
*/
|
||||
@RolesAllowed({Roles.USER})
|
||||
public long getLastModifiedDeviceForCurrentUser() throws EntityNotFoundException {
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
|
||||
return AbstractUserSpecificEntity.getLastModifiedForUser(em, DeviceEntity.class, user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects a device that has been created without user account with an existing
|
||||
* user account.
|
||||
*
|
||||
* @return The device, if successful.
|
||||
* @throws EntityForbiddenException Thrown if the user or device is not valid.
|
||||
* @throws EntityConflictException Thrown if the device is already connected
|
||||
* with a user account.
|
||||
*/
|
||||
@RolesAllowed({ Roles.DEVICE, Roles.USER })
|
||||
public Device setCurrentDeviceUser() throws EntityForbiddenException, EntityConflictException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (device == null)
|
||||
throw new EntityForbiddenException(DeviceEntity.class, null);
|
||||
if (user == null)
|
||||
throw new EntityForbiddenException(UserEntity.class, null);
|
||||
if (device.getUser() != null)
|
||||
throw new EntityConflictException(DeviceEntity.class, device.getId());
|
||||
device.setUser(user);
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(device, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time stamp of the last modification to the set of devices.
|
||||
*
|
||||
* @return The time stamp of the last device modification.
|
||||
*/
|
||||
@PermitAll
|
||||
public long getLastModifiedDevice() {
|
||||
return AbstractEntity.getLastModified(em, DeviceEntity.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows an admin to access all devices by id and a user to access his own devices by id.
|
||||
*
|
||||
* @param id The id to fetch.
|
||||
* @return The device with the id.
|
||||
* @throws EntityNotFoundException Thrown if the device cannot be found.
|
||||
* @throws EntityForbiddenException Thrown if the entity cannot be accessed.
|
||||
*/
|
||||
@RolesAllowed({Roles.USER, Roles.ADMIN})
|
||||
public Device getDevice(long id) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = em.find(DeviceEntity.class, new Long(id));
|
||||
if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
|
||||
if (!sessionContext.isCallerInRole(Roles.ADMIN)) {
|
||||
if (device.isDeleted()) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device is deleted.");
|
||||
}
|
||||
UserEntity principal = getPrincipalUser();
|
||||
if (principal == null || device.getUser() != principal) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device access is not allowed.");
|
||||
}
|
||||
}
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(device, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the device values.
|
||||
*
|
||||
* @param id The id of the device.
|
||||
* @param device The device values.
|
||||
* @return The updated device.
|
||||
* @throws EntityNotFoundException Thrown if the entity cannot be found.
|
||||
*/
|
||||
@RolesAllowed({Roles.ADMIN})
|
||||
public Device setDevice(long id, Device device) throws EntityNotFoundException {
|
||||
DeviceEntity entity = em.find(DeviceEntity.class, new Long(id));
|
||||
if (entity == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
|
||||
entity.setDeleted(device.isDeleted());
|
||||
entity.setDevice(device.getDevice());
|
||||
entity.setManufacturer(device.getManufacturer());
|
||||
entity.setModel(device.getModel());
|
||||
entity.setOs(device.getOs());
|
||||
if (device.getUser() != null) {
|
||||
entity.setUser(em.find(UserEntity.class, device.getUser()));
|
||||
} else {
|
||||
entity.setUser(null);
|
||||
}
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(entity, false);
|
||||
}
|
||||
/**
|
||||
* Returns the current device.
|
||||
*
|
||||
* @return The current device.
|
||||
* @throws EntityNotFoundException Thrown if the entity cannot be found.
|
||||
* @throws EntityForbiddenException Thrown if the entity is deleted.
|
||||
*/
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
public Device getCurrentDevice() throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity entity = getPrincipalDevice();
|
||||
if (entity == null)
|
||||
throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device.");
|
||||
if (entity.isDeleted())
|
||||
throw new EntityForbiddenException(DeviceEntity.class, entity.getId(), "Device is deleted.");
|
||||
return Convert.with(DeviceConverter.class).apply(entity, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the current device.
|
||||
*
|
||||
* @throws EntityNotFoundException Throw if the device is not found.
|
||||
* @throws EntityForbiddenException Thrown if the device is deleted already.
|
||||
*/
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
public void deleteCurrentDevice() throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
if (device == null)
|
||||
throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device.");
|
||||
if (device.isDeleted())
|
||||
throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted.");
|
||||
device.setDeleted(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a device page ordered by their inverse id.
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param filtered True to filter deleted objects.
|
||||
* @return The page of devices.
|
||||
*/
|
||||
@RolesAllowed({ Roles.ADMIN })
|
||||
public DevicePage getAllDevices(PageConfig pageConfig, boolean filtered) {
|
||||
return getAll(DeviceEntity.class, pageConfig, new OrderCriterion("id", true), filtered, new DevicePage(),
|
||||
DeviceConverter.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a device page for the current user ordered by the creation time.
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param filtered True to filter.
|
||||
* @return The page of devices.
|
||||
* @throws EntityNotFoundException Thrown if the user cannot be found.
|
||||
*/
|
||||
@RolesAllowed({ Roles.USER })
|
||||
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered)
|
||||
throws EntityNotFoundException {
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (user == null)
|
||||
throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
|
||||
return getAllForUser(DeviceEntity.class, user, pageConfig, new OrderCriterion("id"), filtered, new DevicePage(),
|
||||
DeviceConverter.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last modification time for the devices of the current user.
|
||||
*
|
||||
* @return The last modification time for the devices of the current user or 0
|
||||
* if the user does not have any devices.
|
||||
* @throws EntityNotFoundException Thrown if the current user cannot be found.
|
||||
*/
|
||||
@RolesAllowed({ Roles.USER })
|
||||
public long getLastModifiedDeviceForCurrentUser() throws EntityNotFoundException {
|
||||
UserEntity user = getPrincipalUser();
|
||||
if (user == null)
|
||||
throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
|
||||
return AbstractUserSpecificEntity.getLastModifiedForUser(em, DeviceEntity.class, user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time stamp of the last modification to the set of devices.
|
||||
*
|
||||
* @return The time stamp of the last device modification.
|
||||
*/
|
||||
@PermitAll
|
||||
public long getLastModifiedDevice() {
|
||||
return AbstractEntity.getLastModified(em, DeviceEntity.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows an admin to access all devices by id and a user to access his own
|
||||
* devices by id.
|
||||
*
|
||||
* @param id The id to fetch.
|
||||
* @return The device with the id.
|
||||
* @throws EntityNotFoundException Thrown if the device cannot be found.
|
||||
* @throws EntityForbiddenException Thrown if the entity cannot be accessed.
|
||||
*/
|
||||
@RolesAllowed({ Roles.USER, Roles.ADMIN })
|
||||
public Device getDevice(long id) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = getDeviceEntity(id);
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(device, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the device values.
|
||||
*
|
||||
* @param id The id of the device.
|
||||
* @param device The device values.
|
||||
* @return The updated device.
|
||||
* @throws EntityNotFoundException Thrown if the entity cannot be found.
|
||||
*/
|
||||
@RolesAllowed({ Roles.ADMIN })
|
||||
public Device setDevice(long id, Device device) throws EntityNotFoundException {
|
||||
DeviceEntity entity = em.find(DeviceEntity.class, new Long(id));
|
||||
if (entity == null)
|
||||
throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
|
||||
entity.setDeleted(device.isDeleted());
|
||||
entity.setDevice(device.getDevice());
|
||||
entity.setManufacturer(device.getManufacturer());
|
||||
entity.setModel(device.getModel());
|
||||
entity.setOs(device.getOs());
|
||||
if (device.getUser() != null) {
|
||||
entity.setUser(em.find(UserEntity.class, device.getUser()));
|
||||
} else {
|
||||
entity.setUser(null);
|
||||
}
|
||||
em.flush();
|
||||
return Convert.with(DeviceConverter.class).apply(entity, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a device.
|
||||
*
|
||||
* @param id The id of the device.
|
||||
* @throws EntityNotFoundException Thrown if the device is not found.
|
||||
* @throws EntityForbiddenException Thrown if the user cannot access the device.
|
||||
*/
|
||||
@RolesAllowed({ Roles.ADMIN, Roles.USER })
|
||||
public void deleteDevice(long id) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = getDeviceEntity(id);
|
||||
device.setDeleted(true);
|
||||
}
|
||||
|
||||
@RolesAllowed({ Roles.ADMIN, Roles.USER })
|
||||
public DeviceEntity getDeviceEntity(long id) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = em.find(DeviceEntity.class, new Long(id));
|
||||
if (device == null)
|
||||
throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
|
||||
if (!sessionContext.isCallerInRole(Roles.ADMIN)) {
|
||||
if (device.isDeleted()) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device is deleted.");
|
||||
}
|
||||
UserEntity principal = getPrincipalUser();
|
||||
if (principal == null || device.getUser() != principal) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device access is not allowed.");
|
||||
}
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a device.
|
||||
*
|
||||
* @param id The id of the device.
|
||||
* @throws EntityNotFoundException Thrown if the device is not found.
|
||||
* @throws EntityForbiddenException Thrown if the user cannot access the device.
|
||||
*/
|
||||
@RolesAllowed({Roles.ADMIN, Roles.USER})
|
||||
public void deleteDevice(long id) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = em.find(DeviceEntity.class, new Long(id));
|
||||
if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
|
||||
if (!sessionContext.isCallerInRole(Roles.ADMIN)) {
|
||||
if (device.isDeleted()) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device is deleted.");
|
||||
}
|
||||
UserEntity principal = getPrincipalUser();
|
||||
if (principal == null || device.getUser() != principal) {
|
||||
throw new EntityForbiddenException(DeviceEntity.class, id, "Device access is not allowed.");
|
||||
}
|
||||
}
|
||||
device.setDeleted(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.mowesta.service.session;
|
||||
|
||||
import javax.annotation.security.DeclareRoles;
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ejb.Stateful;
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
import com.mowesta.service.conversion.Convert;
|
||||
import com.mowesta.service.conversion.MeasurementConverter;
|
||||
import com.mowesta.service.entity.AbstractEntity;
|
||||
import com.mowesta.service.entity.DeviceEntity;
|
||||
import com.mowesta.service.entity.EmbeddedCoordinate;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
|
||||
/**
|
||||
* A stateful session bean to manage measurements.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@Stateful
|
||||
@RequestScoped
|
||||
@DeclareRoles({ Roles.ADMIN, Roles.USER, Roles.DEVICE })
|
||||
public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
|
||||
@Inject
|
||||
DeviceSessionBean deviceSession;
|
||||
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
public Measurement setMeasurementForCurrentDevice(Measurement measurment) throws EntityForbiddenException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
if (device == null)
|
||||
throw new EntityForbiddenException(DeviceEntity.class, null, "Cannot access principal device.");
|
||||
|
||||
MeasurementEntity entity = new MeasurementEntity();
|
||||
entity.setAppVersion(measurment.getAppVersion());
|
||||
entity.setCalculatedTemperature(measurment.getCalculatedTemperature());
|
||||
entity.setContext(measurment.getContext());
|
||||
entity.setCoordinate(new EmbeddedCoordinate(measurment.getCoordinate().getLongitude(),
|
||||
measurment.getCoordinate().getLatitude()));
|
||||
entity.setDevice(device);
|
||||
entity.setHumidity(measurment.getHumidity());
|
||||
entity.setMeasuredTemperature(measurment.getMeasuredTemperature());
|
||||
entity.setPressure(measurment.getPressure());
|
||||
entity.setTimestamp(measurment.getTimestamp());
|
||||
|
||||
em.persist(entity);
|
||||
em.flush();
|
||||
|
||||
return Convert.with(MeasurementConverter.class).apply(entity, false);
|
||||
}
|
||||
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
public MeasurementPage getMeasurementsForCurrentDevice(PageConfig config, long start, long duration,
|
||||
boolean filtered) throws EntityForbiddenException {
|
||||
DeviceEntity device = getPrincipalDevice();
|
||||
if (device == null)
|
||||
throw new EntityForbiddenException(DeviceEntity.class, null, "Cannot access principal device.");
|
||||
return getMeasurements(config, device, start, duration, filtered);
|
||||
}
|
||||
|
||||
@RolesAllowed({ Roles.USER, Roles.ADMIN })
|
||||
public MeasurementPage getMeasurementsForDevice(PageConfig config, long id, long start, long duration,
|
||||
boolean filtered) throws EntityNotFoundException, EntityForbiddenException {
|
||||
DeviceEntity device = deviceSession.getDeviceEntity(id);
|
||||
return getMeasurements(config, device, start, duration, filtered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time stamp of the last modification to the set of measurements.
|
||||
*
|
||||
* @return The time stamp of the last measurement modification.
|
||||
*/
|
||||
@PermitAll
|
||||
public long getLastModifiedMeasurement() {
|
||||
return AbstractEntity.getLastModified(em, MeasurementEntity.class);
|
||||
}
|
||||
|
||||
protected MeasurementPage getMeasurements(PageConfig config, DeviceEntity device, long start, long duration,
|
||||
boolean filtered) {
|
||||
MeasurementPage page = new MeasurementPage();
|
||||
page.setOffset(config.getOffset());
|
||||
page.setSize(config.getSize());
|
||||
int count = MeasurementEntity.countByDeviceAndTimestamp(em, device, start, duration, filtered);
|
||||
page.setTotal(count);
|
||||
if (count > config.getOffset()) {
|
||||
page.setElements(Convert.with(MeasurementConverter.class).apply(
|
||||
MeasurementEntity.findAllByDeviceAndTimestamp(em, config, device, start, duration, filtered),
|
||||
filtered));
|
||||
}
|
||||
return page;
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package com.mowesta.service.test.session;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.device.DeviceHandle;
|
||||
import com.mowesta.api.location.Coordinate;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@RunWith(Arquillian.class)
|
||||
public class MeasurementSessionTest extends AbstractSessionTest {
|
||||
|
||||
/**
|
||||
* Injected during the arquillian test.
|
||||
*/
|
||||
@EJB
|
||||
MeasurementSessionBean measurementSession;
|
||||
|
||||
@EJB
|
||||
DeviceSessionBean deviceSession;
|
||||
|
||||
@BeforeClass
|
||||
public static void addMeasurements() {
|
||||
|
||||
}
|
||||
|
||||
protected Measurement createMeasurement(final MeasurementSessionBean measurementSession)
|
||||
throws EntityForbiddenException {
|
||||
Measurement measurement = new Measurement();
|
||||
measurement.setAppVersion("0.1");
|
||||
measurement.setCoordinate(new Coordinate(1, 2));
|
||||
measurement.setTimestamp(12l);
|
||||
return measurementSession.setMeasurementForCurrentDevice(measurement);
|
||||
}
|
||||
|
||||
protected void assertCreatedMeasurement(Measurement measurement) {
|
||||
assertEquals("0.1", measurement.getAppVersion());
|
||||
assertEquals(new Coordinate(1, 2), measurement.getCoordinate());
|
||||
assertEquals(12l, measurement.getTimestamp());
|
||||
assertNotEquals(null, measurement.getCreationTime());
|
||||
assertNotEquals(null, measurement.getModificationTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddMeasurementAsAdmin() {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, "admin");
|
||||
executeAs("admin", deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddMeasurementAsUser() {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, "handte");
|
||||
executeAs("handte", deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddMeasurementWithoutUser() {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, null);
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMeasurementForDevice() {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, null);
|
||||
// 1. create a measurement to get
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. get measurement created in (1)
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
MeasurementPage page = measurementSession.getMeasurementsForCurrentDevice(new PageConfig(0, 10), 0,
|
||||
1000, false);
|
||||
assertEquals(1, page.getElements().size());
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMeasurementForUser() {
|
||||
Long device = null;
|
||||
// 1. create 5 devices with a measurement
|
||||
for (int i = 0; i < 5; i++) {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, "handte");
|
||||
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
device = deviceHandle.getId();
|
||||
}
|
||||
|
||||
final Long deviceId = device;
|
||||
// 2. get measurement created in (1)
|
||||
executeAs("handte", null, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
MeasurementPage page = measurementSession.getMeasurementsForDevice(new PageConfig(0, 10), deviceId,
|
||||
10l, 13l, false);
|
||||
assertEquals(1, page.getElements().size());
|
||||
} catch (EntityForbiddenException | EntityNotFoundException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMultipleMeasurementForDevice() {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, null);
|
||||
// 1. create 5 devices with a measurement
|
||||
for (int i = 0; i < 5; i++) {
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Measurement persisted = createMeasurement(measurementSession);
|
||||
assertCreatedMeasurement(persisted);
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// 2. get measurement created in (1)
|
||||
executeAs(null, deviceHandle.getToken(), new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
MeasurementPage page = measurementSession.getMeasurementsForCurrentDevice(new PageConfig(0, 10),
|
||||
10l, 13l, false);
|
||||
assertEquals(5, page.getElements().size());
|
||||
} catch (EntityForbiddenException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.mowesta.service.rest;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
import javax.faces.bean.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.EntityTag;
|
||||
import javax.ws.rs.core.Request;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.ResponseBuilder;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.measurement.IMeasurementService;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
|
||||
/**
|
||||
* The JAX-RS resource providing the measurement service.
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@RequestScoped
|
||||
public class MeasurementResource implements IMeasurementService {
|
||||
|
||||
/**
|
||||
* The device session bean that will be injected by the ejb container.
|
||||
*/
|
||||
@EJB
|
||||
DeviceSessionBean deviceSession;
|
||||
|
||||
/**
|
||||
* The measurement session bean that will be injected by the ejb container.
|
||||
*/
|
||||
@EJB
|
||||
MeasurementSessionBean measurementSession;
|
||||
|
||||
/**
|
||||
* The request that will be injected by the jax-rs runtime.
|
||||
*/
|
||||
@Context
|
||||
Request request;
|
||||
|
||||
/**
|
||||
* The uri info to build location urls.
|
||||
*/
|
||||
@Context
|
||||
UriInfo uriInfo;
|
||||
|
||||
/**
|
||||
* A logger injected by CDI.
|
||||
*/
|
||||
@Inject
|
||||
Logger log;
|
||||
|
||||
@Override
|
||||
public Response setCurrentDeviceMeasurement(Measurement measurement) {
|
||||
log.log(Level.INFO, "Received a set request for a measurement of current device.");
|
||||
try {
|
||||
return Response.ok(measurementSession.setMeasurementForCurrentDevice(measurement)).build();
|
||||
} catch(EntityForbiddenException e) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getCurrentDeviceMeasurements(PageConfig pageConfig, long start, long duration) {
|
||||
log.log(Level.INFO, "Received a get request for measurements of current device.");
|
||||
try {
|
||||
EntityTag tag = new EntityTag(Long.toString(measurementSession.getLastModifiedMeasurement()));
|
||||
ResponseBuilder r = request.evaluatePreconditions(tag);
|
||||
|
||||
MeasurementPage measurements = measurementSession.getMeasurementsForCurrentDevice(pageConfig, start, duration, true);
|
||||
|
||||
if (r == null) {
|
||||
r = Response.ok(measurements);
|
||||
}
|
||||
return r.tag(tag).build();
|
||||
} catch (EntityForbiddenException e) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getMeasurements(PageConfig pageConfig, long id, long start, long duration) {
|
||||
log.log(Level.INFO, "Received a get request for measurements of specific device: %s.", id);
|
||||
try {
|
||||
EntityTag tag = new EntityTag(Long.toString(measurementSession.getLastModifiedMeasurement()));
|
||||
ResponseBuilder r = request.evaluatePreconditions(tag);
|
||||
|
||||
MeasurementPage measurements = measurementSession.getMeasurementsForDevice(pageConfig, id, start, duration, true);
|
||||
|
||||
if (r == null) {
|
||||
r = Response.ok(measurements);
|
||||
}
|
||||
return r.tag(tag).build();
|
||||
} catch (EntityNotFoundException e) {
|
||||
return Response.status(Status.NOT_FOUND).build();
|
||||
} catch (EntityForbiddenException e) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user