Merge branch 'dev' into 'master'

Dev

See merge request sa4-2020/the-sanmarinoes/backend!211
This commit is contained in:
Claudio Maggioni 2020-05-27 22:58:39 +02:00
commit 0f24a42b3c
242 changed files with 9704 additions and 2291 deletions

View file

@ -52,14 +52,10 @@ test:
reports: reports:
junit: build/test-results/test/TEST-*.xml junit: build/test-results/test/TEST-*.xml
#Runs a quality check on the code and creates a report on the codes sonarqube:
code_quality: image: gradle:jdk11
stage: code_quality stage: code_quality
allow_failure: true only:
- dev
script: script:
- gradle cpdCheck - gradle build jacocoTestReport sonarqube -Dsonar.verbose=true -Dsonar.host.url=$SONAR_URL -Dsonar.login=$SONAR_LOGIN -Dsonar.projectKey=$CI_PROJECT_PATH_SLUG -Dsonar.projectName=$CI_PROJECT_PATH_SLUG -Dsonar.scm.disabled=True -Dsonar.coverage.jacoco.xmlReportPaths=./build/reports/jacoco/test/jacocoTestReport.xml
artifacts:
paths:
- build/reports/cpd/cpdCheck.xml
#create a report on the quality of the code
expose_as: 'Code Quality Report'

8
.mailmap Normal file
View file

@ -0,0 +1,8 @@
Claudio Maggioni <maggicl@usi.ch> Claudio Maggioni (maggicl) <maggicl@kolabnow.ch>
Claudio Maggioni <maggicl@usi.ch> Claudio Maggioni (maggicl) <maggicl@usi.ch>
Filippo Cesana <cesanf@usi.ch> FilippoCesana <cesanf@usi.ch>
Filippo Cesana <cesanf@usi.ch> Fil Cesana <cesanf@usi.ch>
Andrea Brites Marto <britea@usi.ch> britea <andreabritesma@gmail.com>
Christian Capeáns Pérez <capeac@usi.ch> christiancp <capeac@usi.ch>
Tommaso Rodolfo Masera <rodolt@usi.ch> tommi27 <tommi99@hotmail.it>
Matteo Omenetti <omenem@usi.ch> omenem <omenem@usi.ch>

View file

@ -1,8 +1,10 @@
plugins { plugins {
id 'org.springframework.boot' version '2.2.4.RELEASE' id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE' id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id "de.aaschmid.cpd" version "3.1"
id 'java' id 'java'
id 'jacoco'
id "org.sonarqube" version "2.8"
id 'io.freefair.lombok' version '5.0.1'
} }
group = 'ch.usi.inf.sa4.sanmarinoes' group = 'ch.usi.inf.sa4.sanmarinoes'
version = '0.0.1-SNAPSHOT' version = '0.0.1-SNAPSHOT'
@ -35,6 +37,7 @@ dependencies {
testImplementation('org.springframework.boot:spring-boot-starter-test') { testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
} }
testImplementation 'nl.jqno.equalsverifier:equalsverifier:3.3'
testImplementation 'org.springframework.security:spring-security-test' testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'com.h2database:h2:1.4.200' testImplementation 'com.h2database:h2:1.4.200'
// Fixes https://stackoverflow.com/a/60455550 // Fixes https://stackoverflow.com/a/60455550
@ -43,10 +46,20 @@ dependencies {
gradle.projectsEvaluated { gradle.projectsEvaluated {
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" options.compilerArgs << "-Xlint:deprecation"
} }
} }
test { test {
useJUnitPlatform() useJUnitPlatform()
} }
jacocoTestReport {
reports {
xml.enabled true
}
}
plugins.withType(JacocoPlugin) {
tasks["test"].finalizedBy 'jacocoTestReport'
}

4
gradle.properties Normal file
View file

@ -0,0 +1,4 @@
systemProp.sonar.host.url=https://lab.si.usi.ch:9000
systemProp.sonar.login=871fdfcb09345b1841f1730596ac32aacf3a86fb
systemProp.sonar.projectKey=SMASmarthutBackend
systemProp.sonar.scm.disabled=true

3
lombok.config Normal file
View file

@ -0,0 +1,3 @@
# This file is generated by the 'io.freefair.lombok' Gradle plugin
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true

View file

@ -14,7 +14,8 @@ import org.springframework.stereotype.Component;
public class CORSFilter implements Filter { public class CORSFilter implements Filter {
public static void setCORSHeaders(HttpServletResponse response) { public static void setCORSHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader(
new StringBuilder("nigirO-wollA-lortnoC-sseccA").reverse().toString(), "*");
response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Credentials", "true");
@ -31,10 +32,4 @@ public class CORSFilter implements Filter {
chain.doFilter(req, res); chain.doFilter(req, res);
} }
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
} }

View file

@ -0,0 +1,24 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Component
@Validated
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "camera")
public class CameraConfigurationService {
@NotNull private String videoUrl;
public synchronized String getVideoUrl() {
return videoUrl;
}
public synchronized void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
}

View file

@ -46,67 +46,67 @@ public class EmailConfigurationService {
@NotNull private String registrationRedirect; @NotNull private String registrationRedirect;
public String getRegistrationSubject() { public synchronized String getRegistrationSubject() {
return registrationSubject; return registrationSubject;
} }
public void setRegistrationSubject(String registrationSubject) { public synchronized void setRegistrationSubject(String registrationSubject) {
this.registrationSubject = registrationSubject; this.registrationSubject = registrationSubject;
} }
public String getRegistration() { public synchronized String getRegistration() {
return registration; return registration;
} }
public void setRegistration(String registration) { public synchronized void setRegistration(String registration) {
this.registration = registration; this.registration = registration;
} }
public String getRegistrationPath() { public synchronized String getRegistrationPath() {
return registrationPath; return registrationPath;
} }
public void setRegistrationPath(String registrationPath) { public synchronized void setRegistrationPath(String registrationPath) {
this.registrationPath = registrationPath; this.registrationPath = registrationPath;
} }
public String getResetPasswordSubject() { public synchronized String getResetPasswordSubject() {
return resetPasswordSubject; return resetPasswordSubject;
} }
public void setResetPasswordSubject(String resetPasswordSubject) { public synchronized void setResetPasswordSubject(String resetPasswordSubject) {
this.resetPasswordSubject = resetPasswordSubject; this.resetPasswordSubject = resetPasswordSubject;
} }
public String getResetPassword() { public synchronized String getResetPassword() {
return resetPassword; return resetPassword;
} }
public void setResetPassword(String resetPassword) { public synchronized void setResetPassword(String resetPassword) {
this.resetPassword = resetPassword; this.resetPassword = resetPassword;
} }
public String getResetPasswordPath() { public synchronized String getResetPasswordPath() {
return resetPasswordPath; return resetPasswordPath;
} }
public void setResetPasswordPath(String resetPasswordPath) { public synchronized void setResetPasswordPath(String resetPasswordPath) {
this.resetPasswordPath = resetPasswordPath; this.resetPasswordPath = resetPasswordPath;
} }
public String getResetPasswordRedirect() { public synchronized String getResetPasswordRedirect() {
return resetPasswordRedirect; return resetPasswordRedirect;
} }
public void setResetPasswordRedirect(String resetPasswordRedirect) { public synchronized void setResetPasswordRedirect(String resetPasswordRedirect) {
this.resetPasswordRedirect = resetPasswordRedirect; this.resetPasswordRedirect = resetPasswordRedirect;
} }
public String getRegistrationRedirect() { public synchronized String getRegistrationRedirect() {
return registrationRedirect; return registrationRedirect;
} }
public void setRegistrationRedirect(String registrationRedirect) { public synchronized void setRegistrationRedirect(String registrationRedirect) {
this.registrationRedirect = registrationRedirect; this.registrationRedirect = registrationRedirect;
} }
} }

View file

@ -1,9 +1,7 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationFastUpdateRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableState; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.State;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableState;
import com.google.gson.*; import com.google.gson.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -27,22 +25,33 @@ public class GsonConfig {
private static GsonBuilder configureBuilder() { private static GsonBuilder configureBuilder() {
final GsonBuilder builder = new GsonBuilder(); final GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter()); builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());
@SuppressWarnings({"rawTypes"})
RuntimeTypeAdapterFactory<State> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory<State> runtimeTypeAdapterFactory =
RuntimeTypeAdapterFactory.of(State.class, "kind") RuntimeTypeAdapterFactory.of(State.class, "kind")
.registerSubtype(SwitchableState.class, "switchableState") .registerSubtype(SwitchableState.class, "switchableState")
.registerSubtype(DimmableState.class, "dimmableState"); .registerSubtype(DimmableState.class, "dimmableState");
RuntimeTypeAdapterFactory<AutomationFastUpdateRequest.TriggerDTO> RuntimeTypeAdapterFactory<TriggerDTO> runtimeTypeAdapterFactoryII =
runtimeTypeAdapterFactoryII = RuntimeTypeAdapterFactory.of(TriggerDTO.class, "kind")
RuntimeTypeAdapterFactory.of( .registerSubtype(BooleanTriggerDTO.class, "booleanTrigger")
AutomationFastUpdateRequest.TriggerDTO.class, "kind") .registerSubtype(RangeTriggerDTO.class, "rangeTrigger");
.registerSubtype(
AutomationFastUpdateRequest.BooleanTriggerDTO.class, RuntimeTypeAdapterFactory<ConditionDTO> runtimeTypeAdapterFactoryIII =
"booleanTrigger") RuntimeTypeAdapterFactory.of(ConditionDTO.class, "kind")
.registerSubtype( .registerSubtype(BooleanConditionDTO.class, "booleanCondition")
AutomationFastUpdateRequest.RangeTriggerDTO.class, .registerSubtype(RangeConditionDTO.class, "rangeCondition")
"rangeTrigger"); .registerSubtype(ThermostatConditionDTO.class, "thermostatCondition");
builder.registerTypeAdapterFactory(runtimeTypeAdapterFactory); builder.registerTypeAdapterFactory(runtimeTypeAdapterFactory);
builder.registerTypeAdapterFactory(runtimeTypeAdapterFactoryII); builder.registerTypeAdapterFactory(runtimeTypeAdapterFactoryII);
builder.registerTypeAdapterFactory(runtimeTypeAdapterFactoryIII);
builder.registerTypeAdapter(
Trigger.class,
(JsonSerializer<Trigger<?>>)
(src, typeOfSrc, context) -> context.serialize((Object) src));
builder.registerTypeAdapter(
Condition.class,
(JsonSerializer<Condition<?>>)
(src, typeOfSrc, context) -> context.serialize((Object) src));
return builder; return builder;
} }

View file

