Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84ce2ebbdf | ||
|
|
67b6344b2e | ||
|
|
36a888474c | ||
|
|
17fcbd3cd8 | ||
|
|
d5617a3a0d | ||
|
|
4bc4b05991 | ||
|
|
59eec77e07 | ||
|
|
cffe16e153 | ||
|
|
dc40ec2e5b | ||
|
|
a11656b7b7 | ||
|
|
1ab99c816d | ||
|
|
01d60700ec | ||
|
|
5100a320c4 | ||
|
|
1c7d7e48e0 | ||
|
|
348b46681f | ||
|
|
792a67e6dd | ||
|
|
782c759fb8 | ||
|
|
c69fb5dfdc | ||
|
|
f5b49e2ca3 | ||
|
|
29fcc0fe8f | ||
|
|
f0231235f8 | ||
|
|
46cc9f83ac | ||
|
|
c10871016e | ||
|
|
5a3b0a62f6 | ||
|
|
ecd2119da9 | ||
|
|
d34a88943a | ||
|
|
6a611d57d3 | ||
|
|
9588da3454 | ||
|
|
c0106a720d | ||
|
|
12168e5dc4 | ||
|
|
ed050db16a | ||
|
|
9d0989afb1 | ||
|
|
eb593c8aed | ||
|
|
10aa8a25e6 | ||
|
|
a3e213eea2 | ||
|
|
7b81e8a3ec | ||
|
|
99456ddbf6 | ||
|
|
9849d7c51e | ||
|
|
6de6599924 | ||
|
|
53938dbde8 | ||
|
|
7cd403bc4c | ||
|
|
a2233f477a | ||
|
|
e3d0122fb0 | ||
|
|
327a6eb9e4 | ||
|
|
92eb61828f | ||
|
|
393f2a6304 | ||
|
|
c14c243043 | ||
|
|
a9863fa495 | ||
|
|
532a7cf35e | ||
|
|
751544c0df | ||
|
|
549c4b559b | ||
|
|
c4b92b734c | ||
|
|
ff763ec44c | ||
|
|
912151ef2d | ||
|
|
f341e8eb10 | ||
|
|
64af6ae5aa | ||
|
|
1d64d0bd23 | ||
|
|
bc19ba5fd0 | ||
|
|
aea6edd08b | ||
|
|
9b62b46e0e | ||
|
|
dcad963c7c | ||
|
|
6749700b34 | ||
|
|
f66a6e8a49 | ||
|
|
51931b979f | ||
|
|
d863b0927e | ||
|
|
bfaf634148 | ||
|
|
e8760938af | ||
|
|
5bb3275a54 | ||
|
|
d5362ff41d | ||
|
|
949a0d2770 | ||
|
|
8af818ffbe | ||
|
|
ac8b771ecf | ||
|
|
3f25520284 | ||
|
|
2ef558894f | ||
|
|
b68b63a110 | ||
|
|
9f2ec5fb38 | ||
|
|
9564586f97 | ||
|
|
4fdfeec9a5 | ||
|
|
ffb4b56073 | ||
|
|
b0d71102f3 | ||
|
|
c784c85909 | ||
|
|
b977a80ecc | ||
|
|
f3251a4139 | ||
|
|
d5b82cddc8 | ||
|
|
7ad855a4aa | ||
|
|
9826392819 | ||
|
|
9e8a519bc7 | ||
|
|
2029d47b29 | ||
|
|
0622b4cbc5 | ||
|
|
474432d2a7 | ||
|
|
135afc064b |
@@ -3,18 +3,10 @@
|
||||
// this groovy script is executed by jenkins
|
||||
node {
|
||||
|
||||
|
||||
def gradleInfo
|
||||
def server = Artifactory.server 'project.nes.uni-due.de'
|
||||
def gradleBuild = Artifactory.newGradleBuild()
|
||||
gradleBuild.usesPlugin = true
|
||||
gradleBuild.useWrapper = true
|
||||
|
||||
environment {
|
||||
ANDROID_SDK_ROOT = '/var/lib/android-sdk'
|
||||
}
|
||||
|
||||
|
||||
// checkout code from scm
|
||||
stage('Checkout') {
|
||||
checkout scm
|
||||
@@ -26,34 +18,27 @@ node {
|
||||
// configure the deployer based on the version
|
||||
stage('Configure') {
|
||||
version = sh(returnStdout: true, script: "./gradlew properties -q | grep \"version:\" | awk '{print \$2}'", label: "Detecting project version.").trim()
|
||||
println "Version is: '${version}'"
|
||||
if (version.endsWith("-SNAPSHOT")) {
|
||||
println "Using internal-snapshots for publication."
|
||||
gradleBuild.deployer server: server, repo: 'internal-snapshots'
|
||||
} else {
|
||||
println "Using internal-releases for publication."
|
||||
gradleBuild.deployer server: server, repo: 'internal-releases'
|
||||
release = true;
|
||||
}
|
||||
println "Version is: '${version}'"
|
||||
release = (! version.endsWith("-SNAPSHOT"))
|
||||
}
|
||||
|
||||
// build the source code with gradle
|
||||
stage('Build') {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
|
||||
gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'clean build', switches: switches
|
||||
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD clean build', label: "Building project.")
|
||||
}
|
||||
}
|
||||
|
||||
// deploy the maven publications to artifactory
|
||||
// deploy the maven publications to nexus
|
||||
stage ('Publish') {
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
|
||||
gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'artifactoryPublish', switches: switches
|
||||
}
|
||||
if (env.BRANCH_NAME == "master") {
|
||||
withCredentials([string(credentialsId: 'jenkins-nexus-password', variable: 'NEXUS')]) {
|
||||
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
|
||||
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD -Djenkins.nexus.password=$NEXUS publishAllPublicationsToMavenRepository', label: "Publishing project.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
echo "Skipping deployment for non-release version or non-master branch."
|
||||
echo "Skipping publication for non-release version or non-master branch."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,14 +47,14 @@ node {
|
||||
// release = true; // uncomment to temporary enable snapshot deployments
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
echo "Deploying to production server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "keyfile")]) {
|
||||
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@apps.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear"
|
||||
sh "scp -i ${keyfile} android-app/build/outputs/apk/release/*.apk wildfly@apps.nes.uni-due.de:/opt/android/mowesta/"
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
|
||||
sh 'scp -i $KEYFILE android-app/build/outputs/apk/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
|
||||
}
|
||||
} else if (env.BRANCH_NAME == "master") {
|
||||
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feature/auth") {
|
||||
echo "Deploying to beta server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "keyfile")]) {
|
||||
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@apps.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear"
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
|
||||
}
|
||||
} else {
|
||||
echo "Skipping deployment for non-master branch."
|
||||
|
||||
@@ -82,13 +82,14 @@ configurations {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
defaultConfig {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 29
|
||||
versionCode 11
|
||||
versionCode 12
|
||||
versionName "${version}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
@@ -148,6 +149,7 @@ android {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -86,8 +86,8 @@
|
||||
<string name="collection_title">Hilf MoWeSta</string>
|
||||
<string name="collection_explain">Verwandle Dein Gerät in eine Mobile Wetter Station* und hilf uns dabei herauszufinden, ob wir Wettervorhersagen mit Hilfe von mobilen Messungen durch Freiwillige wie Dich verbessern können!</string>
|
||||
<string name="collection_note_location">* Falls Du mitmachst, erhebt MoWeSta Standortdaten, um den Ort der Messungen zu bestimmen, auch wenn die App geschlossen ist oder nicht verwendet wird. </string>
|
||||
<string name="collection_note_data">* Falls Du mitmachst, überträgt MoWeSta Standort und Messdaten im Hintegrund über Deine mobile Datenverbindung, was sehr teuer sein kann.</string>
|
||||
<string name="collection_note_enable">* Die Datenerfassung und -übertragung im Hintegrund erfolgt nur mit Deiner Zustimmung und Du kannst sie jederzeit über die Einstellungen der Anwendung ein- und ausschalten.</string>
|
||||
<string name="collection_note_data">* Falls Du mitmachst, überträgt MoWeSta Standort und Messdaten im Hintergrund über Deine mobile Datenverbindung, was sehr teuer sein kann.</string>
|
||||
<string name="collection_note_enable">* Die Datenerfassung und -übertragung im Hintergrund erfolgt nur mit Deiner Zustimmung und Du kannst sie jederzeit über die Einstellungen der Anwendung ein- und ausschalten.</string>
|
||||
<string name="collection_note_permission">Zum Mitmachen benötigen wir die Erlaubnis Deinen Standort im Hintergrund zu bestimmen.</string>
|
||||
<string name="collection_on_off">Jetzt mitmachen</string>
|
||||
<string name="collection_button_continue">Lass uns loslegen</string>
|
||||
|
||||
@@ -4,6 +4,11 @@ plugins {
|
||||
|
||||
description = "Mowesta Android Feign"
|
||||
|
||||
// downgrade jackson for Android, since versions > 2.9
|
||||
// will contain module-info.class files that will result
|
||||
// in a large number of android lint warnings
|
||||
versionJackson = "2.9.10"
|
||||
|
||||
dependencies {
|
||||
compile "de.grundid.opendatalab:geojson-jackson:${versionGeojson}"
|
||||
compile "io.swagger:swagger-annotations:${versionSwagger}"
|
||||
|
||||
@@ -2,6 +2,13 @@ apply plugin: 'com.android.library'
|
||||
|
||||
description = "Mowesta Android SDK"
|
||||
|
||||
// remove project version to workaround bugs in
|
||||
// oss-license-plugin that detects local libraries
|
||||
// by checking for a version called "unspecified"
|
||||
// see DependencyTask.groovy on GitHub at
|
||||
// https://github.com/google/play-services-plugins
|
||||
project.version = "unspecified"
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
|
||||
@@ -23,6 +30,12 @@ android {
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
quiet true
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -104,6 +104,7 @@ public abstract class SdkService extends Service {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) {
|
||||
}
|
||||
|
||||
@@ -217,6 +218,7 @@ public abstract class SdkService extends Service {
|
||||
private Handler handler = new Handler();
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onCreate() {
|
||||
Log.d(TAG, "Creating sdk service.");
|
||||
super.onCreate();
|
||||
|
||||
@@ -74,7 +74,7 @@ public class BufferDatabaseTest {
|
||||
Assert.assertEquals(2, b3.get(0).getCoordinate().getLatitude(), 0.0001);
|
||||
Assert.assertEquals(2, b3.get(0).getCoordinate().getLongitude(), 0.0001);
|
||||
Assert.assertEquals(2, b3.get(0).getData().size());
|
||||
|
||||
database.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -79,6 +79,7 @@ public class CacheDatabaseTest {
|
||||
accessor.clearAll();
|
||||
Assert.assertEquals(0, accessor.countLocations());
|
||||
Assert.assertEquals(0, accessor.countNetworks());
|
||||
database.close();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,33 +3,25 @@ apply plugin: 'maven-publish'
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:4.1.1'
|
||||
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.10.0'
|
||||
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.2'
|
||||
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
|
||||
classpath "org.openbakery:xcode-plugin:0.19.1"
|
||||
}
|
||||
repositories {
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/releases';
|
||||
url = 'https://project.nes.uni-due.de/nexus/repository/maven-public';
|
||||
credentials { username = 'public'; password = 'public' }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/snapshots';
|
||||
credentials { username = 'public'; password = 'public' }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
google()
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
apply plugin: 'maven-publish'
|
||||
apply plugin: 'com.jfrog.artifactory'
|
||||
|
||||
// set version for our project
|
||||
group = 'com.mowesta'
|
||||
version = '1.0.11'
|
||||
version = '1.0.12-SNAPSHOT'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
@@ -62,8 +54,9 @@ allprojects {
|
||||
versionAndroidXAppcompat = '1.2.0'
|
||||
versionAndroidXRoom = '2.2.6'
|
||||
versionAndroidXPreference = '1.1.1'
|
||||
versionRobolectric = '4.3.1'
|
||||
|
||||
versionRobolectric = '4.5'
|
||||
//oauth dependencies
|
||||
versionJWT = '0.11.2'
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +80,7 @@ subprojects {
|
||||
publications {
|
||||
maven(MavenPublication) {
|
||||
artifact file('build/outputs/aar/android-sdk-release.aar')
|
||||
version = project.version
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,22 +118,23 @@ subprojects {
|
||||
|
||||
}
|
||||
|
||||
artifactoryPublish.dependsOn('build')
|
||||
artifactoryPublish {
|
||||
publications(publishing.publications.maven);
|
||||
}
|
||||
|
||||
|
||||
repositories {
|
||||
repositories {
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/releases';
|
||||
url = 'https://project.nes.uni-due.de/nexus/repository/maven-public';
|
||||
credentials { username = 'public'; password = 'public' }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/snapshots';
|
||||
credentials { username = 'public'; password = 'public' }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
maven {
|
||||
url = version.endsWith('SNAPSHOT') ?
|
||||
"https://project.nes.uni-due.de/nexus/repository/maven-snapshots" :
|
||||
"https://project.nes.uni-due.de/nexus/repository/maven-releases"
|
||||
credentials { username = 'jenkins'; password = System.properties['jenkins.nexus.password'] }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,11 +143,6 @@ subprojects {
|
||||
|
||||
}
|
||||
|
||||
tasks.register("generatePomFileForMavenPublication") { }
|
||||
|
||||
tasks.register("generatePomFileForMavenPublication") {
|
||||
|
||||
}
|
||||
|
||||
tasks.register("build") {
|
||||
|
||||
}
|
||||
tasks.register("build") { }
|
||||
|
||||
@@ -32,6 +32,7 @@ swagger {
|
||||
'com.mowesta.api.measurement.IMeasurementService',
|
||||
'com.mowesta.api.settings.ISettingsService',
|
||||
'com.mowesta.api.user.IUserService',
|
||||
'com.mowesta.api.oauth2.IOAuth2Service',
|
||||
'com.mowesta.api.version.IVersionService',
|
||||
'com.mowesta.api.weather.IWeatherService',
|
||||
]
|
||||
|
||||
@@ -43,6 +43,11 @@ public class Tags {
|
||||
*/
|
||||
public static final String SETTINGS = "Settings";
|
||||
|
||||
/**
|
||||
* Tag for OAuth.
|
||||
*/
|
||||
public static final String OAUTH = "OAuth";
|
||||
|
||||
|
||||
/**
|
||||
* Prevent instantiation.
|
||||
|
||||
@@ -2,61 +2,66 @@ package com.mowesta.api.access;
|
||||
|
||||
/**
|
||||
* The user roles used by the application.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Roles {
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the admin role.
|
||||
*/
|
||||
public static final String ADMIN = "admin";
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the user role.
|
||||
*/
|
||||
public static final String USER = "user";
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the device role.
|
||||
*/
|
||||
public static final String DEVICE = "device";
|
||||
|
||||
/**
|
||||
* The role granted to valid services that may
|
||||
* use oauth to authenticate for a user.
|
||||
*/
|
||||
public static final String SERVICE = "service";
|
||||
|
||||
/**
|
||||
* Prevents accidential instantiation.
|
||||
*/
|
||||
private Roles() { }
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of roles used for human
|
||||
* subjects.
|
||||
*
|
||||
*
|
||||
* @return The roles used for humans.
|
||||
*/
|
||||
public static String[] getHumanRoles() {
|
||||
return new String[] { ADMIN, USER };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of roles used for machines.
|
||||
*
|
||||
*
|
||||
* @return The roles used for machines.
|
||||
*/
|
||||
public static String[] getMachineRoles() {
|
||||
return new String[] { DEVICE };
|
||||
return new String[] { DEVICE, SERVICE };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of all roles.
|
||||
*
|
||||
*
|
||||
* @return The names of all roles.
|
||||
*/
|
||||
public static String[] getAllRoles() {
|
||||
return new String[] { ADMIN, USER, DEVICE };
|
||||
return new String[] { ADMIN, USER, DEVICE, SERVICE };
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@XmlRootElement
|
||||
@ApiModel(description="Represents an authorization grant. The AccessCode is only used once to get an AuthorizationToken/RequestToken pair.")
|
||||
public class AuthorizationResponse {
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="The Access Code.", required=true)
|
||||
private String accessCode;
|
||||
|
||||
public String getAccessCode() {
|
||||
return accessCode;
|
||||
}
|
||||
|
||||
public void setAccessCode(String accessCode) {
|
||||
this.accessCode = accessCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.mowesta.api.Tags;
|
||||
import com.mowesta.api.access.Authorizations;
|
||||
import com.mowesta.api.access.Roles;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Authorization;
|
||||
|
||||
/**
|
||||
* A service to authenticate with the oauth2 protocol.
|
||||
*
|
||||
* @author Tobias Stottrop
|
||||
*/
|
||||
@Api
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON })
|
||||
@Path("/")
|
||||
public interface IOAuth2Service {
|
||||
|
||||
|
||||
@GET
|
||||
@Path("oauth2/authorize")
|
||||
@ApiOperation(value = "Use this endpoint to authenticate a user with a social provider. Will return an Access- and Refreshtoken.", authorizations = { @Authorization(Authorizations.USER)}, tags = {Tags.DEFAULT, Tags.OAUTH})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Access token created successfully.", response = AuthorizationResponse.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message = "Error creating AccessCode."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_UNAUTHORIZED, message = "User was not authorized.")
|
||||
})
|
||||
@RolesAllowed({Roles.USER})
|
||||
Response getAccessCode(
|
||||
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
|
||||
@ApiParam(value = "Endpoint to which should be redirected.", required = true) @QueryParam(value = "redirect_uri") URI redirect_uri,
|
||||
@ApiParam(value = "Indicates the type of response that should be returned.", required = true) @QueryParam(value="response_type") String response_type,
|
||||
@ApiParam(value = "Internal state of service which wants to authenticate.", required = true) @QueryParam(value="state") String state,
|
||||
@ApiParam(value = "Scope of access.", required = true) @QueryParam(value="scope") String scope
|
||||
);
|
||||
|
||||
|
||||
@POST
|
||||
@Path("oauth2/token")
|
||||
@ApiOperation(value = "Use this endpoint to get an Access Token.", tags = {Tags.DEFAULT, Tags.OAUTH})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_FOUND, message = "Access token created successfully.", response = TokenResponse.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request.")
|
||||
})
|
||||
@RolesAllowed({Roles.SERVICE})
|
||||
Response getAccessRefreshTokenPair(
|
||||
@ApiParam(value = "Grant Type.", required = true) @QueryParam(value = "grant_type") String grant_type,
|
||||
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
|
||||
@ApiParam(value = "Client secret.", required = true) @QueryParam(value = "client_secret") String client_secret,
|
||||
@ApiParam(value = "Access Code.", required = false) @QueryParam(value="code") String code,
|
||||
@ApiParam(value = "Refresh Token.", required = false) @QueryParam(value = "refresh_token") String refresh_token
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@XmlRootElement
|
||||
@ApiModel(description="Represents a token response.")
|
||||
public class TokenResponse {
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="type of token", required=true)
|
||||
private String token_type;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="expiration in seconds", required=false)
|
||||
private long expires_in;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="The access token", required=true)
|
||||
private String access_token;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="The refresh token.", required=false)
|
||||
private String refresh_token;
|
||||
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="The granted scope.", required=false)
|
||||
private String scope;
|
||||
|
||||
public long getExpires_in() {
|
||||
return expires_in;
|
||||
}
|
||||
|
||||
public void setExpires_in(long expires_in) {
|
||||
this.expires_in = expires_in;
|
||||
}
|
||||
|
||||
public String getAccess_token() {
|
||||
return access_token;
|
||||
}
|
||||
|
||||
public void setAccess_token(String access_token) {
|
||||
this.access_token = access_token;
|
||||
}
|
||||
|
||||
public String getRefresh_token() {
|
||||
return refresh_token;
|
||||
}
|
||||
|
||||
public void setRefresh_token(String refresh_token) {
|
||||
this.refresh_token = refresh_token;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
public String getToken_type() {
|
||||
return token_type;
|
||||
}
|
||||
|
||||
public void setToken_type(String token_type) {
|
||||
this.token_type = token_type;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package com.mowesta.api.weather;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@@ -80,6 +80,13 @@ public class WeatherCondition {
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value="The wind speed at ten meters above the ground in meters per second.", required=true)
|
||||
private double windSpeed;
|
||||
|
||||
/**
|
||||
* The maximal wind speed 10 meter above the ground.
|
||||
*/
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value="The maximal wind speed at ten meters above the ground in meters per second.", required=true)
|
||||
private double maxWindSpeed;
|
||||
|
||||
/**
|
||||
* The cloud cover in percent from 0 (no clouds) to 1 (just clouds).
|
||||
@@ -403,5 +410,19 @@ public class WeatherCondition {
|
||||
public void setSnowDepth(double snowDepth) {
|
||||
this.snowDepth = snowDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maxWindSpeed.
|
||||
*
|
||||
* @return The maxWindSpeed.
|
||||
*/
|
||||
public double getMaxWindSpeed() { return maxWindSpeed; }
|
||||
|
||||
/**
|
||||
* Sets the maxWindSpeed.
|
||||
*
|
||||
* @param maxWindSpeed The maxWindSpeed to set.
|
||||
*/
|
||||
public void setMaxWindSpeed(double maxWindSpeed) { this.maxWindSpeed = maxWindSpeed; }
|
||||
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ description = 'Mowesta Alexa Service'
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation project(path: ':service-war')
|
||||
providedCompile project(':service-ejb')
|
||||
compile "com.amazon.alexa:ask-sdk:2.37.1"
|
||||
|
||||
@@ -14,6 +15,11 @@ dependencies {
|
||||
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
|
||||
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
|
||||
|
||||
compile "io.jsonwebtoken:jjwt-api:0.11.2"
|
||||
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
|
||||
compile "org.bouncycastle:bcprov-jdk15on:1.60"
|
||||
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
|
||||
|
||||
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
}
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
package com.mowesta.service.alexa;
|
||||
|
||||
import com.amazon.ask.Skill;
|
||||
import com.amazon.ask.Skills;
|
||||
import com.amazon.ask.servlet.SkillServlet;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.service.alexa.impl.CancelandStopIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.ClothingRecommendationIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.CurrentWeatherIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.HelloWorldIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.HelpIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.LaunchRequestHandler;
|
||||
import com.mowesta.service.alexa.impl.SessionEndedRequestHandler;
|
||||
import com.mowesta.service.alexa.impl.WeatherForecastIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.WeatherstationIntentHandler;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -18,15 +23,14 @@ import java.util.logging.Logger;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@RequestScoped
|
||||
public class WrapperServlet extends HttpServlet {
|
||||
public class AlexaServlet extends HttpServlet {
|
||||
|
||||
private HttpServlet servlet;
|
||||
|
||||
@@ -37,6 +41,18 @@ public class WrapperServlet extends HttpServlet {
|
||||
@Inject
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
@Inject
|
||||
UserSessionBean userSessionBean;
|
||||
|
||||
@Inject
|
||||
DeviceSessionBean deviceSessionBean;
|
||||
|
||||
@Inject
|
||||
MeasurementSessionBean measurementSessionBean;
|
||||
|
||||
@Inject
|
||||
protected EntityManager entityManager;
|
||||
|
||||
Logger log = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
@@ -61,13 +77,14 @@ public class WrapperServlet extends HttpServlet {
|
||||
return new SkillServlet(Skills.standard()
|
||||
.addRequestHandlers(
|
||||
new CancelandStopIntentHandler(),
|
||||
new HelloWorldIntentHandler(),
|
||||
new HelpIntentHandler(),
|
||||
new LaunchRequestHandler(),
|
||||
new SessionEndedRequestHandler(),
|
||||
new CurrentWeatherIntentHandler(locationSessionBean, weatherSessionBean))
|
||||
new CurrentWeatherIntentHandler(locationSessionBean, weatherSessionBean),
|
||||
new WeatherForecastIntentHandler(locationSessionBean, weatherSessionBean),
|
||||
new WeatherstationIntentHandler(userSessionBean, deviceSessionBean, measurementSessionBean, entityManager),
|
||||
new ClothingRecommendationIntentHandler(locationSessionBean, weatherSessionBean))
|
||||
.withSkillId("amzn1.ask.skill.208278db-dd0c-477e-9946-5ebe634831aa")
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
import com.mowesta.api.Language;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.SearchContext;
|
||||
import com.mowesta.api.location.Location;
|
||||
import com.mowesta.api.location.LocationHierarchyPage;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.joda.time.LocalDateTime;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
/**
|
||||
* Recommends clothing to the user for today / tomorrow / the day after for a location.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class ClothingRecommendationIntentHandler implements IntentRequestHandler {
|
||||
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
LocationWeatherService locationWeatherService;
|
||||
|
||||
ClothingWeatherToStringConverter clothingWeatherToStringConverter = new ClothingWeatherToStringConverter();
|
||||
|
||||
|
||||
public ClothingRecommendationIntentHandler(LocationSessionBean locationSessionBean, WeatherSessionBean weatherSessionBean) {
|
||||
this.locationSessionBean = locationSessionBean;
|
||||
this.weatherSessionBean = weatherSessionBean;
|
||||
locationWeatherService = new LocationWeatherService(this.locationSessionBean, this.weatherSessionBean);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("ClothingRecommendationIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
|
||||
String speechText = "";
|
||||
String city = intentRequest.getIntent().getSlots().get("Stadt").getValue();
|
||||
|
||||
String uppercaseCity ="";
|
||||
if(city!=null) uppercaseCity= city.substring(0, 1).toUpperCase() + city.substring(1);
|
||||
|
||||
String timeslot = intentRequest.getIntent().getSlots().get("Zeitpunkt").getValue();
|
||||
int timebegin = getTime(timeslot);
|
||||
int timeend;
|
||||
if(timebegin>=24) {
|
||||
timeend = timebegin+24;
|
||||
} else {
|
||||
timeend = 24;
|
||||
}
|
||||
|
||||
Location location = null;
|
||||
if(city ==null){
|
||||
location = locationWeatherService.getGeoLocation(input);
|
||||
}else{
|
||||
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 60), new SearchContext(Language.GERMAN), city);
|
||||
location = locationWeatherService.getLocation(intentRequest, locationHierarchyPage);
|
||||
}
|
||||
|
||||
|
||||
if (location == null && city!=null) {
|
||||
String errorText = "Die Stadt " + uppercaseCity + " wurde nicht gefunden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
} else if (location == null && city == null){
|
||||
String errorText = "Dein aktueller Ort konnte nicht gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
WeatherForecast weatherForecast = weatherSessionBean.getForecast(location.getCoordinate());
|
||||
|
||||
if (weatherForecast != null) {
|
||||
Double maxTemperature = null;
|
||||
Double maxWindspeed = null;
|
||||
Map<WeatherType, Integer> weatherTypeMap = new HashMap<WeatherType, Integer>();
|
||||
|
||||
for (int i = 0; i < weatherForecast.getConditions().size(); i++) {
|
||||
|
||||
WeatherCondition condition = weatherForecast.getConditions().get(i);
|
||||
|
||||
if (timebegin!=-1 && condition.getHour() >= timebegin && condition.getHour() < timeend) {
|
||||
|
||||
if (maxTemperature == null || condition.getTemperature() > maxTemperature) {
|
||||
maxTemperature = weatherForecast.getConditions().get(i).getTemperature();
|
||||
}
|
||||
|
||||
if (weatherTypeMap.isEmpty() || !weatherTypeMap.containsKey(condition.getType())) {
|
||||
weatherTypeMap.put(condition.getType(), clothingWeatherToStringConverter.setPriorityOfWeather(condition.getType()));
|
||||
}
|
||||
if(maxWindspeed == null || condition.getWindSpeed() > maxWindspeed ){
|
||||
maxWindspeed = weatherForecast.getConditions().get(i).getWindSpeed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(city!=null){
|
||||
speechText += "In " + uppercaseCity + " empfehle ich dir "+timeslot;
|
||||
} else {
|
||||
speechText += "Ich empfehle dir " + timeslot;
|
||||
}
|
||||
|
||||
|
||||
if(maxTemperature != null) {
|
||||
if(maxTemperature<=10){
|
||||
speechText+= " warme Kleidung";
|
||||
}else if(maxTemperature <= 20){
|
||||
speechText+= " eine Jacke oder Weste";
|
||||
}else if(maxTemperature <= 30){
|
||||
speechText+= " eine leichte Jacke";
|
||||
}else if(maxTemperature >30){
|
||||
speechText += " leichte Kleidung";
|
||||
}
|
||||
}
|
||||
|
||||
if(!weatherTypeMap.isEmpty()) {
|
||||
|
||||
Map.Entry<WeatherType, Integer> maxWeather = Collections.max(weatherTypeMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue));
|
||||
|
||||
speechText += clothingWeatherToStringConverter.convertToString(maxWeather.getKey()) + ".";
|
||||
|
||||
}
|
||||
|
||||
if(maxWindspeed!= null && maxTemperature!= null) {
|
||||
String warning = locationWeatherService.checkForWeatherWarning(maxWindspeed, maxTemperature, maxTemperature);
|
||||
if (!Strings.isBlank(warning)) speechText += " Vorsicht! " + warning;
|
||||
}
|
||||
|
||||
if(maxTemperature == null) {
|
||||
speechText = "Es wurde zurzeit keine Kleidungsempfehlung gefunden.";
|
||||
}
|
||||
|
||||
}else {
|
||||
speechText += "Es wurde zurzeit keine Kleidungsempfehlung gefunden.";
|
||||
}
|
||||
|
||||
|
||||
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("ClothingRecommendationIntent", speechText)
|
||||
.build();
|
||||
}
|
||||
|
||||
private int getTime(String timeslot){
|
||||
LocalDateTime localDateTime = LocalDateTime.now();
|
||||
switch (timeslot) {
|
||||
case "heute":
|
||||
return localDateTime.getHourOfDay();
|
||||
case "morgen":
|
||||
return 24;
|
||||
case "übermorgen":
|
||||
return 48;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
|
||||
/**
|
||||
* Converts each weather type to a specific string or gives it a specific priority.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class ClothingWeatherToStringConverter {
|
||||
public String convertToString(WeatherType weatherType) {
|
||||
String weathercondition = "";
|
||||
|
||||
switch (weatherType) {
|
||||
|
||||
case UNKNOWN:
|
||||
break;
|
||||
case FOG:
|
||||
case FOG_DEPOSITING_RIME:
|
||||
case CLOUDY:
|
||||
case PARTLY_CLOUDY:
|
||||
weathercondition = "";
|
||||
break;
|
||||
case CLEAR_SKY:
|
||||
case MAINLY_CLEAR:
|
||||
weathercondition = " und einen Schutz gegen die Sonne";
|
||||
break;
|
||||
case SNOW_GRAINS:
|
||||
case HEAVY_DRIZZLE:
|
||||
case SLIGHT_DRIZZLE:
|
||||
case MODERATE_DRIZZLE:
|
||||
case RAIN_SHOWER_SLIGHT:
|
||||
case SLIGHT_RAIN_NOT_FREEZING:
|
||||
case SNOW_SHOWER_SLIGHT:
|
||||
case SLIGHT_FALL_OF_SNOWFLAKES:
|
||||
case RAIN_SHOWER_MODERATE_HEAVY:
|
||||
case RAIN_SHOWER_VIOLENT:
|
||||
case HEAVY_RAIN_NOT_FREEZING:
|
||||
case RAIN_FREEZING_SLIGHT:
|
||||
case DRIZZLE_FREEZING_SLIGHT:
|
||||
case THUNDERSTORM_HAIL_HEAVY:
|
||||
case HEAVY_FALL_OF_SNOWFLAKES:
|
||||
case SNOW_SHOWER_MODERATE_HEAVY:
|
||||
case MODERATE_RAIN_NOT_FREEZING:
|
||||
case MODERATE_FALL_OF_SNOWFLAKES:
|
||||
case RAIN_FREEZING_MODERATE_HEAVY:
|
||||
case THUNDERSTORM_SLIGHT_MODERATE:
|
||||
case DRIZZLE_FREEZING_MODERATE_HEAVY:
|
||||
weathercondition = " und einen Regenschirm oder wasserfeste Kleidung";
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
return weathercondition;
|
||||
}
|
||||
|
||||
public int setPriorityOfWeather(WeatherType weatherType){
|
||||
int priority = 0;
|
||||
switch (weatherType) {
|
||||
|
||||
case UNKNOWN:
|
||||
break;
|
||||
case FOG:
|
||||
case FOG_DEPOSITING_RIME:
|
||||
case CLOUDY:
|
||||
case PARTLY_CLOUDY:
|
||||
priority = 1;
|
||||
break;
|
||||
case CLEAR_SKY:
|
||||
case MAINLY_CLEAR:
|
||||
priority = 2;
|
||||
break;
|
||||
case SNOW_GRAINS:
|
||||
case HEAVY_DRIZZLE:
|
||||
case SLIGHT_DRIZZLE:
|
||||
case MODERATE_DRIZZLE:
|
||||
case RAIN_SHOWER_SLIGHT:
|
||||
case SLIGHT_RAIN_NOT_FREEZING:
|
||||
case SNOW_SHOWER_SLIGHT:
|
||||
case SLIGHT_FALL_OF_SNOWFLAKES:
|
||||
case RAIN_SHOWER_MODERATE_HEAVY:
|
||||
case RAIN_SHOWER_VIOLENT:
|
||||
case HEAVY_RAIN_NOT_FREEZING:
|
||||
case RAIN_FREEZING_SLIGHT:
|
||||
case DRIZZLE_FREEZING_SLIGHT:
|
||||
case THUNDERSTORM_HAIL_HEAVY:
|
||||
case HEAVY_FALL_OF_SNOWFLAKES:
|
||||
case SNOW_SHOWER_MODERATE_HEAVY:
|
||||
case MODERATE_RAIN_NOT_FREEZING:
|
||||
case MODERATE_FALL_OF_SNOWFLAKES:
|
||||
case RAIN_FREEZING_MODERATE_HEAVY:
|
||||
case THUNDERSTORM_SLIGHT_MODERATE:
|
||||
case DRIZZLE_FREEZING_MODERATE_HEAVY:
|
||||
priority = 3;
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
return priority;
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,32 @@ import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.Language;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.SearchContext;
|
||||
import com.mowesta.api.location.City;
|
||||
import com.mowesta.api.location.Country;
|
||||
import com.mowesta.api.location.Location;
|
||||
import com.mowesta.api.location.LocationHierarchy;
|
||||
import com.mowesta.api.location.LocationHierarchyPage;
|
||||
import com.mowesta.api.location.State;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
|
||||
/**
|
||||
* Tells the user the current weather for a location.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class CurrentWeatherIntentHandler implements IntentRequestHandler {
|
||||
|
||||
|
||||
@@ -27,9 +39,13 @@ public class CurrentWeatherIntentHandler implements IntentRequestHandler {
|
||||
|
||||
WeatherTypeToStringConverter weatherTypeToStringConverter = new WeatherTypeToStringConverter();
|
||||
|
||||
LocationWeatherService locationWeatherService;
|
||||
|
||||
|
||||
public CurrentWeatherIntentHandler(LocationSessionBean locationSessionBean, WeatherSessionBean weatherSessionBean) {
|
||||
this.locationSessionBean = locationSessionBean;
|
||||
this.weatherSessionBean = weatherSessionBean;
|
||||
locationWeatherService = new LocationWeatherService(this.locationSessionBean, this.weatherSessionBean);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -42,44 +58,54 @@ public class CurrentWeatherIntentHandler implements IntentRequestHandler {
|
||||
|
||||
String speechText = "";
|
||||
String city = intentRequest.getIntent().getSlots().get("Stadt").getValue();
|
||||
String uppercaseCity = city.substring(0, 1).toUpperCase() + city.substring(1);
|
||||
String supplement = "";
|
||||
Coordinate locationCoordinates;
|
||||
|
||||
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 20), new SearchContext(Language.GERMAN), city);
|
||||
|
||||
/*if(intentRequest.getIntent().getSlots().get("Zusatz").getValue()!= null){
|
||||
supplement = intentRequest.getIntent().getSlots().get("Zusatz").getValue();
|
||||
for (Location element: locationHierarchyPage.getElements()) {
|
||||
if( get("STATE").replaceAll("-"," ").toLowerCase().equals(supplement)){
|
||||
element.
|
||||
}
|
||||
}
|
||||
}*/
|
||||
String uppercaseCity ="";
|
||||
if(city!=null) uppercaseCity= city.substring(0, 1).toUpperCase() + city.substring(1);
|
||||
|
||||
|
||||
if (locationHierarchyPage.getElements().size() == 0) {
|
||||
Location location = null;
|
||||
if(city ==null){
|
||||
location = locationWeatherService.getGeoLocation(input);
|
||||
}else {
|
||||
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 60), new SearchContext(Language.GERMAN), city);
|
||||
location = locationWeatherService.getLocation(intentRequest, locationHierarchyPage);
|
||||
}
|
||||
|
||||
if (location == null && city!=null) {
|
||||
String errorText = "Die Stadt " + uppercaseCity + " wurde nicht gefunden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
} else if (location == null && city == null){
|
||||
String errorText = "Dein aktueller Ort konnte nicht gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
locationCoordinates = locationHierarchyPage.getElements().get(0).getCoordinate();
|
||||
WeatherCondition currentWeatherOfLocation = weatherSessionBean.getCondition(locationCoordinates);
|
||||
|
||||
WeatherCondition currentWeatherOfLocation = weatherSessionBean.getCondition(location.getCoordinate());
|
||||
|
||||
if (currentWeatherOfLocation != null) {
|
||||
String temperature = String.valueOf(currentWeatherOfLocation.getTemperature()).replaceAll("\\.", ",");
|
||||
DecimalFormat decimalFormat = new DecimalFormat("#.#");
|
||||
String temperature = String.valueOf(decimalFormat.format(currentWeatherOfLocation.getTemperature())).replaceAll("\\.", ",");
|
||||
String[] splitTemperature = temperature.split(",");
|
||||
if (splitTemperature[1].equals("0")) temperature = splitTemperature[0];
|
||||
if (splitTemperature.length > 1 && splitTemperature[1].equals("0")) temperature = splitTemperature[0];
|
||||
|
||||
String weatherType = weatherTypeToStringConverter.convertToString(currentWeatherOfLocation.getType());
|
||||
|
||||
speechText += "In " + uppercaseCity + " sind zurzeit " + temperature + " Grad" + weatherType + ".";
|
||||
if(city!=null){
|
||||
speechText += "In " + uppercaseCity + " sind zurzeit " + temperature + " Grad" + weatherType + ".";
|
||||
} else {
|
||||
speechText += "Es sind zurzeit " + temperature + " Grad" + weatherType + ".";
|
||||
}
|
||||
|
||||
|
||||
String warning =locationWeatherService.checkForWeatherWarning(currentWeatherOfLocation.getWindSpeed(), currentWeatherOfLocation.getTemperature(), currentWeatherOfLocation.getTemperature());
|
||||
if(!Strings.isBlank(warning)) speechText += " Vorsicht! " + warning;
|
||||
|
||||
} else {
|
||||
speechText += "Es wurde zurzeit kein aktuelles Wetter für " + uppercaseCity + "gefunden.";
|
||||
speechText += "Es wurde zurzeit kein aktuelles Wetter gefunden.";
|
||||
}
|
||||
|
||||
return input.getResponseBuilder()
|
||||
@@ -88,4 +114,5 @@ public class CurrentWeatherIntentHandler implements IntentRequestHandler {
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
|
||||
/**
|
||||
* Converts each weather type to a specific string for the weather forecast.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class ForecastWeatherToStringConverter {
|
||||
|
||||
public String convertToString(WeatherType weatherType) {
|
||||
String weathercondition = "";
|
||||
|
||||
switch (weatherType) {
|
||||
|
||||
case UNKNOWN:
|
||||
break;
|
||||
case FOG:
|
||||
case FOG_DEPOSITING_RIME:
|
||||
weathercondition = " nebelig";
|
||||
break;
|
||||
case CLOUDY:
|
||||
case PARTLY_CLOUDY:
|
||||
weathercondition = " bewölkt";
|
||||
break;
|
||||
case CLEAR_SKY:
|
||||
case MAINLY_CLEAR:
|
||||
weathercondition = " klar am Himmel";
|
||||
break;
|
||||
case SNOW_GRAINS:
|
||||
weathercondition = " Graupelschauer geben";
|
||||
break;
|
||||
case HEAVY_DRIZZLE:
|
||||
weathercondition = " starken Nieselregen geben";
|
||||
break;
|
||||
case SLIGHT_DRIZZLE:
|
||||
weathercondition = " leichten Nieselregen geben";
|
||||
break;
|
||||
case MODERATE_DRIZZLE:
|
||||
weathercondition = " Nieselregen geben";
|
||||
break;
|
||||
case RAIN_SHOWER_SLIGHT:
|
||||
case SLIGHT_RAIN_NOT_FREEZING:
|
||||
weathercondition = " leicht regnen";
|
||||
break;
|
||||
case SNOW_SHOWER_SLIGHT:
|
||||
case SLIGHT_FALL_OF_SNOWFLAKES:
|
||||
weathercondition = " leichten Schneefall geben";
|
||||
break;
|
||||
case RAIN_SHOWER_MODERATE_HEAVY:
|
||||
case RAIN_SHOWER_VIOLENT:
|
||||
case HEAVY_RAIN_NOT_FREEZING:
|
||||
weathercondition = " Starkregen geben";
|
||||
break;
|
||||
case RAIN_FREEZING_SLIGHT:
|
||||
weathercondition = " gefrierenden leichten Regen geben";
|
||||
break;
|
||||
case DRIZZLE_FREEZING_SLIGHT:
|
||||
weathercondition = " gefrierenden leichten Nieselregen geben";
|
||||
break;
|
||||
case THUNDERSTORM_HAIL_HEAVY:
|
||||
weathercondition = " Hagelschauern und Gewitter geben";
|
||||
break;
|
||||
case HEAVY_FALL_OF_SNOWFLAKES:
|
||||
case SNOW_SHOWER_MODERATE_HEAVY:
|
||||
weathercondition = " starken Schneefall geben";
|
||||
break;
|
||||
case MODERATE_RAIN_NOT_FREEZING:
|
||||
weathercondition = " regnen";
|
||||
break;
|
||||
case MODERATE_FALL_OF_SNOWFLAKES:
|
||||
weathercondition = " schneien";
|
||||
break;
|
||||
case RAIN_FREEZING_MODERATE_HEAVY:
|
||||
weathercondition = " gefrierenden Regen geben";
|
||||
break;
|
||||
case THUNDERSTORM_SLIGHT_MODERATE:
|
||||
weathercondition = " mitunter gewittern";
|
||||
break;
|
||||
case DRIZZLE_FREEZING_MODERATE_HEAVY:
|
||||
weathercondition = " gefrierenden Sprühregen geben";
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
|
||||
return weathercondition;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/*
|
||||
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
|
||||
except in compliance with the License. A copy of the License is located at
|
||||
|
||||
http://aws.amazon.com/apache2.0/
|
||||
|
||||
or in the "license" file accompanying this file. This file 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.
|
||||
*/
|
||||
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
|
||||
import com.amazon.ask.model.Response;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
public class HelloWorldIntentHandler implements RequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(intentName("HelloWorldIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
String speechText = "Hello world";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("HelloWorld", speechText)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.PermissionStatus;
|
||||
import com.amazon.ask.model.Permissions;
|
||||
import com.amazon.ask.model.interfaces.geolocation.GeolocationState;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.location.CityPage;
|
||||
import com.mowesta.api.location.Country;
|
||||
import com.mowesta.api.location.Location;
|
||||
import com.mowesta.api.location.LocationHierarchy;
|
||||
import com.mowesta.api.location.LocationHierarchyPage;
|
||||
import com.mowesta.api.location.State;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Service that provides an intent with the location the user is looking for.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class LocationWeatherService {
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
private static final String GEO_PERMISSION = "alexa::devices:all:geolocation:read";
|
||||
|
||||
public LocationWeatherService(LocationSessionBean locationSessionBean, WeatherSessionBean weatherSessionBean) {
|
||||
this.locationSessionBean = locationSessionBean;
|
||||
this.weatherSessionBean = weatherSessionBean;
|
||||
}
|
||||
|
||||
public Location getGeoLocation(HandlerInput input){
|
||||
Location geoLocation = null;
|
||||
Permissions permissions = input.getRequestEnvelope().getSession().getUser().getPermissions();
|
||||
|
||||
if(input.getRequestEnvelope().getContext().getSystem().getDevice().getSupportedInterfaces()
|
||||
.getGeolocation() != null && permissions != null && permissions.getScopes() != null
|
||||
&& permissions.getScopes().get(GEO_PERMISSION).getStatus() == PermissionStatus.GRANTED){
|
||||
|
||||
GeolocationState geo = input.getRequestEnvelope().getContext().getGeolocation();
|
||||
|
||||
|
||||
Coordinate userPosition = new Coordinate(geo.getCoordinate().getLongitudeInDegrees(),geo.getCoordinate().getLatitudeInDegrees());
|
||||
Coordinate secondUserPosition = new Coordinate(geo.getCoordinate().getLongitudeInDegrees()+0.01, geo.getCoordinate().getLatitudeInDegrees()+0.01);
|
||||
|
||||
CityPage cities = locationSessionBean.findCities(new PageConfig(0, 1), userPosition , secondUserPosition );
|
||||
geoLocation = cities.getElements().get(0);
|
||||
|
||||
return geoLocation;
|
||||
|
||||
} else return null;
|
||||
|
||||
|
||||
}
|
||||
public Location getLocation(IntentRequest intentRequest, LocationHierarchyPage locationHierarchyPage) {
|
||||
|
||||
if (locationHierarchyPage.getElements().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (intentRequest.getIntent().getSlots().get("Region").getValue() != null) {
|
||||
return getByRegion(intentRequest.getIntent().getSlots().get("Region").getValue(), intentRequest.getIntent().getSlots().get("Stadt").getValue(), locationHierarchyPage);
|
||||
} else if (intentRequest.getIntent().getSlots().get("Land").getValue() != null) {
|
||||
return getByCountry(intentRequest.getIntent().getSlots().get("Land").getValue(), intentRequest.getIntent().getSlots().get("Stadt").getValue(), locationHierarchyPage);
|
||||
} else return locationHierarchyPage.getElements().get(0);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private Location getByRegion(String regionName, String cityName, LocationHierarchyPage locationHierarchyPage) {
|
||||
for (LocationHierarchy element : locationHierarchyPage.getElements()) {
|
||||
|
||||
if(!locationContainsName(cityName, element)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
State state = null;
|
||||
try {
|
||||
state = locationSessionBean.getCity(element.getId(), true).getState();
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (state == null) continue;
|
||||
|
||||
if (locationContainsName(regionName, state)) {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Location getByCountry(String name, String cityName, LocationHierarchyPage locationHierarchyPage) {
|
||||
|
||||
for (LocationHierarchy element : locationHierarchyPage.getElements()) {
|
||||
|
||||
if(!locationContainsName(cityName, element)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Country country = null;
|
||||
try {
|
||||
country = locationSessionBean.getCity(element.getId(), true).getCountry();
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (country == null) continue;
|
||||
|
||||
if (locationContainsName(name, country)) {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean locationContainsName(String name, Location location) {
|
||||
return location.getNames().values().stream()
|
||||
.map(locationName -> locationName.toLowerCase().replaceAll("-", " "))
|
||||
.anyMatch(locationName -> locationName.equals(name));
|
||||
}
|
||||
|
||||
public String checkForWeatherWarning(double windspeed, double minTemperature, double maxTemperature) {
|
||||
String warning = "";
|
||||
|
||||
if(windspeed>=14 && windspeed<18){
|
||||
warning += "Warnung vor starken Windböen. ";
|
||||
}else if(windspeed>=18 && windspeed <=20){
|
||||
warning += "Warnung vor stürmischem Wind. ";
|
||||
}else if(windspeed>=21 && windspeed <=24){
|
||||
warning += "Warnung vor Sturm. ";
|
||||
}else if(windspeed>=25 && windspeed >=28) {
|
||||
warning += "Warnung vor schwerem Sturm. ";
|
||||
}else if(windspeed>=29 && windspeed >=33){
|
||||
warning += "Warnung vor orkanartigen Sturm. ";
|
||||
}else if(windspeed>33){
|
||||
warning += "Warnung vor einem Orkan. ";
|
||||
}
|
||||
|
||||
if(maxTemperature >= 32) {
|
||||
warning += "Warnung vor Hitze. ";
|
||||
}else if(minTemperature< 0 && minTemperature>=-2){
|
||||
warning += "Warnung vor geringem Frost. ";
|
||||
}else if(minTemperature<-2 && minTemperature>=-5){
|
||||
warning += "Warnung vor mäßigen Frost. ";
|
||||
}else if(minTemperature<-5 && minTemperature>=-10){
|
||||
warning += "Warnung vor mäßigen Frost. ";
|
||||
}else if(minTemperature<-10 && minTemperature>=-15){
|
||||
warning += "Warnung vor strengem Frost. ";
|
||||
}else if(minTemperature<-15){
|
||||
warning += "Warnung vor sehr strengem Frost. ";
|
||||
}
|
||||
|
||||
return warning;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.Language;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.SearchContext;
|
||||
import com.mowesta.api.location.Country;
|
||||
import com.mowesta.api.location.Location;
|
||||
import com.mowesta.api.location.LocationHierarchy;
|
||||
import com.mowesta.api.location.LocationHierarchyPage;
|
||||
import com.mowesta.api.location.State;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDateTime;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
/**
|
||||
* Tells the user the weather for today / tomorrow / the day after for a location.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class WeatherForecastIntentHandler implements IntentRequestHandler {
|
||||
|
||||
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
LocationWeatherService locationWeatherService;
|
||||
|
||||
ForecastWeatherToStringConverter forecastWeatherToStringConverter = new ForecastWeatherToStringConverter();
|
||||
|
||||
public WeatherForecastIntentHandler(LocationSessionBean locationSessionBean, WeatherSessionBean weatherSessionBean) {
|
||||
this.locationSessionBean = locationSessionBean;
|
||||
this.weatherSessionBean = weatherSessionBean;
|
||||
locationWeatherService = new LocationWeatherService(this.locationSessionBean, this.weatherSessionBean);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("WeatherForecastIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
|
||||
|
||||
String speechText = "";
|
||||
String city = intentRequest.getIntent().getSlots().get("Stadt").getValue();
|
||||
|
||||
String uppercaseCity ="";
|
||||
if(city!=null) uppercaseCity= city.substring(0, 1).toUpperCase() + city.substring(1);
|
||||
|
||||
String timeslot = intentRequest.getIntent().getSlots().get("Zeitpunkt").getValue();
|
||||
int timebegin = getTime(timeslot);
|
||||
int timeend;
|
||||
if(timebegin>=24) {
|
||||
timeend = timebegin+24;
|
||||
} else {
|
||||
timeend = 24;
|
||||
}
|
||||
|
||||
Location location = null;
|
||||
if(city ==null){
|
||||
location = locationWeatherService.getGeoLocation(input);
|
||||
}else{
|
||||
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 60), new SearchContext(Language.GERMAN), city);
|
||||
location = locationWeatherService.getLocation(intentRequest, locationHierarchyPage);
|
||||
}
|
||||
|
||||
|
||||
if (location == null && city!=null) {
|
||||
String errorText = "Die Stadt " + uppercaseCity + " wurde nicht gefunden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
} else if (location == null && city == null){
|
||||
String errorText = "Dein aktueller Ort konnte nicht gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
WeatherForecast weatherForecast = weatherSessionBean.getForecast(location.getCoordinate());
|
||||
|
||||
|
||||
if (weatherForecast != null) {
|
||||
Double minTemperature = null;
|
||||
Double maxTemperature = null;
|
||||
Double maxWindspeed = null;
|
||||
Map<WeatherType, Integer> weatherTypeMap = new HashMap<WeatherType, Integer>();
|
||||
|
||||
for (int i = 0; i < weatherForecast.getConditions().size(); i++) {
|
||||
|
||||
WeatherCondition condition = weatherForecast.getConditions().get(i);
|
||||
|
||||
if (timebegin!=-1 && condition.getHour() >= timebegin && condition.getHour() < timeend) {
|
||||
if (minTemperature == null || condition.getTemperature() < minTemperature) {
|
||||
minTemperature = weatherForecast.getConditions().get(i).getTemperature();
|
||||
}
|
||||
|
||||
if (maxTemperature == null || condition.getTemperature() > maxTemperature) {
|
||||
maxTemperature = weatherForecast.getConditions().get(i).getTemperature();
|
||||
}
|
||||
|
||||
if(maxWindspeed == null || condition.getWindSpeed() > maxWindspeed){
|
||||
maxWindspeed = weatherForecast.getConditions().get(i).getWindSpeed();
|
||||
}
|
||||
|
||||
if (weatherTypeMap.isEmpty()) {
|
||||
weatherTypeMap.put(condition.getType(), 1);
|
||||
} else if (weatherTypeMap.containsKey(condition.getType())) {
|
||||
weatherTypeMap.put(condition.getType(), weatherTypeMap.get(condition.getType()) + 1);
|
||||
} else {
|
||||
weatherTypeMap.put(condition.getType(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if(city!=null) {
|
||||
speechText += "In " + uppercaseCity + " beträgt " + timeslot + " die ";
|
||||
} else speechText += timeslot.substring(0, 1).toUpperCase() + timeslot.substring(1) + " beträgt die ";
|
||||
|
||||
if(maxTemperature != null) {
|
||||
String maxTemp = getTemperature(maxTemperature);
|
||||
|
||||
speechText += "Maximaltemperatur " + maxTemp + " Grad";
|
||||
}
|
||||
|
||||
if(maxTemperature != null && minTemperature != null) {
|
||||
speechText += " und die ";
|
||||
}
|
||||
|
||||
if(minTemperature != null) {
|
||||
String minTemp = getTemperature(minTemperature);
|
||||
|
||||
speechText += "Minimaltemperatur " + minTemp + " Grad";
|
||||
}
|
||||
|
||||
speechText += ".";
|
||||
|
||||
if(!weatherTypeMap.isEmpty()) {
|
||||
Map.Entry<WeatherType, Integer> maxWeather = Collections.max(weatherTypeMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue));
|
||||
weatherTypeMap.remove(maxWeather.getKey());
|
||||
String maxWeatherString = forecastWeatherToStringConverter.convertToString(maxWeather.getKey());
|
||||
String secMaxWeatherString = "";
|
||||
if(!weatherTypeMap.isEmpty()){
|
||||
Map.Entry<WeatherType, Integer> secMaxWeather = Collections.max(weatherTypeMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue));
|
||||
secMaxWeatherString = forecastWeatherToStringConverter.convertToString(secMaxWeather.getKey());
|
||||
}
|
||||
|
||||
speechText += " Zudem wird es " + maxWeatherString;
|
||||
if(!Strings.isBlank(secMaxWeatherString) && !maxWeatherString.equals(secMaxWeatherString)) speechText+= " und teilweise wird es" + secMaxWeatherString;
|
||||
speechText += ".";
|
||||
|
||||
if(maxWindspeed!= null && minTemperature!=null && maxTemperature!= null){
|
||||
String warning =locationWeatherService.checkForWeatherWarning(maxWindspeed, minTemperature, maxTemperature);
|
||||
if(!Strings.isBlank(warning)) speechText += " Vorsicht! " + warning;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if(maxTemperature == null && minTemperature == null) {
|
||||
speechText = "Es wurde zurzeit keine Wettervorhersage gefunden.";
|
||||
}
|
||||
} else {
|
||||
speechText += "Es wurde zurzeit keine Wettervorhersage gefunden.";
|
||||
}
|
||||
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("CurrentWeather", speechText)
|
||||
.build();
|
||||
}
|
||||
|
||||
private String getTemperature(Double temperature) {
|
||||
DecimalFormat decimalFormat = new DecimalFormat("#.#");
|
||||
String maxTemp = String.valueOf(decimalFormat.format(temperature)).replaceAll("\\.", ",");
|
||||
String[] splitMaxTemp = maxTemp.split(",");
|
||||
if (splitMaxTemp.length > 1 && splitMaxTemp[1].equals("0")) maxTemp = splitMaxTemp[0];
|
||||
return maxTemp;
|
||||
}
|
||||
|
||||
private int getTime(String timeslot){
|
||||
LocalDateTime localDateTime = LocalDateTime.now();
|
||||
switch (timeslot) {
|
||||
case "heute":
|
||||
return localDateTime.getHourOfDay();
|
||||
case "morgen":
|
||||
return 24;
|
||||
case "übermorgen":
|
||||
return 48;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@ package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
|
||||
/**
|
||||
* Converts each weather type to a specific string for the current weather.
|
||||
*
|
||||
* @author Katharina
|
||||
*/
|
||||
public class WeatherTypeToStringConverter {
|
||||
|
||||
public String convertToString(WeatherType weatherType){
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.DevicePage;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.OAuthSecretEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.TypedQuery;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
public class WeatherstationIntentHandler implements IntentRequestHandler {
|
||||
|
||||
UserSessionBean userSessionBean;
|
||||
DeviceSessionBean deviceSessionBean;
|
||||
MeasurementSessionBean measurementSessionBean;
|
||||
EntityManager entityManager;
|
||||
|
||||
Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
public WeatherstationIntentHandler(UserSessionBean userSessionBean,
|
||||
DeviceSessionBean deviceSessionBean,
|
||||
MeasurementSessionBean measurementSessionBean,
|
||||
EntityManager entityManager) {
|
||||
this.userSessionBean = userSessionBean;
|
||||
this.deviceSessionBean = deviceSessionBean;
|
||||
this.measurementSessionBean = measurementSessionBean;
|
||||
this.entityManager = entityManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("WeatherstationIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
|
||||
logger.log(Level.INFO, "WeatherStationIntent started");
|
||||
String accessToken = input.getRequestEnvelope().getContext().getSystem().getUser().getAccessToken();
|
||||
logger.log(Level.INFO, "AccessToken: " + accessToken);
|
||||
|
||||
|
||||
|
||||
|
||||
if (accessToken == null) {
|
||||
String errorText = "Du musst mit angemeldet sein, um diesen Service nutzen zu können. " +
|
||||
"Bitte gehe in die Alexa App und melde dich an.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withLinkAccountCard()
|
||||
.build();
|
||||
} else {
|
||||
|
||||
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
|
||||
if (secretKey.isPresent()) {
|
||||
OAuthSecretEntity secretEntity = secretKey.get();
|
||||
Claims claims = Jwts
|
||||
.parserBuilder()
|
||||
.setSigningKey(secretEntity.getSecret().getBytes())
|
||||
.build()
|
||||
.parseClaimsJws(accessToken)
|
||||
.getBody();
|
||||
String userId = claims.getId();
|
||||
logger.log(Level.INFO, "UserID: " + userId);
|
||||
|
||||
UserEntity userEntity = userSessionBean.findUser(userId);
|
||||
|
||||
if (userEntity != null) {
|
||||
logger.log(Level.INFO, "UserEntity: " + userEntity.getName());
|
||||
DevicePage devicePage = null;
|
||||
try {
|
||||
devicePage = deviceSessionBean.getAllDevicesForCurrentUser(new PageConfig(0, 60), true);
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "device at 0: " + devicePage.getElements().get(0));
|
||||
|
||||
if (devicePage == null) {
|
||||
String errorText = "Es konnten keine Geräte gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
Device device = devicePage.getElements().get(0);
|
||||
Measurement measurement = null;
|
||||
try {
|
||||
measurement = measurementSessionBean.getDeviceMeasurements(device.getId(), new TimeRange(System.currentTimeMillis(), System.currentTimeMillis() + 10),
|
||||
new PageConfig(0, 1), false).getElements().get(0);
|
||||
|
||||
logger.log(Level.INFO, "measurement: " + measurement.getTemperature());
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (EntityForbiddenException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
String measurementString = "";
|
||||
if (measurement != null) {
|
||||
measurementString += "Die Temperatur beträgt " + measurement.getTemperature() + " Grad.";
|
||||
} else measurementString += "Es wurde keine Messung gefunden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(measurementString)
|
||||
.withSimpleCard("Measurement", measurementString)
|
||||
.build();
|
||||
|
||||
} else {
|
||||
String errorText = "Der Nutzer konnte nicht gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
} else {
|
||||
String errorText = "Es ist ein Fehler aufgetreten. Bitte versuche es später nochmal.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
|
||||
TypedQuery<OAuthSecretEntity> query = entityManager.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
|
||||
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
|
||||
|
||||
return oAuthSecretEntityList.stream()
|
||||
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
|
||||
.findAny();
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<display-name>alexaservlet</display-name>
|
||||
<servlet>
|
||||
<servlet-name>alexaservlet</servlet-name>
|
||||
<servlet-class>com.mowesta.service.alexa.WrapperServlet</servlet-class>
|
||||
<servlet-class>com.mowesta.service.alexa.AlexaServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
<servlet-mapping>
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
package com.mowesta.data.dwd;
|
||||
|
||||
import com.mowesta.data.ftp.FileStatus;
|
||||
import com.mowesta.data.ftp.FileStatusListener;
|
||||
import com.mowesta.data.ftp.FtpFolderSync;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.grib2.template.product.ForecastProduct;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.FileNameComparator;
|
||||
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
@@ -13,20 +27,6 @@ import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
||||
|
||||
import com.mowesta.data.ftp.FileStatus;
|
||||
import com.mowesta.data.ftp.FileStatusListener;
|
||||
import com.mowesta.data.ftp.FtpFolderSync;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.grib2.template.product.ForecastProduct;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.FileNameComparator;
|
||||
|
||||
/**
|
||||
* Represents a numeric weather prediction from DWD.
|
||||
*/
|
||||
@@ -284,6 +284,11 @@ public class NumericPrediction {
|
||||
* The meridional wind at 10m height.
|
||||
*/
|
||||
V10M("v_10m", false),
|
||||
|
||||
/**
|
||||
* The maximum wind speed at 10m height.
|
||||
*/
|
||||
VMAX_10M("vmax_10m", false),
|
||||
|
||||
/**
|
||||
* The weather interpretation type.
|
||||
@@ -443,7 +448,7 @@ public class NumericPrediction {
|
||||
type.getSystem().isComputed()?Variable.RLAT:Variable.CLAT,
|
||||
type.getSystem().isComputed()?Variable.RLON:Variable.CLON,
|
||||
Variable.HSURF, Variable.PLCOV, Variable.SOILTYP, Variable.PREC, Variable.T2M, Variable.CLCT, Variable.CLDEPTH,
|
||||
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
|
||||
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.VMAX_10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -12,6 +12,12 @@ dependencies {
|
||||
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
|
||||
compile "org.infinispan:infinispan-query:${versionInfinispan}"
|
||||
|
||||
compile "io.jsonwebtoken:jjwt-api:0.11.2"
|
||||
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
|
||||
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
|
||||
compile "org.bouncycastle:bcprov-jdk15on:1.60"
|
||||
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
|
||||
|
||||
compileOnly "org.hibernate:hibernate-search-orm:${versionHibernateSearch}"
|
||||
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
|
||||
@@ -74,3 +80,4 @@ compileJava {
|
||||
options.annotationProcessorPath = configurations.annotationProcessor
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import java.security.Key;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.NamedQueries;
|
||||
import javax.persistence.NamedQuery;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.UniqueConstraint;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* The entity that represents an OAuthSecret.
|
||||
*
|
||||
* @author Tobias S.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name="oauthsecret", uniqueConstraints=@UniqueConstraint(columnNames= {"secret"}))
|
||||
@NamedQueries({
|
||||
@NamedQuery(name = "OAuth.findAllSecrets", query = "select o from OAuthSecretEntity o")
|
||||
})
|
||||
public class OAuthSecretEntity extends AbstractEntity {
|
||||
|
||||
/**
|
||||
* The serialization version.
|
||||
*/
|
||||
private static final long serialVersionUID = 287153745987186120L;
|
||||
|
||||
@NotNull
|
||||
private String secret;
|
||||
|
||||
@NotNull
|
||||
private long timeValid;
|
||||
|
||||
@NotNull
|
||||
private boolean valid;
|
||||
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
}
|
||||
|
||||
public void setSecret(String secret) {
|
||||
this.secret = secret;
|
||||
}
|
||||
|
||||
public long getTimeValid() {
|
||||
return timeValid;
|
||||
}
|
||||
|
||||
public void setTimeValid(long timeValid) {
|
||||
this.timeValid = timeValid;
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
public void setValid(boolean valid) {
|
||||
this.valid = valid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedQueries;
|
||||
import javax.persistence.NamedQuery;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.UniqueConstraint;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
|
||||
/**
|
||||
* The entity that represents Refreshtoken.
|
||||
*
|
||||
* @author Tobias S.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name="authtoken", uniqueConstraints=@UniqueConstraint(columnNames= {"user_id", "refreshtoken"}))
|
||||
@NamedQueries({
|
||||
@NamedQuery(name="findRefreshToken", query="select r from RefreshTokenEntity r where r.refreshToken=:refreshToken"),
|
||||
})
|
||||
public class RefreshTokenEntity extends AbstractEntity {
|
||||
|
||||
/**
|
||||
* The serialization version.
|
||||
*/
|
||||
private static final long serialVersionUID = 287453795983186000L;
|
||||
|
||||
/**
|
||||
* The user that has this refreshtoken.
|
||||
*/
|
||||
@NotNull
|
||||
@ManyToOne
|
||||
@JoinColumn(name="user_id")
|
||||
private UserEntity user;
|
||||
|
||||
/**
|
||||
* The refreshtoken.
|
||||
*/
|
||||
@NotNull
|
||||
@JoinColumn(name="refreshtoken")
|
||||
private String refreshToken;
|
||||
|
||||
/**
|
||||
* The service name.
|
||||
*/
|
||||
private String serviceName;
|
||||
|
||||
/**
|
||||
* Returns the user.
|
||||
*
|
||||
* @return The user.
|
||||
*/
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the user.
|
||||
*
|
||||
* @param user The user to set.
|
||||
*/
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the refreshtoken.
|
||||
*
|
||||
* @return The refreshtoken.
|
||||
*/
|
||||
public String getRefreshToken() {
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the refreshtoken.
|
||||
*
|
||||
* @param refreshToken The Refreshtoken to set.
|
||||
*/
|
||||
public void setRefreshToken(String refreshToken) {
|
||||
this.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the refreshtoken.
|
||||
*
|
||||
* @return The refreshtoken.
|
||||
*/
|
||||
public String getServiceName() {
|
||||
return serviceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name of the service.
|
||||
*
|
||||
* @param serviceName The servicename to set.
|
||||
*/
|
||||
public void setServiceName(String serviceName) {
|
||||
this.serviceName = serviceName;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -28,8 +30,6 @@ import javax.persistence.criteria.Root;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
|
||||
/**
|
||||
* The entity to store users.
|
||||
*
|
||||
@@ -87,7 +87,14 @@ public class UserEntity extends AbstractEntity {
|
||||
@CollectionTable(name = "user_location")
|
||||
@ElementCollection(fetch = FetchType.LAZY)
|
||||
private List<EmbeddedLocation> locations;
|
||||
|
||||
|
||||
/**
|
||||
* The refresh tokens of the user.
|
||||
*/
|
||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
|
||||
private Set<RefreshTokenEntity> refreshTokens;
|
||||
|
||||
|
||||
/**
|
||||
* The iterations of the password hash.
|
||||
*/
|
||||
@@ -104,12 +111,13 @@ public class UserEntity extends AbstractEntity {
|
||||
*/
|
||||
@NotNull
|
||||
private byte[] salt;
|
||||
|
||||
|
||||
/**
|
||||
* A flag that indicates that the account is deactivated.
|
||||
*/
|
||||
private boolean suspended;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the name.
|
||||
*
|
||||
@@ -271,6 +279,24 @@ public class UserEntity extends AbstractEntity {
|
||||
public void setSuspended(boolean suspended) {
|
||||
this.suspended = suspended;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Refreshtokens.
|
||||
*
|
||||
* @return The refreshTokens.
|
||||
*/
|
||||
public Set<RefreshTokenEntity> getRefreshTokens() {
|
||||
return refreshTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the refreshtokens.
|
||||
*
|
||||
* @param refreshTokens The refreshTokens to set.
|
||||
*/
|
||||
public void setRefreshTokens(Set<RefreshTokenEntity> refreshTokens) {
|
||||
this.refreshTokens = refreshTokens;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.mowesta.service.entity;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectOutput;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.weather.SoilType;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.api.weather.WindDirection;
|
||||
|
||||
import org.apache.lucene.search.Query;
|
||||
import org.apache.lucene.search.Sort;
|
||||
@@ -21,13 +23,11 @@ import org.infinispan.commons.marshall.Externalizer;
|
||||
import org.infinispan.commons.marshall.SerializeWith;
|
||||
import org.infinispan.query.SearchManager;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.weather.SoilType;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.api.weather.WindDirection;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectOutput;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A container to store weather forecasts in an infinispan cache with
|
||||
@@ -136,6 +136,7 @@ public class WeatherForecastContainer implements Coordinates {
|
||||
result.setType(WeatherType.values()[in.readInt()]);
|
||||
result.setWindDirection(WindDirection.values()[in.readInt()]);
|
||||
result.setWindSpeed(in.readDouble());
|
||||
result.setMaxWindSpeed(in.readDouble());
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -161,6 +162,7 @@ public class WeatherForecastContainer implements Coordinates {
|
||||
out.writeInt(c.getType().ordinal());
|
||||
out.writeInt(c.getWindDirection().ordinal());
|
||||
out.writeDouble(c.getWindSpeed());
|
||||
out.writeDouble(c.getMaxWindSpeed());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -21,24 +21,24 @@ import com.mowesta.service.session.sync.LocationSyncSessionBean;
|
||||
/**
|
||||
* A bean that is executed by the startup bean to initialize the database
|
||||
* with a default set of roles and user accounts, unless they exist already.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Stateless
|
||||
public class DataSessionBean {
|
||||
|
||||
|
||||
@Inject
|
||||
protected Logger log;
|
||||
|
||||
|
||||
@Inject
|
||||
protected EntityManager em;
|
||||
|
||||
|
||||
@Inject
|
||||
protected LocationSyncSessionBean syncSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected ShutdownSessionBean shutdownSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected WeatherSessionBean forecastSession;
|
||||
|
||||
@@ -65,11 +65,12 @@ public class DataSessionBean {
|
||||
addRole(Roles.ADMIN, "Grants admin privileges.");
|
||||
addRole(Roles.USER, "Grants user privileges.");
|
||||
addRole(Roles.DEVICE, "Grants device privileges.");
|
||||
addRole(Roles.SERVICE, "Grants service privileges.");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a role, if it is not present already, and returns it.
|
||||
*
|
||||
*
|
||||
* @param name The name of the role.
|
||||
* @param description The description of the role.
|
||||
* @return The role that was present or has been added.
|
||||
@@ -99,11 +100,12 @@ public class DataSessionBean {
|
||||
log.log(Level.INFO, "Initializing users.");
|
||||
initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new String[] { Roles.ADMIN, Roles.USER});
|
||||
initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER });
|
||||
initUser("alexa", "Amazon Alexa", "p8exqbInnyYKe5YkLIDVbKftiNnXbtHTVNohEYSqUfFXF66NuVnrF6psufLPg2BuNRdTjqHkSlz", "nes-admin@uni-due.de", new String[] { Roles.SERVICE });
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a user, if it does not exist already, and returns it.
|
||||
*
|
||||
*
|
||||
* @param login The login.
|
||||
* @param name The name.
|
||||
* @param password The password.
|
||||
@@ -121,10 +123,10 @@ public class DataSessionBean {
|
||||
return createUser(login, name, password, email, roles);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the specified user.
|
||||
*
|
||||
*
|
||||
* @param login The login name.
|
||||
* @param name The user name.
|
||||
* @param password The password.
|
||||
@@ -153,7 +155,7 @@ public class DataSessionBean {
|
||||
|
||||
/**
|
||||
* Creates a new email entity for the user.
|
||||
*
|
||||
*
|
||||
* @param u The user.
|
||||
* @param email The email address.
|
||||
* @param verified The state of the verified flag.
|
||||
@@ -168,7 +170,7 @@ public class DataSessionBean {
|
||||
u.getEmails().add(e);
|
||||
em.persist(e);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
|
||||
* @return The page of devices.
|
||||
* @throws EntityNotFoundException Thrown if the user cannot be found.
|
||||
*/
|
||||
@RolesAllowed({ Roles.USER })
|
||||
@RolesAllowed({ Roles.USER , Roles.SERVICE})
|
||||
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered)
|
||||
throws EntityNotFoundException {
|
||||
UserEntity user = getPrincipalUser();
|
||||
|
||||
@@ -1,18 +1,5 @@
|
||||
package com.mowesta.service.session;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.annotation.security.DeclareRoles;
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.api.user.Email;
|
||||
@@ -33,12 +20,26 @@ import com.mowesta.service.entity.EntityConflictException;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.OrderCriterion;
|
||||
import com.mowesta.service.entity.RefreshTokenEntity;
|
||||
import com.mowesta.service.entity.RoleEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.principal.LoginManager;
|
||||
import com.mowesta.service.template.EmailAssignment;
|
||||
import com.mowesta.service.template.EmailTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.annotation.security.DeclareRoles;
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.inject.Inject;
|
||||
|
||||
/**
|
||||
* A stateful session bean that provides methods to manipulate
|
||||
* users.
|
||||
@@ -116,6 +117,21 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
|
||||
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
|
||||
return Convert.with(UserConverter.class).apply(u, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the account of the user that is currently logged in as UserEntity.
|
||||
*
|
||||
* @return The user that is currently logged in as UserEntity.
|
||||
* @throws EntityForbiddenException Thrown if the current account is suspended or deleted.
|
||||
* @throws EntityNotFoundException Thrown if the current account is not found.
|
||||
*/
|
||||
@RolesAllowed({ Roles.USER })
|
||||
public UserEntity getCurrentUserEntity() throws EntityForbiddenException, EntityNotFoundException {
|
||||
UserEntity u = getPrincipalUser();
|
||||
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
|
||||
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
|
||||
return u;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the current user.
|
||||
@@ -211,6 +227,17 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
|
||||
return page;
|
||||
}
|
||||
|
||||
@PermitAll
|
||||
public void addRefreshTokenToUser(String login, RefreshTokenEntity refreshTokenEntity) throws EntityNotFoundException {
|
||||
UserEntity u = findUser(login);
|
||||
if (u == null)
|
||||
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(login), "User request by admin for non-existing user.");
|
||||
refreshTokenEntity.setUser(u);
|
||||
u.getRefreshTokens().add(refreshTokenEntity);
|
||||
em.persist(refreshTokenEntity);
|
||||
em.flush();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Registers the user and returns the new account or
|
||||
@@ -234,6 +261,7 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
|
||||
setPassword(u, registration.getPassword());
|
||||
setRoles(u, roles);
|
||||
u.setEmails(new HashSet<EmailEntity>());
|
||||
u.setRefreshTokens(new HashSet<RefreshTokenEntity>());
|
||||
em.persist(u);
|
||||
EmailEntity e = addEmail(u, registration.getEmail(), true);
|
||||
em.persist(e);
|
||||
@@ -516,6 +544,19 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
|
||||
emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.RESET_USER, assignment);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if refreshToken matches
|
||||
*
|
||||
* @param refreshToken The refreshToken to compare.
|
||||
*
|
||||
*/
|
||||
@PermitAll
|
||||
public Boolean compareRefreshToken(String refreshToken) throws EntityNotFoundException {
|
||||
UserEntity u = getPrincipalUser();
|
||||
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets and updates an exisiting code for the specified action type
|
||||
@@ -647,4 +688,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
|
||||
c.setExpirationTime(expirationTime);
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.mowesta.service.session.sync;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.service.entity.AbstractEntity;
|
||||
import com.mowesta.service.entity.OAuthSecretEntity;
|
||||
import com.mowesta.service.entity.OrderCriterion;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Encoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
@Stateless
|
||||
public class GenerateOAuthSecretSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
private final long offset = 720000;
|
||||
private final long secretValidTime = 360000;
|
||||
|
||||
@PermitAll
|
||||
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
|
||||
public void syncToken(boolean first) {
|
||||
deleteOldToken();
|
||||
if (first) {
|
||||
invalidateAllToken();
|
||||
} else {
|
||||
invalidateOldToken();
|
||||
}
|
||||
createSecretKey();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new Secret Key.
|
||||
*/
|
||||
private void createSecretKey() {
|
||||
log.log(Level.INFO, "Creating new Secret Key.");
|
||||
Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
||||
OAuthSecretEntity oAuthSecretEntity = new OAuthSecretEntity();
|
||||
oAuthSecretEntity.setValid(true);
|
||||
oAuthSecretEntity.setTimeValid(secretValidTime);
|
||||
oAuthSecretEntity.setSecret(Encoders.BASE64.encode(secretKey.getEncoded()));
|
||||
em.persist(oAuthSecretEntity);
|
||||
log.log(Level.INFO, "New Secret Key: " + oAuthSecretEntity.getSecret().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidates all OAuthSecretEntities without validation check.
|
||||
*/
|
||||
private void invalidateAllToken() {
|
||||
log.log(Level.INFO, "First Startup - invalidating all OAuthSecretEntities.");
|
||||
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
|
||||
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
|
||||
oAuthSecretEntity.setValid(false);
|
||||
em.persist(oAuthSecretEntity);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidates all OAuthSecretEntities, which are no longer valid.
|
||||
*/
|
||||
private void invalidateOldToken() {
|
||||
log.log(Level.INFO, "Checking all OAuthSecretEntities for validation.");
|
||||
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
|
||||
List<OAuthSecretEntity> invalidateoAuthSecretEntities = new ArrayList<>();
|
||||
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
|
||||
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
|
||||
invalidateoAuthSecretEntities.add(oAuthSecretEntity);
|
||||
}
|
||||
}));
|
||||
log.log(Level.INFO,"Found " + invalidateoAuthSecretEntities.size() + " Entities to invalidate");
|
||||
|
||||
invalidateoAuthSecretEntities.forEach((invalidOAuthSecretEntity) -> {
|
||||
invalidOAuthSecretEntity.setValid(false);
|
||||
em.persist(invalidOAuthSecretEntity);
|
||||
});
|
||||
log.log(Level.INFO, "Invalidated all old OAuthSecretEntities");
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all OAuthSecretEntities, which are longer invalid than a defined offset.
|
||||
*/
|
||||
private void deleteOldToken() {
|
||||
log.log(Level.INFO, "Checking for old OAuthSecretEntities.");
|
||||
List<OAuthSecretEntity> allOAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
|
||||
List<OAuthSecretEntity> allOldOAuthSecretEntites = new ArrayList<>();
|
||||
|
||||
allOAuthSecretEntities.forEach((oAuthSecretEntity -> {
|
||||
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
|
||||
allOldOAuthSecretEntites.add(oAuthSecretEntity);
|
||||
}
|
||||
}));
|
||||
log.log(Level.INFO, "Found " + allOldOAuthSecretEntites.size() + "Entities to remove.");
|
||||
|
||||
allOldOAuthSecretEntites.forEach((oldOAuthSecretEntity) -> {
|
||||
oldOAuthSecretEntity.setDeleted(true);
|
||||
em.remove(oldOAuthSecretEntity);
|
||||
em.persist(oldOAuthSecretEntity);
|
||||
});
|
||||
log.log(Level.INFO, "Removed all old OAuthSecretEntities");
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,11 @@ public class PeriodicSyncSessionBean {
|
||||
/**
|
||||
* The task that generates weather videos.
|
||||
*/
|
||||
VIDEO;
|
||||
VIDEO,
|
||||
/**
|
||||
* The task that generates oauth-tokens.
|
||||
*/
|
||||
OAUTHTOKEN;
|
||||
};
|
||||
|
||||
|
||||
@@ -73,6 +77,9 @@ public class PeriodicSyncSessionBean {
|
||||
|
||||
@Inject
|
||||
protected WeatherVideoSyncSessionBean videoSyncSession;
|
||||
|
||||
@Inject
|
||||
protected GenerateOAuthSecretSessionBean generateOAuthSecretSessionBean;
|
||||
|
||||
@Resource
|
||||
protected SessionContext context;
|
||||
@@ -94,6 +101,9 @@ public class PeriodicSyncSessionBean {
|
||||
jobs[JobType.VIDEO.ordinal()] = new Job("VideoSync", (first)-> {
|
||||
videoSyncSession.syncVideos(first);
|
||||
});
|
||||
jobs[JobType.OAUTHTOKEN.ordinal()] = new Job("OAuthTokenSync", (first)-> {
|
||||
generateOAuthSecretSessionBean.syncToken(first);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -111,6 +121,8 @@ public class PeriodicSyncSessionBean {
|
||||
timerService.createIntervalTimer(TimeUnit.MINUTES.toMillis(3), TimeUnit.HOURS.toMillis(1), forecastConfig);
|
||||
final TimerConfig locationConfig = new TimerConfig(JobType.LOCATION, false);
|
||||
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(5), locationConfig);
|
||||
final TimerConfig oAuthConfig = new TimerConfig(JobType.OAUTHTOKEN, false);
|
||||
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(12), oAuthConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
package com.mowesta.service.session.sync;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.weather.SoilType;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.api.weather.WindDirection;
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
|
||||
import com.mowesta.data.process.source.Grib2MixedSource;
|
||||
import com.mowesta.data.process.source.IDataSource;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.service.entity.WeatherForecastContainer;
|
||||
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
|
||||
import org.infinispan.Cache;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
@@ -22,28 +44,6 @@ import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import org.infinispan.Cache;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.api.weather.SoilType;
|
||||
import com.mowesta.api.weather.WeatherCondition;
|
||||
import com.mowesta.api.weather.WeatherForecast;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.api.weather.WindDirection;
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
|
||||
import com.mowesta.data.process.source.Grib2MixedSource;
|
||||
import com.mowesta.data.process.source.IDataSource;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.service.entity.WeatherForecastContainer;
|
||||
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
|
||||
/**
|
||||
* A bean to synchronize the weather forecasts.
|
||||
*
|
||||
@@ -408,6 +408,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
|
||||
double u = getValue(Variable.U10M, hour, chunk, index, cache);
|
||||
double v = getValue(Variable.V10M, hour, chunk, index, cache);
|
||||
result.setWindSpeed(getWindSpeed(u, v));
|
||||
result.setMaxWindSpeed(getValue(Variable.VMAX_10M, hour, chunk, index, cache));
|
||||
result.setWindDirection(getWindDirection(u, v));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
<class>com.mowesta.service.entity.RoleEntity</class>
|
||||
<class>com.mowesta.service.entity.StateEntity</class>
|
||||
<class>com.mowesta.service.entity.UserEntity</class>
|
||||
<class>com.mowesta.service.entity.RefreshTokenEntity</class>
|
||||
<class>com.mowesta.service.entity.OAuthSecretEntity</class>
|
||||
<class>com.mowesta.service.entity.WeatherReportEntity</class>
|
||||
<class>com.mowesta.service.entity.WeatherStationEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
###
|
||||
# This script removes all private data from a mowesta database so that it can be
|
||||
# distributed to developers for testing. The last few lines are producing a more
|
||||
# compact version that requires less resources.
|
||||
#
|
||||
# @author Marcus
|
||||
###
|
||||
|
||||
# delete all measurement data that is not from handte (about 2-3 minutes)
|
||||
delete from measurement_data where measurement_id in (select id from measurement where device_id not in (select id from device where user_id in (select id from user where login='handte')));
|
||||
# delete all measurements that are not from handte (about 1-2 minutes)
|
||||
delete from measurement where device_id not in (select id from device where user_id in (select id from user where login='handte'));
|
||||
# delete all devices that are not from handte (seconds)
|
||||
delete from device where user_id not in (select id from user where login='handte');
|
||||
# delete all devices without a user, since it seems as if null values are special here (seconds)
|
||||
delete from device where user_id is null;
|
||||
# delete the favorites that are not the admin or handte (seconds)
|
||||
delete from user_location where UserEntity_id not in (select id from user where login in ('handte', 'admin') );
|
||||
# delete the roles that are not the admin or handte (seconds)
|
||||
delete from user_role where user_id not in (select id from user where login in ('handte', 'admin') );
|
||||
# delete all email codes (seconds)
|
||||
delete from code;
|
||||
# delete the favorites that are not the admin or handte (seconds)
|
||||
delete from email where user_id not in (select id from user where login in ('handte', 'admin') );
|
||||
# delete all users except the admin and handte (seconds)
|
||||
delete from user where login not in ('handte', 'admin');
|
||||
# copy the well-known password from handte to admin (seconds)
|
||||
update user set hash=(select hash from user where login='handte'), iterations=(select iterations from user where login='handte'), salt=(select salt from user where login='handte') where login='admin';
|
||||
# make the lenovo tablet from handte a device without a user to cover this case (seconds)
|
||||
update device set user_id=null where id=9934728;
|
||||
|
||||
# reduce the amount of data for the compact version (30 seconds, 20 seconds and 17 minutes)
|
||||
delete from measurement_data where measurement_id in (select id from measurement where time<1604188800000);
|
||||
delete from measurement where time<1604188800000;
|
||||
delete from report where time<1604188800000;
|
||||
@@ -18,6 +18,9 @@ dependencies {
|
||||
compile 'com.locoslab.library.geometry:geometry-wgs:1.1.4'
|
||||
compile 'com.locoslab.service.carta:carta-api:1.1.4'
|
||||
|
||||
compileOnly "io.swagger:swagger-annotations:${versionSwagger}"
|
||||
|
||||
|
||||
|
||||
// builds a jar with all dependencies for the nominatim exporter so
|
||||
// we can transfer the code to oz and run it there which is significantly
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@@ -22,12 +20,7 @@ import org.geojson.Feature;
|
||||
import org.geojson.FeatureCollection;
|
||||
import org.geojson.LngLatAlt;
|
||||
import org.geojson.Polygon;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
||||
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.locoslab.library.geometry.wgs.Box;
|
||||
import com.locoslab.library.geometry.wgs.Coordinate;
|
||||
import com.locoslab.library.geometry.wgs.Coordinates;
|
||||
@@ -36,24 +29,27 @@ import com.locoslab.library.geometry.wgs.Surface;
|
||||
import com.locoslab.service.carta.api.vector.geojson.IVectorServiceGeojson;
|
||||
|
||||
/**
|
||||
* A simple program that determines the nearest building given
|
||||
* a particular gps coordinate.
|
||||
* A simple program that determines the nearest building given a particular gps coordinate.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class BuildingTool {
|
||||
public class BuildingResolver {
|
||||
|
||||
/**
|
||||
* The folder containing the tile cache.
|
||||
*/
|
||||
public static final String FOLDER_CACHE = "tile-cache";
|
||||
public static final String FOLDER_CACHE = "building-cache";
|
||||
|
||||
/**
|
||||
* The zoom level at which we load map data.
|
||||
*/
|
||||
public static final int ZOOM_TILE = 15;
|
||||
|
||||
/**
|
||||
* The base url for carta to load vector tiles.
|
||||
*/
|
||||
public static final String URL_BASE = "https://www.mowesta.com/carta";
|
||||
|
||||
/**
|
||||
* Runs the program.
|
||||
*
|
||||
@@ -72,53 +68,29 @@ public class BuildingTool {
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
// parse the inputs
|
||||
double longitude = parseDouble("longitude", cmd.getOptionValue(longitudeOption.getOpt()));
|
||||
double latitude = parseDouble("latitude", cmd.getOptionValue(latitudeOption.getOpt()));
|
||||
double range = parseDouble("range", cmd.getOptionValue(rangeOption.getOpt()));
|
||||
double longitude = StringUtils.toDouble("longitude", cmd.getOptionValue(longitudeOption.getOpt()));
|
||||
double latitude = StringUtils.toDouble("latitude", cmd.getOptionValue(latitudeOption.getOpt()));
|
||||
double range = StringUtils.toDouble("range", cmd.getOptionValue(rangeOption.getOpt()));
|
||||
// validate the inputs (10000 will download > 500 tiles, so lets cap it there)
|
||||
if (range > 10000 || range < 0) {
|
||||
throw new ParseException("Invalid range.");
|
||||
}
|
||||
// print the inputs
|
||||
System.out.println(String.format("Longitude: %.5f Latitude: %.5f Range: %.2f", longitude, latitude, range));
|
||||
// create a tile cache
|
||||
TileCache cache = new TileCache(new File(FOLDER_CACHE));
|
||||
Coordinate c = new Coordinate(longitude, latitude);
|
||||
// compute the tiles that we have to search for buildings based on
|
||||
// the range that the user specified
|
||||
Box box = getBounds(longitude, latitude, range);
|
||||
MapTile topLeft = getTopLeftTile(box, ZOOM_TILE);
|
||||
MapTile bottomRight = getBottomRightTile(box, ZOOM_TILE);
|
||||
int total = (bottomRight.getX()-topLeft.getX()) * (bottomRight.getY() - topLeft.getY());
|
||||
System.out.println(String.format("Tiles are X: %d-%d Y: %d-%d Total: %d", topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(), total));
|
||||
// iterate over the tiles and find the closest building
|
||||
List<Coordinate> minimum = null;
|
||||
double distance = 0;
|
||||
for (int x = topLeft.getX(); x <= bottomRight.getX(); x++) {
|
||||
for (int y = topLeft.getY(); y <= bottomRight.getY(); y++) {
|
||||
List<List<Coordinate>> buildings = getBuildings(cache.getTile(new MapTile(x, y, ZOOM_TILE)));
|
||||
for (List<Coordinate> building : buildings) {
|
||||
double d = computeDistance(building, c);
|
||||
if (minimum == null || d < distance) {
|
||||
distance = d;
|
||||
minimum = building;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (minimum == null) {
|
||||
BuildingResolver tool = new BuildingResolver();
|
||||
Resolution match = tool.resolve(longitude, latitude, range);
|
||||
if (match == null) {
|
||||
System.out.println("Found no nearby building.");
|
||||
} else {
|
||||
Surface surface = new Surface(minimum);
|
||||
if (surface.contains(c)) {
|
||||
System.out.println(String.format("We are inside. Outer wall is %.2f meters away.", distance));
|
||||
if (match.isInside()) {
|
||||
System.out.println(String.format("We are inside. Outer wall is %.2f meters away.", match.getDistance()));
|
||||
} else {
|
||||
System.out.println(String.format("We are outside. Nearest building is %.2f meters away.", distance));
|
||||
System.out.println(String.format("We are outside. Nearest building is %.2f meters away.", match.getDistance()));
|
||||
}
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(BuildingTool.class.getSimpleName(), options);
|
||||
formatter.printHelp(BuildingResolver.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@@ -126,6 +98,81 @@ public class BuildingTool {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The logger to print debug output.
|
||||
*/
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
/**
|
||||
* The tile cache to load data.
|
||||
*/
|
||||
private TileCache cache;
|
||||
|
||||
/**
|
||||
* The zoom level to perform lookups.
|
||||
*/
|
||||
private int zoom;
|
||||
|
||||
/**
|
||||
* Creates a new resolver with the default settings.
|
||||
*/
|
||||
public BuildingResolver() {
|
||||
this(URL_BASE, new File(FOLDER_CACHE), ZOOM_TILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new resolver.
|
||||
*
|
||||
* @param baseUrl The base url to load tiles.
|
||||
* @param cacheFolder The folder to cache tiles.
|
||||
* @param zoom The zoom level to load tiles.
|
||||
*/
|
||||
public BuildingResolver(String baseUrl, File cacheFolder, int zoom) {
|
||||
this.zoom = zoom;
|
||||
this.cache = new TileCache(baseUrl, cacheFolder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the closest matching building for a coordinate in a particular range or null, if there is none.
|
||||
*
|
||||
* @param longitude The longitude.
|
||||
* @param latitude The latitude.
|
||||
* @param range The search range in meters.
|
||||
* @return The match or null, if there is no building.
|
||||
* @throws IOException Thrown by the web request or disk io.
|
||||
*/
|
||||
public Resolution resolve(double longitude, double latitude, double range) throws IOException {
|
||||
Coordinate c = new Coordinate(longitude, latitude);
|
||||
// compute the tiles that we have to search for buildings based on
|
||||
// the range that the user specified
|
||||
Box box = getBounds(longitude, latitude, range);
|
||||
MapTile topLeft = getTopLeftTile(box, zoom);
|
||||
MapTile bottomRight = getBottomRightTile(box, zoom);
|
||||
int total = (bottomRight.getX()-topLeft.getX()) * (bottomRight.getY() - topLeft.getY());
|
||||
logger.log(Level.FINE, String.format("Tiles are X: %d-%d Y: %d-%d Total: %d", topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(), total));
|
||||
// iterate over the tiles and find the closest building
|
||||
List<Coordinate> minimum = null;
|
||||
double distance = 0;
|
||||
for (int x = topLeft.getX(); x <= bottomRight.getX(); x++) {
|
||||
for (int y = topLeft.getY(); y <= bottomRight.getY(); y++) {
|
||||
List<List<Coordinate>> buildings = getBuildings(cache.get(new MapTile(x, y, zoom)));
|
||||
for (List<Coordinate> building : buildings) {
|
||||
double d = computeDistance(building, c);
|
||||
if (minimum == null || d < distance) {
|
||||
distance = d;
|
||||
minimum = building;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (minimum == null) return null;
|
||||
Surface surface = new Surface(minimum);
|
||||
return new Resolution(c, minimum, distance, surface.contains(c));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Computes the minimum distance to a building.
|
||||
*
|
||||
@@ -133,7 +180,7 @@ public class BuildingTool {
|
||||
* @param c The coordinate to compute the distance.
|
||||
* @return The minimum distance.
|
||||
*/
|
||||
public static double computeDistance(List<Coordinate> coordinates, Coordinate c) {
|
||||
private double computeDistance(List<Coordinate> coordinates, Coordinate c) {
|
||||
double distance = 0;
|
||||
Coordinate minimum = null;
|
||||
// handle cases where polygon is not closed
|
||||
@@ -157,7 +204,7 @@ public class BuildingTool {
|
||||
* @param collection The feature collection to search.
|
||||
* @return The outer rings of the buildings.
|
||||
*/
|
||||
public static List<List<Coordinate>> getBuildings(FeatureCollection collection) {
|
||||
private List<List<Coordinate>> getBuildings(FeatureCollection collection) {
|
||||
List<List<Coordinate>> result = new ArrayList<>();
|
||||
for (Feature feature: collection.getFeatures()) {
|
||||
if (feature.getProperties().containsKey("building") &&
|
||||
@@ -170,7 +217,7 @@ public class BuildingTool {
|
||||
}
|
||||
result.add(coordinates);
|
||||
} else {
|
||||
System.err.println("Ignoring invalid exterior polygon ring.");
|
||||
logger.log(Level.WARNING, "Ignoring invalid exterior polygon ring.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +231,7 @@ public class BuildingTool {
|
||||
* @param zoom The zoom level.
|
||||
* @return The top left tile.
|
||||
*/
|
||||
private static MapTile getTopLeftTile(Box box, int zoom) {
|
||||
private MapTile getTopLeftTile(Box box, int zoom) {
|
||||
return MapTile.getMapTile(box.getMin().getLongitude(), box.getMax().getLatitude(), zoom);
|
||||
}
|
||||
|
||||
@@ -195,7 +242,7 @@ public class BuildingTool {
|
||||
* @param zoom The zoom level.
|
||||
* @return The bottom right tile.
|
||||
*/
|
||||
private static MapTile getBottomRightTile(Box box, int zoom) {
|
||||
private MapTile getBottomRightTile(Box box, int zoom) {
|
||||
return MapTile.getMapTile(box.getMax().getLongitude(), box.getMin().getLatitude(), zoom);
|
||||
}
|
||||
|
||||
@@ -208,7 +255,7 @@ public class BuildingTool {
|
||||
* @param range The range.
|
||||
* @return The bounding box with the range.
|
||||
*/
|
||||
private static Box getBounds(double longitude, double latitude, double range) {
|
||||
private Box getBounds(double longitude, double latitude, double range) {
|
||||
double dx = range / Coordinates.DISTANCE.getDistance(new Coordinate(longitude, latitude), new Coordinate(longitude + 1, latitude));
|
||||
double dy = range / Coordinates.DISTANCE.getDistance(new Coordinate(longitude, latitude), new Coordinate(longitude, latitude + 1));
|
||||
return new Box(longitude - dx, latitude - dy, longitude + dx, latitude + dy);
|
||||
@@ -216,89 +263,20 @@ public class BuildingTool {
|
||||
|
||||
|
||||
/**
|
||||
* Parses a double from the value or throws an exception hinting at the name.
|
||||
*
|
||||
* @param name The name used to indicate the source of the problem, if parsing fails.
|
||||
* @param value The value to parse.
|
||||
* @return The double representing the value.
|
||||
* @throws ParseException Thrown if the value cannot be converted to a double.
|
||||
*/
|
||||
private static double parseDouble(String name, String value) throws ParseException {
|
||||
try {
|
||||
return Double.parseDouble(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new ParseException(String.format("Failed to parse %s.", name));
|
||||
} catch (NullPointerException e) {
|
||||
throw new ParseException(String.format("Missing parameter %s.", name));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A class that implements a simple tile cache using the file
|
||||
* system.
|
||||
* A class that implements a simple tile cache using the file system.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class TileCache {
|
||||
|
||||
/**
|
||||
* The mapper to read and write json data.
|
||||
*/
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The folder used to cache the files.
|
||||
*/
|
||||
private File folder;
|
||||
|
||||
/**
|
||||
* The service to download the tiles.
|
||||
*/
|
||||
private IVectorServiceGeojson service;
|
||||
public static class TileCache extends RequestCache<IVectorServiceGeojson, MapTile, FeatureCollection>{
|
||||
|
||||
/**
|
||||
* Creates a tile cache with the specified folder.
|
||||
*
|
||||
* @param baseUrl The url to load the tiles form.
|
||||
* @param folder The folder.
|
||||
*/
|
||||
public TileCache(File folder) {
|
||||
this.folder = folder;
|
||||
folder.mkdirs();
|
||||
ResteasyClientBuilder builder = new ResteasyClientBuilder();
|
||||
builder.httpEngine(new URLConnectionEngine());
|
||||
ResteasyClient client = builder.build();
|
||||
ResteasyWebTarget target = client.target("https://www.mowesta.com/carta");
|
||||
service = target.proxy(IVectorServiceGeojson.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns feature collection of a tile from local cache or by
|
||||
* downloading it. Downloaded tiles are stored in the cache for
|
||||
* later retrieval.
|
||||
*
|
||||
* @param tile The tile to load.
|
||||
* @return The feature collection.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public FeatureCollection getTile(MapTile tile) throws IOException {
|
||||
File file = new File(folder, getFileName(tile));
|
||||
if (file.exists()) {
|
||||
System.out.println(String.format("Loading cached tile from %s.", file.getName()));
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String line = reader.readLine();
|
||||
return mapper.readValue(line, FeatureCollection.class);
|
||||
} catch (IOException e) {
|
||||
System.err.println(String.format("Failed to load tile from %s.", file.getName()));
|
||||
}
|
||||
}
|
||||
System.out.println(String.format("Downloading new tile to %s.", file.getName()));
|
||||
FeatureCollection features = fetchTile(tile);
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
|
||||
writer.write(mapper.writeValueAsString(features));
|
||||
writer.flush();
|
||||
}
|
||||
return features;
|
||||
public TileCache(String baseUrl, File folder) {
|
||||
super(IVectorServiceGeojson.class, FeatureCollection.class, baseUrl, folder);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -307,20 +285,13 @@ public class BuildingTool {
|
||||
* @param tile The tile.
|
||||
* @return The file name of the tile.
|
||||
*/
|
||||
private String getFileName(MapTile tile) {
|
||||
return tile.getZ() + "-" + tile.getX() + "-" + tile.getY() + ".json";
|
||||
@Override
|
||||
protected String getFileName(MapTile tile) {
|
||||
return "tile-" + tile.getZ() + "-" + tile.getX() + "-" + tile.getY() + ".json";
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a particular tile.
|
||||
*
|
||||
* @param tile The tile.
|
||||
* @return The feature collection using the tiles.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
private FeatureCollection fetchTile(MapTile tile) throws IOException {
|
||||
@Override
|
||||
protected FeatureCollection download(IVectorServiceGeojson service, MapTile tile) throws IOException {
|
||||
Response response = service.getFeatures(tile.getX(), tile.getY(), tile.getZ(), -1, true, null);
|
||||
if (response.getStatus() != 200) throw new IOException("Failed to download tile.");
|
||||
return response.readEntity(FeatureCollection.class);
|
||||
@@ -328,8 +299,84 @@ public class BuildingTool {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the result of a successful resolution attempt.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class Resolution {
|
||||
|
||||
/**
|
||||
* The building outline.
|
||||
*/
|
||||
private List<Coordinate> outline;
|
||||
|
||||
/**
|
||||
* The coordinate that we searched.
|
||||
*/
|
||||
private Coordinate coordinate;
|
||||
|
||||
/**
|
||||
* The distance to the building.
|
||||
*/
|
||||
private double distance;
|
||||
|
||||
/**
|
||||
* A flag to indicate whether it is inside.
|
||||
*/
|
||||
private boolean inside;
|
||||
|
||||
/**
|
||||
* Creates a resolution.
|
||||
*
|
||||
* @param coordinate The coordinate.
|
||||
* @param outline The outline.
|
||||
* @param distance The distance.
|
||||
* @param inside A flag to indicate whether the coordinate lies inside the building.
|
||||
*/
|
||||
public Resolution(Coordinate coordinate, List<Coordinate> outline, double distance, boolean inside) {
|
||||
this.coordinate = coordinate;
|
||||
this.outline = outline;
|
||||
this.distance = distance;
|
||||
this.inside = inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the coordinate that was queried.
|
||||
*
|
||||
* @return The coordinate.
|
||||
*/
|
||||
public Coordinate getCoordinate() {
|
||||
return coordinate;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if the coordinate lies inside.
|
||||
*
|
||||
* @return True if the coordinate lies inside the building,.
|
||||
*/
|
||||
public boolean isInside() {
|
||||
return inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the outline of the building.
|
||||
*
|
||||
* @return The outline of the building.
|
||||
*/
|
||||
public List<Coordinate> getOutline() {
|
||||
return outline;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the distance from the building to the coordinate.
|
||||
*
|
||||
* @return The distance in meters.
|
||||
*/
|
||||
public double getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.DefaultParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Option;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.IMeasurementService;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
|
||||
/**
|
||||
* The measurement fetcher.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasurementFetcher {
|
||||
|
||||
/**
|
||||
* The url of the mowesta api.
|
||||
*/
|
||||
public static final String URL_BASE = "https://www.mowesta.com/api";
|
||||
|
||||
/**
|
||||
* The folder to store the results.
|
||||
*/
|
||||
public static final String FOLDER_CACHE = "measurement-cache";
|
||||
|
||||
/**
|
||||
* The default page size.
|
||||
*/
|
||||
public static final int SIZE_PAGE = 1000;
|
||||
|
||||
/**
|
||||
* The measurement cache to use.
|
||||
*/
|
||||
private MeasurementCache cache;
|
||||
|
||||
|
||||
/**
|
||||
* A program to download the measurements.
|
||||
*
|
||||
* @param args The arguments to define the time range.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Options options = new Options();
|
||||
Option dateOption = new Option("dt", "date", true, "The start date given as YYYY-MM-DD");
|
||||
options.addOption(dateOption);
|
||||
Option daysOption = new Option("pd", "days", true, "The period in days.");
|
||||
options.addOption(daysOption);
|
||||
Option userOption = new Option("u", "user", true, "The user name to login.");
|
||||
options.addOption(userOption);
|
||||
Option passOption = new Option("p", "pass", true, "The user password to login.");
|
||||
options.addOption(passOption);
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
// parse the inputs
|
||||
int[] date = StringUtils.toDate("date", cmd.getOptionValue(dateOption.getOpt()));
|
||||
int days = StringUtils.toInt("days", cmd.getOptionValue(daysOption.getOpt()));
|
||||
System.out.println(String.format("Year: %d Month: %d Day: %d - Days: %d", date[0], date[1], date[2], days));
|
||||
MeasurementFetcher fetcher = new MeasurementFetcher(cmd.getOptionValue(userOption.getOpt()), cmd.getOptionValue(passOption.getOpt()));
|
||||
RangeBuilder builder = new RangeBuilder(date[0], date[1], date[2]);
|
||||
Enumeration<TimeRange> enumeration = builder.getDayRanges(days);
|
||||
while (enumeration.hasMoreElements()) {
|
||||
TimeRange range = enumeration.nextElement();
|
||||
System.out.println(String.format("Fetched day %d with %d measurements.", range.getStart(), fetcher.fetch(range).length));
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(MeasurementFetcher.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a fetcher with the user and password.
|
||||
*
|
||||
* @param user The user.
|
||||
* @param pass The password.
|
||||
*/
|
||||
public MeasurementFetcher(String user, String pass) {
|
||||
this(URL_BASE, new File(FOLDER_CACHE), SIZE_PAGE, user, pass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a fetcher with the user, password and
|
||||
* configuration.
|
||||
*
|
||||
* @param user The user.
|
||||
* @param pass The password.
|
||||
* @param folder The cache folder.
|
||||
* @param pageSize The page size.
|
||||
* @param url The base url.
|
||||
*/
|
||||
public MeasurementFetcher(String url, File folder, int pageSize, String user, String pass) {
|
||||
cache = new MeasurementCache(URL_BASE, new File(FOLDER_CACHE), SIZE_PAGE, user, pass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a set of measurements in a range.
|
||||
*
|
||||
* @param range The range.
|
||||
* @return The measurements in the range.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public Measurement[] fetch(TimeRange range) throws IOException {
|
||||
return cache.get(range);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The measurement cache to download measurements.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class MeasurementCache extends RequestCache<IMeasurementService, TimeRange, Measurement[]> {
|
||||
|
||||
/**
|
||||
* The page size to download.
|
||||
*/
|
||||
private int pageSize;
|
||||
|
||||
/**
|
||||
* The user name.
|
||||
*/
|
||||
private String user;
|
||||
|
||||
/**
|
||||
* The user password.
|
||||
*/
|
||||
private String pass;
|
||||
|
||||
/**
|
||||
* Creates a new cache.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @param cacheFolder The cache folder.
|
||||
* @param pageSize The page size.
|
||||
* @param user The user name.
|
||||
* @param pass The password.
|
||||
*/
|
||||
public MeasurementCache(String baseUrl, File cacheFolder, int pageSize, String user, String pass) {
|
||||
super(IMeasurementService.class, Measurement[].class, baseUrl, cacheFolder);
|
||||
this.pageSize = pageSize;
|
||||
this.user = user;
|
||||
this.pass = pass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResteasyWebTarget getWebTarget(String baseUrl) {
|
||||
ResteasyWebTarget target = super.getWebTarget(baseUrl);
|
||||
target.register(new BasicAuthentication(user, pass));
|
||||
return target;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Measurement[] download(IMeasurementService service, TimeRange input) throws IOException {
|
||||
int remainder = 0;
|
||||
List<Measurement> result = new ArrayList<>();
|
||||
PageConfig config = new PageConfig(0, pageSize);
|
||||
do {
|
||||
Response r = service.getAllMeasurementsByRange(input, config);
|
||||
MeasurementPage page = r.readEntity(MeasurementPage.class);
|
||||
result.addAll(page.getElements());
|
||||
config.setOffset(config.getOffset() + pageSize);
|
||||
remainder = page.getTotal() - config.getOffset();
|
||||
} while (remainder > 0);
|
||||
return result.toArray(new Measurement[result.size()]);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getFileName(TimeRange input) {
|
||||
return "measurements-" + input.getStart() + "-" + input.getEnd() + ".json";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.mowesta.api.TimeRange;
|
||||
|
||||
/**
|
||||
* A helper class to build time ranges.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class RangeBuilder {
|
||||
|
||||
/**
|
||||
* The internal calendar with the start date.
|
||||
*/
|
||||
private Calendar c;
|
||||
|
||||
/**
|
||||
* Creates a range builder with the given start date.
|
||||
*
|
||||
* @param year The year.
|
||||
* @param month The month (1-based).
|
||||
* @param day The day of the month.
|
||||
*/
|
||||
public RangeBuilder(int year, int month, int day) {
|
||||
initCalendar();
|
||||
c.set(Calendar.YEAR, year);
|
||||
c.set(Calendar.MONTH, month - 1);
|
||||
c.set(Calendar.DAY_OF_MONTH, day);
|
||||
resetCalendar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new range builder initialized to the start
|
||||
* of the day represented by the time stamp.
|
||||
*
|
||||
* @param timestamp The time stamp to initialize the builder.
|
||||
*/
|
||||
public RangeBuilder(long timestamp) {
|
||||
initCalendar();
|
||||
c.setTimeInMillis(timestamp);
|
||||
resetCalendar();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the calendar.
|
||||
*/
|
||||
private void initCalendar() {
|
||||
c = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"), Locale.GERMAN);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the calendar to the first hour, minute, second and millisecond of the day.
|
||||
*/
|
||||
private void resetCalendar() {
|
||||
c.set(Calendar.HOUR_OF_DAY, 0);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.set(Calendar.MILLISECOND, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerates the daily ranges for the next or
|
||||
* previous n days.
|
||||
*
|
||||
* @param n The number of days to enumerate.
|
||||
* @return The enumeration of the time ranges.
|
||||
*/
|
||||
public Enumeration<TimeRange> getDayRanges(int n) {
|
||||
Calendar copy = (Calendar) c.clone();
|
||||
if (n < 0) {
|
||||
copy.add(Calendar.DAY_OF_MONTH, n);
|
||||
}
|
||||
return new Enumeration<TimeRange>() {
|
||||
|
||||
Calendar c = copy;
|
||||
int remainder = Math.abs(n);
|
||||
|
||||
@Override
|
||||
public TimeRange nextElement() {
|
||||
if (!hasMoreElements())
|
||||
throw new NoSuchElementException();
|
||||
remainder -= 1;
|
||||
return getDayRange(c, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasMoreElements() {
|
||||
return remainder > 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the day range starting from a particular offset
|
||||
* and adds one day to the calendar.
|
||||
*
|
||||
* @param copy The copy.
|
||||
* @param offset The offset.
|
||||
* @return The time range.
|
||||
*/
|
||||
private TimeRange getDayRange(Calendar copy, int offset) {
|
||||
copy.add(Calendar.DAY_OF_MONTH, offset);
|
||||
long start = copy.getTimeInMillis();
|
||||
copy.add(Calendar.DAY_OF_MONTH, 1);
|
||||
long end = copy.getTimeInMillis();
|
||||
return new TimeRange(start, end - start);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time range starting from a given offset.
|
||||
*
|
||||
* @param offset The offset.
|
||||
* @return The time range.
|
||||
*/
|
||||
public TimeRange getDayRange(int offset) {
|
||||
Calendar copy = (Calendar) c.clone();
|
||||
return getDayRange(copy, offset);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
||||
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* A class that provide a base class for caching the results of
|
||||
* JAX-RS requests using the file system.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
* @param <S> The service interface.
|
||||
* @param <I> The input type.
|
||||
* @param <O> The output type.
|
||||
*/
|
||||
public abstract class RequestCache<S, I, O> {
|
||||
|
||||
/**
|
||||
* The logger to print debug output.
|
||||
*/
|
||||
protected Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
/**
|
||||
* The mapper to read and write json data.
|
||||
*/
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The folder used to cache the downloads.
|
||||
*/
|
||||
private File folder;
|
||||
|
||||
/**
|
||||
* The service class.
|
||||
*/
|
||||
private Class<S> service;
|
||||
|
||||
/**
|
||||
* The service to download the data.
|
||||
*/
|
||||
private S proxy;
|
||||
|
||||
/**
|
||||
* The base url for the service.
|
||||
*/
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* The output type.
|
||||
*/
|
||||
private Class<O> output;
|
||||
|
||||
/**
|
||||
* Creates a tile cache with the specified folder.
|
||||
*
|
||||
* @param baseUrl
|
||||
* The url to load the tiles form.
|
||||
* @param folder
|
||||
* The folder.
|
||||
* @param service
|
||||
* The service interface.
|
||||
* @param output
|
||||
* The output type.
|
||||
*/
|
||||
public RequestCache(Class<S> service, Class<O> output, String baseUrl, File folder) {
|
||||
this.output = output;
|
||||
this.folder = folder;
|
||||
this.baseUrl = baseUrl;
|
||||
this.service = service;
|
||||
folder.mkdirs();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the service for the base url and the class.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @param serviceClass The service class.
|
||||
* @return The proxy to the service.
|
||||
*/
|
||||
protected S getProxy(String baseUrl, Class<S> serviceClass) {
|
||||
if (this.proxy == null) {
|
||||
this.proxy = getWebTarget(baseUrl).proxy(serviceClass);
|
||||
}
|
||||
return this.proxy;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the web target for the url.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @return The web target for the url.
|
||||
*/
|
||||
public ResteasyWebTarget getWebTarget(String baseUrl) {
|
||||
ResteasyClientBuilder builder = new ResteasyClientBuilder();
|
||||
builder.httpEngine(new URLConnectionEngine());
|
||||
ResteasyClient client = builder.build();
|
||||
return client.target(baseUrl);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the data from the cache or downloads it, if it is not yet available.
|
||||
*
|
||||
* @param input The input to control what to download.
|
||||
* @return The output that has been fetched.
|
||||
* @throws IOException Thrown if the download fails.
|
||||
*/
|
||||
public O get(I input) throws IOException {
|
||||
File file = new File(folder, getFileName(input));
|
||||
if (file.exists()) {
|
||||
logger.log(Level.FINE, String.format("Loading data from %s.", file.getName()));
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String line = reader.readLine();
|
||||
return mapper.readValue(line, output);
|
||||
} catch (IOException e) {
|
||||
logger.log(Level.WARNING, String.format("Failed to load data from %s.", file.getName()), e);
|
||||
}
|
||||
}
|
||||
logger.log(Level.FINE, String.format("Downloading new data to %s.", file.getName()));
|
||||
O features = download(getProxy(baseUrl, service), input);
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
|
||||
writer.write(mapper.writeValueAsString(features));
|
||||
writer.flush();
|
||||
}
|
||||
return features;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file name for the input.
|
||||
*
|
||||
* @param input The input.
|
||||
* @return The file name of the input.
|
||||
*/
|
||||
protected abstract String getFileName(I input);
|
||||
|
||||
/**
|
||||
* Performs a download for a specific input.
|
||||
*
|
||||
* @param input The input.
|
||||
* @return The output from the download.
|
||||
* @throws IOException Thrown if the download fails.
|
||||
*/
|
||||
protected abstract O download(S service, I input) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.apache.commons.cli.ParseException;
|
||||
|
||||
/**
|
||||
* The string utilities.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class StringUtils {
|
||||
|
||||
/**
|
||||
* Parses year given as year-month-day and returns it as an array with 3 entries.
|
||||
*
|
||||
* @param name The name used to indicate the source of the problem, if parsing fails.
|
||||
* @param value The value to parse.
|
||||
* @return The double representing the value.
|
||||
* @throws ParseException Thrown if the value cannot be converted to a double.
|
||||
*/
|
||||
public static int[] toDate(String name, String value) throws ParseException {
|
||||
if (value == null)
|
||||
throw new ParseException(String.format("Missing parameter %s.", name));
|
||||
String[] tokens = value.trim().split("-");
|
||||
if (tokens.length < 3)
|
||||
throw new ParseException("Illegal date format.");
|
||||
int[] result = new int[3];
|
||||
result[0] = toInt("year", tokens[0]);
|
||||
result[1] = toInt("month", tokens[1]);
|
||||
result[2] = toInt("day", tokens[2]);
|
||||
if (result[1] > 12 || result[1] < 1)
|
||||
throw new ParseException("Illegal date format, invalid month.");
|
||||
if (result[2] > 31 || result[1] < 1)
|
||||
throw new ParseException("Illegal date format, invalid day.");
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an int from the value or throws an exception hinting at the name.
|
||||
*
|
||||
* @param name The name used to indicate the source of the problem, if parsing fails.
|
||||
* @param value The value to parse.
|
||||
* @return The int representing the value.
|
||||
* @throws ParseException Thrown if the value cannot be converted to an int.
|
||||
*/
|
||||
public static int toInt(String name, String value) throws ParseException{
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new ParseException(String.format("Failed to parse %s.", name));
|
||||
} catch (NullPointerException e) {
|
||||
throw new ParseException(String.format("Missing parameter %s.", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a long from the value or throws an exception hinting at the name.
|
||||
*
|
||||
* @param name The name used to indicate the source of the problem, if parsing fails.
|
||||
* @param value The value to parse.
|
||||
* @return The long representing the value.
|
||||
* @throws ParseException Thrown if the value cannot be converted to a long.
|
||||
*/
|
||||
public static long toLong(String name, String value) throws ParseException{
|
||||
try {
|
||||
return Long.parseLong(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new ParseException(String.format("Failed to parse %s.", name));
|
||||
} catch (NullPointerException e) {
|
||||
throw new ParseException(String.format("Missing parameter %s.", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a double from the value or throws an exception hinting at the name.
|
||||
*
|
||||
* @param name The name used to indicate the source of the problem, if parsing fails.
|
||||
* @param value The value to parse.
|
||||
* @return The double representing the value.
|
||||
* @throws ParseException Thrown if the value cannot be converted to a double.
|
||||
*/
|
||||
public static double toDouble(String name, String value) throws ParseException {
|
||||
try {
|
||||
return Double.parseDouble(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new ParseException(String.format("Failed to parse %s.", name));
|
||||
} catch (NullPointerException e) {
|
||||
throw new ParseException(String.format("Missing parameter %s.", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a time stamp into a string that is actually human readable.
|
||||
*
|
||||
* @param time The time.
|
||||
* @return The date time.
|
||||
*/
|
||||
public static String toDateTime(long time) {
|
||||
DateFormat format = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, Locale.GERMAN);
|
||||
return format.format(new Date(time));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.util.Enumeration;
|
||||
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.DefaultParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Option;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.tool.analysis.WeatherResolver.DataType;
|
||||
|
||||
/**
|
||||
* A quick and incomplete hack to experiment with the data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TraceGenerator {
|
||||
|
||||
/**
|
||||
* Runs the program.
|
||||
*
|
||||
* @param args The date, the period as well as the user name and password
|
||||
* of a user with administrative privileges.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Options options = new Options();
|
||||
Option dateOption = new Option("dt", "date", true, "The start date given as YYYY-MM-DD");
|
||||
options.addOption(dateOption);
|
||||
Option daysOption = new Option("pd", "days", true, "The period in days.");
|
||||
options.addOption(daysOption);
|
||||
Option userOption = new Option("u", "user", true, "The user name to login.");
|
||||
options.addOption(userOption);
|
||||
Option passOption = new Option("p", "pass", true, "The user password to login.");
|
||||
options.addOption(passOption);
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
// parse the inputs
|
||||
int[] date = StringUtils.toDate("date", cmd.getOptionValue(dateOption.getOpt()));
|
||||
int days = StringUtils.toInt("days", cmd.getOptionValue(daysOption.getOpt()));
|
||||
System.out.println(String.format("Year: %d Month: %d Day: %d - Days: %d", date[0], date[1], date[2], days));
|
||||
MeasurementFetcher fetcher = new MeasurementFetcher(cmd.getOptionValue(userOption.getOpt()), cmd.getOptionValue(passOption.getOpt()));
|
||||
BuildingResolver buildingResolver = new BuildingResolver();
|
||||
WeatherResolver weatherResolver = new WeatherResolver();
|
||||
RangeBuilder builder = new RangeBuilder(date[0], date[1], date[2]);
|
||||
Enumeration<TimeRange> enumeration = builder.getDayRanges(days);
|
||||
while (enumeration.hasMoreElements()) {
|
||||
TimeRange range = enumeration.nextElement();
|
||||
System.out.println("Fetching " + range.getStart() + " " + range.getDuration());
|
||||
Measurement[] ms = fetcher.fetch(range);
|
||||
for (Measurement m : ms) {
|
||||
if (m.getDevice() == 9732599) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
Object[] values = MeasurementType.BATTERY_TEMPERATURE.getValues(m.getData().get(MeasurementType.BATTERY_TEMPERATURE));
|
||||
if (values.length == 0 || values[0].getClass() != Double.class) continue;
|
||||
WeatherResolver.Resolution temp = weatherResolver.resolve(DataType.TEMPERATURE, m.getTime(), m.getCoordinate().getLongitude(), m.getCoordinate().getLatitude());
|
||||
if (temp == null) continue;
|
||||
BuildingResolver.Resolution building = buildingResolver.resolve(m.getCoordinate().getLongitude(), m.getCoordinate().getLatitude(), 200);
|
||||
boolean outside = (building == null) || (building.getDistance() > 50 && !building.isInside());
|
||||
double realTemp = temp.getReport().getTemperature();
|
||||
b.append(m.getDevice() + ", ");
|
||||
b.append(StringUtils.toDateTime(m.getTime()) + ", ");
|
||||
b.append(m.getTime() + ", ");
|
||||
b.append(values[0]+ ", ");
|
||||
b.append(realTemp + ", ");
|
||||
b.append(((Double)values[0] - realTemp) + ", ");
|
||||
b.append(outside);
|
||||
if (outside) {
|
||||
System.out.println(b.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(TraceGenerator.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
package com.mowesta.tool.analysis;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.DefaultParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Option;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
|
||||
import com.locoslab.library.geometry.wgs.Coordinate;
|
||||
import com.locoslab.library.geometry.wgs.Coordinates;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.weather.IWeatherService;
|
||||
import com.mowesta.api.weather.WeatherReport;
|
||||
import com.mowesta.api.weather.WeatherReportPage;
|
||||
import com.mowesta.api.weather.WeatherStation;
|
||||
import com.mowesta.api.weather.WeatherStationPage;
|
||||
|
||||
/**
|
||||
* A tool to resolve the weather information for a particular measurement.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class WeatherResolver {
|
||||
|
||||
/**
|
||||
* The data types that are contained in a weather report.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public enum DataType {
|
||||
/** The temperature. */
|
||||
TEMPERATURE,
|
||||
/** The air pressure. */
|
||||
PRESSURE,
|
||||
/** The relative humditiy. */
|
||||
HUMIDITY;
|
||||
|
||||
/**
|
||||
* Returns the value from the weather report
|
||||
* that corresponds to the data type.
|
||||
*
|
||||
* @param report The report.
|
||||
* @return The data or null, if the report is
|
||||
* null or does not contain the data.
|
||||
*/
|
||||
public Double getValue(WeatherReport report) {
|
||||
if (report == null) return null;
|
||||
switch (this) {
|
||||
case TEMPERATURE:
|
||||
return report.getTemperature();
|
||||
case PRESSURE:
|
||||
return report.getPressure();
|
||||
default:
|
||||
return report.getHumidity();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The url of the mowesta api.
|
||||
*/
|
||||
public static final String URL_BASE = "https://www.mowesta.com/api";
|
||||
|
||||
/**
|
||||
* The folder to store the results.
|
||||
*/
|
||||
public static final String FOLDER_CACHE = "weather-cache";
|
||||
|
||||
/**
|
||||
* The default page size.
|
||||
*/
|
||||
public static final int SIZE_PAGE = 500;
|
||||
|
||||
/**
|
||||
* The maximum distance to consider weather stations (100km).
|
||||
*/
|
||||
public static final double MAX_DISTANCE = 100000;
|
||||
|
||||
/**
|
||||
* The maximum delay to consider reports (1 hour).
|
||||
*/
|
||||
public static final long MAX_DELAY = 3600000;
|
||||
|
||||
/**
|
||||
* The cache to perform lookups.
|
||||
*/
|
||||
private ReportCache reportCache;
|
||||
|
||||
/**
|
||||
* The cache to find the stations for a reading.
|
||||
*/
|
||||
private StationCache stationCache;
|
||||
|
||||
/**
|
||||
* The maximum distance to the next weather station that we consider.
|
||||
*/
|
||||
private double maxDistance = MAX_DISTANCE;
|
||||
|
||||
/**
|
||||
* The maximum delay that we tolerate between measurement and report.
|
||||
*/
|
||||
private long maxDelay = MAX_DELAY;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Options options = new Options();
|
||||
Option longitudeOption = new Option("lng", "longitude", true, "The longitude of the coordinate.");
|
||||
options.addOption(longitudeOption);
|
||||
Option latitudeOption = new Option("lat", "latitude", true, "The latitude of the coordinate.");
|
||||
options.addOption(latitudeOption);
|
||||
Option rangeOption = new Option("t", "time", true, "The time to lookup.");
|
||||
options.addOption(rangeOption);
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
// parse the inputs
|
||||
double longitude = StringUtils.toDouble("longitude", cmd.getOptionValue(longitudeOption.getOpt()));
|
||||
double latitude = StringUtils.toDouble("latitude", cmd.getOptionValue(latitudeOption.getOpt()));
|
||||
long time = StringUtils.toLong("time", cmd.getOptionValue(rangeOption.getOpt()));
|
||||
// print the inputs
|
||||
System.out.println(String.format("Longitude: %.5f Latitude: %.5f Time: %d (%s)", longitude, latitude, time, StringUtils.toDateTime(time)));
|
||||
WeatherResolver resolver = new WeatherResolver();
|
||||
for (DataType type: DataType.values()) {
|
||||
Resolution resolution = resolver.resolve(type, time, longitude, latitude);
|
||||
if (resolution == null) {
|
||||
System.out.println(String.format("%s: No data found.", type.name()));
|
||||
} else {
|
||||
long t = resolution.getReport().getTime();
|
||||
double data = type.getValue(resolution.getReport());
|
||||
String station = resolution.getStation().getName();
|
||||
double distance = HaversineDistance.getDistance
|
||||
(longitude, latitude,
|
||||
resolution.getStation().getCoordinate().getLongitude(),
|
||||
resolution.getStation().getCoordinate().getLatitude());
|
||||
System.out.println(String.format("%s: %.2f on %d (%s) from %s (%.2f)", type.name(), data, t, StringUtils.toDateTime(t), station, distance));
|
||||
}
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(WeatherResolver.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a resolver with the default configuration.
|
||||
*/
|
||||
public WeatherResolver() {
|
||||
this(URL_BASE, new File(FOLDER_CACHE), SIZE_PAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new weather resolver with the specified cache folder,
|
||||
* base url and page size.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @param folder The folder to store cached data.
|
||||
* @param pageSize The page size.
|
||||
*/
|
||||
public WeatherResolver(String baseUrl, File folder, int pageSize) {
|
||||
this.reportCache = new ReportCache(baseUrl, folder, pageSize);
|
||||
this.stationCache = new StationCache(baseUrl, folder, pageSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum delay tolerated during lookups.
|
||||
*
|
||||
* @return The maximum delay in milliseconds.
|
||||
*/
|
||||
public long getMaxDelay() {
|
||||
return maxDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum delay tolerated during lookups.
|
||||
*
|
||||
* @param maxDelay The maximum delay in milliseconds.
|
||||
*/
|
||||
public void setMaxDelay(long maxDelay) {
|
||||
this.maxDelay = maxDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum distance tolerated during lookups.
|
||||
*
|
||||
* @return The maximum delay in meters.
|
||||
*/
|
||||
public double getMaxDistance() {
|
||||
return maxDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum distance tolerated during lookups.
|
||||
*
|
||||
* @param maxDistance The maximum distance.
|
||||
*/
|
||||
public void setMaxDistance(double maxDistance) {
|
||||
this.maxDistance = maxDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the best value of the specified type at the
|
||||
* specified time, latitude and longitude, considering
|
||||
* the maximum distance and delay thresholds.
|
||||
*
|
||||
* @param type The data type to lookup.
|
||||
* @param time The time to lookup.
|
||||
* @param longitude The latitude.
|
||||
* @param latitude The longitude.
|
||||
* @return The resolution or null, if none is found considering
|
||||
* the available data and the thresholds.
|
||||
* @throws IOException Thrown if the download fails.
|
||||
*/
|
||||
public Resolution resolve(DataType type, long time, double longitude, double latitude) throws IOException {
|
||||
Coordinate p = new Coordinate(longitude, latitude);
|
||||
WeatherStation[] stations = stationCache.get(null);
|
||||
// compute distances between stations and coordinate
|
||||
Map<WeatherStation, Double> distances = new HashMap<>();
|
||||
for (WeatherStation s: stations) {
|
||||
distances.put(s, Coordinates.DISTANCE.getDistance(p, new Coordinate(s.getCoordinate().getLongitude(), s.getCoordinate().getLatitude())));
|
||||
}
|
||||
// sort array by distance to p (nearer stations go first)
|
||||
Arrays.sort(stations, (a, b) -> (int)(distances.get(a) - distances.get(b)));
|
||||
for (int i = 0; i < stations.length; i++) {
|
||||
// check if station meets the distance threshold, if not, we're done
|
||||
if (distances.get(stations[i]) > maxDistance) return null;
|
||||
// get best value and return if not null
|
||||
WeatherReport result = getReport(type, time, stations[i]);
|
||||
if (result != null) return new Resolution(stations[i], result);
|
||||
}
|
||||
// all stations exhausted, return no result
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the weather value with the specified type from the specified
|
||||
* station that is closest to the specified time and within the maximum
|
||||
* delay bounds.
|
||||
*
|
||||
* @param type The data type.
|
||||
* @param time The time.
|
||||
* @param station The station.
|
||||
* @return The data type value or null, if no value is found within the
|
||||
* max delay bounds.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
private WeatherReport getReport(DataType type, long time, WeatherStation station) throws IOException {
|
||||
RangeBuilder builder = new RangeBuilder(time - MAX_DELAY);
|
||||
int offset = 0;
|
||||
WeatherReport best = null;
|
||||
TimeRange range;
|
||||
do {
|
||||
range = builder.getDayRange(offset);
|
||||
WeatherReport[] reports = reportCache.get(new ReportRequest(station.getId(), range));
|
||||
WeatherReport next = findReport(type, time, reports);
|
||||
if (next != null && Math.abs(time - next.getTime()) <= MAX_DELAY
|
||||
&& (best == null || Math.abs(time - next.getTime()) < Math.abs(time - best.getTime()))) {
|
||||
best = next;
|
||||
}
|
||||
offset += 1;
|
||||
} while (range.getEnd() < time + MAX_DELAY);
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the weather report that exhibits the specified data type and is closest
|
||||
* to the time stamp.
|
||||
*
|
||||
* @param type The data type to search.
|
||||
* @param time The time to perform the lookup.
|
||||
* @param reports The reports to search through.
|
||||
* @return The weather report that is closest and exhibits the type or null, if
|
||||
* such a report does not exist.
|
||||
*/
|
||||
private WeatherReport findReport(DataType type, long time, WeatherReport[] reports) {
|
||||
long delta = 0;
|
||||
int index = -1;
|
||||
for (int i = 0; i < reports.length; i++) {
|
||||
if (type.getValue(reports[i]) == null) continue;
|
||||
long d = Math.abs(reports[i].getTime() - time);
|
||||
if (index == -1 || delta > d) {
|
||||
index = i;
|
||||
delta = d;
|
||||
}
|
||||
}
|
||||
if (index < 0) return null;
|
||||
else return reports[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolution.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class Resolution {
|
||||
/**
|
||||
* The weather station.
|
||||
*/
|
||||
WeatherStation station;
|
||||
/**
|
||||
* The weather report.
|
||||
*/
|
||||
WeatherReport report;
|
||||
|
||||
/**
|
||||
* Creates a resolution.
|
||||
*
|
||||
* @param station The station.
|
||||
* @param report The report.
|
||||
*/
|
||||
public Resolution(WeatherStation station, WeatherReport report) {
|
||||
this.station = station;
|
||||
this.report = report;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the report.
|
||||
*
|
||||
* @return The report.
|
||||
*/
|
||||
public WeatherReport getReport() {
|
||||
return report;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the station.
|
||||
*
|
||||
* @return The station.
|
||||
*/
|
||||
public WeatherStation getStation() {
|
||||
return station;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A class to represent requests for station reports.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class ReportRequest {
|
||||
|
||||
/**
|
||||
* The time range to request.
|
||||
*/
|
||||
private TimeRange range;
|
||||
|
||||
/**
|
||||
* The stations to request.
|
||||
*/
|
||||
private long station;
|
||||
|
||||
/**
|
||||
* Creates a request for the station and time range.
|
||||
*
|
||||
* @param station The station.
|
||||
* @param range The time range.
|
||||
*/
|
||||
public ReportRequest(long station, TimeRange range) {
|
||||
this.station = station;
|
||||
this.range = range;
|
||||
}
|
||||
/**
|
||||
* Returns the station id.
|
||||
*
|
||||
* @return The station id.
|
||||
*/
|
||||
public long getStation() {
|
||||
return station;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time range.
|
||||
*
|
||||
* @return The time range.
|
||||
*/
|
||||
public TimeRange getRange() {
|
||||
return range;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A cache for storing weather data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class ReportCache extends RequestCache<IWeatherService, ReportRequest, WeatherReport[]> {
|
||||
|
||||
/**
|
||||
* The page size to fetch.
|
||||
*/
|
||||
private int pageSize;
|
||||
|
||||
/**
|
||||
* Creates a cache for weather reports.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @param folder The folder to store the data.
|
||||
* @param pageSize The page size.
|
||||
*/
|
||||
public ReportCache(String baseUrl, File folder, int pageSize) {
|
||||
super(IWeatherService.class, WeatherReport[].class, baseUrl, folder);
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getFileName(ReportRequest input) {
|
||||
return "report-" + input.getStation() + "-" + input.getRange().getStart() + "-" + input.getRange().getDuration() + ".json";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected WeatherReport[] download(IWeatherService service, ReportRequest input) throws IOException {
|
||||
int remainder = 0;
|
||||
List<WeatherReport> result = new ArrayList<>();
|
||||
PageConfig config = new PageConfig(0, pageSize);
|
||||
do {
|
||||
Response r = service.getStationReports(input.getStation(), input.getRange(), config);
|
||||
WeatherReportPage page = r.readEntity(WeatherReportPage.class);
|
||||
result.addAll(page.getElements());
|
||||
config.setOffset(config.getOffset() + pageSize);
|
||||
remainder = page.getTotal() - config.getOffset();
|
||||
} while (remainder > 0);
|
||||
return result.toArray(new WeatherReport[result.size()]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A cache for storing the list of weather stations.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class StationCache extends RequestCache<IWeatherService, Void, WeatherStation[]> {
|
||||
|
||||
/**
|
||||
* The page size to fetch.
|
||||
*/
|
||||
private int pageSize;
|
||||
|
||||
/**
|
||||
* Creates a cache for weather station.
|
||||
*
|
||||
* @param baseUrl The base url.
|
||||
* @param folder The folder to store the data.
|
||||
* @param pageSize The page size.
|
||||
*/
|
||||
public StationCache(String baseUrl, File folder, int pageSize) {
|
||||
super(IWeatherService.class, WeatherStation[].class, baseUrl, folder);
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getFileName(Void input) {
|
||||
return "stations.json";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected WeatherStation[] download(IWeatherService service, Void input) throws IOException {
|
||||
int remainder = 0;
|
||||
List<WeatherStation> result = new ArrayList<>();
|
||||
PageConfig config = new PageConfig(0, pageSize);
|
||||
do {
|
||||
Response r = service.getStations("", config);
|
||||
WeatherStationPage page = r.readEntity(WeatherStationPage.class);
|
||||
result.addAll(page.getElements());
|
||||
config.setOffset(config.getOffset() + pageSize);
|
||||
remainder = page.getTotal() - config.getOffset();
|
||||
} while (remainder > 0);
|
||||
return result.toArray(new WeatherStation[result.size()]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,11 +12,19 @@ dependencies {
|
||||
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
|
||||
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
|
||||
|
||||
compile "io.jsonwebtoken:jjwt-api:0.11.2"
|
||||
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
|
||||
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
|
||||
compile "org.bouncycastle:bcprov-jdk15on:1.60"
|
||||
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
|
||||
compile 'com.google.code.gson:gson:2.8.6'
|
||||
|
||||
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
providedCompile("org.jboss.resteasy:resteasy-client:${versionResteasy}") {
|
||||
exclude group: 'org.reactivestreams', module: 'reactive-streams'
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
jar {
|
||||
|
||||
@@ -1,17 +1,29 @@
|
||||
package com.mowesta.service.app;
|
||||
|
||||
import com.mowesta.service.access.AccessControlFilter;
|
||||
import com.mowesta.service.rest.*;
|
||||
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
|
||||
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
|
||||
|
||||
import com.mowesta.service.access.AccessControlFilter;
|
||||
import com.mowesta.service.rest.CorsResponseFilter;
|
||||
import com.mowesta.service.rest.DeviceResource;
|
||||
import com.mowesta.service.rest.LocationResource;
|
||||
import com.mowesta.service.rest.LogResource;
|
||||
import com.mowesta.service.rest.MeasurementResource;
|
||||
import com.mowesta.service.rest.ProcessingTimeFilter;
|
||||
import com.mowesta.service.rest.ServerDebugFilter;
|
||||
import com.mowesta.service.rest.SettingsResource;
|
||||
import com.mowesta.service.rest.UserResource;
|
||||
import com.mowesta.service.rest.VersionResource;
|
||||
import com.mowesta.service.rest.WeatherResource;
|
||||
|
||||
/**
|
||||
* The application is the main entry point of JAX-RS.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
@@ -22,7 +34,7 @@ public class MowestaApplication extends Application {
|
||||
* The cors filter implementing the cors policy.
|
||||
*/
|
||||
protected CorsFilter corsFilter = new CorsFilter();
|
||||
|
||||
|
||||
/**
|
||||
* The set of classes.
|
||||
*/
|
||||
@@ -32,7 +44,7 @@ public class MowestaApplication extends Application {
|
||||
* The singleton objects.
|
||||
*/
|
||||
protected Set<Object> singletons = new HashSet<>();
|
||||
|
||||
|
||||
/**
|
||||
* Initializes the application and explicitly
|
||||
* sets the cors policy and the exposed resources.
|
||||
@@ -57,17 +69,17 @@ public class MowestaApplication extends Application {
|
||||
classes.add(SettingsResource.class);
|
||||
classes.add(CorsResponseFilter.class);
|
||||
// uncomment to enable heavy debugging
|
||||
// classes.add(ServerDebugFilter.class);
|
||||
classes.add(ServerDebugFilter.class);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<Object> getSingletons() {
|
||||
return singletons;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<Class<?>> getClasses() {
|
||||
return classes;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -33,22 +33,22 @@ import com.mowesta.service.principal.LoginManager;
|
||||
import com.mowesta.service.principal.MowestaPrincipal;
|
||||
|
||||
/**
|
||||
* The server authentication module that
|
||||
*
|
||||
* The server authentication module that
|
||||
*
|
||||
*/
|
||||
public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
|
||||
|
||||
/**
|
||||
* The realm transmitted as part of a challenge.
|
||||
*/
|
||||
public static final String REALM_CHALLENGE = "Basic realm=\"mowesta-api\"";
|
||||
|
||||
|
||||
/**
|
||||
* The "magic" parameter that enables challenges.
|
||||
*/
|
||||
public static final String PARAMETER_CHALLENGE = "testAuth";
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The logger to write debug data to the console.
|
||||
*/
|
||||
@@ -56,7 +56,6 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
|
||||
@Override
|
||||
protected AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
|
||||
|
||||
// extract credentials from (possibly multiple headers)
|
||||
HttpServletRequest request = messageInfo.getRequest();
|
||||
BearerAuthCredential deviceCredential = null;
|
||||
@@ -68,8 +67,10 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
String[] subHeaders = header.split(",");
|
||||
for (String subHeader: subHeaders) {
|
||||
subHeader = subHeader.trim();
|
||||
if (deviceCredential == null) deviceCredential = BearerAuthCredential.valueOf(subHeader);
|
||||
if (userCredential == null) userCredential = BasicAuthCredential.valueOf(subHeader);
|
||||
if (deviceCredential == null)
|
||||
deviceCredential = BearerAuthCredential.valueOf(subHeader);
|
||||
if (userCredential == null)
|
||||
userCredential = BasicAuthCredential.valueOf(subHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,7 +84,7 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
return sendForbidden(messageInfo, "Access not allowed.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// perform user and device authentication
|
||||
Device device = null;
|
||||
User user = null;
|
||||
@@ -99,15 +100,16 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
try {
|
||||
LoginManager manager = new LoginManager(em);
|
||||
ta.begin();
|
||||
if (deviceCredential != null) device = manager.login(deviceCredential.getToken());
|
||||
if (userCredential != null) user = manager.login(userCredential.getUsername(), userCredential.getPassword());
|
||||
if (deviceCredential != null)
|
||||
device = manager.login(deviceCredential.getToken());
|
||||
if (userCredential != null)
|
||||
user = manager.login(userCredential.getUsername(), userCredential.getPassword());
|
||||
} finally {
|
||||
ta.commit();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return sendServerError(messageInfo, "Transactional error.");
|
||||
}
|
||||
|
||||
// create principal or issue error
|
||||
if (user != null || device != null) {
|
||||
// create principal
|
||||
@@ -143,11 +145,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
return sendForbidden(messageInfo, "Access not allowed.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Tests whether the request requires an auth challenge to be sent out.
|
||||
* This is done, if the caller has set the
|
||||
*
|
||||
*
|
||||
* @param request The request.
|
||||
* @return
|
||||
*/
|
||||
@@ -163,37 +165,37 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
|
||||
/**
|
||||
* Returns the entity manager for the mowesta datastore.
|
||||
*
|
||||
*
|
||||
* @return The entity manager or null, if the entity manager cannot be found.
|
||||
*/
|
||||
private EntityManager getEntityManager() {
|
||||
try {
|
||||
Context context = new InitialContext();
|
||||
return (EntityManager)context.lookup("java:app/mowesta/datastore");
|
||||
return (EntityManager)context.lookup("java:app/mowesta/datastore");
|
||||
} catch (NamingException e) {
|
||||
log.log(Level.SEVERE, "Failed to resolve entity manager.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a user transaction for the datastore.
|
||||
*
|
||||
*
|
||||
* @return The user transaction or null, if the transaction cannot be found.
|
||||
*/
|
||||
private UserTransaction getUserTransaction() {
|
||||
try {
|
||||
Context context = new InitialContext();
|
||||
return (UserTransaction)context.lookup("java:comp/UserTransaction");
|
||||
return (UserTransaction)context.lookup("java:comp/UserTransaction");
|
||||
} catch (NamingException e) {
|
||||
log.log(Level.SEVERE, "Failed to resolve user transaction.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a forbidden message and returns failed.
|
||||
*
|
||||
*
|
||||
* @param messageInfo The message info.
|
||||
* @param message The error message.
|
||||
* @return AuthStatus.FAILED
|
||||
@@ -202,11 +204,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
HttpServletResponse response = messageInfo.getResponse();
|
||||
return sendError(response, HttpServletResponse.SC_FORBIDDEN, message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends an unauthorized message and returns failed. A browser will create a
|
||||
* credentials dialog in response to receiving this message.
|
||||
*
|
||||
*
|
||||
* @param messageInfo The message info.
|
||||
* @param message The error message.
|
||||
* @return AuthStatus.FAILED
|
||||
@@ -216,10 +218,10 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, REALM_CHALLENGE);
|
||||
return sendError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a server error and returns a auth status failure.
|
||||
*
|
||||
*
|
||||
* @param messageInfo The message info.
|
||||
* @param message The error message.
|
||||
* @return AuthStatus.FAILED
|
||||
@@ -227,11 +229,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
private AuthStatus sendServerError(HttpServletMessageInfo messageInfo, String message) {
|
||||
return sendError(messageInfo.getResponse(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sends an http error with the specified code and message and returns failure.
|
||||
*
|
||||
*
|
||||
* @param response The servlet response.
|
||||
* @param code The message code.
|
||||
* @param message The error message.
|
||||
@@ -239,11 +241,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
|
||||
*/
|
||||
private AuthStatus sendError(HttpServletResponse response, int code, String message) {
|
||||
try {
|
||||
response.sendError(code, message);
|
||||
response.sendError(code, message);
|
||||
} catch (IOException e) {
|
||||
log.log(Level.WARNING, "Failed to send error " + code + " " + message + ".", e);
|
||||
}
|
||||
return AuthStatus.FAILURE;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -15,42 +17,39 @@ import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import javax.ws.rs.container.ContainerResponseContext;
|
||||
import javax.ws.rs.container.ContainerResponseFilter;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
|
||||
/**
|
||||
* A filter that provides heavy (i.e. expensive) debug output after the
|
||||
* completion of each request.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Provider
|
||||
public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequestFilter {
|
||||
|
||||
|
||||
@Inject
|
||||
Logger log;
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) throws IOException {
|
||||
log.log(Level.INFO, "Request: " + requestContext.getMethod() + " " + requestContext.getUriInfo().getAbsolutePath().toString());
|
||||
printParameters("Path", requestContext.getUriInfo().getPathParameters());
|
||||
printParameters("Query", requestContext.getUriInfo().getQueryParameters());
|
||||
List<String> authHeaders = requestContext.getHeaders().get(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeaders != null) {
|
||||
for (String authHeader: authHeaders) {
|
||||
log.log(Level.INFO, " Authorization: " + authHeader);
|
||||
}
|
||||
Map<String, List<String>> allHeaders = requestContext.getHeaders();
|
||||
for (Entry<String, List<String>> e: allHeaders.entrySet()) {
|
||||
for (String s: e.getValue()) {
|
||||
log.log(Level.INFO, " " + e.getKey() + ": " + s);
|
||||
}
|
||||
}
|
||||
log.log(Level.INFO, " Accept: " + requestContext.getHeaderString(HttpHeaders.ACCEPT));
|
||||
log.log(Level.INFO, " Encoding: " + requestContext.getHeaderString(HttpHeaders.ACCEPT_ENCODING));
|
||||
byte[] data = readBytes(requestContext.getEntityStream());
|
||||
if (data != null) {
|
||||
if (data.length > 0) {
|
||||
log.log(Level.INFO, "Begin request entity (" + data.length + " bytes):");
|
||||
log.log(Level.INFO, new String(data, "UTF-8"));
|
||||
log.log(Level.INFO, "End request entity.");
|
||||
log.log(Level.INFO, "End request entity.");
|
||||
} else {
|
||||
log.log(Level.INFO, "Request entity has 0 bytes.");
|
||||
}
|
||||
@@ -59,10 +58,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
|
||||
log.log(Level.INFO, "Request entity stream is null.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prints a parameter map.
|
||||
*
|
||||
*
|
||||
* @param type The parameter type.
|
||||
* @param params The parameter map.
|
||||
*/
|
||||
@@ -77,10 +76,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
|
||||
log.log(Level.INFO, " " + paramName + " = " + b.toString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Logs most parts of the request and the resulting response.
|
||||
*
|
||||
*
|
||||
* @param requestContext The request context.
|
||||
* @param responseContext The response context.
|
||||
*/
|
||||
@@ -98,13 +97,13 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
|
||||
log.log(Level.INFO, "Result header: " + key + ": " + o);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Copies the response entity from the input stream and returns it.
|
||||
*
|
||||
*
|
||||
* @param is The input stream which may be null.
|
||||
* @return The bytes that have been read or null (if the input stream
|
||||
* is null).
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.mowesta.service.servlet;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.mowesta.api.oauth2.AuthorizationResponse;
|
||||
import com.mowesta.api.user.User;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.attribute.UserPrincipalNotFoundException;
|
||||
import java.security.Key;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.UnsupportedJwtException;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
@WebServlet(urlPatterns = "/oauth2/authorize")
|
||||
public class OAuthAccessCodeServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final long timeAccessCodeIsValidInMilliSeconds = 240000;
|
||||
protected static final String secretKey = "SecretForGeneratingAccessCode730474";
|
||||
|
||||
//only authorization code is supported
|
||||
private final List<String> supportedGrantTypes = Arrays.asList("code");
|
||||
|
||||
@Inject
|
||||
protected EntityManager em;
|
||||
|
||||
@Inject
|
||||
UserSessionBean userSessionBean;
|
||||
|
||||
Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
|
||||
String client_id = "";
|
||||
String redirect_uri = "";
|
||||
String response_type = "";
|
||||
String state = "";
|
||||
String scope = "";
|
||||
|
||||
logger.log(Level.INFO, "Received Authorize Request - HEADER:");
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while(headerNames.hasMoreElements()) {
|
||||
String headerName = headerNames.nextElement();
|
||||
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
|
||||
Enumeration<String> parameterNames = request.getParameterNames();
|
||||
while(parameterNames.hasMoreElements()) {
|
||||
String paramName = parameterNames.nextElement();
|
||||
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
|
||||
}
|
||||
logger.log(Level.INFO, "End Authorize request.");
|
||||
|
||||
Enumeration<String> params = request.getParameterNames();
|
||||
while(params.hasMoreElements()){
|
||||
String paramName = params.nextElement();
|
||||
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
|
||||
if (paramName.equals("redirect_uri")) redirect_uri = request.getParameter(paramName);
|
||||
if (paramName.equals("response_type")) response_type = request.getParameter(paramName);
|
||||
if (paramName.equals("state")) state = request.getParameter(paramName);
|
||||
if (paramName.equals("scope")) scope = request.getParameter(paramName);
|
||||
}
|
||||
|
||||
//logger.log(Level.INFO, "Authorize Request with: clientid " + client_id + "; redirect_uri: " + redirect_uri + "; response_type " + response_type + "; state:" + state + "; scope: " + scope);
|
||||
|
||||
if (!supportedGrantTypes.contains(response_type)) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Grant Type currently not supported.");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("Grant Type currently not supported.");
|
||||
}
|
||||
|
||||
// state and scope are optional, checking if client_id, redirect_uri and response type is set
|
||||
if (Arrays.asList(client_id, redirect_uri, response_type).contains("")) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Please provide a client_id, redirect_uri and response_type.");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
|
||||
}
|
||||
|
||||
//an authorization code can only be generated if user is logged in
|
||||
if (request.getUserPrincipal() != null || request.authenticate(response)) {
|
||||
logger.log(Level.INFO, "UserPrincipal: " + request.getUserPrincipal().getName());
|
||||
|
||||
//Principal is set, we can use the UserSessionBean to get the current user
|
||||
try {
|
||||
User user = userSessionBean.getCurrentUser();
|
||||
logger.log(Level.INFO, "User: " + user.getName() + " with ID:" + user.getId() + "and login: " + user.getLogin());
|
||||
|
||||
//generate AccessCode
|
||||
String accessCode = createAccessCode(user.getLogin());
|
||||
String base64Accesscode = Base64.getUrlEncoder().encodeToString(accessCode.getBytes());
|
||||
|
||||
AuthorizationResponse authorizationResponse = new AuthorizationResponse();
|
||||
authorizationResponse.setAccessCode(base64Accesscode);
|
||||
Gson gson = new Gson();
|
||||
String jsonAuthorizationResponse = gson.toJson(authorizationResponse);
|
||||
|
||||
//generate Response
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
PrintWriter out = response.getWriter();
|
||||
out.print(jsonAuthorizationResponse);
|
||||
out.flush();
|
||||
out.close();
|
||||
} catch (EntityForbiddenException e) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Could not identify user.");
|
||||
w.close();
|
||||
throw new UserPrincipalNotFoundException("Could not identify user");
|
||||
} catch (EntityNotFoundException e) {
|
||||
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("An error occurred. Please try again.");
|
||||
w.close();
|
||||
throw new UserPrincipalNotFoundException("Could not identify user");
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Could not identify user.");
|
||||
w.close();
|
||||
throw new UserPrincipalNotFoundException("Could not identify user");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String createAccessCode(String id) {
|
||||
Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
|
||||
|
||||
return Jwts.builder()
|
||||
.setSubject("mowesta:access")
|
||||
.setId(id)
|
||||
.setIssuedAt(new Date())
|
||||
.setNotBefore(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + timeAccessCodeIsValidInMilliSeconds))
|
||||
.signWith(key).compact();
|
||||
}
|
||||
|
||||
|
||||
public String getAccessToken(String refreshToken, String secret) {
|
||||
Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes())).build().parseClaimsJws(refreshToken).getBody().getSubject().equals("access");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package com.mowesta.service.servlet;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.mowesta.api.oauth2.TokenResponse;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.OAuthSecretEntity;
|
||||
import com.mowesta.service.entity.RefreshTokenEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Key;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.UnsupportedJwtException;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
@WebServlet(urlPatterns = "/oauth2/token")
|
||||
public class OAuthTokenServlet extends HttpServlet {
|
||||
//only authorization code is supported
|
||||
enum SupportedGrantTypes {
|
||||
authorization_code ("authorization_code"),
|
||||
refresh_token ("refresh_token");
|
||||
|
||||
private final String identifier;
|
||||
|
||||
private SupportedGrantTypes(String s) {
|
||||
identifier = s;
|
||||
}
|
||||
|
||||
public boolean equals(String other) {
|
||||
// (otherName == null) check is not needed because name.equals(null) returns false
|
||||
return identifier.equals(other);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.identifier;
|
||||
}
|
||||
}
|
||||
private final List<String> supportedGrantTypes = Arrays.asList("authorization_code, refresh_token");
|
||||
private static final long timeAccessTokenIsValidInMilliSeconds = 360000;
|
||||
|
||||
|
||||
@Inject
|
||||
protected EntityManager em;
|
||||
|
||||
@Inject
|
||||
protected UserSessionBean userSessionBean;
|
||||
|
||||
Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException {
|
||||
String code = "";
|
||||
|
||||
logger.log(Level.INFO, "Received Token Request - HEADER:");
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while(headerNames.hasMoreElements()) {
|
||||
String headerName = headerNames.nextElement();
|
||||
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
|
||||
Enumeration<String> parameterNames = request.getParameterNames();
|
||||
while(parameterNames.hasMoreElements()) {
|
||||
String paramName = parameterNames.nextElement();
|
||||
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
|
||||
}
|
||||
logger.log(Level.INFO, "End Token request.");
|
||||
|
||||
response.setHeader("Cache-Control", "no-cache, no-store");
|
||||
response.setHeader("Pragma", "no-cache");
|
||||
|
||||
|
||||
Enumeration<String> params = request.getParameterNames();
|
||||
while (params.hasMoreElements()) {
|
||||
String paramName = params.nextElement();
|
||||
if (paramName.equals("grant_type")) code = request.getParameter(paramName);
|
||||
}
|
||||
//if code is present in request, verify and return refresh/accesstoken pair
|
||||
if (code.equals("authorization_code")) {
|
||||
handleAccessCodeRequest(request, response);
|
||||
} else if (code.equals("refresh_token")) {
|
||||
handleRefreshTokenRequest(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRefreshTokenRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String grant_type = "";
|
||||
String client_id = "";
|
||||
String refresh_token = "";
|
||||
String code = "";
|
||||
|
||||
Enumeration<String> params = request.getParameterNames();
|
||||
while (params.hasMoreElements()) {
|
||||
String paramName = params.nextElement();
|
||||
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
|
||||
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
|
||||
if (paramName.equals("refresh_token")) refresh_token = request.getParameter(paramName);
|
||||
}
|
||||
|
||||
if (Arrays.asList(grant_type, refresh_token).contains("")) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Please provide a refresh token.");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("Request needs to include grant type and refresh_token.");
|
||||
}
|
||||
|
||||
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
|
||||
|
||||
//find the current secret to generate an AccessToken
|
||||
if (!secretKey.isPresent()) {
|
||||
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("An error occurred. Please try again.");
|
||||
w.close();
|
||||
}
|
||||
|
||||
try {
|
||||
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(code).getBody();
|
||||
String userId = claims.getId();
|
||||
UserEntity u = userSessionBean.findUser(userId);
|
||||
if (u == null)
|
||||
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
|
||||
|
||||
|
||||
String accessToken = createAccessTokenForUser(u, secretKey.get());
|
||||
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
|
||||
|
||||
|
||||
TokenResponse tokenResponse = new TokenResponse();
|
||||
tokenResponse.setAccess_token(accessToken);
|
||||
tokenResponse.setToken_type("bearer");
|
||||
tokenResponse.setExpires_in(accessTokenExpirationTime);
|
||||
|
||||
Gson gson = new Gson();
|
||||
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
|
||||
|
||||
logger.log(Level.INFO, "Token response: " + tokenResponse.getAccess_token() + " " + tokenResponse.getToken_type() + " " + tokenResponse.getExpires_in());
|
||||
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write(jsonAuthorizationResponse);
|
||||
w.close();
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void handleAccessCodeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String grant_type = "";
|
||||
String client_id = "";
|
||||
String client_secret = "";
|
||||
String code = "";
|
||||
|
||||
Enumeration<String> params = request.getParameterNames();
|
||||
while (params.hasMoreElements()) {
|
||||
String paramName = params.nextElement();
|
||||
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
|
||||
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
|
||||
if (paramName.equals("code")) code = request.getParameter(paramName);
|
||||
}
|
||||
|
||||
if (Arrays.asList(grant_type, client_id, code).contains("")) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Please provide a client_id and accesscode.");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] accessClaimBytes = Base64.getUrlDecoder().decode(code);
|
||||
String accessClaimString = new String(accessClaimBytes, StandardCharsets.UTF_8);
|
||||
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(accessClaimString).getBody();
|
||||
|
||||
if (new Date().after(claims.getExpiration())) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("AccessCode was invalid");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("AccessCode expired.");
|
||||
}
|
||||
|
||||
String userId = claims.getId();
|
||||
logger.log(Level.INFO, "Claims had userID: " + userId);
|
||||
UserEntity u = userSessionBean.findUser(userId);
|
||||
if (u == null)
|
||||
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
|
||||
|
||||
//here we could use client secret to identify service type (for example alexa as service type)
|
||||
|
||||
String refreshToken = createRefreshTokenForUser(u);
|
||||
|
||||
RefreshTokenEntity refreshTokenEntity = new RefreshTokenEntity();
|
||||
refreshTokenEntity.setRefreshToken(refreshToken);
|
||||
refreshTokenEntity.setServiceName("dummy");
|
||||
|
||||
userSessionBean.addRefreshTokenToUser(userId, refreshTokenEntity);
|
||||
|
||||
|
||||
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
|
||||
|
||||
//find the current secret to generate an AccessToken
|
||||
if (!secretKey.isPresent()) {
|
||||
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("An error occurred. Please try again.");
|
||||
w.close();
|
||||
}
|
||||
|
||||
String accessToken = createAccessTokenForUser(u, secretKey.get());
|
||||
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
|
||||
|
||||
TokenResponse tokenResponse = new TokenResponse();
|
||||
tokenResponse.setAccess_token(accessToken);
|
||||
tokenResponse.setExpires_in(accessTokenExpirationTime);
|
||||
tokenResponse.setRefresh_token(refreshToken);
|
||||
tokenResponse.setToken_type("bearer");
|
||||
|
||||
Gson gson = new Gson();
|
||||
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
|
||||
|
||||
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write(jsonAuthorizationResponse);
|
||||
w.close();
|
||||
|
||||
|
||||
} catch (JwtException | EntityNotFoundException e) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.setContentType("text/plain");
|
||||
BufferedWriter w = new BufferedWriter(response.getWriter());
|
||||
w.write("Something went wrong.");
|
||||
w.close();
|
||||
throw new UnsupportedJwtException("AccessCode could not be verified.");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return returns an refresh token. The refresh token is signed with a static secret and is mapped to a user
|
||||
*/
|
||||
private String createRefreshTokenForUser(UserEntity userEntity) {
|
||||
Key key = Keys.hmacShaKeyFor(OAuthAccessCodeServlet.secretKey.getBytes());
|
||||
|
||||
return Jwts.builder()
|
||||
.setSubject("mowesta:refresh:token")
|
||||
.setId(String.valueOf(userEntity.getLogin()))
|
||||
.setIssuedAt(new Date())
|
||||
.setNotBefore(new Date())
|
||||
.signWith(key).compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param userEntity
|
||||
* @param oAuthSecretEntity
|
||||
* @return returns an access token. An access token includes a user id and expiration date in his body and is signed with a dynamically changing key.
|
||||
*/
|
||||
private String createAccessTokenForUser(UserEntity userEntity, OAuthSecretEntity oAuthSecretEntity) {
|
||||
Key key = Keys.hmacShaKeyFor(oAuthSecretEntity.getSecret().getBytes());
|
||||
return Jwts.builder()
|
||||
.setSubject("mowesta:acess:token")
|
||||
.setId(String.valueOf(userEntity.getId()))
|
||||
.setIssuedAt(new Date())
|
||||
.setNotBefore(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + timeAccessTokenIsValidInMilliSeconds))
|
||||
.signWith(key).compact();
|
||||
}
|
||||
|
||||
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
|
||||
TypedQuery<OAuthSecretEntity> query = em.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
|
||||
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
|
||||
|
||||
return oAuthSecretEntityList.stream()
|
||||
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
|
||||
.findAny();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
<filter-name>Resteasy</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
|
||||
@@ -26,6 +26,7 @@ public class WarDeployment {
|
||||
public static JavaArchive createEjb() {
|
||||
return mergeLibraries(ShrinkWrap.create(JavaArchive.class, "ejb.jar")) // name used in ear (see application.xml)
|
||||
.addPackages(true, "org.geojson")
|
||||
.addPackages(true, "io.jsonwebtoken")
|
||||
.addPackages(true, "org.apache.commons.compress")
|
||||
.addPackages(true, "com.mowesta.api")
|
||||
.addPackages(true, "com.mowesta.data")
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
"builder": "@angular-devkit/build-angular:browser",
|
||||
"options": {
|
||||
"aot": true,
|
||||
"outputPath": "dist",
|
||||
"baseHref": "/app/",
|
||||
"outputPath": "build/outputs/mowesta-app",
|
||||
"index": "src/index.html",
|
||||
"main": "src/main.ts",
|
||||
"tsConfig": "src/tsconfig.app.json",
|
||||
@@ -20,12 +21,15 @@
|
||||
"assets": [
|
||||
"src/assets",
|
||||
"src/favicon.ico"
|
||||
],
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.scss",
|
||||
"node_modules/video.js/dist/video-js.min.css",
|
||||
"node_modules/videojs-overlay/dist/videojs-overlay.css"
|
||||
],
|
||||
"allowedCommonJsDependencies": [
|
||||
"video.js", "mux.js", "xhr", "videojs-vtt.js", "global/document"
|
||||
],
|
||||
"scripts": []
|
||||
},
|
||||
"configurations": {
|
||||
@@ -55,7 +59,6 @@
|
||||
"serve": {
|
||||
"builder": "@angular-devkit/build-angular:dev-server",
|
||||
"options": {
|
||||
"baseHref": "/app",
|
||||
"browserTarget": "webapp-ng:build",
|
||||
"proxyConfig": "proxy.conf.json"
|
||||
},
|
||||
@@ -129,37 +132,37 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"weather-forecast-today": {
|
||||
"mowesta-forecast": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"style": "scss"
|
||||
}
|
||||
},
|
||||
"root": "projects/weather-forecast-today",
|
||||
"sourceRoot": "projects/weather-forecast-today/src",
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular-devkit/build-angular:browser",
|
||||
"options": {
|
||||
"outputPath": "dist/weather-forecast-today",
|
||||
"index": "projects/weather-forecast-today/src/index.html",
|
||||
"main": "projects/weather-forecast-today/src/main.ts",
|
||||
"polyfills": "projects/weather-forecast-today/src/polyfills.ts",
|
||||
"tsConfig": "projects/weather-forecast-today/tsconfig.app.json",
|
||||
"outputPath": "build/outputs/mowesta-forecast",
|
||||
"index": "src/elements/forecast/index.html",
|
||||
"main": "src/elements/forecast/main.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "src/elements/forecast/tsconfig.app.json",
|
||||
"aot": true,
|
||||
"assets": [
|
||||
"projects/weather-forecast-today/src/favicon.ico",
|
||||
"projects/weather-forecast-today/src/assets"
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
],
|
||||
"styles": [
|
||||
"projects/weather-forecast-today/src/styles.scss"
|
||||
"src/styles.scss"
|
||||
],
|
||||
"scripts": [],
|
||||
"stylePreprocessorOptions": {
|
||||
"includePaths": [
|
||||
"projects/weather-forecast-today/src/"
|
||||
"src/elements/forecast"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -167,8 +170,8 @@
|
||||
"production": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "projects/weather-forecast-today/src/environments/environment.ts",
|
||||
"with": "projects/weather-forecast-today/src/environments/environment.prod.ts"
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
],
|
||||
"optimization": true,
|
||||
@@ -195,90 +198,53 @@
|
||||
"serve": {
|
||||
"builder": "@angular-devkit/build-angular:dev-server",
|
||||
"options": {
|
||||
"browserTarget": "weather-forecast-today:build"
|
||||
"browserTarget": "mowesta-forecast:build"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"browserTarget": "weather-forecast-today:build:production"
|
||||
"browserTarget": "mowesta-forecast:build:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extract-i18n": {
|
||||
"builder": "@angular-devkit/build-angular:extract-i18n",
|
||||
"options": {
|
||||
"browserTarget": "weather-forecast-today:build"
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular-devkit/build-angular:karma",
|
||||
"options": {
|
||||
"main": "projects/weather-forecast-today/src/test.ts",
|
||||
"polyfills": "projects/weather-forecast-today/src/polyfills.ts",
|
||||
"tsConfig": "projects/weather-forecast-today/tsconfig.spec.json",
|
||||
"karmaConfig": "projects/weather-forecast-today/karma.conf.js",
|
||||
"assets": [
|
||||
"projects/weather-forecast-today/src/favicon.ico",
|
||||
"projects/weather-forecast-today/src/assets"
|
||||
],
|
||||
"styles": [
|
||||
"projects/weather-forecast-today/src/styles.scss"
|
||||
],
|
||||
"scripts": []
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"builder": "@angular-devkit/build-angular:tslint",
|
||||
"options": {
|
||||
"tsConfig": [
|
||||
"projects/weather-forecast-today/tsconfig.app.json",
|
||||
"projects/weather-forecast-today/tsconfig.spec.json",
|
||||
"projects/weather-forecast-today/e2e/tsconfig.json"
|
||||
"src/elements/forecast/tsconfig.app.json"
|
||||
],
|
||||
"exclude": [
|
||||
"**/node_modules/**"
|
||||
]
|
||||
}
|
||||
},
|
||||
"e2e": {
|
||||
"builder": "@angular-devkit/build-angular:protractor",
|
||||
"options": {
|
||||
"protractorConfig": "projects/weather-forecast-today/e2e/protractor.conf.js",
|
||||
"devServerTarget": "weather-forecast-today:serve"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"devServerTarget": "weather-forecast-today:serve:production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"weather-search": {
|
||||
"mowesta-search": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"style": "scss"
|
||||
}
|
||||
},
|
||||
"root": "projects/weather-search",
|
||||
"sourceRoot": "projects/weather-search/src",
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular-devkit/build-angular:browser",
|
||||
"options": {
|
||||
"outputPath": "dist/weather-search",
|
||||
"index": "projects/weather-search/src/index.html",
|
||||
"main": "projects/weather-search/src/main.ts",
|
||||
"polyfills": "projects/weather-search/src/polyfills.ts",
|
||||
"tsConfig": "projects/weather-search/tsconfig.app.json",
|
||||
"outputPath": "build/outputs/mowesta-search",
|
||||
"index": "src/elements/search/index.html",
|
||||
"main": "src/elements/search/main.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "src/elements/search/tsconfig.app.json",
|
||||
"aot": true,
|
||||
"assets": [
|
||||
"projects/weather-search/src/favicon.ico",
|
||||
"projects/weather-search/src/assets"
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
],
|
||||
"styles": [
|
||||
"projects/weather-search/src/styles.scss"
|
||||
"src/styles.scss"
|
||||
],
|
||||
"scripts": []
|
||||
},
|
||||
@@ -286,8 +252,8 @@
|
||||
"production": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "projects/weather-search/src/environments/environment.ts",
|
||||
"with": "projects/weather-search/src/environments/environment.prod.ts"
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
],
|
||||
"optimization": true,
|
||||
@@ -314,62 +280,25 @@
|
||||
"serve": {
|
||||
"builder": "@angular-devkit/build-angular:dev-server",
|
||||
"options": {
|
||||
"browserTarget": "weather-search:build",
|
||||
"browserTarget": "mowesta-search:build",
|
||||
"proxyConfig": "proxy.conf.json"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"browserTarget": "weather-search:build:production"
|
||||
"browserTarget": "mowesta-search:build:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extract-i18n": {
|
||||
"builder": "@angular-devkit/build-angular:extract-i18n",
|
||||
"options": {
|
||||
"browserTarget": "weather-search:build"
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular-devkit/build-angular:karma",
|
||||
"options": {
|
||||
"main": "projects/weather-search/src/test.ts",
|
||||
"polyfills": "projects/weather-search/src/polyfills.ts",
|
||||
"tsConfig": "projects/weather-search/tsconfig.spec.json",
|
||||
"karmaConfig": "projects/weather-search/karma.conf.js",
|
||||
"assets": [
|
||||
"projects/weather-search/src/favicon.ico",
|
||||
"projects/weather-search/src/assets"
|
||||
],
|
||||
"styles": [
|
||||
"projects/weather-search/src/styles.scss"
|
||||
],
|
||||
"scripts": []
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"builder": "@angular-devkit/build-angular:tslint",
|
||||
"options": {
|
||||
"tsConfig": [
|
||||
"projects/weather-search/tsconfig.app.json",
|
||||
"projects/weather-search/tsconfig.spec.json",
|
||||
"projects/weather-search/e2e/tsconfig.json"
|
||||
"src/elements/search/tsconfig.app.json"
|
||||
],
|
||||
"exclude": [
|
||||
"**/node_modules/**"
|
||||
]
|
||||
}
|
||||
},
|
||||
"e2e": {
|
||||
"builder": "@angular-devkit/build-angular:protractor",
|
||||
"options": {
|
||||
"protractorConfig": "projects/weather-search/e2e/protractor.conf.js",
|
||||
"devServerTarget": "weather-search:serve"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"devServerTarget": "weather-search:serve:production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,44 +17,54 @@ node {
|
||||
|
||||
class IoNodeTask extends com.moowork.gradle.node.task.NodeTask {
|
||||
@InputDirectory
|
||||
File inputFile;
|
||||
File inputDir;
|
||||
@OutputDirectory
|
||||
File outputDir;
|
||||
}
|
||||
|
||||
task cleanApi(type: Delete) {
|
||||
task cleanup(type: Delete) {
|
||||
delete './src/api', './dist'
|
||||
}
|
||||
|
||||
task ngBuild(type: IoNodeTask) {
|
||||
task ngBuildApp(type: IoNodeTask) {
|
||||
script = file('node_modules/@angular/cli/bin/ng')
|
||||
args = ['build', '--prod']
|
||||
inputFile = project.file('./src/')
|
||||
outputDir = project.file('./dist/')
|
||||
inputDir = project.file('./src/')
|
||||
outputDir = project.file('./build/outputs/mowesta-app/')
|
||||
}
|
||||
|
||||
task ngBuildWeatherForecastToday(type: IoNodeTask) {
|
||||
task buildApp(type: Copy) {
|
||||
from 'build/outputs/mowesta-app'
|
||||
into 'dist'
|
||||
exclude '**/*.map'
|
||||
}
|
||||
|
||||
task ngBuildForecast(type: IoNodeTask) {
|
||||
script = file('node_modules/@angular/cli/bin/ng')
|
||||
args = ['build', '--prod', 'weather-forecast-today']
|
||||
inputFile = project.file('./projects/weather-forecast-today/src/')
|
||||
outputDir = project.file('./dist/weather-forecast-today/')
|
||||
args = ['build', '--prod', 'mowesta-forecast']
|
||||
inputDir = project.file('./src/')
|
||||
outputDir = project.file('./build/outputs/mowesta-forecast/')
|
||||
}
|
||||
|
||||
task generateWeatherForecastToday(type: NodeTask) {
|
||||
task buildForecast(type: IoNodeTask) {
|
||||
script = file('./ng-element-concat.js')
|
||||
args = ['weather-forecast-today']
|
||||
args = ['mowesta-forecast']
|
||||
inputDir = project.file('./build/outputs/mowesta-forecast/')
|
||||
outputDir = project.file('./dist/')
|
||||
}
|
||||
|
||||
task ngBuildWeatherSearch(type: IoNodeTask) {
|
||||
task ngBuildSearch(type: IoNodeTask) {
|
||||
script = file('node_modules/@angular/cli/bin/ng')
|
||||
args = ['build', '--prod', 'weather-search']
|
||||
inputFile = project.file('./projects/weather-search/src/')
|
||||
outputDir = project.file('./dist/weather-search/')
|
||||
args = ['build', '--prod', 'mowesta-search']
|
||||
inputDir = project.file('./src/')
|
||||
outputDir = project.file('./build/outputs/mowesta-search/')
|
||||
}
|
||||
|
||||
task generateWeatherSearch(type: NodeTask) {
|
||||
task buildSearch(type: IoNodeTask) {
|
||||
script = file('./ng-element-concat.js')
|
||||
args = ['weather-search']
|
||||
args = ['mowesta-search']
|
||||
inputDir = project.file('./build/outputs/mowesta-search/')
|
||||
outputDir = project.file('./dist/')
|
||||
}
|
||||
|
||||
swaggerSources {
|
||||
@@ -74,21 +84,23 @@ swaggerSources {
|
||||
// require api build to access swagger definition
|
||||
tasks['resolveSwaggerTemplate'].dependsOn(project(':common-api').tasks['build'])
|
||||
// make sure that common api is built before generating the api
|
||||
ngBuild.dependsOn(npmInstall)
|
||||
ngBuildApp.dependsOn(npmInstall)
|
||||
// generate the api before running ng build
|
||||
ngBuild.dependsOn("generateSwaggerCode")
|
||||
// build Angular Element "weather-forecast-today" after ngBuild finishes
|
||||
ngBuildWeatherForecastToday.mustRunAfter("ngBuild")
|
||||
generateWeatherForecastToday.dependsOn("ngBuildWeatherForecastToday")
|
||||
// build Angular Element "weather-search" after ngBuild finishes
|
||||
ngBuildWeatherSearch.mustRunAfter("ngBuild")
|
||||
generateWeatherForecastToday.dependsOn("ngBuildWeatherSearch")
|
||||
ngBuildApp.dependsOn("generateSwaggerCode")
|
||||
buildApp.dependsOn("ngBuildApp")
|
||||
|
||||
// build Angular Element "mowesta-forecast"
|
||||
ngBuildForecast.dependsOn("ngBuildApp")
|
||||
buildForecast.dependsOn("ngBuildForecast")
|
||||
// build Angular Element "mowesta-search"
|
||||
ngBuildSearch.dependsOn("ngBuildApp")
|
||||
buildSearch.dependsOn("ngBuildSearch")
|
||||
|
||||
// run ng build whenever the project is built unless skipAngular is set
|
||||
// use e.g. "gradlew site-ear:build -x test -PskipAngular"
|
||||
if (! project.hasProperty('skipAngular')) {
|
||||
build.dependsOn("ngBuild", "generateWeatherForecastToday", "generateWeatherSearch")
|
||||
build.dependsOn("buildApp", "buildSearch", "buildForecast")
|
||||
}
|
||||
|
||||
// clean the api folder upon clean
|
||||
clean.dependsOn("cleanApi")
|
||||
clean.dependsOn("cleanup")
|
||||
|
||||
@@ -7,8 +7,9 @@ const concat = require('concat');
|
||||
// const distDir = `./dist/${elementName}`;
|
||||
// const outputDir = distDir;
|
||||
// const cssDir = distDir;
|
||||
let elementName, distDir, outputDir, cssDir;
|
||||
|
||||
let elementName;
|
||||
let outputDir;
|
||||
let inputDir;
|
||||
|
||||
/**
|
||||
* Builds the web component through concatenating all javascript files.
|
||||
@@ -16,35 +17,36 @@ let elementName, distDir, outputDir, cssDir;
|
||||
* @param {string} versionString The ECMAScript version. Either ES5 or ES2015.
|
||||
*/
|
||||
async function buildElement(versionString) {
|
||||
const files = fs.readdirSync(distDir)
|
||||
const files = fs.readdirSync(inputDir)
|
||||
.filter(item => item.includes(versionString) && !item.includes('.map'))
|
||||
.map(filtered => `${distDir}/${filtered}`);
|
||||
.map(filtered => `${inputDir}/${filtered}`);
|
||||
await concat(files, `${outputDir}/${elementName}${versionString}.js`);
|
||||
files.forEach(value => fs.removeSync(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copying and renaming the global styles.css file of the main web app.
|
||||
*/
|
||||
async function copyStylesCss() {
|
||||
const styleFile = fs.readdirSync(cssDir)
|
||||
const styleFile = fs.readdirSync(inputDir)
|
||||
.filter(item => item.includes('styles') && item.includes('css'))
|
||||
.map(filtered => `${cssDir}/${filtered}`);
|
||||
.map(filtered => `${inputDir}/${filtered}`);
|
||||
if (styleFile.length !== 0) {
|
||||
await fs.renameSync(styleFile[0], `${outputDir}/${elementName}.css`);
|
||||
await fs.copySync(styleFile[0], `${outputDir}/${elementName}.css`);
|
||||
} else {
|
||||
throw new Error(`No styles.css file found in ./dist/${cssDir} folder!`);
|
||||
throw new Error(`Missing styles*.css in ${inputDir}.`);
|
||||
}
|
||||
}
|
||||
|
||||
(async function() {
|
||||
if (proc.argv.length !== 3) { throw new Error('You have to pass the name of the web component!'); }
|
||||
if (proc.argv.length !== 3) { throw new Error('Web component missing.'); }
|
||||
elementName = proc.argv[2];
|
||||
distDir = `./dist/${elementName}`;
|
||||
outputDir = cssDir = distDir;
|
||||
if (!fs.pathExistsSync(outputDir)) { fs.mkdirSync(outputDir); }
|
||||
inputDir = `./build/outputs/${elementName}`;
|
||||
outputDir = `./dist/`;
|
||||
if (!fs.pathExistsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir);
|
||||
}
|
||||
buildElement('-es5');
|
||||
buildElement('-es2015');
|
||||
copyStylesCss();
|
||||
console.log(`${elementName} build finished!`);
|
||||
console.log(`Finished building ${elementName}.`);
|
||||
})();
|
||||
|
||||
@@ -2630,6 +2630,16 @@
|
||||
"integrity": "sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ==",
|
||||
"dev": true
|
||||
},
|
||||
"bindings": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
|
||||
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"file-uri-to-path": "1.0.0"
|
||||
}
|
||||
},
|
||||
"blob": {
|
||||
"version": "0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz",
|
||||
@@ -5205,6 +5215,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"file-uri-to-path": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
|
||||
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
},
|
||||
"fill-range": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
|
||||
@@ -7894,6 +7911,13 @@
|
||||
"integrity": "sha512-1t2payD3Y8izfZRq7tfUQlhL2fKzjeLr9v1/2qNCTkEQnd9Abtn1JgzsBgGZubEXh6lM5L8B0iLGoWQiukjtbQ==",
|
||||
"dev": true
|
||||
},
|
||||
"nan": {
|
||||
"version": "2.14.2",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz",
|
||||
"integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
},
|
||||
"nanomatch": {
|
||||
"version": "1.2.13",
|
||||
"resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
|
||||
@@ -12956,7 +12980,11 @@
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
|
||||
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"bindings": "^1.5.0",
|
||||
"nan": "^2.12.1"
|
||||
}
|
||||
},
|
||||
"glob-parent": {
|
||||
"version": "3.1.0",
|
||||
@@ -13633,7 +13661,11 @@
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
|
||||
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"bindings": "^1.5.0",
|
||||
"nan": "^2.12.1"
|
||||
}
|
||||
},
|
||||
"glob-parent": {
|
||||
"version": "3.1.0",
|
||||
|
||||
@@ -5,18 +5,17 @@
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start:forecast": "ng serve weather-forecast-today",
|
||||
"start:search": "ng serve weather-search",
|
||||
"build": "ng build",
|
||||
"build:forecast": "ng build --prod weather-forecast-today && npm run concat:forecast",
|
||||
"concat:forecast": "node ./ng-element-concat.js weather-forecast-today",
|
||||
"build:search": "ng build --prod weather-search && npm run concat:search",
|
||||
"concat:search": "node ./ng-element-concat.js weather-search",
|
||||
"build:all": "ng b --prod && npm run build:forecast && npm run build:search",
|
||||
"start:forecast": "ng serve mowesta-forecast",
|
||||
"start:search": "ng serve mowesta-search",
|
||||
"build": "ng build --prod",
|
||||
"build:forecast": "ng build --prod mowesta-forecast && npm run concat:forecast",
|
||||
"concat:forecast": "node ./ng-element-concat.js mowesta-forecast",
|
||||
"build:search": "ng build --prod mowesta-search && npm run concat:search",
|
||||
"concat:search": "node ./ng-element-concat.js mowesta-search",
|
||||
"build:all": "npm run build && npm run build:forecast && npm run build:search",
|
||||
"test": "ng test",
|
||||
"lint": "ng lint",
|
||||
"e2e": "ng e2e",
|
||||
"release": "ng b --prod"
|
||||
"e2e": "ng e2e"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
|
||||
# For additional information regarding the format and rule options, please see:
|
||||
# https://github.com/browserslist/browserslist#queries
|
||||
|
||||
# You can see what browsers were selected by your queries by running:
|
||||
# npx browserslist
|
||||
|
||||
> 0.5%
|
||||
last 2 versions
|
||||
Firefox ESR
|
||||
not dead
|
||||
not IE 9-11 # For IE 9-11 support, remove 'not'.
|
||||
@@ -1,3 +0,0 @@
|
||||
# Weather Forecast Today
|
||||
|
||||
A simple widget which displays a weather forecast of a particular city. It is a custom element (web component) that is meant to be embedded on different websites outside of the mowesta web app context.
|
||||
@@ -1,32 +0,0 @@
|
||||
// @ts-check
|
||||
// Protractor configuration file, see link for more information
|
||||
// https://github.com/angular/protractor/blob/master/lib/config.ts
|
||||
|
||||
const { SpecReporter } = require('jasmine-spec-reporter');
|
||||
|
||||
/**
|
||||
* @type { import("protractor").Config }
|
||||
*/
|
||||
exports.config = {
|
||||
allScriptsTimeout: 11000,
|
||||
specs: [
|
||||
'./src/**/*.e2e-spec.ts'
|
||||
],
|
||||
capabilities: {
|
||||
browserName: 'chrome'
|
||||
},
|
||||
directConnect: true,
|
||||
baseUrl: 'http://localhost:4200/',
|
||||
framework: 'jasmine',
|
||||
jasmineNodeOpts: {
|
||||
showColors: true,
|
||||
defaultTimeoutInterval: 30000,
|
||||
print: function() {}
|
||||
},
|
||||
onPrepare() {
|
||||
require('ts-node').register({
|
||||
project: require('path').join(__dirname, './tsconfig.json')
|
||||
});
|
||||
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
|
||||
}
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
import { AppPage } from './app.po';
|
||||
import { browser, logging } from 'protractor';
|
||||
|
||||
describe('workspace-project App', () => {
|
||||
let page: AppPage;
|
||||
|
||||
beforeEach(() => {
|
||||
page = new AppPage();
|
||||
});
|
||||
|
||||
it('should display welcome message', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getTitleText()).toEqual('weather-forecast-today app is running!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Assert that there are no errors emitted from the browser
|
||||
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
|
||||
expect(logs).not.toContain(jasmine.objectContaining({
|
||||
level: logging.Level.SEVERE,
|
||||
} as logging.Entry));
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import { browser, by, element } from 'protractor';
|
||||
|
||||
export class AppPage {
|
||||
navigateTo(): Promise<unknown> {
|
||||
return browser.get(browser.baseUrl) as Promise<unknown>;
|
||||
}
|
||||
|
||||
getTitleText(): Promise<string> {
|
||||
return element(by.css('app-root .content span')).getText() as Promise<string>;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../out-tsc/e2e",
|
||||
"module": "commonjs",
|
||||
"target": "es2018",
|
||||
"types": [
|
||||
"jasmine",
|
||||
"jasminewd2",
|
||||
"node"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Karma configuration file, see link for more information
|
||||
// https://karma-runner.github.io/1.0/config/configuration-file.html
|
||||
|
||||
module.exports = function (config) {
|
||||
config.set({
|
||||
basePath: '',
|
||||
frameworks: ['jasmine', '@angular-devkit/build-angular'],
|
||||
plugins: [
|
||||
require('karma-jasmine'),
|
||||
require('karma-chrome-launcher'),
|
||||
require('karma-jasmine-html-reporter'),
|
||||
require('karma-coverage-istanbul-reporter'),
|
||||
require('@angular-devkit/build-angular/plugins/karma')
|
||||
],
|
||||
client: {
|
||||
clearContext: false // leave Jasmine Spec Runner output visible in browser
|
||||
},
|
||||
coverageIstanbulReporter: {
|
||||
dir: require('path').join(__dirname, '../../coverage/weather-forecast-today'),
|
||||
reports: ['html', 'lcovonly', 'text-summary'],
|
||||
fixWebpackSourcePaths: true
|
||||
},
|
||||
reporters: ['progress', 'kjhtml'],
|
||||
port: 9876,
|
||||
colors: true,
|
||||
logLevel: config.LOG_INFO,
|
||||
autoWatch: true,
|
||||
browsers: ['Chrome'],
|
||||
singleRun: false,
|
||||
restartOnFileChange: true
|
||||
});
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-de" width="640" height="480">
|
||||
<path fill="#ffce00" d="M0 320h640v160.002H0z"/>
|
||||
<path d="M0 0h640v160H0z"/>
|
||||
<path fill="#d00" d="M0 160h640v160H0z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 220 B |
@@ -1,15 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-gb" width="640" height="480">
|
||||
<defs>
|
||||
<clipPath id="a">
|
||||
<path fill-opacity=".67" d="M-85.333 0h682.67v512h-682.67z"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#a)" transform="translate(80) scale(.94)">
|
||||
<g stroke-width="1pt">
|
||||
<path fill="#006" d="M-256 0H768.02v512.01H-256z"/>
|
||||
<path fill="#fff" d="M-256 0v57.244l909.535 454.768H768.02V454.77L-141.515 0H-256zM768.02 0v57.243L-141.515 512.01H-256v-57.243L653.535 0H768.02z"/>
|
||||
<path fill="#fff" d="M170.675 0v512.01h170.67V0h-170.67zM-256 170.67v170.67H768.02V170.67H-256z"/>
|
||||
<path fill="#c00" d="M-256 204.804v102.402H768.02V204.804H-256zM204.81 0v512.01h102.4V0h-102.4zM-256 512.01L85.34 341.34h76.324l-341.34 170.67H-256zM-256 0L85.34 170.67H9.016L-256 38.164V0zm606.356 170.67L691.696 0h76.324L426.68 170.67h-76.324zM768.02 512.01L426.68 341.34h76.324L768.02 473.848v38.162z"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 956 B |
|
Before Width: | Height: | Size: 142 KiB |
@@ -1,7 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-fr" width="640" height="480">
|
||||
<g fill-rule="evenodd" stroke-width="1pt">
|
||||
<path fill="#fff" d="M0 0h640v480H0z"/>
|
||||
<path fill="#00267f" d="M0 0h213.337v480H0z"/>
|
||||
<path fill="#f31830" d="M426.662 0H640v480H426.662z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 301 B |
@@ -1,7 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-it" width="640" height="480">
|
||||
<g fill-rule="evenodd" stroke-width="1pt">
|
||||
<path fill="#fff" d="M0 0h640v479.997H0z"/>
|
||||
<path fill="#009246" d="M0 0h213.331v479.997H0z"/>
|
||||
<path fill="#ce2b37" d="M426.663 0h213.331v479.997H426.663z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 317 B |
|
Before Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 8.2 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 6.2 KiB |
@@ -1,30 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="61.1423mm" height="61.1423mm" version="1.1" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" viewBox="0 0 36540.45 36540.45" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<defs>
|
||||
<style type="text/css">
|
||||
<![CDATA[
|
||||
.fil0 {fill:none}
|
||||
.fil2 {fill:#FFD95A}
|
||||
.fil1 {fill:#EBECEC;fill-opacity:0.501961}
|
||||
.fil3 {fill:url(#id0)}
|
||||
]]>
|
||||
</style>
|
||||
<radialGradient id="id0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1.5625 -0 -0 1.5625 -13372 -6953)" cx="23772.1" cy="12360.78" r="7258.39" fx="23772.1" fy="12360.78">
|
||||
<stop offset="0" style="stop-opacity:1; stop-color:#FEFEFE"/>
|
||||
<stop offset="1" style="stop-opacity:1; stop-color:#F9A825"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<g id="Ebene_x0020_1">
|
||||
<rect class="fil0" x="-0.03" y="-0.03" width="36540.45" height="36540.45"/>
|
||||
<g>
|
||||
<polygon class="fil1" points="18270.2,3041.28 19920.19,7165.46 20436.55,7379.35 22781.29,7379.35 24439.35,9037.36 24770.5,9174.51 28671.17,7501.69 27161.19,11275.9 27502.98,12100.99 29161.04,13759.11 29161.04,16103.91 29427.41,16746.96 32979.36,18270.2 29427.41,19793.44 29161.04,20436.55 29161.04,22781.29 27503.04,24439.35 27161.25,25264.56 28671.17,29038.71 24770.44,27365.88 24439.41,27502.98 22781.29,29161.04 20436.49,29161.04 19920.19,29374.93 18270.2,33499.12 16620.2,29374.93 16103.85,29161.04 13759.11,29161.04 12101.05,27503.04 11769.9,27365.88 7869.23,29038.71 9379.2,25264.5 9037.42,24439.41 7379.35,22781.29 7379.35,20436.49 7112.99,19793.44 3561.04,18270.2 7112.99,16746.96 7379.35,16103.85 7379.35,13759.11 9037.36,12101.05 9379.14,11275.84 7869.23,7501.69 11769.96,9174.51 12100.99,9037.42 13759.11,7379.35 16103.91,7379.35 16620.2,7165.46 "/>
|
||||
<path id="1" class="fil1" d="M18823.48 2819.5l1557.06 3891.88 169.79 70.34 2230.95 0 247.36 0 175.17 175.11 1568.3 1568.24 3665.62 -1572.01 1321.66 -566.85 -534.94 1337.26 -1419.91 3549.08 201.58 486.53 1577.44 1577.5 175.11 175.11 0 247.42 0 2231.01 125.98 304.19 3328.14 1427.26 1279.29 548.62 -1279.29 548.62 -3328.14 1427.26 -125.98 304.19 0 2231.01 0 247.36 -175.11 175.17 -1577.38 1577.44 -201.58 486.65 1419.85 3549.02 534.94 1337.2 -1321.66 -566.79 -3665.62 -1572.01 -1568.3 1568.24 -175.17 175.11 -247.36 0 -2231.01 0 -169.73 70.28 -1557.06 3891.94 -553.29 1382.92 -553.29 -1382.92 -1557.06 -3891.88 -169.79 -70.34 -2230.95 0 -247.42 0 -175.11 -175.11 -1568.3 -1568.24 -3665.62 1572.01 -1321.72 566.79 535 -1337.2 1419.91 -3549.08 -201.58 -486.53 -1577.44 -1577.5 -175.11 -175.17 0 -247.36 0 -2231.01 -125.98 -304.19 -3328.14 -1427.26 -1279.35 -548.62 1279.35 -548.62 3328.14 -1427.26 125.98 -304.19 0 -2231.01 0 -247.42 175.11 -175.11 1577.38 -1577.44 201.58 -486.65 -1419.85 -3549.02 -535 -1337.26 1321.72 566.85 3665.62 1572.01 1568.3 -1568.24 175.11 -175.11 247.42 0 2231.01 0 169.73 -70.28 1557.06 -3891.94 553.29 -1382.97 553.29 1382.97zm-553.29 221.78l1650 4124.18 516.35 213.89 2344.74 0 1658.06 1658 331.15 137.16 3900.67 -1672.83 -1509.97 3774.21 341.78 825.09 1658.06 1658.12 0 2344.8 266.36 643.05 3551.95 1523.24 -3551.95 1523.24 -266.36 643.11 0 2344.74 -1658 1658.06 -341.78 825.21 1509.91 3774.15 -3900.73 -1672.83 -331.03 137.1 -1658.12 1658.06 -2344.8 0 -516.29 213.89 -1650 4124.18 -1650 -4124.18 -516.35 -213.89 -2344.74 0 -1658.06 -1658 -331.15 -137.16 -3900.67 1672.83 1509.97 -3774.21 -341.78 -825.09 -1658.06 -1658.12 0 -2344.8 -266.36 -643.05 -3551.95 -1523.24 3551.95 -1523.24 266.36 -643.11 0 -2344.74 1658 -1658.06 341.78 -825.21 -1509.91 -3774.15 3900.73 1672.83 331.03 -137.1 1658.12 -1658.06 2344.8 0 516.29 -213.89 1650 -4124.18z"/>
|
||||
</g>
|
||||
<g>
|
||||
<polygon class="fil2" points="18270.2,3041.28 21316.56,10655.74 28671.17,7501.69 25624.81,15116.21 32979.36,18270.2 25624.81,21424.19 28671.17,29038.71 21316.56,25884.66 18270.2,33499.12 15223.84,25884.66 7869.23,29038.71 10915.59,21424.19 3561.04,18270.2 10915.59,15116.21 7869.23,7501.69 15223.84,10655.74 "/>
|
||||
<polygon class="fil2" points="18270.2,6482.01 20436.55,7379.35 22781.29,7379.35 24439.35,9037.36 26605.7,9934.7 27502.98,12100.99 29161.04,13759.11 29161.04,16103.91 30058.38,18270.2 29161.04,20436.55 29161.04,22781.29 27503.04,24439.35 26605.7,26605.7 24439.41,27502.98 22781.29,29161.04 20436.49,29161.04 18270.2,30058.38 16103.85,29161.04 13759.11,29161.04 12101.05,27503.04 9934.7,26605.7 9037.42,24439.41 7379.35,22781.29 7379.35,20436.49 6482.01,18270.2 7379.35,16103.85 7379.35,13759.11 9037.36,12101.05 9934.7,9934.7 12100.99,9037.42 13759.11,7379.35 16103.91,7379.35 "/>
|
||||
<circle class="fil3" cx="18270.2" cy="18270.2" r="10188.63"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 84 KiB |
|
Before Width: | Height: | Size: 8.7 KiB |
|
Before Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 39 KiB |
@@ -1,5 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-de" width="640" height="480">
|
||||
<path fill="#ffce00" d="M0 320h640v160.002H0z"/>
|
||||
<path d="M0 0h640v160H0z"/>
|
||||
<path fill="#d00" d="M0 160h640v160H0z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 220 B |
@@ -1,15 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-gb" width="640" height="480">
|
||||
<defs>
|
||||
<clipPath id="a">
|
||||
<path fill-opacity=".67" d="M-85.333 0h682.67v512h-682.67z"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#a)" transform="translate(80) scale(.94)">
|
||||
<g stroke-width="1pt">
|
||||
<path fill="#006" d="M-256 0H768.02v512.01H-256z"/>
|
||||
<path fill="#fff" d="M-256 0v57.244l909.535 454.768H768.02V454.77L-141.515 0H-256zM768.02 0v57.243L-141.515 512.01H-256v-57.243L653.535 0H768.02z"/>
|
||||
<path fill="#fff" d="M170.675 0v512.01h170.67V0h-170.67zM-256 170.67v170.67H768.02V170.67H-256z"/>
|
||||
<path fill="#c00" d="M-256 204.804v102.402H768.02V204.804H-256zM204.81 0v512.01h102.4V0h-102.4zM-256 512.01L85.34 341.34h76.324l-341.34 170.67H-256zM-256 0L85.34 170.67H9.016L-256 38.164V0zm606.356 170.67L691.696 0h76.324L426.68 170.67h-76.324zM768.02 512.01L426.68 341.34h76.324L768.02 473.848v38.162z"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 956 B |