@ -18,9 +18,15 @@ import org.springframework.web.filter.OncePerRequestFilter;
@Component @Component
public class JWTRequestFilter extends OncePerRequestFilter { public class JWTRequestFilter extends OncePerRequestFilter {
@Autowired private JWTUserDetailsService jwtUserDetailsService; private final JWTUserDetailsService jwtUserDetailsService;
private final JWTTokenUtils jwtTokenUtils;
@Autowired private JWTTokenUtils jwtTokenUtils; @Autowired
public JWTRequestFilter(
JWTUserDetailsService jwtUserDetailsService, JWTTokenUtils jwtTokenUtils) {
this.jwtUserDetailsService = jwtUserDetailsService;
this.jwtTokenUtils = jwtTokenUtils;
}
@Override @Override
protected void doFilterInternal( protected void doFilterInternal(
@ -36,9 +42,9 @@ public class JWTRequestFilter extends OncePerRequestFilter {
try { try {
username = jwtTokenUtils.getUsernameFromToken(jwtToken); username = jwtTokenUtils.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token"); logger.info("Unable to get JWT Token");
} catch (ExpiredJwtException e) { } catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired"); logger.info("JWT Token has expired");
} }
} else { } else {
logger.warn("JWT Token does not begin with Bearer String"); logger.warn("JWT Token does not begin with Bearer String");

View file

@ -14,7 +14,7 @@ import org.springframework.stereotype.Component;
@Component @Component
public class JWTTokenUtils { public class JWTTokenUtils {
/** The duration in seconds of the validity of a single token */ /** The duration in seconds of the validity of a single token */
private static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; private static final long JWT_TOKEN_VALIDITY = (long) 5 * 60 * 60;
/** The secret key used to encrypt all JWTs */ /** The secret key used to encrypt all JWTs */
@Value("${jwt.secret}") @Value("${jwt.secret}")
@ -68,7 +68,7 @@ public class JWTTokenUtils {
* @param userDetails user details to validate against * @param userDetails user details to validate against
* @return true if valid, false if not * @return true if valid, false if not
*/ */
public Boolean validateToken(String token, UserDetails userDetails) { public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token); final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
} }

View file

@ -1,28 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
/* import com.google.gson.*;
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.Streams; import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
@ -77,8 +55,8 @@ import java.util.Map;
* } * }
* }</pre> * }</pre>
* *
* This class addresses this problem by adding type information to the serialized JSON and honoring * <p>This class addresses this problem by adding type information to the serialized JSON and
* that type information when the JSON is deserialized: * honoring that type information when the JSON is deserialized:
* *
* <pre>{@code * <pre>{@code
* { * {
@ -98,12 +76,12 @@ import java.util.Map;
* } * }
* }</pre> * }</pre>
* *
* Both the type field name ({@code "type"}) and the type labels ({@code "Rectangle"}) are * <p>Both the type field name ({@code "type"}) and the type labels ({@code "Rectangle"}) are
* configurable. * configurable.
* *
* <h3>Registering Types</h3> * <h3>Registering Types</h3>
* *
* Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field name to the * <p>Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field name to the
* {@link #of} factory method. If you don't supply an explicit type field name, {@code "type"} will * {@link #of} factory method. If you don't supply an explicit type field name, {@code "type"} will
* be used. * be used.
* *
@ -112,7 +90,7 @@ import java.util.Map;
* = RuntimeTypeAdapterFactory.of(Shape.class, "type"); * = RuntimeTypeAdapterFactory.of(Shape.class, "type");
* }</pre> * }</pre>
* *
* Next register all of your subtypes. Every subtype must be explicitly registered. This protects * <p>Next register all of your subtypes. Every subtype must be explicitly registered. This protects
* your application from injection attacks. If you don't supply an explicit type label, the type's * your application from injection attacks. If you don't supply an explicit type label, the type's
* simple name will be used. * simple name will be used.
* *
@ -122,7 +100,7 @@ import java.util.Map;
* shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond"); * shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
* }</pre> * }</pre>
* *
* Finally, register the type adapter factory in your application's GSON builder: * <p>Finally, register the type adapter factory in your application's GSON builder:
* *
* <pre>{@code * <pre>{@code
* Gson gson = new GsonBuilder() * Gson gson = new GsonBuilder()
@ -130,7 +108,7 @@ import java.util.Map;
* .create(); * .create();
* }</pre> * }</pre>
* *
* Like {@code GsonBuilder}, this API supports chaining: * <p>Like {@code GsonBuilder}, this API supports chaining:
* *
* <pre>{@code * <pre>{@code
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class) * RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
@ -141,7 +119,7 @@ import java.util.Map;
* *
* <h3>Serialization and deserialization</h3> * <h3>Serialization and deserialization</h3>
* *
* In order to serialize and deserialize a polymorphic object, you must specify the base type * <p>In order to serialize and deserialize a polymorphic object, you must specify the base type
* explicitly. * explicitly.
* *
* <pre>{@code * <pre>{@code
@ -149,7 +127,7 @@ import java.util.Map;
* String json = gson.toJson(diamond, Shape.class); * String json = gson.toJson(diamond, Shape.class);
* }</pre> * }</pre>
* *
* And then: * <p>And then:
* *
* <pre>{@code * <pre>{@code
* Shape shape = gson.fromJson(json, Shape.class); * Shape shape = gson.fromJson(json, Shape.class);
@ -158,8 +136,8 @@ import java.util.Map;
public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType; private final Class<?> baseType;
private final String typeFieldName; private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
private final boolean maintainType; private final boolean maintainType;
private RuntimeTypeAdapterFactory( private RuntimeTypeAdapterFactory(
@ -179,7 +157,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of( public static <T> RuntimeTypeAdapterFactory<T> of(
Class<T> baseType, String typeFieldName, boolean maintainType) { Class<T> baseType, String typeFieldName, boolean maintainType) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, maintainType); return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType);
} }
/** /**
@ -187,7 +165,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* the type field name. Type field names are case sensitive. * the type field name. Type field names are case sensitive.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, false); return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false);
} }
/** /**
@ -195,7 +173,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* field name. * field name.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
return new RuntimeTypeAdapterFactory<T>(baseType, "type", false); return new RuntimeTypeAdapterFactory<>(baseType, "type", false);
} }
/** /**
@ -217,14 +195,46 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
} }
/** /**
* Registers {@code type} identified by its {@link Class#getSimpleName simple name}. Labels are * Registers {@code type} identified by {@code label}. Labels are case sensitive.
* case sensitive.
* *
* @throws IllegalArgumentException if either {@code type} or its simple name have already been * @throws IllegalArgumentException if either {@code type} or {@code label} have already been
* registered on this type adapter. * registered on this type adapter.
*/ */
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) { public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
return registerSubtype(type, type.getSimpleName()); registerSubtype(type, type.getSimpleName());
return this;
}
private void initMaps(
Gson gson,
Map<String, TypeAdapter<?>> labelToDelegate,
Map<Class<?>, TypeAdapter<?>> subtypeToDelegate) {
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate =
gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate);
subtypeToDelegate.put(entry.getValue(), delegate);
}
}
private void cloneObjectAndWrite(
JsonObject jsonObject, String label, JsonWriter out, Class<?> srcType)
throws IOException {
JsonObject clone = new JsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException(
"cannot serialize "
+ srcType.getName()
+ " because it already defines a field named "
+ typeFieldName);
}
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
} }
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
@ -233,19 +243,16 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
} }
final Map<String, TypeAdapter<?>> labelToDelegate = final Map<String, TypeAdapter<?>> labelToDelegate =
new LinkedHashMap<String, TypeAdapter<?>>(); new LinkedHashMap<>(labelToSubtype.size());
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate =
new LinkedHashMap<Class<?>, TypeAdapter<?>>(); new LinkedHashMap<>(labelToSubtype.size());
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = initMaps(gson, labelToDelegate, subtypeToDelegate);
gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); final RuntimeTypeAdapterFactory<T> that = this;
labelToDelegate.put(entry.getKey(), delegate);
subtypeToDelegate.put(entry.getValue(), delegate);
}
return new TypeAdapter<R>() { return new TypeAdapter<R>() {
@Override @Override
public R read(JsonReader in) throws IOException { public R read(JsonReader in) {
JsonElement jsonElement = Streams.parse(in); JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement; JsonElement labelJsonElement;
if (maintainType) { if (maintainType) {
@ -294,21 +301,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
return; return;
} }
JsonObject clone = new JsonObject(); that.cloneObjectAndWrite(jsonObject, label, out, srcType);
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException(
"cannot serialize "
+ srcType.getName()
+ " because it already defines a field named "
+ typeFieldName);
}
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
} }
}.nullSafe(); }.nullSafe();
} }

View file

@ -5,17 +5,16 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.JWTRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.JWTResponse; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.JWTResponse;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.UnauthorizedException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.UnauthorizedException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.UserNotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.UserNotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.UserRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.JWTUserDetailsService;
import java.security.Principal; import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.JWTUserDetailsService;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -30,8 +29,6 @@ public class AuthenticationController {
private final JWTUserDetailsService userDetailsService; private final JWTUserDetailsService userDetailsService;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
public AuthenticationController( public AuthenticationController(
AuthenticationManager authenticationManager, AuthenticationManager authenticationManager,
UserRepository userRepository, UserRepository userRepository,
@ -82,9 +79,9 @@ public class AuthenticationController {
authenticationManager.authenticate( authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)); new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) { } catch (DisabledException e) {
throw new UnauthorizedException(true); throw new UnauthorizedException(true, e);
} catch (BadCredentialsException e) { } catch (BadCredentialsException e) {
throw new UnauthorizedException(false); throw new UnauthorizedException(false, e);
} }
} }
} }

View file

@ -2,6 +2,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationFastUpdateRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationFastUpdateRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.ConditionDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.ScenePriorityDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.TriggerDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import java.security.Principal; import java.security.Principal;
@ -10,15 +13,7 @@ import java.util.stream.Collectors;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -28,13 +23,13 @@ public class AutomationController {
@Autowired private AutomationRepository automationRepository; @Autowired private AutomationRepository automationRepository;
@Autowired private ScenePriorityRepository sceneRepository; @Autowired private ScenePriorityRepository sceneRepository;
@Autowired private TriggerRepository<Trigger<?>> triggerRepository; @Autowired private TriggerRepository<Trigger<?>> triggerRepository;
@Autowired private ConditionRepository<Condition<?>> conditionRepository;
@Autowired private UserRepository userService; @Autowired private UserRepository userService;
@GetMapping @GetMapping
public List<Automation> getAll( public List<Automation> getAll(
@RequestParam(value = "hostId", required = false) Long hostId, @RequestParam(value = "hostId", required = false) Long hostId,
final Principal principal) final Principal principal) {
throws NotFoundException {
final Long userId = userService.findByUsername(principal.getName()).getId(); final Long userId = userService.findByUsername(principal.getName()).getId();
return automationRepository.findAllByUserId(userId); return automationRepository.findAllByUserId(userId);
} }
@ -87,26 +82,45 @@ public class AutomationController {
triggerRepository.deleteAllByAutomationId(a.getId()); triggerRepository.deleteAllByAutomationId(a.getId());
sceneRepository.deleteAllByAutomationId(a.getId()); sceneRepository.deleteAllByAutomationId(a.getId());
conditionRepository.deleteAllByAutomationId(a.getId());
Iterable<Trigger<?>> tt = Iterable<Trigger<?>> tt =
triggerRepository.saveAll( triggerRepository.saveAll(
req.getTriggers() req.getTriggers()
.stream() .stream()
.map(AutomationFastUpdateRequest.TriggerDTO::toModel) .map(TriggerDTO::toModel)
.map(t -> t.setAutomationId(a.getId())) .map(t -> t.setAutomationId(a.getId()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
Iterable<ScenePriority> ss = Iterable<ScenePriority> ss =
sceneRepository.saveAll( sceneRepository.saveAll(
req.getScenes() req.getScenes()
.stream() .stream()
.map(AutomationFastUpdateRequest.ScenePriorityDTO::toModel) .map(ScenePriorityDTO::toModel)
.collect(Collectors.toList()));
Iterable<Condition<?>> cc =
conditionRepository.saveAll(
req.getConditions()
.stream()
.map(ConditionDTO::toModel)
.map(t -> t.setAutomationId(a.getId())) .map(t -> t.setAutomationId(a.getId()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
for (final ScenePriority s : ss) {
s.setAutomationId(a.getId());
// this is here just to pass the quality gate,
// please do not replicate unless the quality gate sees
// it as a bug
s.setAutomation(a);
}
a.getScenes().clear(); a.getScenes().clear();
a.getTriggers().clear(); a.getTriggers().clear();
a.getConditions().clear();
ss.forEach(t -> a.getScenes().add(t)); ss.forEach(t -> a.getScenes().add(t));
tt.forEach(t -> a.getTriggers().add(t)); tt.forEach(t -> a.getTriggers().add(t));
cc.forEach(t -> a.getConditions().add(t));
return a; return a;
} }

View file

@ -0,0 +1,54 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.BooleanConditionOrTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanCondition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanConditionRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/booleanCondition")
public class BooleanConditionController {
@Autowired BooleanConditionRepository booleanConditionRepository;
@GetMapping("/{automationId}")
public List<BooleanCondition> getAll(@PathVariable long automationId) {
return booleanConditionRepository.findAllByAutomationId(automationId);
}
private BooleanCondition save(BooleanCondition newRL, BooleanConditionOrTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOn(s.isOn());
return booleanConditionRepository.save(newRL);
}
@PostMapping
public BooleanCondition create(
@Valid @RequestBody BooleanConditionOrTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new BooleanCondition(), booleanTriggerSaveRequest);
}
@PutMapping
public BooleanCondition update(
@Valid @RequestBody BooleanConditionOrTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException {
return save(
booleanConditionRepository
.findById(booleanTriggerSaveRequest.getId())
.orElseThrow(NotFoundException::new),
booleanTriggerSaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
booleanConditionRepository.deleteById(id);
}
}

View file

@ -1,6 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.BooleanTriggerSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.BooleanConditionOrTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTriggerRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTriggerRepository;
@ -8,14 +8,7 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -25,11 +18,11 @@ public class BooleanTriggerController {
@Autowired BooleanTriggerRepository booleanTriggerRepository; @Autowired BooleanTriggerRepository booleanTriggerRepository;
@GetMapping("/{automationId}") @GetMapping("/{automationId}")
public List<BooleanTrigger<?>> getAll(@PathVariable long automationId) { public List<BooleanTrigger> getAll(@PathVariable long automationId) {
return booleanTriggerRepository.findAllByAutomationId(automationId); return booleanTriggerRepository.findAllByAutomationId(automationId);
} }
private BooleanTrigger<?> save(BooleanTrigger<?> newRL, BooleanTriggerSaveRequest s) { private BooleanTrigger save(BooleanTrigger newRL, BooleanConditionOrTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId()); newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId()); newRL.setAutomationId(s.getAutomationId());
newRL.setOn(s.isOn()); newRL.setOn(s.isOn());
@ -38,14 +31,14 @@ public class BooleanTriggerController {
} }
@PostMapping @PostMapping
public BooleanTrigger<?> create( public BooleanTrigger create(
@Valid @RequestBody BooleanTriggerSaveRequest booleanTriggerSaveRequest) { @Valid @RequestBody BooleanConditionOrTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new BooleanTrigger<>(), booleanTriggerSaveRequest); return save(new BooleanTrigger(), booleanTriggerSaveRequest);
} }
@PutMapping @PutMapping
public BooleanTrigger<?> update( public BooleanTrigger update(
@Valid @RequestBody BooleanTriggerSaveRequest booleanTriggerSaveRequest) @Valid @RequestBody BooleanConditionOrTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException { throws NotFoundException {
return save( return save(
booleanTriggerRepository booleanTriggerRepository

View file

@ -1,9 +1,12 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ButtonDimmerDimRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ButtonDimmerDimRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ButtonDimmer;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ButtonDimmerRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Dimmable;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.Set; import java.util.Set;
@ -18,15 +21,15 @@ import org.springframework.web.bind.annotation.*;
public class ButtonDimmerController public class ButtonDimmerController
extends InputDeviceConnectionController<ButtonDimmer, Dimmable> { extends InputDeviceConnectionController<ButtonDimmer, Dimmable> {
private DeviceService deviceService; private final DeviceService deviceService;
private ButtonDimmerRepository buttonDimmerRepository; private final ButtonDimmerRepository buttonDimmerRepository;
@Autowired @Autowired
protected ButtonDimmerController( protected ButtonDimmerController(
ButtonDimmerRepository inputRepository, ButtonDimmerRepository inputRepository,
DimmableRepository<Dimmable> outputRepository, DimmableRepository<Dimmable> outputRepository,
DeviceService deviceService) { DeviceService deviceService) {
super(inputRepository, outputRepository, DimmableLight.BUTTON_DIMMER_DIMMABLE_CONNECTOR); super(inputRepository, outputRepository, deviceService);
this.deviceService = deviceService; this.deviceService = deviceService;
this.buttonDimmerRepository = inputRepository; this.buttonDimmerRepository = inputRepository;
} }
@ -38,7 +41,7 @@ public class ButtonDimmerController
@PostMapping @PostMapping
public ButtonDimmer create( public ButtonDimmer create(
@Valid @RequestBody final GenericDeviceSaveReguest bd, final Principal principal) @Valid @RequestBody final GenericDeviceSaveRequest bd, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.throwIfRoomNotOwned(bd.getRoomId(), principal.getName()); deviceService.throwIfRoomNotOwned(bd.getRoomId(), principal.getName());
@ -58,23 +61,21 @@ public class ButtonDimmerController
.findByIdAndUsername(bd.getId(), principal.getName()) .findByIdAndUsername(bd.getId(), principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
switch (bd.getDimType()) { if (bd.getDimType() == ButtonDimmerDimRequest.DimType.UP) {
case UP:
buttonDimmer.increaseIntensity(); buttonDimmer.increaseIntensity();
break; } else {
case DOWN: buttonDimmer.decreaseIntensity();
buttonDimmer.decreaseIntensity();
break;
} }
deviceService.saveAllAsOwner(buttonDimmer.getOutputs(), principal.getName(), false); deviceService.saveAllAsOwner(buttonDimmer.getOutputs(), principal.getName());
return buttonDimmer.getOutputs(); return buttonDimmer.getDimmables();
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
} }

View file

@ -18,7 +18,7 @@ public class CurtainsController {
@Autowired private DeviceService deviceService; @Autowired private DeviceService deviceService;
@Autowired private CurtainsRepository curtainsService; @Autowired private CurtainsRepository curtainsService;
@Autowired private SceneRepository sceneRepository; @Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository; @Autowired private StateRepository<State> stateRepository;
private Curtains save(Curtains newRL, DimmableSaveRequest s, final Principal principal) { private Curtains save(Curtains newRL, DimmableSaveRequest s, final Principal principal) {
newRL.setName(s.getName()); newRL.setName(s.getName());
@ -49,11 +49,11 @@ public class CurtainsController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Dimmable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -63,9 +63,9 @@ public class CurtainsController {
curtainsService curtainsService
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Dimmable> s = c.cloneState(); State s = c.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -5,6 +5,7 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.error.BadDataException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Device; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Device;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Room;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RoomRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RoomRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
@ -40,11 +41,12 @@ public class DeviceController {
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
// check if roomId is valid // check if roomId is valid
roomRepository final Room r =
.findByIdAndUsername(deviceSaveRequest.getRoomId(), principal.getName()) roomRepository
.orElseThrow(() -> new BadDataException("roomId is not a valid room id")); .findByIdAndUsername(deviceSaveRequest.getRoomId(), principal.getName())
.orElseThrow(() -> new BadDataException("roomId is not a valid room id"));
d.setRoomId(deviceSaveRequest.getRoomId()); d.setRoomId(r.getId());
d.setName(deviceSaveRequest.getName()); d.setName(deviceSaveRequest.getName());
deviceService.saveAsOwner(d, principal.getName()); deviceService.saveAsOwner(d, principal.getName());

View file

@ -16,17 +16,17 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/dimmableLight") @RequestMapping("/dimmableLight")
public class DimmableLightController extends GuestEnabledController<DimmableLight> { public class DimmableLightController extends GuestEnabledController<DimmableLight> {
private DimmableLightRepository dimmableLightRepository; private final DimmableLightRepository dimmableLightRepository;
private SceneRepository sceneRepository; private final SceneRepository sceneRepository;
private StateRepository<State<?>> stateRepository; private final StateRepository<State> stateRepository;
private DeviceService deviceService; private final DeviceService deviceService;
@Autowired @Autowired
public DimmableLightController( public DimmableLightController(
UserRepository userRepository, UserRepository userRepository,
DimmableLightRepository dimmableLightRepository, DimmableLightRepository dimmableLightRepository,
SceneRepository sceneRepository, SceneRepository sceneRepository,
StateRepository<State<?>> stateRepository, StateRepository<State> stateRepository,
DeviceService deviceService) { DeviceService deviceService) {
super(userRepository, dimmableLightRepository); super(userRepository, dimmableLightRepository);
this.dimmableLightRepository = dimmableLightRepository; this.dimmableLightRepository = dimmableLightRepository;
@ -49,10 +49,10 @@ public class DimmableLightController extends GuestEnabledController<DimmableLigh
} }
} }
/* /**
Assume that only the host can create a device * Assume that only the host can create a device Here save always as host, but remember to
Here save always as host, but remember to propagate change to guests (DeviceService.saveAsOwner()) * propagate change to guests (DeviceService.saveAsOwner())
*/ */
@PostMapping @PostMapping
public DimmableLight create( public DimmableLight create(
@Valid @RequestBody DimmableSaveRequest dl, final Principal principal) @Valid @RequestBody DimmableSaveRequest dl, final Principal principal)
@ -61,12 +61,12 @@ public class DimmableLightController extends GuestEnabledController<DimmableLigh
return save(new DimmableLight(), dl, principal.getName(), null); return save(new DimmableLight(), dl, principal.getName(), null);
} }
/* /** Logic for saving either as owner or guest is handled in method save of this controller */
Logic for saving either as owner or guest is handled in method save of this controller
*/
@PutMapping @PutMapping
public DimmableLight update( public DimmableLight update(
@Valid @RequestBody DimmableSaveRequest sp, final Principal principal, Long hostId) @Valid @RequestBody DimmableSaveRequest sp,
final Principal principal,
@RequestParam(value = "hostId", required = false) Long hostId)
throws NotFoundException { throws NotFoundException {
return save( return save(
@ -79,13 +79,15 @@ public class DimmableLightController extends GuestEnabledController<DimmableLigh
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
// the full url should be: "/dimmableLight/{id}/state?sceneId={sceneId} /**
// however it is not necessary to specify the query in the mapping * the full url should be: "/dimmableLight/{id}/state?sceneId={sceneId} however it is not
* necessary to specify the query in the mapping
*/
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Dimmable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -95,9 +97,9 @@ public class DimmableLightController extends GuestEnabledController<DimmableLigh
dimmableLightRepository dimmableLightRepository
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Dimmable> s = d.cloneState(); State s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -17,9 +17,9 @@ public class DimmableStateController {
@Autowired private DimmableStateRepository dimmableStateRepository; @Autowired private DimmableStateRepository dimmableStateRepository;
@PutMapping @PutMapping
public DimmableState<?> update(@Valid @RequestBody DimmableStateSaveRequest ss) public DimmableState update(@Valid @RequestBody DimmableStateSaveRequest ss)
throws NotFoundException { throws NotFoundException {
final DimmableState<?> initial = final DimmableState initial =
dimmableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new); dimmableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new);
initial.setIntensity(ss.getIntensity()); initial.setIntensity(ss.getIntensity());
dimmableStateRepository.save(initial); dimmableStateRepository.save(initial);

View file

@ -3,11 +3,15 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList; import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GuestPermissionsRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GuestPermissionsRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GuestsUpdateRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.UserResponse;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.EagerUserRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.UserRepository;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -18,23 +22,47 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/user") @RequestMapping("/user")
public class GuestController { public class GuestController {
@Autowired private UserRepository userRepository; @Autowired private EagerUserRepository userRepository;
@GetMapping @GetMapping
public List<User> findAll() { public List<UserResponse> findAll() {
return toList(userRepository.findAll()); return StreamSupport.stream(userRepository.findAll().spliterator(), false)
.map(UserResponse::fromUser)
.collect(Collectors.toList());
} }
@PostMapping("/guest") @GetMapping("/hosts")
public User addUserAsGuest(@RequestParam("userId") long id, final Principal principal) public List<UserResponse> findHosts(final Principal principal) {
throws NotFoundException { final User u = userRepository.findByUsername(principal.getName());
User guest = userRepository.findById(id).orElseThrow(NotFoundException::new); return u.getHosts().stream().map(UserResponse::fromUser).collect(Collectors.toList());
}
@GetMapping("/guests")
public List<UserResponse> findGuests(final Principal principal) {
final User u = userRepository.findByUsername(principal.getName());
return u.getGuests().stream().map(UserResponse::fromUser).collect(Collectors.toList());
}
@PutMapping("/guests")
public List<User> setGuests(
@RequestBody @Valid GuestsUpdateRequest g, final Principal principal) {
Iterable<User> guests = userRepository.findAllById(g.getIds());
User host = userRepository.findByUsername(principal.getName()); User host = userRepository.findByUsername(principal.getName());
host.addGuest(guest); for (final User oldGuest : host.getGuests()) {
guest.addHost(host); oldGuest.getHosts().remove(host);
userRepository.save(guest); }
return userRepository.save(host);
final Set<User> oldGuests = Set.copyOf(host.getGuests());
for (final User guest : guests) {
host.addGuest(guest);
guest.addHost(host);
}
userRepository.saveAll(oldGuests);
userRepository.save(host);
return toList(userRepository.saveAll(guests));
} }
@PutMapping("/permissions") @PutMapping("/permissions")
@ -44,16 +72,4 @@ public class GuestController {
currentUser.setCameraEnabled(g.isCameraEnabled()); currentUser.setCameraEnabled(g.isCameraEnabled());
return userRepository.save(currentUser); return userRepository.save(currentUser);
} }
@DeleteMapping("/guest")
public void removeUserAsGuest(@RequestParam("userId") long id, final Principal principal)
throws NotFoundException {
User guest = userRepository.findById(id).orElseThrow(NotFoundException::new);
User host = userRepository.findByUsername(principal.getName());
host.removeGuest(guest);
guest.getHosts().remove(host);
userRepository.save(host);
userRepository.save(guest);
}
} }

View file

@ -3,13 +3,15 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.returnIfGuest; import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.returnIfGuest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Device;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.UserRepository;
import java.security.Principal; import java.security.Principal;
public abstract class GuestEnabledController<T extends Device> { public abstract class GuestEnabledController<T extends Device> {
private UserRepository userRepository; private final UserRepository userRepository;
private DeviceRepository<T> deviceRepository; private final DeviceRepository<T> deviceRepository;
public GuestEnabledController( public GuestEnabledController(
final UserRepository userRepository, final DeviceRepository<T> deviceRepository) { final UserRepository userRepository, final DeviceRepository<T> deviceRepository) {

View file

@ -3,13 +3,15 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList; import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Connectable;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.InputDevice;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.OutputDevice;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -23,9 +25,9 @@ import org.springframework.web.bind.annotation.RequestBody;
* @param <O> the output device attached to I * @param <O> the output device attached to I
*/ */
public abstract class InputDeviceConnectionController< public abstract class InputDeviceConnectionController<
I extends InputDevice, O extends OutputDevice> { I extends InputDevice & Connectable<O>, O extends OutputDevice> {
private class Connection { protected class Connection {
private final I input; private final I input;
private final List<O> outputs; private final List<O> outputs;
@ -33,30 +35,43 @@ public abstract class InputDeviceConnectionController<
this.input = input; this.input = input;
this.outputs = outputs; this.outputs = outputs;
} }
public I getInput() {
return input;
}
public List<O> getOutputs() {
return outputs;
}
} }
@Autowired private DeviceService deviceService; protected DeviceRepository<I> getInputRepository() {
return inputRepository;
}
private DeviceRepository<I> inputRepository; protected DeviceRepository<O> getOutputReposiory() {
return outputReposiory;
}
private DeviceRepository<O> outputReposiory; private final DeviceService deviceService;
private Connector<I, O> connector; private final DeviceRepository<I> inputRepository;
private final DeviceRepository<O> outputReposiory;
/** /**
* Contstructs the controller by requiring essential object for the controller implementation * Contstructs the controller by requiring essential object for the controller implementation
* *
* @param inputRepository the input device repository * @param inputRepository the input device repository
* @param outputRepository the output device repository * @param outputRepository the output device repository
* @param connector a appropriate Connector instance for the I and O tyoes.
*/ */
protected InputDeviceConnectionController( protected InputDeviceConnectionController(
DeviceRepository<I> inputRepository, DeviceRepository<I> inputRepository,
DeviceRepository<O> outputRepository, DeviceRepository<O> outputRepository,
Connector<I, O> connector) { DeviceService deviceService) {
this.inputRepository = inputRepository; this.inputRepository = inputRepository;
this.outputReposiory = outputRepository; this.outputReposiory = outputRepository;
this.connector = connector; this.deviceService = deviceService;
} }
private Connection checkConnectionIDs(Long inputId, List<Long> outputs, String username) private Connection checkConnectionIDs(Long inputId, List<Long> outputs, String username)
@ -65,7 +80,7 @@ public abstract class InputDeviceConnectionController<
inputRepository inputRepository
.findByIdAndUsername(inputId, username) .findByIdAndUsername(inputId, username)
.orElseThrow(() -> new NotFoundException("input device")); .orElseThrow(() -> new NotFoundException("input device"));
final List<O> outputDevices = new ArrayList<>(); final List<O> outputDevices = new ArrayList<>(outputs.size());
for (final Long outputId : outputs) { for (final Long outputId : outputs) {
outputDevices.add( outputDevices.add(
outputReposiory outputReposiory
@ -83,16 +98,16 @@ public abstract class InputDeviceConnectionController<
* @return the list of output devices attached to the input device of id inputId * @return the list of output devices attached to the input device of id inputId
* @throws NotFoundException if inputId or outputId are not valid * @throws NotFoundException if inputId or outputId are not valid
*/ */
protected Set<? extends OutputDevice> addOutput( protected Set<OutputDevice> addOutput(Long inputId, List<Long> outputs, String username)
Long inputId, List<Long> outputs, String username) throws NotFoundException { throws NotFoundException {
final Connection pair = checkConnectionIDs(inputId, outputs, username); final Connection pair = checkConnectionIDs(inputId, outputs, username);
for (final O o : pair.outputs) { for (final O o : pair.getOutputs()) {
connector.connect(pair.input, o, true); pair.getInput().connect(o, true);
} }
deviceService.saveAllAsOwner(pair.outputs, username, false); deviceService.saveAllAsOwner(pair.getOutputs(), username);
return pair.input.getOutputs(); return pair.getInput().getOutputs();
} }
/** /**
@ -103,16 +118,16 @@ public abstract class InputDeviceConnectionController<
* @return the list of output devices attached to the input device of id inputId * @return the list of output devices attached to the input device of id inputId
* @throws NotFoundException if inputId or outputId are not valid * @throws NotFoundException if inputId or outputId are not valid
*/ */
protected Set<? extends OutputDevice> removeOutput( protected Set<OutputDevice> removeOutput(Long inputId, List<Long> outputs, String username)
Long inputId, List<Long> outputs, String username) throws NotFoundException { throws NotFoundException {
final Connection pair = checkConnectionIDs(inputId, outputs, username); final Connection pair = checkConnectionIDs(inputId, outputs, username);
for (final O o : pair.outputs) { for (final O o : pair.getOutputs()) {
connector.connect(pair.input, o, false); pair.getInput().connect(o, false);
} }
deviceService.saveAllAsOwner(pair.outputs, username, false); deviceService.saveAllAsOwner(pair.getOutputs(), username);
return pair.input.getOutputs(); return pair.getInput().getOutputs();
} }
@PostMapping("/{id}/lights") @PostMapping("/{id}/lights")

View file

@ -1,9 +1,12 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.KnobDimmerDimRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.KnobDimmerDimRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Dimmable;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.KnobDimmer;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.KnobDimmerRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.Set; import java.util.Set;
@ -17,14 +20,17 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/knobDimmer") @RequestMapping("/knobDimmer")
public class KnobDimmerController extends InputDeviceConnectionController<KnobDimmer, Dimmable> { public class KnobDimmerController extends InputDeviceConnectionController<KnobDimmer, Dimmable> {
@Autowired private DeviceService deviceService; private final DeviceService deviceService;
@Autowired private KnobDimmerRepository knobDimmerRepository; private final KnobDimmerRepository knobDimmerRepository;
@Autowired @Autowired
protected KnobDimmerController( protected KnobDimmerController(
KnobDimmerRepository inputRepository, DimmableRepository<Dimmable> outputRepository) { KnobDimmerRepository inputRepository,
super(inputRepository, outputRepository, Dimmable.KNOB_DIMMER_DIMMABLE_CONNECTOR); DimmableRepository<Dimmable> outputRepository,
DeviceService deviceService) {
super(inputRepository, outputRepository, deviceService);
this.knobDimmerRepository = inputRepository; this.knobDimmerRepository = inputRepository;
this.deviceService = deviceService;
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@ -34,7 +40,7 @@ public class KnobDimmerController extends InputDeviceConnectionController<KnobDi
@PostMapping @PostMapping
public KnobDimmer create( public KnobDimmer create(
@Valid @RequestBody GenericDeviceSaveReguest kd, final Principal principal) @Valid @RequestBody GenericDeviceSaveRequest kd, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.throwIfRoomNotOwned(kd.getRoomId(), principal.getName()); deviceService.throwIfRoomNotOwned(kd.getRoomId(), principal.getName());
KnobDimmer newKD = new KnobDimmer(); KnobDimmer newKD = new KnobDimmer();
@ -54,14 +60,14 @@ public class KnobDimmerController extends InputDeviceConnectionController<KnobDi
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
dimmer.setLightIntensity(bd.getIntensity()); dimmer.setLightIntensity(bd.getIntensity());
deviceService.saveAllAsOwner(dimmer.getOutputs(), principal.getName(), false); deviceService.saveAllAsOwner(dimmer.getOutputs(), principal.getName());
return dimmer.getOutputs(); return dimmer.getDimmables();
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
} }

View file

@ -1,12 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensor; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensor;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensorRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensorRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.MotionSensorService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.MotionSensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.security.Principal; import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -21,11 +20,10 @@ public class MotionSensorController {
@Autowired private DeviceService deviceService; @Autowired private DeviceService deviceService;
@Autowired private MotionSensorService motionSensorService; @Autowired private MotionSensorService motionSensorService;
@Autowired private MotionSensorRepository motionSensorRepository; @Autowired private MotionSensorRepository motionSensorRepository;
@Autowired private SensorSocketEndpoint sensorSocketEndpoint;
@PostMapping @PostMapping
public MotionSensor create( public MotionSensor create(
@Valid @RequestBody GenericDeviceSaveReguest ms, final Principal principal) @Valid @RequestBody GenericDeviceSaveRequest ms, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.throwIfRoomNotOwned(ms.getRoomId(), principal.getName()); deviceService.throwIfRoomNotOwned(ms.getRoomId(), principal.getName());
MotionSensor newMS = new MotionSensor(); MotionSensor newMS = new MotionSensor();
@ -53,6 +51,6 @@ public class MotionSensorController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
} }

View file

@ -0,0 +1,55 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RangeConditionOrTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeCondition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeConditionRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/rangeCondition")
public class RangeConditionController {
@Autowired RangeConditionRepository rangeConditionRepository;
@GetMapping("/{automationId}")
public List<RangeCondition> getAll(@PathVariable long automationId) {
return rangeConditionRepository.findAllByAutomationId(automationId);
}
private RangeCondition save(RangeCondition newRL, RangeConditionOrTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOperator(s.getOperator());
newRL.setRange(s.getRange());
return rangeConditionRepository.save(newRL);
}
@PostMapping
public RangeCondition create(
@Valid @RequestBody RangeConditionOrTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new RangeCondition(), booleanTriggerSaveRequest);
}
@PutMapping
public RangeCondition update(
@Valid @RequestBody RangeConditionOrTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException {
return save(
rangeConditionRepository
.findById(booleanTriggerSaveRequest.getId())
.orElseThrow(NotFoundException::new),
booleanTriggerSaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
rangeConditionRepository.deleteById(id);
}
}

View file

@ -1,6 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RangeTriggerSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RangeConditionOrTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTriggerRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTriggerRepository;
@ -8,14 +8,7 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -25,11 +18,11 @@ public class RangeTriggerController {
@Autowired RangeTriggerRepository rangeTriggerRepository; @Autowired RangeTriggerRepository rangeTriggerRepository;
@GetMapping("/{automationId}") @GetMapping("/{automationId}")
public List<RangeTrigger<?>> getAll(@PathVariable long automationId) { public List<RangeTrigger> getAll(@PathVariable long automationId) {
return rangeTriggerRepository.findAllByAutomationId(automationId); return rangeTriggerRepository.findAllByAutomationId(automationId);
} }
private RangeTrigger<?> save(RangeTrigger<?> newRL, RangeTriggerSaveRequest s) { private RangeTrigger save(RangeTrigger newRL, RangeConditionOrTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId()); newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId()); newRL.setAutomationId(s.getAutomationId());
newRL.setOperator(s.getOperator()); newRL.setOperator(s.getOperator());
@ -39,14 +32,14 @@ public class RangeTriggerController {
} }
@PostMapping @PostMapping
public RangeTrigger<?> create( public RangeTrigger create(
@Valid @RequestBody RangeTriggerSaveRequest booleanTriggerSaveRequest) { @Valid @RequestBody RangeConditionOrTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new RangeTrigger<>(), booleanTriggerSaveRequest); return save(new RangeTrigger(), booleanTriggerSaveRequest);
} }
@PutMapping @PutMapping
public RangeTrigger<?> update( public RangeTrigger update(
@Valid @RequestBody RangeTriggerSaveRequest booleanTriggerSaveRequest) @Valid @RequestBody RangeConditionOrTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException { throws NotFoundException {
return save( return save(
rangeTriggerRepository rangeTriggerRepository

View file

@ -12,32 +12,24 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/regularLight") @RequestMapping("/regularLight")
public class RegularLightController extends GuestEnabledController<RegularLight> { public class RegularLightController extends GuestEnabledController<RegularLight> {
private RegularLightRepository regularLightRepository; private final RegularLightRepository regularLightRepository;
private SceneRepository sceneRepository; private final SceneRepository sceneRepository;
private StateRepository<State<?>> stateRepository; private final StateRepository<State> stateRepository;
private DeviceService deviceService; private final DeviceService deviceService;
@Autowired @Autowired
public RegularLightController( public RegularLightController(
UserRepository userRepository, UserRepository userRepository,
RegularLightRepository regularLightRepository, RegularLightRepository regularLightRepository,
SceneRepository sceneRepository, SceneRepository sceneRepository,
StateRepository<State<?>> stateRepository, StateRepository<State> stateRepository,
DeviceService deviceService) { DeviceService deviceService) {
super(userRepository, regularLightRepository); super(userRepository, regularLightRepository);
this.regularLightRepository = regularLightRepository; this.regularLightRepository = regularLightRepository;
@ -80,7 +72,9 @@ public class RegularLightController extends GuestEnabledController<RegularLight>
@PutMapping @PutMapping
public RegularLight update( public RegularLight update(
@Valid @RequestBody SwitchableSaveRequest rl, final Principal principal, Long hostId) @Valid @RequestBody SwitchableSaveRequest rl,
final Principal principal,
@RequestParam(value = "hostId", required = false) Long hostId)
throws NotFoundException { throws NotFoundException {
return save( return save(
fetchIfOwnerOrGuest(principal, rl.getId(), hostId), fetchIfOwnerOrGuest(principal, rl.getId(), hostId),
@ -92,13 +86,11 @@ public class RegularLightController extends GuestEnabledController<RegularLight>
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
// the full url should be: "/regularLight/{id}/state?sceneId={sceneId}
// however it is not necessary to specify the query in the mapping
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -107,9 +99,9 @@ public class RegularLightController extends GuestEnabledController<RegularLight>
regularLightRepository regularLightRepository
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState(); State s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -6,13 +6,12 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RoomSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils; import ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils;
import java.security.Principal; import java.security.Principal;
import java.util.*; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -20,19 +19,33 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/room") @RequestMapping("/room")
public class RoomController { public class RoomController {
@Autowired private RoomRepository roomRepository; private final RoomRepository roomRepository;
@Autowired private UserRepository userRepository; private final UserRepository userRepository;
@Autowired private DeviceService deviceService; private final DeviceService deviceService;
@Autowired private SwitchRepository switchRepository; private final SwitchRepository switchRepository;
@Autowired private ButtonDimmerRepository buttonDimmerRepository; private final ButtonDimmerRepository buttonDimmerRepository;
@Autowired private KnobDimmerRepository knobDimmerRepository; private final KnobDimmerRepository knobDimmerRepository;
@Autowired private ThermostatService thermostatService; @Autowired
public RoomController(
RoomRepository roomRepository,
UserRepository userRepository,
DeviceService deviceService,
SwitchRepository switchRepository,
ButtonDimmerRepository buttonDimmerRepository,
KnobDimmerRepository knobDimmerRepository) {
this.roomRepository = roomRepository;
this.userRepository = userRepository;
this.deviceService = deviceService;
this.switchRepository = switchRepository;
this.buttonDimmerRepository = buttonDimmerRepository;
this.knobDimmerRepository = knobDimmerRepository;
}
private <T> List<T> fetchOwnerOrGuest( private <T> List<T> fetchOwnerOrGuest(
final List<T> list, Long hostId, final Principal principal) throws NotFoundException { final List<T> list, Long hostId, final Principal principal) throws NotFoundException {
@ -75,7 +88,7 @@ public class RoomController {
final String username = principal.getName(); final String username = principal.getName();
final Long userId = userRepository.findByUsername(username).getId(); final Long userId = userRepository.findByUsername(username).getId();
final String img = r.getImage(); final String img = r.getImage();
final Room.Icon icon = r.getIcon(); final Icon icon = r.getIcon();
final Room newRoom = new Room(); final Room newRoom = new Room();
newRoom.setUserId(userId); newRoom.setUserId(userId);
@ -95,7 +108,7 @@ public class RoomController {
.findByIdAndUsername(id, principal.getName()) .findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
final String img = r.getImage(); final String img = r.getImage();
final Room.Icon icon = r.getIcon(); final Icon icon = r.getIcon();
if (r.getName() != null) { if (r.getName() != null) {
newRoom.setName(r.getName()); newRoom.setName(r.getName());
@ -124,6 +137,11 @@ public class RoomController {
roomRepository roomRepository
.findByIdAndUsername(id, principal.getName()) .findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
List<Device> devices = deviceService.findAll(r.getId(), null, principal.getName());
for (Device d : devices) {
deviceService.deleteByIdAsOwner(d.getId(), principal.getName());
}
roomRepository.delete(r); roomRepository.delete(r);
} }

View file

@ -6,20 +6,13 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SceneSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SceneService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SceneService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -27,21 +20,20 @@ import org.springframework.web.bind.annotation.RestController;
public class SceneController { public class SceneController {
@Autowired private SceneRepository sceneRepository; @Autowired private SceneRepository sceneRepository;
@Autowired private UserRepository userRepository;
@Autowired private SceneService sceneService; @Autowired private SceneService sceneService;
@Autowired private UserRepository userService; @Autowired private StateRepository<State> stateRepository;
@Autowired private StateRepository<State<?>> stateService;
@GetMapping @GetMapping
public List<Scene> findAll(Principal principal) { public List<Scene> findAll(
return toList(sceneRepository.findByUsername(principal.getName())); Principal principal, @RequestParam(value = "hostId", required = false) Long hostId)
}
@GetMapping("/{id}")
public @ResponseBody Scene findById(@PathVariable("id") long id, Principal principal)
throws NotFoundException { throws NotFoundException {
return sceneRepository if (hostId == null) {
.findByIdAndUsername(id, principal.getName()) return toList(sceneRepository.findByUsername(principal.getName()));
.orElseThrow(NotFoundException::new); } else {
Utils.returnIfGuest(userRepository, null, hostId, principal);
return sceneRepository.findByHostId(hostId);
}
} }
@PostMapping @PostMapping
@ -49,26 +41,58 @@ public class SceneController {
@Valid @RequestBody SceneSaveRequest s, final Principal principal) { @Valid @RequestBody SceneSaveRequest s, final Principal principal) {
final String username = principal.getName(); final String username = principal.getName();
final Long userId = userService.findByUsername(username).getId(); final Long userId = userRepository.findByUsername(username).getId();
final Scene newScene = new Scene(); final Scene newScene = new Scene();
newScene.setUserId(userId); newScene.setUserId(userId);
newScene.setName(s.getName()); newScene.setName(s.getName());
newScene.setGuestAccessEnabled(s.isGuestAccessEnabled()); newScene.setGuestAccessEnabled(s.isGuestAccessEnabled());
newScene.setIcon(s.getIcon());
return sceneRepository.save(newScene); return sceneRepository.save(newScene);
} }
@PostMapping("/{id}/apply") @PostMapping("/{id}/apply")
public @ResponseBody List<Device> apply(@PathVariable("id") long id, final Principal principal) public @ResponseBody List<Device> apply(
@PathVariable("id") long id,
final Principal principal,
@RequestParam(value = "hostId", required = false) Long hostId)
throws NotFoundException { throws NotFoundException {
final Scene newScene = if (hostId == null) {
return sceneService.apply(
sceneRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new),
principal.getName(),
false);
} else {
Utils.returnIfGuest(userRepository, null, hostId, principal);
return sceneService.applyAsGuest(
sceneRepository
.findByIdAndUserIdAndGuestAccessEnabled(id, hostId, true)
.orElseThrow(NotFoundException::new),
principal.getName(),
hostId);
}
}
@PostMapping("/{id}/copyFrom/{copyId}")
public @ResponseBody List<State> copy(
@PathVariable("id") long id,
@PathVariable("copyId") long copyId,
final Principal principal)
throws NotFoundException {
final Scene scene =
sceneRepository sceneRepository
.findByIdAndUsername(id, principal.getName()) .findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
final Scene copyFrom =
sceneRepository
.findByIdAndUsername(copyId, principal.getName())
.orElseThrow(NotFoundException::new);
return sceneService.apply(newScene); return sceneService.copyStates(scene, copyFrom);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@ -84,6 +108,8 @@ public class SceneController {
newScene.setName(s.getName()); newScene.setName(s.getName());
} }
newScene.setIcon(s.getIcon());
newScene.setGuestAccessEnabled(s.isGuestAccessEnabled()); newScene.setGuestAccessEnabled(s.isGuestAccessEnabled());
return sceneRepository.save(newScene); return sceneRepository.save(newScene);
@ -91,7 +117,7 @@ public class SceneController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) { public void deleteById(@PathVariable("id") long id) {
stateService.deleteAllBySceneId(id); stateRepository.deleteAllBySceneId(id);
sceneRepository.deleteById(id); sceneRepository.deleteById(id);
} }
@ -100,8 +126,8 @@ public class SceneController {
* id). * id).
*/ */
@GetMapping(path = "/{sceneId}/states") @GetMapping(path = "/{sceneId}/states")
public List<State<?>> getDevices(@PathVariable("sceneId") long sceneId) { public List<State> getStates(@PathVariable("sceneId") long sceneId) {
Iterable<State<?>> states = stateService.findBySceneId(sceneId); Iterable<State> states = stateRepository.findBySceneId(sceneId);
return toList(states); return toList(states);
} }
} }

View file

@ -8,14 +8,7 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -24,10 +17,8 @@ public class ScenePriorityController {
@Autowired ScenePriorityRepository scenePriorityRepository; @Autowired ScenePriorityRepository scenePriorityRepository;
@GetMapping("/{automationId}") @GetMapping("/{automationId}")
public List<ScenePriority> getByAutomationId(@PathVariable long automationId) public List<ScenePriority> getByAutomationId(@PathVariable long automationId) {
throws NotFoundException {
return scenePriorityRepository.findAllByAutomationId(automationId); return scenePriorityRepository.findAllByAutomationId(automationId);
} }

View file

@ -1,5 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.CameraConfigurationService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
@ -9,31 +10,38 @@ import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/securityCamera") @RequestMapping("/securityCamera")
public class SecurityCameraController { public class SecurityCameraController {
private final DeviceService deviceService;
private final SecurityCameraRepository securityCameraService;
private final SceneRepository sceneRepository;
private final StateRepository<State> stateRepository;
private final CameraConfigurationService cameraConfigurationService;
@Autowired private DeviceService deviceService; @Autowired
@Autowired private SecurityCameraRepository securityCameraService; public SecurityCameraController(
@Autowired private SceneRepository sceneRepository; DeviceService deviceService,
@Autowired private StateRepository<State<?>> stateRepository; SecurityCameraRepository securityCameraService,
@Autowired private RoomRepository roomRepository; SceneRepository sceneRepository,
StateRepository<State> stateRepository,
CameraConfigurationService cameraConfigurationService) {
this.deviceService = deviceService;
this.securityCameraService = securityCameraService;
this.sceneRepository = sceneRepository;
this.stateRepository = stateRepository;
this.cameraConfigurationService = cameraConfigurationService;
}
private SecurityCamera save( private SecurityCamera save(
SecurityCamera newSC, SwitchableSaveRequest sc, final Principal principal) { SecurityCamera newSC, SwitchableSaveRequest sc, final Principal principal) {
newSC.setName(sc.getName()); newSC.setName(sc.getName());
newSC.setRoomId(sc.getRoomId()); newSC.setRoomId(sc.getRoomId());
newSC.setOn(sc.isOn()); newSC.setOn(sc.isOn());
newSC.setPath(cameraConfigurationService.getVideoUrl());
return deviceService.saveAsOwner(newSC, principal.getName()); return deviceService.saveAsOwner(newSC, principal.getName());
} }
@ -61,11 +69,11 @@ public class SecurityCameraController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal) public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -75,9 +83,9 @@ public class SecurityCameraController {
securityCameraService securityCameraService
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState(); State s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -2,16 +2,15 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SensorSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SensorSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Sensor;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SensorRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SensorService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.security.Principal; import java.security.Principal;
import java.util.*;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -19,13 +18,21 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/sensor") @RequestMapping("/sensor")
public class SensorController { public class SensorController {
@Autowired private DeviceService deviceService; private final DeviceService deviceService;
@Autowired private SensorRepository sensorRepository; private final SensorRepository sensorRepository;
@Autowired private SensorSocketEndpoint sensorSocketEndpoint; private final SensorService sensorService;
@Autowired private SensorService sensorService; @Autowired
public SensorController(
DeviceService deviceService,
SensorRepository sensorRepository,
SensorService sensorService) {
this.deviceService = deviceService;
this.sensorRepository = sensorRepository;
this.sensorService = sensorService;
}
@PostMapping @PostMapping
public Sensor create(@Valid @RequestBody SensorSaveRequest s, final Principal principal) public Sensor create(@Valid @RequestBody SensorSaveRequest s, final Principal principal)
@ -54,9 +61,24 @@ public class SensorController {
value); value);
} }
@PutMapping("/{id}/simulation")
public Sensor updateSimulation(
@PathVariable("id") Long sensorId,
@RequestBody BigDecimal error,
@RequestBody BigDecimal typical,
final Principal principal)
throws NotFoundException {
return sensorService.updateSimulationFromSensor(
sensorRepository
.findByIdAndUsername(sensorId, principal.getName())
.orElseThrow(NotFoundException::new),
error,
typical);
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id, final Principal principal) public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
} }

View file

@ -8,7 +8,7 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -19,11 +19,10 @@ public class SmartPlugController {
@Autowired private DeviceService deviceService; @Autowired private DeviceService deviceService;
@Autowired private SmartPlugRepository smartPlugRepository; @Autowired private SmartPlugRepository smartPlugRepository;
@Autowired private SceneRepository sceneRepository; @Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository; @Autowired private StateRepository<State> stateRepository;
private SmartPlug save(SmartPlug newSP, SwitchableSaveRequest sp, final Principal principal) { private SmartPlug save(SmartPlug newSP, SwitchableSaveRequest sp, final Principal principal) {
newSP.setOn(sp.isOn()); newSP.setOn(sp.isOn());
newSP.setId(sp.getId());
newSP.setName(sp.getName()); newSP.setName(sp.getName());
newSP.setRoomId(sp.getRoomId()); newSP.setRoomId(sp.getRoomId());
@ -63,11 +62,11 @@ public class SmartPlugController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id, final Principal principal) public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -77,9 +76,9 @@ public class SmartPlugController {
smartPlugRepository smartPlugRepository
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState(); State s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -1,15 +1,18 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchOperationRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchOperationRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Switch;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Switchable;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -17,9 +20,8 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/switch") @RequestMapping("/switch")
public class SwitchController extends InputDeviceConnectionController<Switch, Switchable> { public class SwitchController extends InputDeviceConnectionController<Switch, Switchable> {
private SwitchRepository switchRepository; private final SwitchRepository switchRepository;
private SwitchableRepository<Switchable> switchableRepository; private final DeviceService deviceService;
private DeviceService deviceService;
/** /**
* Contstructs the controller by requiring essential object for the controller implementation * Contstructs the controller by requiring essential object for the controller implementation
@ -32,7 +34,7 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
SwitchRepository inputRepository, SwitchRepository inputRepository,
SwitchableRepository<Switchable> outputRepository, SwitchableRepository<Switchable> outputRepository,
DeviceService deviceService) { DeviceService deviceService) {
super(inputRepository, outputRepository, Switchable.SWITCH_SWITCHABLE_CONNECTOR); super(inputRepository, outputRepository, deviceService);
this.deviceService = deviceService; this.deviceService = deviceService;
this.switchRepository = inputRepository; this.switchRepository = inputRepository;
} }
@ -43,7 +45,7 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
} }
@PostMapping @PostMapping
public Switch create(@Valid @RequestBody GenericDeviceSaveReguest s, final Principal principal) public Switch create(@Valid @RequestBody GenericDeviceSaveRequest s, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.throwIfRoomNotOwned(s.getRoomId(), principal.getName()); deviceService.throwIfRoomNotOwned(s.getRoomId(), principal.getName());
Switch newSwitch = new Switch(); Switch newSwitch = new Switch();
@ -75,12 +77,12 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
} }
deviceService.saveAsOwner(s, principal.getName()); deviceService.saveAsOwner(s, principal.getName());
return deviceService.saveAllAsOwner(s.getOutputs(), principal.getName(), false); return deviceService.saveAllAsOwner(s.getSwitchables(), principal.getName());
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id, final Principal principal) public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
} }

View file

@ -7,12 +7,7 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableStateRepository;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ -22,9 +17,9 @@ public class SwitchableStateController {
@Autowired private SwitchableStateRepository switchableStateRepository; @Autowired private SwitchableStateRepository switchableStateRepository;
@PutMapping @PutMapping
public SwitchableState<?> update(@Valid @RequestBody SwitchableStateSaveRequest ss) public SwitchableState update(@Valid @RequestBody SwitchableStateSaveRequest ss)
throws NotFoundException { throws NotFoundException {
final SwitchableState<?> initial = final SwitchableState initial =
switchableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new); switchableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new);
initial.setOn(ss.isOn()); initial.setOn(ss.isOn());
switchableStateRepository.save(initial); switchableStateRepository.save(initial);

View file

@ -0,0 +1,55 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ThermostatConditionSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ThermostatCondition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ThermostatConditionRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/thermostatCondition")
public class ThermostatConditionController {
@Autowired ThermostatConditionRepository thermostatConditionRepository;
@GetMapping("/{automationId}")
public List<ThermostatCondition> getAll(@PathVariable long automationId) {
return thermostatConditionRepository.findAllByAutomationId(automationId);
}
private ThermostatCondition save(ThermostatCondition newRL, ThermostatConditionSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOperator(s.getOperator());
newRL.setMode(s.getMode());
return thermostatConditionRepository.save(newRL);
}
@PostMapping
public ThermostatCondition create(
@Valid @RequestBody ThermostatConditionSaveRequest booleanTriggerSaveRequest) {
return save(new ThermostatCondition(), booleanTriggerSaveRequest);
}
@PutMapping
public ThermostatCondition update(
@Valid @RequestBody ThermostatConditionSaveRequest booleanTriggerSaveRequest)
throws NotFoundException {
return save(
thermostatConditionRepository
.findById(booleanTriggerSaveRequest.getId())
.orElseThrow(NotFoundException::new),
booleanTriggerSaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
thermostatConditionRepository.deleteById(id);
}
}

View file

@ -5,11 +5,11 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatPopulationService;
import java.security.Principal; import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@ -19,22 +19,29 @@ public class ThermostatController {
@Autowired private DeviceService deviceService; @Autowired private DeviceService deviceService;
@Autowired private ThermostatRepository thermostatRepository; @Autowired private ThermostatRepository thermostatRepository;
@Autowired private ThermostatService thermostatService; @Autowired private ThermostatPopulationService thermostatService;
@Autowired private SceneRepository sceneRepository; @Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository; @Autowired private StateRepository<State> stateRepository;
private Thermostat save(Thermostat newT, ThermostatSaveRequest t, final Principal principal) { private Thermostat save(Thermostat newT, ThermostatSaveRequest t, final Principal principal) {
newT.setTargetTemperature(t.getTargetTemperature()); newT.setTargetTemperature(t.getTargetTemperature());
newT.setId(t.getId()); newT.setId(t.getId());
newT.setName(t.getName()); newT.setName(t.getName());
newT.setRoomId(t.getRoomId()); newT.setRoomId(t.getRoomId());
newT.setMeasuredTemperature(t.getMeasuredTemperature());
newT.setUseExternalSensors(t.isUseExternalSensors()); newT.setUseExternalSensors(t.isUseExternalSensors());
newT.setOn(t.isTurnOn()); newT.setOn(false);
if (t.getErr() != null) {
newT.setErr(t.getErr());
}
if (t.getTypical() != null) {
newT.setTypical(t.getTypical());
}
thermostatService.populateMeasuredTemperature(newT); thermostatService.populateMeasuredTemperature(newT);
newT = deviceService.saveAsOwner(newT, principal.getName()); newT = thermostatRepository.save(newT);
return newT;
newT.setOn(t.isTurnOn());
return deviceService.saveAsOwner(newT, principal.getName());
} }
@PostMapping @PostMapping
@ -58,11 +65,11 @@ public class ThermostatController {
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id, final Principal principal) public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException { throws NotFoundException {
deviceService.delete(id, principal.getName()); deviceService.deleteByIdAsOwner(id, principal.getName());
} }
@PostMapping("/{id}/state") @PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding( public State sceneBinding(
@PathVariable("id") long deviceId, @PathVariable("id") long deviceId,
@RequestParam long sceneId, @RequestParam long sceneId,
final Principal principal) final Principal principal)
@ -72,9 +79,9 @@ public class ThermostatController {
thermostatRepository thermostatRepository
.findByIdAndUsername(deviceId, principal.getName()) .findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState(); State s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new); final Scene sc = sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId); s.setSceneId(sc.getId());
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0) if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException(); throw new DuplicateStateException();
return stateRepository.save(s); return stateRepository.save(s);

View file

@ -2,7 +2,6 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.EmailConfigurationService; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.EmailConfigurationService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.InitPasswordResetRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.InitPasswordResetRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.OkResponse;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.PasswordResetRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.PasswordResetRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.UserRegistrationRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.UserRegistrationRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateRegistrationException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateRegistrationException;
@ -65,7 +64,7 @@ public class UserAccountController {
+ (isRegistration + (isRegistration
? emailConfig.getRegistrationPath() ? emailConfig.getRegistrationPath()
: emailConfig.getResetPasswordPath()) : emailConfig.getResetPasswordPath())
+ token.getConfirmationToken()); + token.getConfirmToken());
emailSenderService.sendEmail(mailMessage); emailSenderService.sendEmail(mailMessage);
} }
@ -78,7 +77,7 @@ public class UserAccountController {
* @throws DuplicateRegistrationException if a user exists with same email or username * @throws DuplicateRegistrationException if a user exists with same email or username
*/ */
@PostMapping @PostMapping
public OkResponse registerUser(@Valid @RequestBody UserRegistrationRequest registrationData) public void registerUser(@Valid @RequestBody UserRegistrationRequest registrationData)
throws DuplicateRegistrationException { throws DuplicateRegistrationException {
final User existingEmailUser = final User existingEmailUser =
userRepository.findByEmailIgnoreCase(registrationData.getEmail()); userRepository.findByEmailIgnoreCase(registrationData.getEmail());
@ -102,18 +101,11 @@ public class UserAccountController {
toSave.setEmail(registrationData.getEmail()); toSave.setEmail(registrationData.getEmail());
userRepository.save(toSave); userRepository.save(toSave);
ConfirmationToken token; ConfirmationToken token = new ConfirmationToken(toSave);
do {
token = new ConfirmationToken(toSave);
} while (confirmationTokenRepository.findByConfirmationToken(
token.getConfirmationToken())
!= null);
confirmationTokenRepository.save(token); confirmationTokenRepository.save(token);
sendEmail(toSave.getEmail(), token, true); sendEmail(toSave.getEmail(), token, true);
return new OkResponse();
} }
} }
@ -125,7 +117,7 @@ public class UserAccountController {
* @throws UserNotFoundException if given email does not belong to any user * @throws UserNotFoundException if given email does not belong to any user
*/ */
@PostMapping("/init-reset-password") @PostMapping("/init-reset-password")
public OkResponse initResetPassword(@Valid @RequestBody InitPasswordResetRequest resetRequest) public void initResetPassword(@Valid @RequestBody InitPasswordResetRequest resetRequest)
throws UserNotFoundException { throws UserNotFoundException {
final User toReset = userRepository.findByEmailIgnoreCase(resetRequest.getEmail()); final User toReset = userRepository.findByEmailIgnoreCase(resetRequest.getEmail());
@ -134,12 +126,8 @@ public class UserAccountController {
throw new UserNotFoundException(); throw new UserNotFoundException();
} }
ConfirmationToken token; ConfirmationToken token = new ConfirmationToken(toReset);
do { token.setResetPassword(true);
token = new ConfirmationToken(toReset);
token.setResetPassword(true);
} while (confirmationTokenRepository.findByConfirmationToken(token.getConfirmationToken())
!= null);
// Delete existing email password reset tokens // Delete existing email password reset tokens
confirmationTokenRepository.deleteByUserAndResetPassword(toReset, true); confirmationTokenRepository.deleteByUserAndResetPassword(toReset, true);
@ -148,8 +136,6 @@ public class UserAccountController {
confirmationTokenRepository.save(token); confirmationTokenRepository.save(token);
sendEmail(toReset.getEmail(), token, false); sendEmail(toReset.getEmail(), token, false);
return new OkResponse();
} }
/** /**
@ -160,15 +146,12 @@ public class UserAccountController {
* @throws EmailTokenNotFoundException if given token is not a valid token for password reset * @throws EmailTokenNotFoundException if given token is not a valid token for password reset
*/ */
@PutMapping("/reset-password") @PutMapping("/reset-password")
public OkResponse resetPassword( public void resetPassword(@Valid @RequestBody PasswordResetRequest resetRequest)
@Valid @RequestBody PasswordResetRequest resetRequest, throws EmailTokenNotFoundException {
final HttpServletResponse response)
throws EmailTokenNotFoundException, IOException {
final ConfirmationToken token = final ConfirmationToken token =
confirmationTokenRepository.findByConfirmationToken( confirmationTokenRepository.findByConfirmToken(resetRequest.getConfirmationToken());
resetRequest.getConfirmationToken());
if (token == null || !token.getResetPassword()) { if (token == null || !token.isResetPassword()) {
throw new EmailTokenNotFoundException(); throw new EmailTokenNotFoundException();
} }
@ -178,8 +161,6 @@ public class UserAccountController {
// Delete token to prevent further password changes // Delete token to prevent further password changes
confirmationTokenRepository.delete(token); confirmationTokenRepository.delete(token);
return new OkResponse();
} }
/** /**
@ -196,9 +177,9 @@ public class UserAccountController {
final HttpServletResponse response) final HttpServletResponse response)
throws EmailTokenNotFoundException, IOException { throws EmailTokenNotFoundException, IOException {
final ConfirmationToken token = final ConfirmationToken token =
confirmationTokenRepository.findByConfirmationToken(confirmationToken); confirmationTokenRepository.findByConfirmToken(confirmationToken);
if (token != null && !token.getResetPassword()) { if (token != null && !token.isResetPassword()) {
token.getUser().setEnabled(true); token.getUser().setEnabled(true);
userRepository.save(token.getUser()); userRepository.save(token.getUser());
response.sendRedirect(emailConfig.getRegistrationRedirect()); response.sendRedirect(emailConfig.getRegistrationRedirect());

View file

@ -1,97 +1,18 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.ConditionDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.ScenePriorityDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ScenePriority; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation.TriggerDTO;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Trigger;
import java.util.List; import java.util.List;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class AutomationFastUpdateRequest { public class AutomationFastUpdateRequest {
public abstract static class TriggerDTO {
@NotNull public long deviceId;
public abstract Trigger<?> toModel();
}
public static class BooleanTriggerDTO extends TriggerDTO {
@NotNull public boolean on;
@Override
public Trigger<?> toModel() {
BooleanTrigger<?> t = new BooleanTrigger<>();
t.setDeviceId(this.deviceId);
t.setOn(this.on);
return t;
}
}
public static class RangeTriggerDTO extends TriggerDTO {
@NotNull RangeTrigger.Operator operator;
@NotNull double range;
@Override
public Trigger<?> toModel() {
RangeTrigger<?> t = new RangeTrigger<>();
t.setDeviceId(this.deviceId);
t.setOperator(this.operator);
t.setRange(this.range);
return t;
}
}
public static class ScenePriorityDTO {
@NotNull public long sceneId;
@NotNull
@Min(0)
public Integer priority;
public ScenePriority toModel() {
ScenePriority s = new ScenePriority();
s.setSceneId(sceneId);
s.setPriority(priority);
return s;
}
}
@NotNull private List<ScenePriorityDTO> scenes; @NotNull private List<ScenePriorityDTO> scenes;
@NotNull private List<TriggerDTO> triggers; @NotNull private List<TriggerDTO> triggers;
@NotNull private List<ConditionDTO> conditions;
@NotNull private long id; @NotNull private long id;
@NotNull @NotEmpty private String name; @NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ScenePriorityDTO> getScenes() {
return scenes;
}
public void setScenes(List<ScenePriorityDTO> scenes) {
this.scenes = scenes;
}
public List<TriggerDTO> getTriggers() {
return triggers;
}
public void setTriggers(List<TriggerDTO> triggers) {
this.triggers = triggers;
}
public void setId(long id) {
this.id = id;
}
} }

View file

@ -2,22 +2,12 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class AutomationSaveRequest { public class AutomationSaveRequest {
private long id; private long id;
@NotNull @NotEmpty private String name; @NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} }

View file

@ -0,0 +1,16 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class BooleanConditionOrTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
private boolean on;
}

View file

@ -1,42 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull;
public class BooleanTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
private boolean on;
public long getId() {
return id;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
}

View file

@ -1,8 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
/** A 'dim' event from a button dimmer. */ /** A 'dim' event from a button dimmer. */
@Data
public class ButtonDimmerDimRequest { public class ButtonDimmerDimRequest {
/** The device id */ /** The device id */
@ -15,20 +17,4 @@ public class ButtonDimmerDimRequest {
/** Whether the dim is up or down */ /** Whether the dim is up or down */
@NotNull private DimType dimType; @NotNull private DimType dimType;
public DimType getDimType() {
return dimType;
}
public void setDimType(DimType dimType) {
this.dimType = dimType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
} }

View file

@ -2,7 +2,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class DeviceSaveRequest { public class DeviceSaveRequest {
/** Device identifier */ /** Device identifier */
private long id; private long id;
@ -15,28 +17,4 @@ public class DeviceSaveRequest {
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull @NotEmpty private String name; @NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Long getRoomId() {
return roomId;
}
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} }

View file

@ -3,7 +3,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Max; import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class DimmableSaveRequest { public class DimmableSaveRequest {
/** Device id (used only for update requests) */ /** Device id (used only for update requests) */
@ -23,36 +25,4 @@ public class DimmableSaveRequest {
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name; @NotNull private String name;
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public Integer getIntensity() {
return intensity;
}
public void setIntensity(Integer intensity) {
this.intensity = intensity;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
} }

View file

@ -3,7 +3,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Max; import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class DimmableStateSaveRequest { public class DimmableStateSaveRequest {
/** Device id (used only for update requests) */ /** Device id (used only for update requests) */
@ -13,16 +15,4 @@ public class DimmableStateSaveRequest {
@Min(0) @Min(0)
@Max(100) @Max(100)
private Integer intensity = 0; private Integer intensity = 0;
public Integer getIntensity() {
return intensity;
}
public void setIntensity(Integer intensity) {
this.intensity = intensity;
}
public Long getId() {
return id;
}
} }

View file

@ -2,7 +2,14 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
public class GenericDeviceSaveReguest { import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GenericDeviceSaveRequest {
/** /**
* The room this device belongs in, as a foreign key id. To use when updating and inserting from * The room this device belongs in, as a foreign key id. To use when updating and inserting from
* a REST call. * a REST call.
@ -11,20 +18,4 @@ public class GenericDeviceSaveReguest {
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name; @NotNull private String name;
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
} }

View file

@ -1,13 +1,8 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import lombok.Data;
@Data
public class GuestPermissionsRequest { public class GuestPermissionsRequest {
private boolean cameraEnabled; private boolean cameraEnabled;
public boolean isCameraEnabled() {
return cameraEnabled;
}
public void setCameraEnabled(boolean cameraEnabled) {
this.cameraEnabled = cameraEnabled;
}
} }

View file

@ -0,0 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class GuestsUpdateRequest {
@NotNull private List<Long> ids;
}

View file

@ -3,8 +3,14 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern; import javax.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** DTO for password reset request */ /** DTO for password reset request */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class InitPasswordResetRequest { public class InitPasswordResetRequest {
/** /**
* The user's email (validated according to criteria used in <code>&gt;input type="email"&lt;> * The user's email (validated according to criteria used in <code>&gt;input type="email"&lt;>
@ -14,12 +20,4 @@ public class InitPasswordResetRequest {
@Email(message = "Please provide a valid email address") @Email(message = "Please provide a valid email address")
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address") @Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
private String email; private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} }

View file

@ -1,36 +1,14 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JWTRequest { public class JWTRequest {
@NotNull private String usernameOrEmail; @NotNull private String usernameOrEmail;
@NotNull private String password; @NotNull private String password;
public String getUsernameOrEmail() {
return this.usernameOrEmail;
}
public void setUsernameOrEmail(String usernameOrEmail) {
this.usernameOrEmail = usernameOrEmail;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "JWTRequest{"
+ "usernameOrEmail='"
+ usernameOrEmail
+ '\''
+ ", password='"
+ password
+ '\''
+ '}';
}
} }

View file

@ -1,13 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class JWTResponse { public class JWTResponse {
private final String jwttoken; private final String jwttoken;
public JWTResponse(String jwttoken) {
this.jwttoken = jwttoken;
}
public String getToken() {
return this.jwttoken;
}
} }

View file

@ -3,7 +3,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Max; import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class KnobDimmerDimRequest { public class KnobDimmerDimRequest {
/** The device id */ /** The device id */
@ -14,20 +16,4 @@ public class KnobDimmerDimRequest {
@Min(0) @Min(0)
@Max(100) @Max(100)
private Integer intensity; private Integer intensity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getIntensity() {
return intensity;
}
public void setIntensity(Integer intensity) {
this.intensity = intensity;
}
} }

View file

@ -1,6 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
/** A dummy DTO to return when there is no data to return */
public class OkResponse {
private boolean success = true;
}

View file

@ -1,8 +1,16 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.*; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** DTO for password reset request */ /** DTO for password reset request */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PasswordResetRequest { public class PasswordResetRequest {
@NotNull private String confirmationToken; @NotNull private String confirmationToken;
@ -15,20 +23,4 @@ public class PasswordResetRequest {
max = 255, max = 255,
message = "Your password should be at least 6 characters long and up to 255 chars long") message = "Your password should be at least 6 characters long and up to 255 chars long")
private String password; private String password;
public String getConfirmationToken() {
return confirmationToken;
}
public void setConfirmationToken(String confirmationToken) {
this.confirmationToken = confirmationToken;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} }

View file

@ -0,0 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Operator;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class RangeConditionOrTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
@NotNull private Operator operator;
@NotNull private double range;
}

View file

@ -1,57 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import javax.validation.constraints.NotNull;
public class RangeTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
@NotNull private RangeTrigger.Operator operator;
@NotNull private double range;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public RangeTrigger.Operator getOperator() {
return operator;
}
public void setOperator(RangeTrigger.Operator operator) {
this.operator = operator;
}
public double getRange() {
return range;
}
public void setRange(Double range) {
this.range = range;
}
}

View file

@ -1,15 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Room; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Icon;
import javax.persistence.Lob; import javax.persistence.Lob;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class RoomSaveRequest { public class RoomSaveRequest {
/** Room identifier */ /** Room identifier */
private long id; private long id;
@NotNull private Room.Icon icon; @NotNull private Icon icon;
/** /**
* Image is to be given as byte[]. In order to get an encoded string from it, the * Image is to be given as byte[]. In order to get an encoded string from it, the
@ -21,36 +25,4 @@ public class RoomSaveRequest {
/** The user given name of this room (e.g. 'Master bedroom') */ /** The user given name of this room (e.g. 'Master bedroom') */
@NotNull private String name; @NotNull private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Room.Icon getIcon() {
return icon;
}
public void setIcon(Room.Icon icon) {
this.icon = icon;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
} }

View file

@ -2,7 +2,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class ScenePrioritySaveRequest { public class ScenePrioritySaveRequest {
@NotNull private Long automationId; @NotNull private Long automationId;
@ -11,28 +13,4 @@ public class ScenePrioritySaveRequest {
private Integer priority; private Integer priority;
@NotNull private Long sceneId; @NotNull private Long sceneId;
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Long getSceneId() {
return sceneId;
}
public void setSceneId(Long sceneId) {
this.sceneId = sceneId;
}
} }

View file

@ -1,8 +1,15 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import com.sun.istack.NotNull; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Icon;
import javax.persistence.Column; import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SceneSaveRequest { public class SceneSaveRequest {
/** Room identifier */ /** Room identifier */
@ -11,26 +18,8 @@ public class SceneSaveRequest {
/** The user given name of this room (e.g. 'Master bedroom') */ /** The user given name of this room (e.g. 'Master bedroom') */
@NotNull private String name; @NotNull private String name;
@NotNull private Icon icon;
/** Determines whether a guest can access this scene */ /** Determines whether a guest can access this scene */
@Column @NotNull private boolean guestAccessEnabled; @Column @NotNull private boolean guestAccessEnabled;
public boolean isGuestAccessEnabled() {
return guestAccessEnabled;
}
public void setGuestAccessEnabled(boolean guestAccessEnabled) {
this.guestAccessEnabled = guestAccessEnabled;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} }

View file

@ -1,29 +1,18 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Sensor; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Sensor;
import com.google.gson.annotations.SerializedName;
import java.math.BigDecimal; import java.math.BigDecimal;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SensorSaveRequest { public class SensorSaveRequest {
/** Type of sensor, i.e. of the thing the sensor measures. */
public enum SensorType {
/** A sensor that measures temperature in degrees celsius */
@SerializedName("TEMPERATURE")
TEMPERATURE,
/** A sensor that measures relative humidity in percentage points */
@SerializedName("HUMIDITY")
HUMIDITY,
/** A sensor that measures light in degrees */
@SerializedName("LIGHT")
LIGHT
}
/** The type of this sensor */ /** The type of this sensor */
@NotNull @NotNull
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
@ -39,36 +28,4 @@ public class SensorSaveRequest {
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name; @NotNull private String name;
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public Sensor.SensorType getSensor() {
return sensor;
}
public void setSensor(Sensor.SensorType sensor) {
this.sensor = sensor;
}
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
} }

View file

@ -1,8 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
/** An on/off/toggle operation on a switch */ /** An on/off/toggle operation on a switch */
@Data
public class SwitchOperationRequest { public class SwitchOperationRequest {
/** The device id */ /** The device id */
@ -16,20 +18,4 @@ public class SwitchOperationRequest {
/** The type of switch operation */ /** The type of switch operation */
@NotNull private SwitchOperationRequest.OperationType type; @NotNull private SwitchOperationRequest.OperationType type;
public OperationType getType() {
return type;
}
public void setType(OperationType type) {
this.type = type;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
} }

View file

@ -1,7 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SwitchableSaveRequest { public class SwitchableSaveRequest {
/** The state of this switch */ /** The state of this switch */
private boolean on; private boolean on;
@ -17,36 +23,4 @@ public class SwitchableSaveRequest {
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name; @NotNull private String name;
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public void setId(long id) {
this.id = id;
}
} }

View file

@ -1,23 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class SwitchableStateSaveRequest { public class SwitchableStateSaveRequest {
/** Device id (used only for update requests) */ /** Device id (used only for update requests) */
@NotNull private Long id; @NotNull private Long id;
@NotNull private boolean on; @NotNull private boolean on;
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public Long getId() {
return id;
}
} }

View file

@ -0,0 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Thermostat;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ThermostatCondition;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class ThermostatConditionSaveRequest {
@NotNull private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
@NotNull private ThermostatCondition.Operator operator;
@NotNull private Thermostat.Mode mode;
}

View file

@ -2,7 +2,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import java.math.BigDecimal; import java.math.BigDecimal;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class ThermostatSaveRequest { public class ThermostatSaveRequest {
/** Device identifier */ /** Device identifier */
@ -22,64 +24,11 @@ public class ThermostatSaveRequest {
@NotNull private boolean useExternalSensors; @NotNull private boolean useExternalSensors;
@NotNull private BigDecimal measuredTemperature;
/** State of this thermostat */ /** State of this thermostat */
@NotNull private boolean turnOn; @NotNull private boolean turnOn;
public boolean isTurnOn() { /** The value of the error according to this value */
return turnOn; private BigDecimal err;
}
public void setTurnOn(boolean turnOn) { private BigDecimal typical;
this.turnOn = turnOn;
}
public boolean isUseExternalSensors() {
return useExternalSensors;
}
public void setUseExternalSensors(boolean useExternalSensors) {
this.useExternalSensors = useExternalSensors;
}
public BigDecimal getTargetTemperature() {
return this.targetTemperature;
}
public void setTargetTemperature(BigDecimal targetTemperature) {
this.targetTemperature = targetTemperature;
}
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public void setId(long id) {
this.id = id;
}
public BigDecimal getMeasuredTemperature() {
return measuredTemperature;
}
public void setMeasuredTemperature(BigDecimal measuredTemperature) {
this.measuredTemperature = measuredTemperature;
}
} }

View file

@ -1,7 +1,9 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto; package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.*; import javax.validation.constraints.*;
import lombok.Data;
@Data
public class UserRegistrationRequest { public class UserRegistrationRequest {
/** The full name of the user */ /** The full name of the user */
@ -35,36 +37,4 @@ public class UserRegistrationRequest {
@Email(message = "Please provide a valid email address") @Email(message = "Please provide a valid email address")
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address") @Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
private String email; private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} }

View file

@ -0,0 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
import lombok.Data;
@Data
public class UserResponse {
private Long id;
private String username;
private String name;
public static UserResponse fromUser(User u) {
final UserResponse us = new UserResponse();
us.name = u.getName();
us.id = u.getId();
us.username = u.getUsername();
return us;
}
}

View file

@ -1,48 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
public class UserUpdateRequest {
/** The full name of the user */
@NotEmpty(message = "Please provide a full name")
private String name;
/** A non-salted password */
@NotEmpty(message = "Please provide a password")
private String password;
/**
* The user's email (validated according to criteria used in <code>&gt;input type="email"&lt;>
* </code>, technically not RFC 5322 compliant
*/
@NotEmpty(message = "Please provide an email")
@Email(message = "Please provide a valid email address")
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
private String email;
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
}

View file

@ -0,0 +1,24 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanCondition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Condition;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
public class BooleanConditionDTO extends ConditionDTO {
@NotNull @Getter @Setter private boolean on;
@Override
public Condition<?> toModel() {
BooleanCondition t = new BooleanCondition();
t.setDeviceId(this.getDeviceId());
t.setOn(this.on);
return t;
}
}

View file

@ -0,0 +1,23 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Trigger;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
public class BooleanTriggerDTO extends TriggerDTO {
@NotNull @Getter @Setter private boolean on;
@Override
public Trigger<?> toModel() {
BooleanTrigger t = new BooleanTrigger();
t.setDeviceId(this.getDeviceId());
t.setOn(this.on);
return t;
}
}

View file

@ -0,0 +1,12 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Condition;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
public abstract class ConditionDTO {
@NotNull @Getter @Setter private long deviceId;
public abstract Condition<?> toModel();
}

View file

@ -0,0 +1,23 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Condition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Operator;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeCondition;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
public class RangeConditionDTO extends ConditionDTO {
@NotNull @Getter @Setter private Operator operator;
@NotNull @Getter @Setter private double range;
@Override
public Condition<?> toModel() {
RangeCondition t = new RangeCondition();
t.setDeviceId(this.getDeviceId());
t.setOperator(this.operator);
t.setRange(this.range);
return t;
}
}

View file

@ -0,0 +1,22 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Operator;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Trigger;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
public class RangeTriggerDTO extends TriggerDTO {
@NotNull @Getter @Setter private Operator operator;
@NotNull @Getter @Setter private double range;
@Override
public Trigger<?> toModel() {
RangeTrigger t = new RangeTrigger();
t.setDeviceId(this.getDeviceId());
t.setOperator(this.operator);
t.setRange(this.range);
return t;
}
}

View file

@ -0,0 +1,26 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ScenePriority;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
public class ScenePriorityDTO {
@NotNull @Getter @Setter private long sceneId;
@NotNull
@Min(0)
private @Getter @Setter Integer priority;
public ScenePriority toModel() {
ScenePriority s = new ScenePriority();
s.setSceneId(sceneId);
s.setPriority(priority);
return s;
}
}

View file

@ -0,0 +1,29 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Condition;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Thermostat;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ThermostatCondition;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
public class ThermostatConditionDTO extends ConditionDTO {
@NotNull @Getter @Setter private ThermostatCondition.Operator operator;
@NotNull @Getter @Setter private Thermostat.Mode mode;
@Override
public Condition<?> toModel() {
ThermostatCondition t = new ThermostatCondition();
t.setDeviceId(this.getDeviceId());
t.setOperator(this.operator);
t.setMode(this.mode);
return t;
}
}

View file

@ -0,0 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto.automation;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Trigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Triggerable;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
public abstract class TriggerDTO {
@NotNull @Getter @Setter private long deviceId;
public abstract Trigger<? extends Triggerable> toModel();
}

View file

@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.ResponseStatus;
public class UnauthorizedException extends Exception { public class UnauthorizedException extends Exception {
private final boolean isUserDisabled; private final boolean isUserDisabled;
public UnauthorizedException(boolean isDisabled) { public UnauthorizedException(boolean isDisabled, Throwable cause) {
super("Access denied: " + (isDisabled ? "user is disabled" : "wrong credentials")); super("Access denied: " + (isDisabled ? "user is disabled" : "wrong credentials"), cause);
this.isUserDisabled = isDisabled; this.isUserDisabled = isDisabled;
} }

View file

@ -6,8 +6,9 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; import lombok.Data;
@Data
@Entity @Entity
public class Automation { public class Automation {
@ -17,65 +18,23 @@ public class Automation {
@ApiModelProperty(hidden = true) @ApiModelProperty(hidden = true)
private long id; private long id;
@ManyToOne @OneToMany(mappedBy = "automation", orphanRemoval = true, cascade = CascadeType.REMOVE)
@JoinColumn(name = "user_id", updatable = false, insertable = false)
@GsonExclude
private User user;
@NotNull
@Column(name = "user_id", nullable = false)
@GsonExclude
private Long userId;
@OneToMany(mappedBy = "automation", orphanRemoval = true)
private Set<Trigger<?>> triggers = new HashSet<>(); private Set<Trigger<?>> triggers = new HashSet<>();
@OneToMany(mappedBy = "automation", cascade = CascadeType.REMOVE) @OneToMany(mappedBy = "automation", cascade = CascadeType.REMOVE)
private Set<ScenePriority> scenes = new HashSet<>(); private Set<ScenePriority> scenes = new HashSet<>();
@NotNull @NotEmpty private String name; @ManyToOne
@JoinColumn(name = "user_id", updatable = false, insertable = false)
@GsonExclude
private User user;
public long getId() { @OneToMany(mappedBy = "automation", orphanRemoval = true, cascade = CascadeType.REMOVE)
return id; private Set<Condition<?>> conditions = new HashSet<>();
}
public void setId(long id) { @Column(name = "user_id", nullable = false)
this.id = id; @GsonExclude
} private Long userId;
public Set<Trigger<?>> getStates() { @NotEmpty private String name;
return triggers;
}
public Set<ScenePriority> getScenes() {
return scenes;
}
public Set<Trigger<?>> getTriggers() {
return triggers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
} }

View file

@ -7,9 +7,9 @@ import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
public interface AutomationRepository extends CrudRepository<Automation, Long> { public interface AutomationRepository extends CrudRepository<Automation, Long> {
@EntityGraph(attributePaths = {"scenes", "triggers"}) @EntityGraph(attributePaths = {"scenes", "triggers", "conditions"})
List<Automation> findAllByUserId(@Param("userId") long userId); List<Automation> findAllByUserId(@Param("userId") long userId);
@EntityGraph(attributePaths = {"scenes", "triggers"}) @EntityGraph(attributePaths = {"scenes", "triggers", "conditions"})
Optional<Automation> findByIdAndUserId(@Param("id") long id, @Param("userId") long userId); Optional<Automation> findByIdAndUserId(@Param("id") long id, @Param("userId") long userId);
} }

View file

@ -0,0 +1,26 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Entity
@EqualsAndHashCode(callSuper = true)
public class BooleanCondition extends Condition<BooleanTriggerable> {
@Getter
@Setter
@Column(name = "switchable_on")
private boolean on;
public BooleanCondition() {
super("booleanCondition");
}
@Override
public boolean triggered() {
return this.getDevice().readTriggerState() == isOn();
}
}

View file

@ -0,0 +1,9 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import org.springframework.data.repository.query.Param;
public interface BooleanConditionRepository extends ConditionRepository<BooleanCondition> {
List<BooleanCondition> findAllByAutomationId(@Param("automationId") long automationId);
}

View file

@ -2,29 +2,21 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.Getter;
import lombok.Setter;
@Entity @Entity
public class BooleanTrigger<D extends Device & BooleanTriggerable> extends Trigger<D> { public class BooleanTrigger extends Trigger<BooleanTriggerable> {
@Column(name = "switchable_on") @Column(name = "switchable_on")
@Getter
@Setter
private boolean on; private boolean on;
public BooleanTrigger() { public BooleanTrigger() {
super("booleanTrigger"); super("booleanTrigger");
} }
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public boolean check(boolean on) {
return this.on == on;
}
@Override @Override
public boolean triggered() { public boolean triggered() {
return getDevice().readTriggerState() == isOn(); return getDevice().readTriggerState() == isOn();

View file

@ -3,8 +3,7 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List; import java.util.List;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
public interface BooleanTriggerRepository public interface BooleanTriggerRepository extends TriggerRepository<BooleanTrigger> {
extends TriggerRepository<BooleanTrigger<? extends Device>> {
List<BooleanTrigger<?>> findAllByAutomationId(@Param("automationId") long automationId); List<BooleanTrigger> findAllByAutomationId(@Param("automationId") long automationId);
} }

View file

@ -1,5 +1,5 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface BooleanTriggerable { public interface BooleanTriggerable extends Triggerable {
boolean readTriggerState(); boolean readTriggerState();
} }

View file

@ -18,14 +18,14 @@ public class ButtonDimmer extends Dimmer {
/** Increases the current intensity level of the dimmable light by DIM_INCREMENT */ /** Increases the current intensity level of the dimmable light by DIM_INCREMENT */
public void increaseIntensity() { public void increaseIntensity() {
for (Dimmable dl : getOutputs()) { for (Dimmable dl : getDimmables()) {
dl.setIntensity(dl.getIntensity() + DIM_INCREMENT); dl.setIntensity(dl.getIntensity() + DIM_INCREMENT);
} }
} }
/** Decreases the current intensity level of the dimmable light by DIM_INCREMENT */ /** Decreases the current intensity level of the dimmable light by DIM_INCREMENT */
public void decreaseIntensity() { public void decreaseIntensity() {
for (Dimmable dl : getOutputs()) { for (Dimmable dl : getDimmables()) {
dl.setIntensity(dl.getIntensity() - DIM_INCREMENT); dl.setIntensity(dl.getIntensity() - DIM_INCREMENT);
} }
} }

View file

@ -0,0 +1,57 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Condition<D> {
@Transient private String kind;
protected Condition(String kind) {
this.kind = kind;
}
public String getKind() {
return kind;
}
@ManyToOne(targetEntity = Device.class)
@JoinColumn(name = "device_id", updatable = false, insertable = false)
@GsonExclude
private D device;
@Column(name = "automation_id", nullable = false)
private Long automationId;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne
@JoinColumn(name = "automation_id", updatable = false, insertable = false)
@GsonExclude
@EqualsAndHashCode.Exclude
private Automation automation;
/**
* The device this condition belongs to, as a foreign key id. To use when updating and inserting
* from a REST call.
*/
@Column(name = "device_id", nullable = false)
private Long deviceId;
public abstract boolean triggered();
public Condition<D> setAutomationId(Long automationId) {
this.automationId = automationId;
return this;
}
}

View file

@ -0,0 +1,16 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface ConditionRepository<T extends Condition<?>> extends CrudRepository<T, Long> {
List<T> findAllByDeviceId(@Param("deviceId") long deviceId);
List<T> findAllByAutomationId(@Param("automationId") long automationId);
@Transactional
void deleteAllByAutomationId(@Param("automationId") long automationId);
}

View file

@ -1,20 +1,15 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.Date; import java.util.Date;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import javax.persistence.Column; import javax.persistence.*;
import javax.persistence.Entity; import lombok.Data;
import javax.persistence.FetchType; import lombok.NonNull;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Data
@Entity @Entity
public class ConfirmationToken { public final class ConfirmationToken {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@ -22,9 +17,18 @@ public class ConfirmationToken {
private Long id; private Long id;
@Column(name = "confirmation_token", unique = true) @Column(name = "confirmation_token", unique = true)
private String confirmationToken; private String confirmToken;
public Date getCreatedDate() {
return new Date(createdDate.getTime());
}
public void setCreatedDate(Date createdDate) {
this.createdDate = new Date(createdDate.getTime());
}
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
@NonNull
private Date createdDate; private Date createdDate;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@ -32,55 +36,32 @@ public class ConfirmationToken {
private User user; private User user;
@Column(nullable = false) @Column(nullable = false)
private Boolean resetPassword; private boolean resetPassword;
public ConfirmationToken(User user) { public ConfirmationToken(User user) {
this.user = user; this.user = user;
createdDate = new Date(); createdDate = new Date();
confirmationToken = UUID.randomUUID().toString(); confirmToken = UUID.randomUUID().toString();
resetPassword = false; resetPassword = false;
} }
/** Constructor for hibernate reflective stuff things whatever */ public ConfirmationToken() {
public ConfirmationToken() {} this((User) null);
public Long getId() {
return id;
} }
public String getConfirmationToken() { @Override
return confirmationToken; public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConfirmationToken that = (ConfirmationToken) o;
return resetPassword == that.resetPassword
&& confirmToken.equals(that.confirmToken)
&& createdDate.equals(that.createdDate)
&& Objects.equals(user, that.user);
} }
public Date getCreatedDate() { @Override
return createdDate; public int hashCode() {
} return Objects.hash(confirmToken, createdDate, user, resetPassword);
public User getUser() {
return user;
}
public void setId(Long id) {
this.id = id;
}
public void setConfirmationToken(String confirmationToken) {
this.confirmationToken = confirmationToken;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public void setUser(User user) {
this.user = user;
}
public Boolean getResetPassword() {
return resetPassword;
}
public void setResetPassword(Boolean resetPassword) {
this.resetPassword = resetPassword;
} }
} }

View file

@ -4,7 +4,7 @@ import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
public interface ConfirmationTokenRepository extends CrudRepository<ConfirmationToken, String> { public interface ConfirmationTokenRepository extends CrudRepository<ConfirmationToken, String> {
ConfirmationToken findByConfirmationToken(String confirmationToken); ConfirmationToken findByConfirmToken(String confirmToken);
ConfirmationToken findByUser(User user); ConfirmationToken findByUser(User user);

View file

@ -0,0 +1,5 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface Connectable<O extends OutputDevice> {
void connect(O output, boolean connect);
}

View file

@ -1,47 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* A rule on how to connect an input device type to an output device type
*
* @param <I> the input device type
* @param <O> the output device type
*/
@FunctionalInterface
public interface Connector<I extends InputDevice, O extends OutputDevice> {
/**
* Connects or disconnects input to output
*
* @param input the input device
* @param output the output device
* @param connect true if connection, false if disconnection
*/
void connect(I input, O output, boolean connect);
/**
* Produces a basic implementation of a connector, assuming there is a ManyToMany relationship
* between J and K
*
* @param outputsGetter the getter method of the set of outputs on the input class
* @param inputsGetter the getter method of the set of outputs on the input class
* @param <J> the input device type
* @param <K> the output device type
* @return a Connector implementation for the pair of types J and K
*/
static <J extends InputDevice, K extends OutputDevice> Connector<J, K> basic(
Function<J, Set<? super K>> outputsGetter, Function<K, Set<? super J>> inputsGetter) {
return (i, o, connect) -> {
if (connect) {
outputsGetter.apply(i).add(o);
inputsGetter.apply(o).add(i);
} else {
outputsGetter.apply(i).remove(o);
inputsGetter.apply(o).remove(i);
}
};
}
}

View file

@ -3,8 +3,8 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Entity; import javax.persistence.Entity;
/** /**
* Represents a curtain. The intensity represents how much the curtains are opened, * Represents a curtain. The intensity represents how much the curtains are opened, 0 is completely
* 0 is completely closed 100 is completely open * closed 100 is completely open
*/ */
@Entity @Entity
public class Curtains extends Dimmable { public class Curtains extends Dimmable {

View file

@ -4,13 +4,13 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.NotNull; import lombok.Data;
/** Generic abstraction for a smart home device */ /** Generic abstraction for a smart home device */
@Entity @Entity
@Data
@Inheritance(strategy = InheritanceType.JOINED) @Inheritance(strategy = InheritanceType.JOINED)
public abstract class Device { public abstract class Device {
@ -39,18 +39,16 @@ public abstract class Device {
@OneToMany(mappedBy = "device", orphanRemoval = true) @OneToMany(mappedBy = "device", orphanRemoval = true)
@GsonExclude @GsonExclude
@SocketGsonExclude @SocketGsonExclude
private Set<Trigger<? extends Device>> triggers = new HashSet<>(); private Set<Trigger<? extends Device>> triggers;
/** /**
* The room this device belongs in, as a foreign key id. To use when updating and inserting from * The room this device belongs in, as a foreign key id. To use when updating and inserting from
* a REST call. * a REST call.
*/ */
@Column(name = "room_id", nullable = false) @Column(name = "room_id", nullable = false)
@NotNull
private Long roomId; private Long roomId;
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */ /** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@ -69,63 +67,15 @@ public abstract class Device {
@OneToMany(mappedBy = "device", orphanRemoval = true) @OneToMany(mappedBy = "device", orphanRemoval = true)
@GsonExclude @GsonExclude
@SocketGsonExclude @SocketGsonExclude
private Set<State<?>> states = new HashSet<>(); private Set<State> states;
@Transient @GsonExclude private boolean fromHost = false; @Transient @GsonExclude private Long fromHostId = null;
@Transient @GsonExclude private boolean fromGuest = false; @Transient @GsonExclude private boolean fromGuest = false;
@Transient @GsonExclude private boolean deleted = false; @Transient @GsonExclude private boolean deleted = false;
public boolean isFromHost() { protected Device(String kind, FlowType flowType) {
return fromHost;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isFromGuest() {
return fromGuest;
}
public void setFromGuest(boolean fromGuest) {
this.fromGuest = fromGuest;
}
public void setFromHost(boolean fromHost) {
this.fromHost = fromHost;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getRoomId() {
return roomId;
}
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public Device(String kind, FlowType flowType) {
this.kind = kind; this.kind = kind;
this.flowType = flowType; this.flowType = flowType;
} }

View file

@ -2,22 +2,20 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.Max; import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Entity @Entity
@EqualsAndHashCode(callSuper = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Dimmable extends Switchable implements RangeTriggerable { public class Dimmable extends Switchable implements RangeTriggerable {
public static final Connector<KnobDimmer, Dimmable> KNOB_DIMMER_DIMMABLE_CONNECTOR =
Connector.basic(KnobDimmer::getOutputs, Dimmable::getDimmers);
public static final Connector<ButtonDimmer, Dimmable> BUTTON_DIMMER_DIMMABLE_CONNECTOR =
Connector.basic(ButtonDimmer::getOutputs, Dimmable::getDimmers);
protected Dimmable(String kind) { protected Dimmable(String kind) {
super(kind); super(kind);
} }
@ -25,23 +23,23 @@ public class Dimmable extends Switchable implements RangeTriggerable {
@ManyToMany(mappedBy = "dimmables", cascade = CascadeType.DETACH) @ManyToMany(mappedBy = "dimmables", cascade = CascadeType.DETACH)
@GsonExclude @GsonExclude
@SocketGsonExclude @SocketGsonExclude
private Set<Dimmer> dimmers; @EqualsAndHashCode.Exclude
@Getter
@Setter
private Set<Dimmer> dimmers = new HashSet<>();
/** The light intensity value. Goes from 0 (off) to 100 (on) */ /** The light intensity value. Goes from 0 (off) to 100 (on) */
@NotNull
@Column(nullable = false) @Column(nullable = false)
@Min(0) @Min(0)
@Max(100) @Max(100)
@Getter
private Integer intensity = 0; private Integer intensity = 0;
@NotNull
@Column(nullable = false) @Column(nullable = false)
@Getter
@Setter
private Integer oldIntensity = 100; private Integer oldIntensity = 100;
public Integer getIntensity() {
return intensity;
}
/** /**
* Sets the intensity to a certain level. Out of bound values are corrected to the respective * Sets the intensity to a certain level. Out of bound values are corrected to the respective
* extremums. An intensity level of 0 turns the light off, but keeps the old intensity level * extremums. An intensity level of 0 turns the light off, but keeps the old intensity level
@ -71,19 +69,14 @@ public class Dimmable extends Switchable implements RangeTriggerable {
intensity = on ? oldIntensity : 0; intensity = on ? oldIntensity : 0;
} }
public Set<Dimmer> getDimmers() { public void readStateAndSet(DimmableState state) {
return this.dimmers;
}
public void readStateAndSet(DimmableState<? extends Dimmable> state) {
setIntensity(state.getIntensity()); setIntensity(state.getIntensity());
} }
@Override @Override
public State<? extends Dimmable> cloneState() { public State cloneState() {
final DimmableState<Dimmable> newState = new DimmableState<>(); final DimmableState newState = new DimmableState();
newState.setDeviceId(getId()); newState.setDeviceId(getId());
newState.setDevice(this);
newState.setIntensity(getIntensity()); newState.setIntensity(getIntensity());
return newState; return newState;
} }

View file

@ -1,6 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.*; import javax.persistence.Entity;
/** Represent a dimmable light */ /** Represent a dimmable light */
@Entity @Entity

View file

@ -1,4 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface DimmableRepository<T extends Dimmable> extends SwitchableRepository<T> { public interface DimmableRepository<T extends Dimmable> extends SwitchableRepository<T> {}
}

View file

@ -3,26 +3,33 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.validation.constraints.Max; import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import lombok.Getter;
import lombok.Setter;
/** Represent a state for an IDimmable device */ /** Represent a state for an IDimmable device */
@Entity @Entity
public class DimmableState<T extends Dimmable> extends State<T> { public class DimmableState extends State {
public void setDevice(Dimmable device) {
setInnerDevice(device);
}
/** The light intensity value. Goes from 0 (off) to 100 (on) */ /** The light intensity value. Goes from 0 (off) to 100 (on) */
@Min(0) @Min(0)
@Max(100) @Max(100)
@Getter
@Setter
private int intensity = 0; private int intensity = 0;
public int getIntensity() {
return intensity;
}
public void setIntensity(int dimAmount) {
this.intensity = dimAmount;
}
@Override @Override
public void apply() { public void apply() {
getDevice().readStateAndSet(this); ((Dimmable) getDevice()).readStateAndSet(this);
}
@Override
protected DimmableState copy() {
final DimmableState d = new DimmableState();
d.setIntensity(intensity);
return d;
} }
} }

Some files were not shown because too many files have changed in this diff Show more