Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bff009cfc | ||
|
|
ba1b5ab29a | ||
|
|
8bfce31f2e | ||
|
|
bca818e734 | ||
|
|
c95015c234 | ||
|
|
3eced06154 | ||
|
|
894b24a4ff | ||
|
|
5a3b0a62f6 | ||
|
|
d34a88943a | ||
|
|
6a611d57d3 | ||
|
|
a3e213eea2 | ||
|
|
9849d7c51e | ||
|
|
e3d0122fb0 | ||
|
|
549c4b559b | ||
|
|
c4b92b734c | ||
|
|
ff763ec44c | ||
|
|
912151ef2d | ||
|
|
f341e8eb10 | ||
|
|
64af6ae5aa | ||
|
|
1d64d0bd23 | ||
|
|
bc19ba5fd0 | ||
|
|
aea6edd08b | ||
|
|
9b62b46e0e | ||
|
|
dcad963c7c | ||
|
|
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 | ||
|
|
17006aafe3 | ||
|
|
e5aa030857 | ||
|
|
c8e0a7f16e | ||
|
|
35d8f06e5d | ||
|
|
b967f318c7 | ||
|
|
e1f28ffd23 | ||
|
|
6d5ce170bd | ||
|
|
4d1d87d8ef | ||
|
|
d032e2e577 | ||
|
|
0a7e33503f | ||
|
|
f62c5b41cf | ||
|
|
cdfc018c33 | ||
|
|
9a773ca13f | ||
|
|
1b80e9415f | ||
|
|
706f24f104 | ||
|
|
4029c15eb9 | ||
|
|
6fd3209304 | ||
|
|
ffa3ff7d46 | ||
|
|
83530a9a41 | ||
|
|
7ed7d8cfcf | ||
|
|
aff152543c | ||
|
|
bb92acc66a | ||
|
|
bfad0d8716 | ||
|
|
a8028ff446 | ||
|
|
32bcbf3647 | ||
|
|
52ff3d660c | ||
|
|
e794d83ec5 | ||
|
|
95b82b133a | ||
|
|
a66cc3bb0c | ||
|
|
87abaf05c1 | ||
|
|
3e575f96e6 | ||
|
|
a318d10f79 | ||
|
|
969d59c4c3 | ||
|
|
66ba4e0d09 | ||
|
|
e87199c024 | ||
|
|
7a6b7084ac | ||
|
|
42ed5a03e1 | ||
|
|
8a564df34f | ||
|
|
746faf92b1 | ||
|
|
de74b222af | ||
|
|
66daf0c7b7 | ||
|
|
7e0b4d88d5 | ||
|
|
543b3587eb | ||
|
|
aa6d0cfab5 |
Vendored
+22
-31
@@ -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."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,12 +46,18 @@ node {
|
||||
stage ('Deploy') {
|
||||
// release = true; // uncomment to temporary enable snapshot deployments
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
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-17-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/"
|
||||
}
|
||||
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-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" || env.BRANCH_NAME == "feat/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-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
|
||||
}
|
||||
} else {
|
||||
echo "Skipping deployment for non-release version or non-master branch."
|
||||
echo "Skipping deployment for non-master branch."
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,3 +13,4 @@ To build the project, you will have to install [Java](http://www.oracle.com/tech
|
||||
# Jenkins CI
|
||||
|
||||
Pull requests and new commits to any branch are automatically built by a Jenkins service. A Gitea webhook informs the service about changes to the repository. In addition, the service will automatically scan the lbs Gitea organization for new repositories every hour. Successful builds of new commits are indicated by a green tick on the commit page. The build status of pull requests is currently not shown in Gitea. However, you can go to the [Jenkins](https://project.nes.uni-due.de/jenkins/job/LocationBasedServices/job/mowesta/) service to view the result of builds including the console output. To modify the build process, you can change the Jenkinsfile groovy script in the root of the repository, if necessary.
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@ ext {
|
||||
versionAndroidXPaging = '2.1.2'
|
||||
versionAndroidXCard = '1.0.0'
|
||||
versionAndroidXCoordinator = '1.1.0'
|
||||
versionAndroidXConstraint = '1.1.3'
|
||||
versionAndroidXNavigation = '2.3.0'
|
||||
versionAndroidXConstraint = '2.0.4'
|
||||
versionAndroidXNavigation = '2.3.2'
|
||||
versionAndroidXLifecycle = '2.2.0'
|
||||
versionAndroidXSecurity = '1.1.0-alpha02'
|
||||
versionAndroidXSecurity = '1.1.0-alpha03'
|
||||
versionAndroidXViewpager = '1.0.0'
|
||||
versionGoogleMaterial = '1.2.0'
|
||||
versionGoogleMaterial = '1.2.1'
|
||||
versionAndroidXSwipeRefresh = '1.1.0'
|
||||
versionExoPlayer = '2.11.5'
|
||||
}
|
||||
@@ -82,13 +82,14 @@ configurations {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
defaultConfig {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 29
|
||||
versionCode 10
|
||||
versionCode 13
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
+10
-11
@@ -71,18 +71,17 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_unit_system:
|
||||
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
|
||||
system.show(getChildFragmentManager(), "system");
|
||||
return true;
|
||||
case R.id.action_temperature_unit:
|
||||
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
|
||||
unit.show(getChildFragmentManager(), "unit");
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
int itemId = item.getItemId();
|
||||
if (itemId == R.id.action_unit_system) {
|
||||
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
|
||||
system.show(getChildFragmentManager(), "system");
|
||||
return true;
|
||||
} else if (itemId == R.id.action_temperature_unit) {
|
||||
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
|
||||
unit.show(getChildFragmentManager(), "unit");
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+13
-13
@@ -82,19 +82,19 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_favorite_add:
|
||||
getPlaceViewModel().addFavorite();
|
||||
return true;
|
||||
case R.id.action_favorite_remove:
|
||||
getPlaceViewModel().removeFavorite();
|
||||
return true;
|
||||
case R.id.action_wikipedia:
|
||||
openWikipedia();
|
||||
return true;
|
||||
case R.id.action_google_maps:
|
||||
openGoogleMaps();
|
||||
return true;
|
||||
int itemId = item.getItemId();
|
||||
if (itemId == R.id.action_favorite_add) {
|
||||
getPlaceViewModel().addFavorite();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_favorite_remove) {
|
||||
getPlaceViewModel().removeFavorite();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_wikipedia) {
|
||||
openWikipedia();
|
||||
return true;
|
||||
} else if (itemId == R.id.action_google_maps) {
|
||||
openGoogleMaps();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -85,16 +85,14 @@ public class CityFragment extends AbstractPlaceFragment {
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_customize:
|
||||
getChildFragmentManager()
|
||||
.beginTransaction()
|
||||
.add(new CustomizeDialogFragment(), "customize")
|
||||
.commit();
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
if (item.getItemId() == R.id.action_customize) {
|
||||
getChildFragmentManager()
|
||||
.beginTransaction()
|
||||
.add(new CustomizeDialogFragment(), "customize")
|
||||
.commit();
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
@@ -88,9 +88,11 @@ public class CollectionFragment extends Fragment {
|
||||
// add a funky animation
|
||||
if (savedInstanceState == null) {
|
||||
List<View> views = new ArrayList<>();
|
||||
views.add(binding.collectionNotePermission);
|
||||
views.add(binding.collectionNoteLocation);
|
||||
views.add(binding.collectionNoteData);
|
||||
views.add(binding.collectionNoteEnable);
|
||||
views.add(binding.privacyMeasureSwitch);
|
||||
views.add(binding.collectionNotePermission);
|
||||
views.add(binding.buttonContinue);
|
||||
AnimatorSet set = new AnimatorSet();
|
||||
ObjectAnimator first = ObjectAnimator.ofFloat(binding.logoSun, "translationY", DisplayUtils.dpToPixels(getContext(), 90), 0f);
|
||||
|
||||
@@ -78,6 +78,7 @@ public class SplashFragment extends Fragment {
|
||||
View title = root.findViewById(R.id.splash_title);
|
||||
View subtitle = root.findViewById(R.id.splash_subtitle);
|
||||
View world = root.findViewById(R.id.splash_world);
|
||||
View logos = root.findViewById(R.id.logo_panel);
|
||||
AnimatorSet set = new AnimatorSet();
|
||||
ValueAnimator gradientAnimator = ValueAnimator.ofFloat(0, 1);
|
||||
gradientAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
@@ -93,6 +94,10 @@ public class SplashFragment extends Fragment {
|
||||
ObjectAnimator worldAnimator = ObjectAnimator.ofFloat(world, "alpha", 0, 1);
|
||||
worldAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
worldAnimator.setDuration(750);
|
||||
logos.setAlpha(0);
|
||||
ObjectAnimator logoAnimator = ObjectAnimator.ofFloat(logos, "alpha", 0, 1);
|
||||
logoAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
|
||||
logoAnimator.setDuration(750);
|
||||
ObjectAnimator sunAnimator = ObjectAnimator.ofFloat(sun, "alpha", 0, 1);
|
||||
sunAnimator.setInterpolator(new LinearInterpolator());
|
||||
sunAnimator.setDuration(150);
|
||||
@@ -105,6 +110,7 @@ public class SplashFragment extends Fragment {
|
||||
|
||||
set.playTogether(sunAnimator, titleAnimator, subtitleAnimator);
|
||||
set.play(worldAnimator).after(sunAnimator);
|
||||
set.play(logoAnimator).after(sunAnimator);
|
||||
set.play(gradientAnimator).after(sunAnimator);
|
||||
set.start();
|
||||
return root;
|
||||
|
||||
@@ -832,7 +832,7 @@ public class BindingAdapters {
|
||||
} else if (o instanceof Double) {
|
||||
switch (value.getType()) {
|
||||
case CPU_FREQUENCY:
|
||||
valueText = r.getString(R.string.format_frequency, ((Double)o).floatValue());
|
||||
valueText = r.getString(R.string.format_frequency, ((Double)o).floatValue() / 1000000);
|
||||
break;
|
||||
case SOLAR_VOLTAGE:
|
||||
case BATTERY_VOLTAGE:
|
||||
|
||||
@@ -218,6 +218,8 @@ public class BindingTransforms {
|
||||
return R.string.video_type_pressure;
|
||||
case PRECIPITATION:
|
||||
return R.string.video_type_precipitation;
|
||||
case WIND:
|
||||
return R.string.video_type_wind;
|
||||
default:
|
||||
return R.string.video_type_temperature;
|
||||
}
|
||||
|
||||
@@ -52,6 +52,42 @@ public class UnitUtils {
|
||||
return speed * 3.6;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class on the Beaufort scale for a wind speed
|
||||
* given in meter per second.
|
||||
*
|
||||
* @param value The wind speed.
|
||||
* @return The beaufort scale (0-12).
|
||||
*/
|
||||
public static int mpsToBFT(double value) {
|
||||
if (value < 0.5d)
|
||||
return 0;
|
||||
else if (value < 1.6d)
|
||||
return 1;
|
||||
else if (value < 3.4d)
|
||||
return 2;
|
||||
else if (value < 5.6d)
|
||||
return 3;
|
||||
else if (value < 8.0d)
|
||||
return 4;
|
||||
else if (value < 10.8d)
|
||||
return 5;
|
||||
else if (value < 13.9d)
|
||||
return 6;
|
||||
else if (value < 17.2d)
|
||||
return 7;
|
||||
else if (value < 20.8d)
|
||||
return 8;
|
||||
else if (value < 24.5d)
|
||||
return 9;
|
||||
else if (value < 28.5d)
|
||||
return 10;
|
||||
else if (value < 32.7d)
|
||||
return 11;
|
||||
else
|
||||
return 12;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the pressure given in hpa into
|
||||
* psi.
|
||||
@@ -125,13 +161,13 @@ public class UnitUtils {
|
||||
public static String getTemperature(@NonNull Context context, double celsisus) {
|
||||
MowestaSettings.TemperatureUnit unit = getSettings(context).getTemperatureUnit();
|
||||
if (unit == MowestaSettings.TemperatureUnit.CELSIUS) {
|
||||
return context.getString(R.string.format_temperature_celsius, round(celsisus));
|
||||
return context.getString(R.string.format_temperature_celsius, celsisus);
|
||||
} else {
|
||||
int fahrenheit = round(celsiusToFahrenheit(celsisus));
|
||||
double fahrenheit = celsiusToFahrenheit(celsisus);
|
||||
if (unit == MowestaSettings.TemperatureUnit.FAHRENHEIT) {
|
||||
return context.getString(R.string.format_temperature_fahrenheit, fahrenheit);
|
||||
} else {
|
||||
return context.getString(R.string.format_temperature_both, round(celsisus), fahrenheit);
|
||||
return context.getString(R.string.format_temperature_both, celsisus, fahrenheit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,12 +188,13 @@ public class UnitUtils {
|
||||
|
||||
public static String getWindSpeed(@NonNull Context context, double mps) {
|
||||
MowestaSettings.UnitSystem system = getSettings(context).getUnitSystem();
|
||||
mps = Math.abs(mps); // make sure this is a positive value
|
||||
if (system == MowestaSettings.UnitSystem.STANDARD) {
|
||||
return context.getString(R.string.format_wind_speed_si, round(mpsToKmph(mps)));
|
||||
return context.getString(R.string.format_wind_speed_si, round(mpsToKmph(mps)), mpsToBFT(mps));
|
||||
} else {
|
||||
double mph = mpsToMph(mps);
|
||||
if (system == MowestaSettings.UnitSystem.IMPERIAL) {
|
||||
return context.getString(R.string.format_wind_speed_im, round(mph));
|
||||
return context.getString(R.string.format_wind_speed_im, round(mph), mpsToBFT(mps));
|
||||
} else {
|
||||
return context.getString(R.string.format_wind_speed_both, round(mpsToKmph(mps)), round(mph));
|
||||
}
|
||||
@@ -166,6 +203,7 @@ public class UnitUtils {
|
||||
|
||||
public static String getPrecipitation(@NonNull Context context, double mm) {
|
||||
MowestaSettings.UnitSystem system = getSettings(context).getUnitSystem();
|
||||
mm = Math.max(0, mm); // make sure this is positive
|
||||
if (system == MowestaSettings.UnitSystem.STANDARD) {
|
||||
return context.getString(R.string.format_precipitation_si, mm);
|
||||
} else {
|
||||
@@ -180,6 +218,7 @@ public class UnitUtils {
|
||||
|
||||
public static String getSnowDepth(@NonNull Context context, double m) {
|
||||
MowestaSettings.UnitSystem system = getSettings(context).getUnitSystem();
|
||||
m = Math.max(0, m); // make sure this is positive
|
||||
if (system == MowestaSettings.UnitSystem.STANDARD) {
|
||||
return context.getString(R.string.format_snow_si, m);
|
||||
} else {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.0 KiB |
@@ -2,10 +2,10 @@
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<gradient
|
||||
android:gradientRadius="150%p"
|
||||
android:centerX="0.8"
|
||||
android:centerY="1"
|
||||
android:centerX="0.2"
|
||||
android:centerY="0.5"
|
||||
android:endColor="#00695C"
|
||||
android:startColor="#CBCDD1"
|
||||
android:type="radial" />
|
||||
android:startColor="#CBCDD1"
|
||||
android:type="radial" />
|
||||
|
||||
</shape>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<gradient
|
||||
android:centerX="0.5"
|
||||
android:angle="270"
|
||||
android:endColor="#A0ffffff"
|
||||
android:centerColor="#40ffffff"
|
||||
android:startColor="#00ffffff"
|
||||
android:type="linear" />
|
||||
|
||||
</shape>
|
||||
@@ -29,7 +29,7 @@
|
||||
android:layout_width="48dp"
|
||||
android:layout_gravity="center_vertical"
|
||||
android:layout_height="wrap_content"
|
||||
android:tint="@color/fg_accent"
|
||||
app:tint="@color/fg_accent"
|
||||
app:srcCompat="@drawable/ic_view_headline_normal_24"/>
|
||||
<TextView
|
||||
android:layout_weight="1"
|
||||
@@ -125,7 +125,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="RAINDROPS" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
@@ -146,7 +146,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="WIND_DIRECTION" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
@@ -167,7 +167,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="CLOUD" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
@@ -188,7 +188,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="HUMIDITY" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
@@ -209,7 +209,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="SNOWFLAKE_COLD" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
@@ -230,7 +230,7 @@
|
||||
android:textSize="24dp"
|
||||
android:gravity="center"
|
||||
app:weather="BAROMETER" />
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:layout_gravity="center"
|
||||
style="@style/TextAppearance.MaterialComponents.Body1"
|
||||
android:singleLine="true"
|
||||
|
||||
@@ -60,21 +60,12 @@
|
||||
android:text="@string/collection_explain"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1" />
|
||||
|
||||
<Switch
|
||||
android:id="@+id/privacy_measure_switch"
|
||||
android:layout_margin="@dimen/space_large"
|
||||
android:layout_width="match_parent"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Button"
|
||||
android:textColor="@color/primary"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/collection_on_off" />
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
android:id="@+id/collection_note_permission"
|
||||
android:id="@+id/collection_note_location"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_margin="@dimen/space_medium"
|
||||
android:text="@string/collection_note_permission"
|
||||
android:text="@string/collection_note_location"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2" />
|
||||
|
||||
|
||||
@@ -97,6 +88,24 @@
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2" />
|
||||
|
||||
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:id="@+id/privacy_measure_switch"
|
||||
android:layout_margin="@dimen/space_medium"
|
||||
android:layout_width="match_parent"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Button"
|
||||
android:textColor="@color/primary"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/collection_on_off" />
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
android:id="@+id/collection_note_permission"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_margin="@dimen/space_medium"
|
||||
android:text="@string/collection_note_permission"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2" />
|
||||
|
||||
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/button_continue"
|
||||
|
||||
@@ -38,10 +38,7 @@
|
||||
android:padding="@dimen/space_medium"
|
||||
android:contentDescription="@null"
|
||||
app:srcCompat="@drawable/ic_toys_normal_24"
|
||||
android:tint="@color/accent" />
|
||||
|
||||
|
||||
|
||||
app:tint="@color/accent" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
@@ -106,7 +103,7 @@
|
||||
android:layout_width="@dimen/space_medium"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<Switch
|
||||
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||
android:id="@+id/setup_switch_manual"
|
||||
android:checked="@={ model.manualPosition }"
|
||||
android:gravity="center"
|
||||
|
||||
@@ -10,6 +10,17 @@
|
||||
tools:context=".MowestaActivity"
|
||||
android:orientation="vertical">
|
||||
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/logo_panel"
|
||||
android:orientation="horizontal"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:layout_alignParentEnd="true"
|
||||
android:background="@drawable/bg_launch_logo"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="96dp">
|
||||
</LinearLayout>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/splash_world"
|
||||
android:layout_width="match_parent"
|
||||
@@ -78,17 +89,44 @@
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/logo_locoslab"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="48dp"
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="horizontal"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:layout_alignParentEnd="true"
|
||||
android:padding="8dp"
|
||||
android:adjustViewBounds="true"
|
||||
android:contentDescription="@null"
|
||||
android:scaleType="fitEnd"
|
||||
app:srcCompat="@drawable/logo_locoslab" />
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/logo_ciss"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_weight="1"
|
||||
android:adjustViewBounds="false"
|
||||
android:contentDescription="@null"
|
||||
android:scaleType="fitStart"
|
||||
app:srcCompat="@drawable/logo_ciss" />
|
||||
|
||||
<Space
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/logo_locoslab"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_weight="1"
|
||||
android:paddingBottom="3dp"
|
||||
android:adjustViewBounds="false"
|
||||
android:contentDescription="@null"
|
||||
android:scaleType="fitEnd"
|
||||
app:srcCompat="@drawable/logo_locoslab" />
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</RelativeLayout>
|
||||
</layout>
|
||||
@@ -26,7 +26,7 @@
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_marginEnd="16dp"
|
||||
android:tint="@color/fg_accent"
|
||||
app:tint="@color/fg_accent"
|
||||
android:contentDescription="@null"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center_vertical" />
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_marginEnd="16dp"
|
||||
android:tint="@color/fg_accent"
|
||||
app:tint="@color/fg_accent"
|
||||
android:contentDescription="@null"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center_vertical" />
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_marginEnd="16dp"
|
||||
android:contentDescription="@null"
|
||||
android:tint="@color/fg_accent"
|
||||
app:tint="@color/fg_accent"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center_vertical" />
|
||||
<LinearLayout
|
||||
@@ -67,7 +67,7 @@
|
||||
android:layout_gravity="bottom"
|
||||
android:gravity="bottom"
|
||||
android:contentDescription="@string/label_altitude"
|
||||
android:tint="@color/fg_accent"
|
||||
app:tint="@color/fg_accent"
|
||||
tools:targetApi="O"
|
||||
android:tooltipText="@string/label_altitude"
|
||||
app:srcCompat="@drawable/ic_landscape_normal_24" />
|
||||
|
||||
@@ -85,9 +85,10 @@
|
||||
<string name="collection_logo_fair">FAIR Forschungsprojekt</string>
|
||||
<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_permission">* Die Datenerfassung benötigt die Erlaubnis Deinen Standort im Hintergrund zu bestimmen.</string>
|
||||
<string name="collection_note_data">* Die Übertragung der Messdaten an MoWeSta nutzt Deine mobile Datenverbindung, was sehr teuer sein kann.</string>
|
||||
<string name="collection_note_enable">* Du kannst die Datenerfassung und -übertragung jederzeit über die Einstellungen der Anwendung ein- und ausschalten.</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 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>
|
||||
|
||||
@@ -100,7 +101,7 @@
|
||||
<!-- Settings -->
|
||||
<string name="setting_category_privacy">Datenschutz</string>
|
||||
<string name="setting_privacy_measure_title">Datenerfassung</string>
|
||||
<string name="setting_privacy_measure_summary">Aktiviert die Erfassung von Messungen im Hintergrund. Deaktivierung beendet die Messung und Übertragung von Daten.</string>
|
||||
<string name="setting_privacy_measure_summary">Aktiviert die Erfassung von Messungen im Hintergrund. Falls aktiviert, erhebt MoWeSta Standortdaten, auch wenn die App geschlossen ist oder nicht verwendet wird..</string>
|
||||
<string name="setting_privacy_reset_title">Zurücksetzen</string>
|
||||
<string name="setting_privacy_reset_summary">Entfernt alle auf dem Gerät gespeicherten Daten und setzt die Geräteregistierung zurück. Nach der Ausführung muss das Gerät erneut registriert werden.</string>
|
||||
<string name="setting_privacy_reset_message">Möchtest Du wirklich ALLE Daten löschen? Das kannst Du nicht mehr rückgängig machen!</string>
|
||||
@@ -177,6 +178,7 @@
|
||||
<string name="video_source_icon_europe">Europa</string>
|
||||
<string name="video_source_cosmo_europe">D-A-CH</string>
|
||||
<string name="video_type_temperature">Temperatur</string>
|
||||
<string name="video_type_wind">Wind</string>
|
||||
<string name="video_type_pressure">Luftdruck</string>
|
||||
<string name="video_type_cloud">Bewölkung</string>
|
||||
<string name="video_type_precipitation">Niederschlag</string>
|
||||
|
||||
@@ -8,16 +8,15 @@
|
||||
|
||||
<string tools:ignore="UnusedResources" name="mowesta_sdk_notification_activity_class_name" translatable="false">com.mowesta.android.app.MowestaActivity</string>
|
||||
|
||||
|
||||
<string name="format_temperature_both" translatable="false">%d<small>\u00A0°C</small> / %d<small>\u00A0°F</small></string>
|
||||
<string name="format_temperature_celsius" translatable="false">%d<small> °C</small></string>
|
||||
<string name="format_temperature_fahrenheit" translatable="false">%d<small> °F</small></string>
|
||||
<string name="format_temperature_both" translatable="false">%.1f<small>\u00A0°C</small> / %.1f<small>\u00A0°F</small></string>
|
||||
<string name="format_temperature_celsius" translatable="false">%.1f<small> °C</small></string>
|
||||
<string name="format_temperature_fahrenheit" translatable="false">%.1f<small> °F</small></string>
|
||||
<string name="format_pressure_both" translatable="false"><span>%.1f<small>\u00A0hPa</small></span> / <span>%.3f<small>\u00A0psi</small></span></string>
|
||||
<string name="format_pressure_si" translatable="false">%.1f<small> hPa</small></string>
|
||||
<string name="format_pressure_im" translatable="false">%.3f<small> psi</small></string>
|
||||
<string name="format_wind_speed_both" translatable="false">%d<small>\u00A0km\u2215h</small> / %d<small>\u00A0mph</small></string>
|
||||
<string name="format_wind_speed_si" translatable="false">%d<small> km\u2215h</small></string>
|
||||
<string name="format_wind_speed_im" translatable="false">%d<small> mph</small></string>
|
||||
<string name="format_wind_speed_si" translatable="false">%d<small> km\u2215h</small> (<small>BFT</small> %d)</string>
|
||||
<string name="format_wind_speed_im" translatable="false">%d<small> mph</small> (<small>BFT</small> %d)</string>
|
||||
<string name="format_precipitation_both" translatable="false">%.1f<small>\u00A0mm\u2215h</small> / %.2f<small>\u00A0in\u2215h</small></string>
|
||||
<string name="format_precipitation_si" translatable="false">%.1f<small> mm\u2215h</small></string>
|
||||
<string name="format_precipitation_im" translatable="false">%.2f<small> in\u2215h</small></string>
|
||||
@@ -30,7 +29,7 @@
|
||||
|
||||
<string name="format_humidity" translatable="false">%.2f<small> %%</small></string>
|
||||
<string name="format_cloud_coverage" translatable="false">%.2f<small> %%</small></string>
|
||||
<string name="format_frequency" translatable="false">%.0f<small> Hz</small></string>
|
||||
<string name="format_frequency" translatable="false">%.0f<small> MHz</small></string>
|
||||
<string name="format_voltage" translatable="false">%.2f<small> V</small></string>
|
||||
<string name="format_compact" translatable="false">%.0f</string>
|
||||
<string name="format_integer" translatable="false">%d</string>
|
||||
|
||||
@@ -87,9 +87,10 @@
|
||||
<string name="collection_logo_fair">FAIR Research Project</string>
|
||||
<string name="collection_title">Help MoWeSta</string>
|
||||
<string name="collection_explain">Transform your device into a Mobile Weather Station* and help us to determine whether we can improve weather forecasts using crowd-sourced weather information provided by people like you!</string>
|
||||
<string name="collection_note_permission">* Data collection requires the permission to determine your location in the background.</string>
|
||||
<string name="collection_note_data">* The transmission of measurements to MoWeSta uses your mobile data which can be very expensive.</string>
|
||||
<string name="collection_note_enable">* You can activate or deactivate the measurements and transmission at any time through the app settings.</string>
|
||||
<string name="collection_note_location">* If you participate, MoWeSta collects location data to determine the location of temperature readings even when the app is closed or not in use.</string>
|
||||
<string name="collection_note_data">* If you participate, MoWeSta collects and transmits the location and measurement data in the background via your mobile data connection which can be very expensive.</string>
|
||||
<string name="collection_note_enable">* Data collection is opt-in only, you can activate or deactivate the data collection and transmission in the background at any time through the app settings.</string>
|
||||
<string name="collection_note_permission">Participation requires you to grant the permission for background localization.</string>
|
||||
<string name="collection_on_off">Participate now</string>
|
||||
<string name="collection_button_continue">Let\'s get started</string>
|
||||
|
||||
@@ -102,7 +103,7 @@
|
||||
<!-- Settings -->
|
||||
<string name="setting_category_privacy">Privacy</string>
|
||||
<string name="setting_privacy_measure_title">Measurements</string>
|
||||
<string name="setting_privacy_measure_summary">Enables the service to perform measurements in the background. If disabled, the application will no longer perform and upload measurements.</string>
|
||||
<string name="setting_privacy_measure_summary">Enables the service to perform measurements in the background. If enabled, MoWeSta collects location data even when the app is closed or not in use.</string>
|
||||
<string name="setting_privacy_reset_title">Reset</string>
|
||||
<string name="setting_privacy_reset_summary">Removes all app data stored on your device and unregisters the device. After deletion, you will have to re-register your device.</string>
|
||||
<string name="setting_privacy_reset_message">Do you really want remove ALL data? You cannot undo this later!</string>
|
||||
@@ -180,6 +181,7 @@
|
||||
<string name="video_source_icon_europe">Europe</string>
|
||||
<string name="video_source_cosmo_europe">D-A-CH</string>
|
||||
<string name="video_type_temperature">Temperature</string>
|
||||
<string name="video_type_wind">Wind</string>
|
||||
<string name="video_type_pressure">Pressure</string>
|
||||
<string name="video_type_cloud">Cloudiness</string>
|
||||
<string name="video_type_precipitation">Precipitation</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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+31
-37
@@ -2,34 +2,26 @@ apply plugin: 'maven-publish'
|
||||
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:4.0.0'
|
||||
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.10.0'
|
||||
classpath 'com.android.tools.build:gradle:4.1.1'
|
||||
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.10'
|
||||
version = '1.0.13'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
@@ -40,12 +32,14 @@ allprojects {
|
||||
versionSwagger = '1.5.22'
|
||||
versionGeojson = '1.8.1'
|
||||
// wildfly dependencies, keep in sync
|
||||
versionJackson = '2.9.9'
|
||||
versionResteasy = '3.7.0.Final'
|
||||
versionWildfly = '17.0.1.Final'
|
||||
versionJackson = '2.10.5'
|
||||
versionResteasy = '3.13.2.Final'
|
||||
versionWildfly = '21.0.0.Final'
|
||||
versionPicketbox = '5.0.3.Final'
|
||||
versionHibernateSearch = '5.10.5.Final'
|
||||
versionInfinispan = '9.4.14.Final'
|
||||
versionHibernate = '5.3.18.Final'
|
||||
versionHibernateSearch = '5.10.7.Final'
|
||||
// built-in infinispan dependency
|
||||
versionInfinispan = '9.4.20.Final'
|
||||
// testing dependencies
|
||||
versionJunit = '4.12'
|
||||
versionArquillianContainer = '2.2.0.Final'
|
||||
@@ -56,11 +50,11 @@ allprojects {
|
||||
// other frameworks
|
||||
mapstructVersion = '1.3.1.Final'
|
||||
// shared android dependencies
|
||||
versionAndroidXTest = '1.2.0'
|
||||
versionAndroidXTest = '1.3.0'
|
||||
versionAndroidXAppcompat = '1.2.0'
|
||||
versionAndroidXRoom = '2.2.5'
|
||||
versionAndroidXRoom = '2.2.6'
|
||||
versionAndroidXPreference = '1.1.1'
|
||||
versionRobolectric = '4.3.1'
|
||||
versionRobolectric = '4.5'
|
||||
|
||||
}
|
||||
|
||||
@@ -85,6 +79,7 @@ subprojects {
|
||||
publications {
|
||||
maven(MavenPublication) {
|
||||
artifact file('build/outputs/aar/android-sdk-release.aar')
|
||||
version = project.version
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,32 +117,31 @@ subprojects {
|
||||
|
||||
}
|
||||
|
||||
artifactoryPublish.dependsOn('build')
|
||||
artifactoryPublish {
|
||||
publications(publishing.publications.maven);
|
||||
}
|
||||
|
||||
|
||||
repositories {
|
||||
repositories {
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/releases';
|
||||
credentials { username = 'public'; password = 'public' }
|
||||
authentication { basic(BasicAuthentication) }
|
||||
}
|
||||
maven {
|
||||
url = 'https://project.nes.uni-due.de/artifactory/snapshots';
|
||||
url = 'https://project.nes.uni-due.de/nexus/repository/maven-public';
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
tasks.register("generatePomFileForMavenPublication") {
|
||||
// rename subprojects in eclipse to avoid collisions with other projects
|
||||
eclipse.project.name = 'mowesta-' + project.name
|
||||
|
||||
}
|
||||
|
||||
tasks.register("build") {
|
||||
tasks.register("generatePomFileForMavenPublication") { }
|
||||
|
||||
}
|
||||
tasks.register("build") { }
|
||||
|
||||
@@ -42,7 +42,7 @@ import io.swagger.annotations.Authorization;
|
||||
public interface IDeviceService {
|
||||
|
||||
// device functions (for the mobile app)
|
||||
|
||||
|
||||
/**
|
||||
* Creates and returns a new device.
|
||||
*
|
||||
@@ -66,6 +66,7 @@ public interface IDeviceService {
|
||||
/**
|
||||
* Sets the user account for a previously registered device.
|
||||
*
|
||||
* @param device The device to associate with the user.
|
||||
* @return A response.
|
||||
*/
|
||||
@POST
|
||||
@@ -100,7 +101,7 @@ public interface IDeviceService {
|
||||
|
||||
/**
|
||||
* Deletes the current device.
|
||||
*
|
||||
*
|
||||
* @return A response code to indicate the success.
|
||||
*/
|
||||
@DELETE
|
||||
|
||||
@@ -29,7 +29,7 @@ import io.swagger.annotations.ApiResponses;
|
||||
|
||||
/**
|
||||
* The api to query and fetch locations.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Api
|
||||
@@ -40,7 +40,7 @@ public interface ILocationService {
|
||||
|
||||
/**
|
||||
* Returns a page of locations that match the query.
|
||||
*
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param context The search context.
|
||||
* @param term The search term.
|
||||
@@ -53,16 +53,16 @@ public interface ILocationService {
|
||||
@ApiResponses({
|
||||
@ApiResponse(code=HttpServletResponse.SC_OK, message="Location hierarchy page retrieved successfully.", response=LocationHierarchyPage.class),
|
||||
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
|
||||
})
|
||||
})
|
||||
@PermitAll
|
||||
Response searchLocations(@BeanParam @Valid PageConfig pageConfig, @BeanParam @Valid SearchContext context,
|
||||
@ApiParam(value="The search term.", required=true) @QueryParam("term") @NotNull @Valid String term);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of cities that are inside a particular area defined by two coordinates.
|
||||
*
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @param longitude1 The longitude of the first coordinate.
|
||||
* @param latitude1 The latitude of the first coordinate.
|
||||
@@ -76,18 +76,18 @@ public interface ILocationService {
|
||||
@ApiResponses({
|
||||
@ApiResponse(code=HttpServletResponse.SC_OK, message="The pages.", response=CityPage.class),
|
||||
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
|
||||
})
|
||||
})
|
||||
@PermitAll
|
||||
Response searchCities(@BeanParam @Valid PageConfig pageConfig,
|
||||
@ApiParam(value = "The longitude of the first coordinate.", required = true) @QueryParam("longitude1") double longitude1,
|
||||
Response searchCities(@BeanParam @Valid PageConfig pageConfig,
|
||||
@ApiParam(value = "The longitude of the first coordinate.", required = true) @QueryParam("longitude1") double longitude1,
|
||||
@ApiParam(value = "The latitude of the first coordinate.", required = true) @QueryParam("latitude1") double latitude1,
|
||||
@ApiParam(value = "The longitude of the second coordinate.", required = true) @QueryParam("longitude2") double longitude2,
|
||||
@ApiParam(value = "The longitude of the second coordinate.", required = true) @QueryParam("longitude2") double longitude2,
|
||||
@ApiParam(value = "The latitude of the second coordinate.", required = true) @QueryParam("latitude2") double latitude2);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of cities.
|
||||
*
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @return A page of cities.
|
||||
*/
|
||||
@@ -97,10 +97,10 @@ public interface ILocationService {
|
||||
@ApiResponses({
|
||||
@ApiResponse(code=HttpServletResponse.SC_OK, message="City page retrieved successfully.", response=CityPage.class),
|
||||
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
|
||||
})
|
||||
})
|
||||
@PermitAll
|
||||
Response getCities(@BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a particular city.
|
||||
*
|
||||
@@ -119,8 +119,8 @@ public interface ILocationService {
|
||||
|
||||
/**
|
||||
* Returns a geojson representation of the city boundaries.
|
||||
*
|
||||
* @param id The id of the city.
|
||||
*
|
||||
* @param id The id of the city.
|
||||
* @return The boundaries of geojson or an error code.
|
||||
*/
|
||||
@GET
|
||||
@@ -134,8 +134,8 @@ public interface ILocationService {
|
||||
@PermitAll
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
Response getCityBoundary(@ApiParam(value = "The city id.", required = true) @PathParam("id") @Valid @Min(0) long id);
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of states.
|
||||
*
|
||||
@@ -151,7 +151,7 @@ public interface ILocationService {
|
||||
})
|
||||
@PermitAll
|
||||
Response getStates(@BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a particular state.
|
||||
*
|
||||
@@ -167,15 +167,15 @@ public interface ILocationService {
|
||||
})
|
||||
@PermitAll
|
||||
Response getState(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a geojson representation of the state boundaries.
|
||||
*
|
||||
* @param id The id of the state.
|
||||
* @return The boundaries of geojson or an error code.
|
||||
* @return The boundaries as geojson or an error code.
|
||||
*/
|
||||
@GET
|
||||
@Path("state/{id: [0-9]+}/boundary")
|
||||
@Path("states/{id: [0-9]+}/boundary")
|
||||
@ApiOperation(value = "Gets the state boundary for a state with a particular id.", tags = {Tags.DEFAULT, Tags.LOCATION})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "State boundary retrieved successfully.", response=Geometry.class),
|
||||
@@ -185,7 +185,28 @@ public interface ILocationService {
|
||||
@PermitAll
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
Response getStateBoundary(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
|
||||
|
||||
|
||||
/**
|
||||
* The deprecated version of the method that has a typo in the path name (state instead of states).
|
||||
* To be removed, if Android Apps < V14 are no longer present.
|
||||
*
|
||||
* @param id The id of the state.
|
||||
* @return The boundaries as geojson or an error code.
|
||||
*/
|
||||
@GET
|
||||
@Path("state/{id: [0-9]+}/boundary")
|
||||
@ApiOperation(value = "Deprecated: Gets the state boundary for a state with a particular id.", tags = {Tags.DEFAULT, Tags.LOCATION})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "State boundary retrieved successfully.", response=Geometry.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_NO_CONTENT, message = "The state boundary are not available."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The state does not exist."),
|
||||
})
|
||||
@PermitAll
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
@Deprecated
|
||||
Response getStateBoundaryDeprecated(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of cities for a state ordered by importance.
|
||||
*
|
||||
@@ -202,10 +223,10 @@ public interface ILocationService {
|
||||
})
|
||||
@PermitAll
|
||||
Response getStateCities(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id, @BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of countries.
|
||||
*
|
||||
*
|
||||
* @param pageConfig The page configuration.
|
||||
* @return A page of countries.
|
||||
*/
|
||||
@@ -215,10 +236,10 @@ public interface ILocationService {
|
||||
@ApiResponses({
|
||||
@ApiResponse(code=HttpServletResponse.SC_OK, message="Country page retrieved successfully.", response=CountryPage.class),
|
||||
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
|
||||
})
|
||||
})
|
||||
@PermitAll
|
||||
Response getCountries(@BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a particular country.
|
||||
*
|
||||
@@ -237,8 +258,8 @@ public interface ILocationService {
|
||||
|
||||
/**
|
||||
* Returns a geojson representation of the country boundaries.
|
||||
*
|
||||
* @param id The id of the country.
|
||||
*
|
||||
* @param id The id of the country.
|
||||
* @return The boundaries of geojson or an error code.
|
||||
*/
|
||||
@GET
|
||||
@@ -252,7 +273,7 @@ public interface ILocationService {
|
||||
@PermitAll
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
Response getCountryBoundary(@ApiParam(value = "The country id.", required = true) @PathParam("id") @Valid @Min(0) long id);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of cities for a country ordered by importance.
|
||||
*
|
||||
@@ -270,5 +291,5 @@ public interface ILocationService {
|
||||
@PermitAll
|
||||
Response getCountryCities(@ApiParam(value = "The country id.", required = true) @PathParam("id") @Valid @Min(0) long id, @BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.mowesta.api.weather;
|
||||
/**
|
||||
* An enumeration with different video types that
|
||||
* we generate from our dataset.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public enum VideoType {
|
||||
@@ -23,6 +23,10 @@ public enum VideoType {
|
||||
/**
|
||||
* The temperature video.
|
||||
*/
|
||||
TEMPERATURE;
|
||||
|
||||
TEMPERATURE,
|
||||
/**
|
||||
* The wind video.
|
||||
*/
|
||||
WIND;
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
#Sat May 30 11:33:41 CEST 2020
|
||||
#Sat Nov 07 15:10:18 CET 2020
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
plugins {
|
||||
id 'war'
|
||||
}
|
||||
|
||||
description = 'Mowesta Alexa Service'
|
||||
|
||||
dependencies {
|
||||
|
||||
providedCompile project(':service-ejb')
|
||||
compile "com.amazon.alexa:ask-sdk:2.37.1"
|
||||
|
||||
testCompile project(':service-ejb')
|
||||
testCompile "junit:junit:${versionJunit}"
|
||||
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
|
||||
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
|
||||
|
||||
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.mowesta.service.alexa;
|
||||
|
||||
import com.amazon.ask.Skills;
|
||||
import com.amazon.ask.servlet.SkillServlet;
|
||||
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.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.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
|
||||
@RequestScoped
|
||||
public class AlexaServlet extends HttpServlet {
|
||||
|
||||
private HttpServlet servlet;
|
||||
|
||||
|
||||
@Inject
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
@Inject
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
Logger log = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
|
||||
getServlet().service(req, res);
|
||||
}
|
||||
|
||||
public HttpServlet getServlet() {
|
||||
if (servlet == null) {
|
||||
servlet = createServlet();
|
||||
try {
|
||||
servlet.init(getServletConfig());
|
||||
} catch (ServletException e) {
|
||||
throw new RuntimeException("Failed to initialize skill servlet.", e);
|
||||
}
|
||||
}
|
||||
return servlet;
|
||||
}
|
||||
|
||||
public SkillServlet createServlet() {
|
||||
log.log(Level.INFO,"Servlet created " + locationSessionBean + " " + weatherSessionBean);
|
||||
return new SkillServlet(Skills.standard()
|
||||
.addRequestHandlers(
|
||||
new CancelandStopIntentHandler(),
|
||||
new HelpIntentHandler(),
|
||||
new LaunchRequestHandler(),
|
||||
new SessionEndedRequestHandler(),
|
||||
new CurrentWeatherIntentHandler(locationSessionBean, weatherSessionBean),
|
||||
new WeatherForecastIntentHandler(locationSessionBean, weatherSessionBean),
|
||||
new ClothingRecommendationIntentHandler(locationSessionBean, weatherSessionBean))
|
||||
.withSkillId("amzn1.ask.skill.208278db-dd0c-477e-9946-5ebe634831aa")
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
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 CancelandStopIntentHandler implements RequestHandler {
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(intentName("AMAZON.StopIntent").or(intentName("AMAZON.CancelIntent")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
String speechText = "Goodbye";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("HelloWorld", speechText)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+182
@@ -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;
|
||||
}
|
||||
}
|
||||
+101
@@ -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;
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
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.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 {
|
||||
|
||||
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
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
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("CurrentWeatherIntent"));
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
WeatherCondition currentWeatherOfLocation = weatherSessionBean.getCondition(location.getCoordinate());
|
||||
|
||||
if (currentWeatherOfLocation != null) {
|
||||
DecimalFormat decimalFormat = new DecimalFormat("#.#");
|
||||
String temperature = String.valueOf(decimalFormat.format(currentWeatherOfLocation.getTemperature())).replaceAll("\\.", ",");
|
||||
String[] splitTemperature = temperature.split(",");
|
||||
if (splitTemperature.length > 1 && splitTemperature[1].equals("0")) temperature = splitTemperature[0];
|
||||
|
||||
String weatherType = weatherTypeToStringConverter.convertToString(currentWeatherOfLocation.getType());
|
||||
|
||||
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 gefunden.";
|
||||
}
|
||||
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("CurrentWeather", speechText)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
|
||||
// 2018-July-09: AMAZON.FallackIntent is only currently available in en-US locale.
|
||||
// This handler will not be triggered except in that locale, so it can be
|
||||
// safely deployed for any locale.
|
||||
public class FallbackIntentHandler implements RequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(intentName("AMAZON.FallbackIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
String speechText = "Sorry, I don't know that. You can say try saying help!";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("HelloWorld", speechText)
|
||||
.withReprompt(speechText)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+90
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
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 HelpIntentHandler implements RequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(intentName("AMAZON.HelpIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
String speechText = "You can say hello to me!";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("HelloWorld", speechText)
|
||||
.withReprompt(speechText)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
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.LaunchRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.requestType;
|
||||
|
||||
public class LaunchRequestHandler implements RequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(requestType(LaunchRequest.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
String speechText = "Welcome to the Alexa Skills Kit, you can say hello";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(speechText)
|
||||
.withSimpleCard("HelloWorld", speechText)
|
||||
.withReprompt(speechText)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+167
@@ -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;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
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 com.amazon.ask.model.SessionEndedRequest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.requestType;
|
||||
|
||||
public class SessionEndedRequestHandler implements RequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input) {
|
||||
return input.matches(requestType(SessionEndedRequest.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input) {
|
||||
// any cleanup logic goes here
|
||||
return input.getResponseBuilder().build();
|
||||
}
|
||||
|
||||
}
|
||||
+219
@@ -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;
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
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){
|
||||
String weathercondition = "";
|
||||
|
||||
switch (weatherType){
|
||||
|
||||
case UNKNOWN:
|
||||
break;
|
||||
case FOG:
|
||||
weathercondition = " und es ist nebelig";
|
||||
break;
|
||||
case CLOUDY:
|
||||
weathercondition = " und es ist bewölkt";
|
||||
break;
|
||||
case CLEAR_SKY:
|
||||
weathercondition = " und der Himmel ist klar";
|
||||
break;
|
||||
case SNOW_GRAINS:
|
||||
weathercondition = " und es gibt Graupelschauer";
|
||||
break;
|
||||
case MAINLY_CLEAR:
|
||||
weathercondition = " und der Himmel ist hauptsächlich klar";
|
||||
break;
|
||||
case HEAVY_DRIZZLE:
|
||||
weathercondition = " und es gibt einen starken Nieselregen";
|
||||
break;
|
||||
case PARTLY_CLOUDY:
|
||||
weathercondition = " und es ist teilweise bewölkt";
|
||||
break;
|
||||
case SLIGHT_DRIZZLE:
|
||||
weathercondition = " und es gibt leichten Nieselregen";
|
||||
break;
|
||||
case MODERATE_DRIZZLE:
|
||||
weathercondition = " und es gibt Nieselregen";
|
||||
break;
|
||||
case RAIN_SHOWER_SLIGHT:
|
||||
case SLIGHT_RAIN_NOT_FREEZING:
|
||||
weathercondition = " und es regnet leicht";
|
||||
break;
|
||||
case SNOW_SHOWER_SLIGHT:
|
||||
case SLIGHT_FALL_OF_SNOWFLAKES:
|
||||
weathercondition = " und es gibt leichten Schneefall";
|
||||
break;
|
||||
case FOG_DEPOSITING_RIME:
|
||||
weathercondition = " und es gibt Nebel";
|
||||
break;
|
||||
case RAIN_SHOWER_VIOLENT:
|
||||
case HEAVY_RAIN_NOT_FREEZING:
|
||||
weathercondition = " und es gibt Starkregen";
|
||||
break;
|
||||
case RAIN_FREEZING_SLIGHT:
|
||||
weathercondition = " und es gibt gefrierenden leichten Regen";
|
||||
break;
|
||||
case DRIZZLE_FREEZING_SLIGHT:
|
||||
weathercondition = " und es gibt gefrierenden leichten Nieselregen";
|
||||
break;
|
||||
case THUNDERSTORM_HAIL_HEAVY:
|
||||
weathercondition = " und es kann zu Hagelschauern und Gewitter kommen";
|
||||
break;
|
||||
case HEAVY_FALL_OF_SNOWFLAKES:
|
||||
weathercondition = " und es gibt starken Schneefall";
|
||||
break;
|
||||
case MODERATE_RAIN_NOT_FREEZING:
|
||||
weathercondition = " und es regnet";
|
||||
break;
|
||||
case RAIN_SHOWER_MODERATE_HEAVY:
|
||||
weathercondition = " und es regnet teilweise schwer";
|
||||
break;
|
||||
case SNOW_SHOWER_MODERATE_HEAVY:
|
||||
weathercondition = " und es schneit teilweise stark";
|
||||
break;
|
||||
case MODERATE_FALL_OF_SNOWFLAKES:
|
||||
weathercondition = " und es schneit";
|
||||
break;
|
||||
case RAIN_FREEZING_MODERATE_HEAVY:
|
||||
weathercondition = " und es gibt gefrierenden Regen";
|
||||
break;
|
||||
case THUNDERSTORM_SLIGHT_MODERATE:
|
||||
weathercondition = " und es gewittert teilweise";
|
||||
break;
|
||||
case DRIZZLE_FREEZING_MODERATE_HEAVY:
|
||||
weathercondition = " und es kommt zu gefrierenden Sprühregen";
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
|
||||
return weathercondition;
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
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.service.entity.UserEntity;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
public class WeatherstationIntentHandler implements IntentRequestHandler {
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("WeatherstationIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
|
||||
String accessToken = input.getRequestEnvelope().getContext().getSystem().getUser().getAccessToken();
|
||||
|
||||
|
||||
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 {
|
||||
String errorText = "Herzlichen Glückwunsch";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Glückwunsch", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE xml>
|
||||
<jboss-web>
|
||||
<context-root>alexa</context-root>
|
||||
</jboss-web>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
|
||||
|
||||
|
||||
<display-name>alexaservlet</display-name>
|
||||
<servlet>
|
||||
<servlet-name>alexaservlet</servlet-name>
|
||||
<servlet-class>com.mowesta.service.alexa.AlexaServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>alexaservlet</servlet-name>
|
||||
<url-pattern>/alexa</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!--<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>-->
|
||||
|
||||
</web-app>
|
||||
@@ -0,0 +1,8 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Alexa Context Root</title>
|
||||
</head>
|
||||
<body>
|
||||
Web context Alexa has been loaded successfully.
|
||||
</body>
|
||||
</html>
|
||||
@@ -20,6 +20,7 @@ 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.BitmapInterpreter;
|
||||
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
@@ -31,16 +32,15 @@ import com.mowesta.data.process.util.FileNameComparator;
|
||||
* Represents a numeric weather prediction from DWD.
|
||||
*/
|
||||
public class NumericPrediction {
|
||||
|
||||
|
||||
/**
|
||||
* The extension of the data files.
|
||||
*/
|
||||
private static final String GRIB_EXTENSION = "grib2.bz2";
|
||||
|
||||
|
||||
/**
|
||||
* A enum to describe the coordinate system used
|
||||
* to represent locations.
|
||||
*
|
||||
* A enum to describe the coordinate system used to represent locations.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
@@ -57,55 +57,54 @@ public class NumericPrediction {
|
||||
* A icosahedral system.
|
||||
*/
|
||||
ICOSAHEDRAL("icosahedral", false);
|
||||
|
||||
|
||||
/**
|
||||
* The string to filter files.
|
||||
*/
|
||||
private final String filter;
|
||||
|
||||
|
||||
/**
|
||||
* A flag to indicate whether the values
|
||||
* are computed from a grid definition.
|
||||
* A flag to indicate whether the values are computed from a grid definition.
|
||||
*/
|
||||
private final boolean computed;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new coordinate system.
|
||||
*
|
||||
* @param filter The keyword to filter.
|
||||
* @param computed A boolean to indicate whether the
|
||||
* values are computed.
|
||||
*
|
||||
* @param filter
|
||||
* The keyword to filter.
|
||||
* @param computed
|
||||
* A boolean to indicate whether the values are computed.
|
||||
*/
|
||||
private CoordinateSystem(String filter, boolean computed) {
|
||||
this.filter = filter;
|
||||
this.computed = computed;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the keyword to filter files.
|
||||
*
|
||||
*
|
||||
* @return The filter.
|
||||
*/
|
||||
public String getFilter() {
|
||||
return filter;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns true if the values of the positions are
|
||||
* computed from a grid definition. False if they shall
|
||||
* be read from a file.
|
||||
*
|
||||
* Returns true if the values of the positions are computed from a grid
|
||||
* definition. False if they shall be read from a file.
|
||||
*
|
||||
* @return True if the coordinates are computed, false otherwise.
|
||||
*/
|
||||
public boolean isComputed() {
|
||||
return computed;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The predictions that we use to download data.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public enum PredictionType {
|
||||
@@ -116,12 +115,13 @@ public class NumericPrediction {
|
||||
/**
|
||||
* The european icon prediction.
|
||||
*/
|
||||
ICON_EUROPE("opendata.dwd.de", "weather/nwp/icon-eu/grib/00/", 0, CoordinateSystem.REGULAR, 93),
|
||||
ICON_EUROPE("opendata.dwd.de", "weather/nwp/icon-eu/grib/00/", 0, CoordinateSystem.REGULAR, 93),
|
||||
/**
|
||||
* The cosmo d2 prediction (the 3 o'clock prediction has more data, but sizes vary across variables).
|
||||
* The cosmo d2 prediction (the 3 o'clock prediction has more data, but sizes
|
||||
* vary across variables).
|
||||
*/
|
||||
COSMO_EUROPE("opendata.dwd.de", "weather/nwp/cosmo-d2/grib/03/", 3, CoordinateSystem.ROTATED, 46);
|
||||
|
||||
COSMO_EUROPE("opendata.dwd.de", "weather/nwp/icon-d2/grib/03/", 3, CoordinateSystem.ICOSAHEDRAL, 46);
|
||||
|
||||
/**
|
||||
* The number of files expected in variant data folders.
|
||||
*/
|
||||
@@ -138,19 +138,23 @@ public class NumericPrediction {
|
||||
* The server name.
|
||||
*/
|
||||
private String server;
|
||||
|
||||
|
||||
/**
|
||||
* The hour when the prediction is generated.
|
||||
*/
|
||||
private int hour;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new prediction.
|
||||
*
|
||||
* @param server The server name.
|
||||
* @param folder The remote folder.
|
||||
* @param system The coordinate system used by the simulation.
|
||||
* @param files The number of files in for time variant variables.
|
||||
*
|
||||
* @param server
|
||||
* The server name.
|
||||
* @param folder
|
||||
* The remote folder.
|
||||
* @param system
|
||||
* The coordinate system used by the simulation.
|
||||
* @param files
|
||||
* The number of files in for time variant variables.
|
||||
*/
|
||||
private PredictionType(String server, String folder, int hour, CoordinateSystem system, int files) {
|
||||
this.server = server;
|
||||
@@ -159,58 +163,57 @@ public class NumericPrediction {
|
||||
this.system = system;
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the hour when the prediction is made.
|
||||
*
|
||||
*
|
||||
* @return The hour.
|
||||
*/
|
||||
public int getHour() {
|
||||
return hour;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The number of files for time variant variables.
|
||||
*
|
||||
*
|
||||
* @return The number of files for time variant variables.
|
||||
*/
|
||||
public int getFiles() {
|
||||
return files;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The folder on the server.
|
||||
*
|
||||
*
|
||||
* @return The folder on the server.
|
||||
*/
|
||||
public String getFolder() {
|
||||
return folder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The name of the ftp server.
|
||||
*
|
||||
*
|
||||
* @return The name of the ftp server.
|
||||
*/
|
||||
public String getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the coordinate system used by the simulation.
|
||||
*
|
||||
*
|
||||
* @return The coordinate system.
|
||||
*/
|
||||
public CoordinateSystem getSystem() {
|
||||
return system;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An enumeration with the variables.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public enum Variable {
|
||||
@@ -274,65 +277,67 @@ public class NumericPrediction {
|
||||
* The total precipitation (accumulated (!)).
|
||||
*/
|
||||
PREC("tot_prec", false),
|
||||
|
||||
|
||||
/**
|
||||
* The zonal wind. at 10m height.
|
||||
*/
|
||||
U10M("u_10m", false),
|
||||
|
||||
|
||||
/**
|
||||
* The meridional wind at 10m height.
|
||||
*/
|
||||
V10M("v_10m", false),
|
||||
|
||||
|
||||
/**
|
||||
* The weather interpretation type.
|
||||
*/
|
||||
WW("ww", false);
|
||||
|
||||
|
||||
/**
|
||||
* The name of the folder.
|
||||
*/
|
||||
private final String folder;
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether the variable is time invariant.
|
||||
*/
|
||||
private final boolean invariant;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new variable.
|
||||
*
|
||||
* @param folder The folder name.
|
||||
* @param invariant True if time invariant.
|
||||
*
|
||||
* @param folder
|
||||
* The folder name.
|
||||
* @param invariant
|
||||
* True if time invariant.
|
||||
*/
|
||||
private Variable(String folder, boolean invariant) {
|
||||
this.folder = folder;
|
||||
this.invariant = invariant;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the folder name.
|
||||
*
|
||||
*
|
||||
* @return The folder name.
|
||||
*/
|
||||
public String getFolder() {
|
||||
return folder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns true if the variable is time invariant.
|
||||
*
|
||||
*
|
||||
* @return True if time invariant, false otherwise.
|
||||
*/
|
||||
public boolean isInvariant() {
|
||||
return invariant;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Utility class used to represent time stamps.
|
||||
*
|
||||
* Utility class used to represent time stamps.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class Time implements Comparable<Time> {
|
||||
@@ -348,28 +353,33 @@ public class NumericPrediction {
|
||||
* The day of the month (1-31).
|
||||
*/
|
||||
public final int day;
|
||||
|
||||
/**
|
||||
* Creates a new time instance with the specified
|
||||
* year, month and day.
|
||||
*
|
||||
* @param year The year.
|
||||
* @param month The month.
|
||||
* @param day The day.
|
||||
* Creates a new time instance with the specified year, month and day.
|
||||
*
|
||||
* @param year
|
||||
* The year.
|
||||
* @param month
|
||||
* The month.
|
||||
* @param day
|
||||
* The day.
|
||||
*/
|
||||
public Time(int year, int month, int day) {
|
||||
this.year = year;
|
||||
this.month = month;
|
||||
this.day = day;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the value of the string.
|
||||
*
|
||||
* @param s The string.
|
||||
*
|
||||
* @param s
|
||||
* The string.
|
||||
* @return The time or null, if the string does not represent time.
|
||||
*/
|
||||
public static Time valueOf(String s) {
|
||||
if (s == null || s.length() != 8) return null;
|
||||
if (s == null || s.length() != 8)
|
||||
return null;
|
||||
try {
|
||||
int year = Integer.parseInt(s.substring(0, 4));
|
||||
int month = Integer.parseInt(s.substring(4, 6));
|
||||
@@ -379,11 +389,12 @@ public class NumericPrediction {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == null || obj.getClass() != getClass()) return false;
|
||||
Time o = (Time)obj;
|
||||
if (obj == null || obj.getClass() != getClass())
|
||||
return false;
|
||||
Time o = (Time) obj;
|
||||
return o.year == year && o.month == month && o.day == day;
|
||||
}
|
||||
|
||||
@@ -391,7 +402,7 @@ public class NumericPrediction {
|
||||
public int hashCode() {
|
||||
return year << 16 | month << 8 | day;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int compareTo(Time o) {
|
||||
int c = Integer.compare(o.year, year);
|
||||
@@ -403,24 +414,24 @@ public class NumericPrediction {
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%04d%02d%02d", year, month, day);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The logger to generate debug output.
|
||||
*/
|
||||
protected Logger log = Logger.getLogger(getClass().getName());
|
||||
|
||||
|
||||
/**
|
||||
* The local folder that contains the data.
|
||||
*/
|
||||
protected File localFolder;
|
||||
|
||||
|
||||
/**
|
||||
* The variables that are synchronized.
|
||||
*/
|
||||
@@ -429,120 +440,147 @@ public class NumericPrediction {
|
||||
* The prediction.
|
||||
*/
|
||||
protected PredictionType type;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a numerical prediction from the specified prediction model.
|
||||
*
|
||||
* @param type The prediction model.
|
||||
* @param localFolder The local folder.
|
||||
*
|
||||
* @param type
|
||||
* The prediction model.
|
||||
* @param localFolder
|
||||
* The local folder.
|
||||
*/
|
||||
public NumericPrediction(PredictionType type, File localFolder) {
|
||||
this.type = type;
|
||||
this.localFolder = localFolder;
|
||||
variables = new Variable[] {
|
||||
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
|
||||
};
|
||||
|
||||
variables = new Variable[] { 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,
|
||||
type.getSystem().isComputed() ? Variable.RLAT : Variable.CLAT,
|
||||
type.getSystem().isComputed() ? Variable.RLON : Variable.CLON };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the prediction.
|
||||
*
|
||||
*
|
||||
* @return The prediction.
|
||||
*/
|
||||
public PredictionType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the local folder.
|
||||
*
|
||||
*
|
||||
* @return The local folder.
|
||||
*/
|
||||
public File getLocalFolder() {
|
||||
return localFolder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the variables.
|
||||
*
|
||||
*
|
||||
* @return The variables.
|
||||
*/
|
||||
public Variable[] getVariables() {
|
||||
return variables;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the longitudes.
|
||||
*
|
||||
* @param time The time.
|
||||
*
|
||||
* @param time
|
||||
* The time.
|
||||
* @return The double array with the longitudes.
|
||||
* @throws IOException Thrown if something fails.
|
||||
* @throws IOException
|
||||
* Thrown if something fails.
|
||||
*/
|
||||
public DoubleArray getLongitues(Time time) throws IOException {
|
||||
if (type.getSystem().isComputed()) {
|
||||
Grib2File file = new Grib2File(createStream(getFile(Variable.RLON, time)));
|
||||
try {
|
||||
switch (type.getSystem()) {
|
||||
case REGULAR:
|
||||
RegularGridDecoder regular = new RegularGridDecoder(file.nextData().getGridSection());
|
||||
return regular.getLongitudes();
|
||||
case ROTATED:
|
||||
RotatedGridDecoder rotated = new RotatedGridDecoder(file.nextData().getGridSection());
|
||||
return rotated.getLongitudes();
|
||||
default:
|
||||
throw new IOException("Failed to decode unknown computed coordinate system.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read data.", e);
|
||||
} finally {
|
||||
file.close();
|
||||
Grib2File filterFile = new Grib2File(createStream(getFile(Variable.HSURF, time)));
|
||||
try {
|
||||
Grib2Data data = filterFile.nextData();
|
||||
BitmapInterpreter interpreter = new BitmapInterpreter(data.getBitmapSection(),
|
||||
data.getGridSection().getPointCount());
|
||||
DoubleArray result = null;
|
||||
if (type.getSystem().isComputed()) {
|
||||
Grib2File gridFile = new Grib2File(createStream(getFile(Variable.RLON, time)));
|
||||
try {
|
||||
switch (type.getSystem()) {
|
||||
case REGULAR:
|
||||
RegularGridDecoder regular = new RegularGridDecoder(gridFile.nextData().getGridSection());
|
||||
result = regular.getLongitudes();
|
||||
break;
|
||||
case ROTATED:
|
||||
RotatedGridDecoder rotated = new RotatedGridDecoder(gridFile.nextData().getGridSection());
|
||||
result = rotated.getLongitudes();
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Failed to decode unknown computed coordinate system.");
|
||||
}
|
||||
} finally {
|
||||
gridFile.close();
|
||||
}
|
||||
} else {
|
||||
result = getValues(getFile(Variable.CLON, time));
|
||||
}
|
||||
} else {
|
||||
return getValues(getFile(Variable.CLON, time));
|
||||
return interpreter.filter(result);
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read data.", e);
|
||||
} finally {
|
||||
filterFile.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the latitudes.
|
||||
*
|
||||
* @param time The time.
|
||||
*
|
||||
* @param time
|
||||
* The time.
|
||||
* @return The double array with the latitudes.
|
||||
* @throws IOException Thrown if something fails.
|
||||
* @throws IOException
|
||||
* Thrown if something fails.
|
||||
*/
|
||||
public DoubleArray getLatitudes(Time time) throws IOException {
|
||||
if (type.getSystem().isComputed()) {
|
||||
Grib2File file = new Grib2File(createStream(getFile(Variable.RLAT, time)));
|
||||
try {
|
||||
switch (type.getSystem()) {
|
||||
case REGULAR:
|
||||
RegularGridDecoder regular = new RegularGridDecoder(file.nextData().getGridSection());
|
||||
return regular.getLatitudes();
|
||||
case ROTATED:
|
||||
RotatedGridDecoder rotated = new RotatedGridDecoder(file.nextData().getGridSection());
|
||||
return rotated.getLatitudes();
|
||||
default:
|
||||
throw new IOException("Failed to decode unknown computed coordinate system.");
|
||||
Grib2File filterFile = new Grib2File(createStream(getFile(Variable.HSURF, time)));
|
||||
try {
|
||||
Grib2Data data = filterFile.nextData();
|
||||
BitmapInterpreter interpreter = new BitmapInterpreter(data.getBitmapSection(),
|
||||
data.getGridSection().getPointCount());
|
||||
DoubleArray result = null;
|
||||
if (type.getSystem().isComputed()) {
|
||||
Grib2File gridFile = new Grib2File(createStream(getFile(Variable.RLAT, time)));
|
||||
try {
|
||||
switch (type.getSystem()) {
|
||||
case REGULAR:
|
||||
RegularGridDecoder regular = new RegularGridDecoder(gridFile.nextData().getGridSection());
|
||||
result = regular.getLatitudes();
|
||||
break;
|
||||
case ROTATED:
|
||||
RotatedGridDecoder rotated = new RotatedGridDecoder(gridFile.nextData().getGridSection());
|
||||
result = rotated.getLatitudes();
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Failed to decode unknown computed coordinate system.");
|
||||
}
|
||||
} finally {
|
||||
gridFile.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read data.", e);
|
||||
} finally {
|
||||
file.close();
|
||||
} else {
|
||||
result = getValues(getFile(Variable.CLAT, time));
|
||||
}
|
||||
} else {
|
||||
return getValues(getFile(Variable.CLAT, time));
|
||||
return interpreter.filter(result);
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read data.", e);
|
||||
} finally {
|
||||
filterFile.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a list of files that is available locally for a particular
|
||||
* variable.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* Returns a list of files that is available locally for a particular variable.
|
||||
*
|
||||
* @param variable
|
||||
* The variable.
|
||||
* @return The list of files.
|
||||
*/
|
||||
public List<File> getFiles(Variable variable) {
|
||||
@@ -550,7 +588,7 @@ public class NumericPrediction {
|
||||
File[] files = folder.listFiles();
|
||||
List<File> result = new ArrayList<File>();
|
||||
if (files != null) {
|
||||
for (File f: files) {
|
||||
for (File f : files) {
|
||||
if (f.isFile() && f.getName().endsWith(GRIB_EXTENSION)) {
|
||||
result.add(f);
|
||||
}
|
||||
@@ -559,71 +597,80 @@ public class NumericPrediction {
|
||||
result.sort(new FileNameComparator());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the files that are available for a particular variable
|
||||
* at a particular time.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* Returns the files that are available for a particular variable at a
|
||||
* particular time.
|
||||
*
|
||||
* @param variable
|
||||
* The variable.
|
||||
* @param time
|
||||
* The time.
|
||||
* @return The list of files.
|
||||
*/
|
||||
public List<File> getFiles(Variable variable, Time time) {
|
||||
List<File> data = getFiles(variable);
|
||||
List<File> result = new ArrayList<>();
|
||||
for (File f: data) {
|
||||
for (File f : data) {
|
||||
if (f.getName().contains("_" + time)) {
|
||||
result.add(f);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the first file for the variable and time
|
||||
* or null, if the file is not available.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time
|
||||
* Returns the first file for the variable and time or null, if the file is not
|
||||
* available.
|
||||
*
|
||||
* @param variable
|
||||
* The variable.
|
||||
* @param time
|
||||
* The time
|
||||
* @return The first file or null, if there is no such file.
|
||||
*/
|
||||
public File getFile(Variable variable, Time time) {
|
||||
List<File> data = getFiles(variable, time);
|
||||
if (data.size() > 0) return data.get(0);
|
||||
if (data.size() > 0)
|
||||
return data.get(0);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file that represents the specified hour on
|
||||
* the specified day or null, if the file does not exist.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @param hour The hour to search.
|
||||
* Returns the file that represents the specified hour on the specified day or
|
||||
* null, if the file does not exist.
|
||||
*
|
||||
* @param variable
|
||||
* The variable.
|
||||
* @param time
|
||||
* The time.
|
||||
* @param hour
|
||||
* The hour to search.
|
||||
* @return The file or null.
|
||||
*/
|
||||
public File getFile(Variable variable, Time time, int hour) {
|
||||
List<File> data = getFiles(variable, time);
|
||||
String search = String.format("_%03d_", hour);
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
if (data.get(i).getName().contains(search)) return data.get(i);
|
||||
if (data.get(i).getName().contains(search))
|
||||
return data.get(i);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether the data for a particular time is completely
|
||||
* available.
|
||||
*
|
||||
* @param time The time stamp.
|
||||
* Determines whether the data for a particular time is completely available.
|
||||
*
|
||||
* @param time
|
||||
* The time stamp.
|
||||
* @return True if all expected files are available. False otherwise.
|
||||
*/
|
||||
public boolean isAvailable(Time time) {
|
||||
boolean success = true;
|
||||
for (Variable v: variables) {
|
||||
for (Variable v : variables) {
|
||||
int count = getFiles(v, time).size();
|
||||
int expected = v.isInvariant()?1:(type.getFiles() - 1); // we exclude hour 0 since it is not available for cosmo ww
|
||||
int expected = v.isInvariant() ? 1 : (type.getFiles() - 1); // we exclude hour 0 since it is not available
|
||||
// for cosmo ww
|
||||
if (count != expected) {
|
||||
// do not return immediately to generate full debug log of variable mismatches
|
||||
log.log(Level.INFO, "Variable mismatch in " + v + ", expected " + expected + " was " + count + ".");
|
||||
@@ -631,65 +678,73 @@ public class NumericPrediction {
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a remote synchronization.
|
||||
*
|
||||
* @param listener An optional listener to keep track of changes.
|
||||
*
|
||||
* @param listener
|
||||
* An optional listener to keep track of changes.
|
||||
*/
|
||||
public void synchronize(FileStatusListener listener) {
|
||||
log.log(Level.INFO, "Synchronizing " + type.getServer() + type.getFolder() + " to " + localFolder.getAbsolutePath() + ".");
|
||||
for (Variable v: variables) {
|
||||
log.log(Level.INFO,
|
||||
"Synchronizing " + type.getServer() + type.getFolder() + " to " + localFolder.getAbsolutePath() + ".");
|
||||
for (Variable v : variables) {
|
||||
log.log(Level.INFO, "Synchronizing files for variable " + v.name());
|
||||
String f = v.getFolder();
|
||||
Predicate<File> fileFilter = new Predicate<File>() {
|
||||
@Override
|
||||
public boolean test(File t) {
|
||||
String substring = type.getSystem().getFilter();
|
||||
return (t.exists() || t.getName().contains(substring)) && getHour(t.getName()) != 0 && t.getName().endsWith(GRIB_EXTENSION);
|
||||
return (t.exists() || t.getName().contains(substring))
|
||||
&& (getHour(t.getName()) != 0 || v.isInvariant()) && t.getName().endsWith(GRIB_EXTENSION);
|
||||
}
|
||||
};
|
||||
FtpFolderSync sync = new FtpFolderSync(new File(localFolder, f), type.getServer(), type.getFolder() + f + "/", fileFilter);
|
||||
};
|
||||
FtpFolderSync sync = new FtpFolderSync(new File(localFolder, f), type.getServer(),
|
||||
type.getFolder() + f + "/", fileFilter);
|
||||
sync.setStatusListener(new FileStatusListener() {
|
||||
@Override
|
||||
public void onFileStatusChanged(FtpFolderSync source, FileStatus status) {
|
||||
log.log(Level.FINE, status.getAction().name() + ": " + status.getFile().getName());
|
||||
if (listener != null) listener.onFileStatusChanged(source, status);
|
||||
log.log(Level.INFO, status.getAction().name() + ": " + status.getFile().getName());
|
||||
if (listener != null)
|
||||
listener.onFileStatusChanged(source, status);
|
||||
}
|
||||
});
|
||||
try {
|
||||
sync.synchronize();
|
||||
} catch (IOException e) {
|
||||
log.log(Level.WARNING, "File synchronization failed for "+ v.name() + ".");
|
||||
log.log(Level.WARNING, "File synchronization failed for " + v.name() + ".");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Extracts the forecast hour from the file.
|
||||
*
|
||||
* @param input The input file.
|
||||
*
|
||||
* @param input
|
||||
* The input file.
|
||||
* @return The forecast hour.
|
||||
* @throws IOException Thrown if the file cannot be read.
|
||||
* @throws IOException
|
||||
* Thrown if the file cannot be read.
|
||||
*/
|
||||
public int getForecastHour(File input) throws IOException {
|
||||
Grib2File file = new Grib2File(createStream(input));
|
||||
try {
|
||||
Grib2Data data = file.nextData();
|
||||
ForecastProduct product = (ForecastProduct)data.getProductSection().getTemplate();
|
||||
ForecastProduct product = (ForecastProduct) data.getProductSection().getTemplate();
|
||||
return product.time / 60;
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to extract forecast hour.", e);
|
||||
} finally {
|
||||
file.close();
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Extracts the hour from the file name.
|
||||
*
|
||||
* @param filename The file name.
|
||||
*
|
||||
* @param filename
|
||||
* The file name.
|
||||
* @return The hour.
|
||||
*/
|
||||
public static int getHour(String filename) {
|
||||
@@ -705,43 +760,47 @@ public class NumericPrediction {
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads the values of the first data section of the file into a double array.
|
||||
*
|
||||
* @param input The input.
|
||||
*
|
||||
* @param input
|
||||
* The input.
|
||||
* @return The values of the first data section.
|
||||
* @throws IOException Thrown if the data cannot be loaded.
|
||||
* @throws IOException
|
||||
* Thrown if the data cannot be loaded.
|
||||
*/
|
||||
public DoubleArray getValues(File input) throws IOException {
|
||||
Grib2File file = new Grib2File(createStream(input));
|
||||
try {
|
||||
Grib2Data data = file.nextData();
|
||||
SimpleDataDecoder decoder = new SimpleDataDecoder(data);
|
||||
DoubleArray result = new DoubleArray((int)data.getGridSection().getPointCount());
|
||||
int s = (int)data.getGridSection().getPointCount();
|
||||
for (int i = 0; i < s; i++) {
|
||||
result.setValue(i, decoder.readNext());
|
||||
DoubleArray result = new DoubleArray((int) decoder.getPoints());
|
||||
int current = 0;
|
||||
for (int i = 0, s = (int) decoder.getSize(); i < s; i++) {
|
||||
boolean valid = decoder.hasNext();
|
||||
double value = decoder.readNext();
|
||||
if (valid)
|
||||
result.setValue(current++, value);
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read data.", e);
|
||||
} finally {
|
||||
file.close();
|
||||
file.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates an input stream from a bzip2 compressed file.
|
||||
*
|
||||
* @param input The input file.
|
||||
*
|
||||
* @param input
|
||||
* The input file.
|
||||
* @return The stream to the file data.
|
||||
* @throws IOException Thrown if the stream cannot be created.
|
||||
* @throws IOException
|
||||
* Thrown if the stream cannot be created.
|
||||
*/
|
||||
public InputStream createStream(File input) throws IOException {
|
||||
return new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(input)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -12,73 +12,74 @@ import com.mowesta.data.dwd.render.PrecipitationVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.PressureVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.TemperatureVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.VideoFrameComposer;
|
||||
import com.mowesta.data.dwd.render.WindVideoRenderer;
|
||||
import com.mowesta.data.process.video.VideoEncoder.Quality;
|
||||
|
||||
/**
|
||||
* A generator for videos.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class VideoGenerator {
|
||||
|
||||
|
||||
/**
|
||||
* A progress monitor that enables a called to
|
||||
* observe and abort the encoding process.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IProgressMonitor {
|
||||
|
||||
|
||||
/**
|
||||
* Called when a frame has been processed.
|
||||
*
|
||||
*
|
||||
* @param keyFrames The number of key frames.
|
||||
* @param interpolatedFrames The number of interpolated frames.
|
||||
* @return True to cancel, false to continue.
|
||||
*/
|
||||
boolean onFrameProcessed(int keyFrames, int interpolatedFrames);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A null progress monitor that keeps on going until we are done.
|
||||
*/
|
||||
private static final IProgressMonitor MONITOR_NULL = (k, i) -> { return false; };
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The weather prediction.
|
||||
*/
|
||||
protected NumericPrediction prediction;
|
||||
|
||||
|
||||
/**
|
||||
* The frame composer.
|
||||
*/
|
||||
protected VideoFrameComposer composer;
|
||||
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
protected Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
|
||||
/**
|
||||
* The video encoder quality.
|
||||
*/
|
||||
protected Quality quality = Quality.MEDIUM;
|
||||
|
||||
|
||||
/**
|
||||
* The video encoder crf value between 0 (lossless) and 51 (compressed).
|
||||
*/
|
||||
protected int crf = 24;
|
||||
protected int crf = 30;
|
||||
|
||||
/**
|
||||
* The frames per second.
|
||||
*/
|
||||
protected int fps = 30;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new video generator.
|
||||
*
|
||||
*
|
||||
* @param prediction The prediction.
|
||||
* @param composer The composer for frames.
|
||||
*/
|
||||
@@ -86,26 +87,26 @@ public class VideoGenerator {
|
||||
this.prediction = prediction;
|
||||
this.composer = composer;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the prediction.
|
||||
*
|
||||
*
|
||||
* @return The prediction.
|
||||
*/
|
||||
public NumericPrediction getPrediction() {
|
||||
return prediction;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the frame composer.
|
||||
*
|
||||
*
|
||||
* @return The frame composer.
|
||||
*/
|
||||
public VideoFrameComposer getComposer() {
|
||||
return composer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the quality.
|
||||
*
|
||||
@@ -159,23 +160,23 @@ public class VideoGenerator {
|
||||
public void setFps(int fps) {
|
||||
this.fps = fps;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the video types.
|
||||
*
|
||||
*
|
||||
* @return The video types.
|
||||
*/
|
||||
public Variable[] getVariables() {
|
||||
return new Variable[] {
|
||||
Variable.CLCT, Variable.PREC, Variable.T2M, Variable.PMSL
|
||||
Variable.CLCT, Variable.PREC, Variable.T2M, Variable.PMSL, Variable.U10M
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates a video and stores it in the destination video file together with
|
||||
* an image icon.
|
||||
*
|
||||
*
|
||||
* @param video The destination for the video file.
|
||||
* @param preview The destination for the video preview.
|
||||
* @param variable The variable.
|
||||
@@ -183,7 +184,7 @@ public class VideoGenerator {
|
||||
* @param first The first hour.
|
||||
* @param last The last hour.
|
||||
* @param monitor The progress monitor.
|
||||
*
|
||||
*
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public void createVideo(Variable variable, Time time, int first, int last, File video, File preview, IProgressMonitor monitor) throws IOException {
|
||||
@@ -202,13 +203,16 @@ public class VideoGenerator {
|
||||
case PREC:
|
||||
renderer = new PrecipitationVideoRenderer(this, time);
|
||||
break;
|
||||
case U10M:
|
||||
renderer = new WindVideoRenderer(this, time);
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Unsupported video type " + variable + ".");
|
||||
}
|
||||
renderer.renderPreview(preview, first);
|
||||
renderer.renderVideo(video, first, last, m);
|
||||
}
|
||||
|
||||
|
||||
private double getIsobars() {
|
||||
switch (prediction.getType()) {
|
||||
case COSMO_EUROPE:
|
||||
@@ -217,12 +221,12 @@ public class VideoGenerator {
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private double getIsotherms() {
|
||||
switch (prediction.getType()) {
|
||||
default:
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+16
-16
@@ -14,7 +14,7 @@ import com.mowesta.data.process.video.VideoFrame;
|
||||
|
||||
/**
|
||||
* A video render that operates on data interpolation.
|
||||
*
|
||||
*
|
||||
* @param <T> The state of the renderer.
|
||||
* @author Marcus
|
||||
*/
|
||||
@@ -22,14 +22,14 @@ public abstract class AbstractDataVideoRenderer<T extends RendererState> extends
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable to load.
|
||||
* @param variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractDataVideoRenderer(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
super(generator, variable, time);
|
||||
public AbstractDataVideoRenderer(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
super(generator, variables, time);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -53,29 +53,29 @@ public abstract class AbstractDataVideoRenderer<T extends RendererState> extends
|
||||
renderDataImage(keyImage, i, i + 1, j/(double)fps, state);
|
||||
renderFrame(frame, keyImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, keyFrame);
|
||||
encoder.addFrame(keyFrame);
|
||||
encoder.addFrame(keyFrame);
|
||||
}
|
||||
}
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
encoder.finish(video);
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the initial rendering state.
|
||||
*
|
||||
*
|
||||
* @return The initial rendering state.
|
||||
*/
|
||||
protected abstract T createState();
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders The data image at the faction between start and end.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param start The start time.
|
||||
* @param end The end time.
|
||||
@@ -84,13 +84,13 @@ public abstract class AbstractDataVideoRenderer<T extends RendererState> extends
|
||||
* @throws IOException Thrown if the image cannot be rendered.
|
||||
*/
|
||||
protected abstract void renderDataImage(BufferedImage image, int start, int end, double fraction, T state) throws IOException;
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
T state = createState();
|
||||
renderDataImage(image, hour, hour + 1, 0, state);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
+21
-20
@@ -6,18 +6,18 @@ import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.dwd.VideoGenerator.IProgressMonitor;
|
||||
import com.mowesta.data.process.video.PixelFormat;
|
||||
import com.mowesta.data.process.video.VideoEncoder;
|
||||
import com.mowesta.data.process.video.VideoFrame;
|
||||
import com.mowesta.data.process.video.VideoInterpolator;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A video renderer that uses a video interpolator to interpolate between rendered
|
||||
* data Images. This enables us to use ffmpegs interpolators such as the motion
|
||||
* data Images. This enables us to use ffmpegs interpolators such as the motion
|
||||
* interpolator which works well for moving objects such as clouds or precipitation.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
@@ -26,31 +26,32 @@ public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
* The interpolation used for this video.
|
||||
*/
|
||||
private VideoInterpolator.Type interpolation;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new frame renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable.
|
||||
* @param variables The variables.
|
||||
* @param time The time.
|
||||
* @param interpolation The interpolation type.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractFrameVideoRenderer(VideoGenerator generator, Variable variable, Time time, VideoInterpolator.Type interpolation) throws IOException {
|
||||
super(generator, variable, time);
|
||||
public AbstractFrameVideoRenderer(VideoGenerator generator, Variable[] variables, Time time, VideoInterpolator.Type interpolation) throws IOException {
|
||||
super(generator, variables, time);
|
||||
this.interpolation = interpolation;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the interpolation type of the renderer.
|
||||
*
|
||||
*
|
||||
* @return The interpolation type of the renderer.
|
||||
*/
|
||||
public VideoInterpolator.Type getInterpolation() {
|
||||
return interpolation;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void renderVideo(File video, int first, int last, IProgressMonitor monitor) throws IOException {
|
||||
// the frame that we need to compose and resize images
|
||||
BufferedImage frame = getComposer().createFrame(BufferedImage.TYPE_INT_ARGB);
|
||||
@@ -58,7 +59,7 @@ public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
BufferedImage keyImage = getComposer().createImage();
|
||||
byte[] keyFrame = VideoFrame.createBuffer(getRenderer().getWidth(), getRenderer().getHeight(), PixelFormat.ARGB);
|
||||
// the buffer for the interpolated frames
|
||||
BufferedImage interpolatedImage = getComposer().createImage();
|
||||
BufferedImage interpolatedImage = getComposer().createImage();
|
||||
byte[] interpolatedFrame = VideoFrame.createBuffer(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB);
|
||||
// key frame, interpolate frame
|
||||
RendererState state = new RendererState();
|
||||
@@ -78,34 +79,34 @@ public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
if (f < (fps + 1) && f > 0) {
|
||||
state.interpolationCount += 1;
|
||||
VideoFrame.decodeImage(PixelFormat.ARGB, data, interpolatedImage);
|
||||
renderFrame(frame, interpolatedImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, interpolatedFrame);
|
||||
encoder.addFrame(interpolatedFrame);
|
||||
renderFrame(frame, interpolatedImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, interpolatedFrame);
|
||||
encoder.addFrame(interpolatedFrame);
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to encode image.", e);
|
||||
}
|
||||
};
|
||||
};
|
||||
for (int i = first; i <= last; i++) {
|
||||
renderDataImage(keyImage, i);
|
||||
state.keyCount += 1;
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
VideoFrame.encodeImage(keyImage, PixelFormat.ARGB, keyFrame);
|
||||
interpolator.addFrame(i, keyFrame, handler);
|
||||
interpolator.addFrame(i, keyFrame, handler);
|
||||
}
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
VideoFrame.encodeImage(keyImage, PixelFormat.ARGB, keyFrame);
|
||||
interpolator.addFrame(last + 1, keyFrame, handler);
|
||||
interpolator.release();
|
||||
encoder.finish(video);
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
interpolator.release();
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
}
|
||||
}
|
||||
|
||||
+57
-33
@@ -12,48 +12,58 @@ import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A base class for renders that generate images from interpolated data.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
* @param <State> The data type to store the state.
|
||||
*/
|
||||
public abstract class AbstractLinearDataVideoRender extends AbstractDataVideoRenderer<LinearRendererState> {
|
||||
public abstract class AbstractLinearDataVideoRender<State extends LinearRendererState> extends AbstractDataVideoRenderer<State> {
|
||||
|
||||
/**
|
||||
* The interpolator.
|
||||
*/
|
||||
protected LinearInterpolation interpolation = new LinearInterpolation();
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable.
|
||||
* @param variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractLinearDataVideoRender(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
super(generator, variable, time);
|
||||
public AbstractLinearDataVideoRender(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
super(generator, variables, time);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LinearRendererState createState() {
|
||||
return new LinearRendererState();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int start, int end, double fraction, LinearRendererState state) throws IOException {
|
||||
DoubleArray s = state.cache.get(start);
|
||||
DoubleArray e = state.cache.get(end);
|
||||
/**
|
||||
* Computes the state by loading the start and end hour and performing the
|
||||
* interpolation by the specified fraction.
|
||||
*
|
||||
* @param start The start hour.
|
||||
* @param end The end hour.
|
||||
* @param fraction The fraction to interpolate.
|
||||
* @param state The state to update.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
protected void prepareState(int start, int end, double fraction, State state) throws IOException {
|
||||
DoubleArray[] s = state.cache.get(start);
|
||||
DoubleArray[] e = state.cache.get(end);
|
||||
state.cache.clear();
|
||||
if (fraction == 0 || fraction == 1) {
|
||||
int h = (fraction == 0) ? start : end;
|
||||
DoubleArray a = (fraction == 0) ? s : e;
|
||||
DoubleArray[] a = (fraction == 0) ? s : e;
|
||||
if (a == null) a = getData(h);
|
||||
state.cache.put(h, a);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray(a.getSize());
|
||||
state.data = new DoubleArray[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
state.data[i] = new DoubleArray(a[i].getSize());
|
||||
}
|
||||
}
|
||||
for (int i = 0, sz = a.getSize(); i < sz; i++) {
|
||||
state.data.setValue(i, a.getValue(i));
|
||||
for (int j = 0; j < a.length; j++) {
|
||||
for (int i = 0, sz = a[j].getSize(); i < sz; i++) {
|
||||
state.data[j].setValue(i, a[j].getValue(i));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (s == null) s = getData(start);
|
||||
@@ -61,36 +71,50 @@ public abstract class AbstractLinearDataVideoRender extends AbstractDataVideoRen
|
||||
if (e == null) e = getData(end);
|
||||
state.cache.put(end, e);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray(s.getSize());
|
||||
state.data = new DoubleArray[s.length];
|
||||
for (int i = 0; i < s.length; i++) {
|
||||
state.data[i] = new DoubleArray(s[i].getSize());
|
||||
}
|
||||
}
|
||||
for (int i = 0, sz = s.getSize(); i < sz; i++) {
|
||||
state.data.setValue(i, interpolation.interpolate(s.getValue(i), e.getValue(i), fraction));
|
||||
for (int j = 0; j < s.length; j++) {
|
||||
for (int i = 0, sz = s[j].getSize(); i < sz; i++) {
|
||||
state.data[j].setValue(i, interpolation.interpolate(s[j].getValue(i), e[j].getValue(i), fraction));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int start, int end, double fraction, State state) throws IOException {
|
||||
prepareState(start, end, fraction, state);
|
||||
renderDataImage(image, state);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the image from the current state.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param state The state.
|
||||
* @throws IOException Thrown if the rendering fails.
|
||||
*/
|
||||
public abstract void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException;
|
||||
|
||||
|
||||
public abstract void renderDataImage(BufferedImage image, State state) throws IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Loads the data for the hour.
|
||||
*
|
||||
*
|
||||
* @param hour The hour.
|
||||
* @return The data.
|
||||
* @throws IOException Thrown if the data is not available.
|
||||
*/
|
||||
protected DoubleArray getData(int hour) throws IOException {
|
||||
File file = getPrediction().getFile(variable, time, hour);
|
||||
if (file == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
return getPrediction().getValues(file);
|
||||
protected DoubleArray[] getData(int hour) throws IOException {
|
||||
DoubleArray[] result = new DoubleArray[variables.length];
|
||||
for (int i = 0; i < variables.length; i++) {
|
||||
File file = getPrediction().getFile(variables[i], time, hour);
|
||||
if (file == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
result[i] = getPrediction().getValues(file);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,19 +8,19 @@ import java.io.IOException;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.dwd.VideoGenerator.IProgressMonitor;
|
||||
|
||||
/**
|
||||
* An abstract base class for video rendering that manages details such
|
||||
* as the generation of preview frames.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractVideoRenderer {
|
||||
|
||||
|
||||
/**
|
||||
* The video generator that created the renderer.
|
||||
*/
|
||||
@@ -28,81 +28,81 @@ public abstract class AbstractVideoRenderer {
|
||||
/**
|
||||
* The variable that we want to render.
|
||||
*/
|
||||
protected Variable variable;
|
||||
|
||||
protected Variable[] variables;
|
||||
|
||||
/**
|
||||
* The time that we render.
|
||||
*/
|
||||
protected Time time;
|
||||
|
||||
|
||||
/**
|
||||
* A static image underneath the data.
|
||||
*/
|
||||
protected BufferedImage baseImage;
|
||||
|
||||
|
||||
/**
|
||||
* A static image on top of the data.
|
||||
*/
|
||||
protected BufferedImage overlayImage;
|
||||
|
||||
|
||||
/**
|
||||
* A temporary image to support multi-step rendering.
|
||||
*/
|
||||
protected BufferedImage tempImage;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a renderer for the specified variable and time.
|
||||
*
|
||||
*
|
||||
* @param generator The video generator with the data and video settings.
|
||||
* @param variable The variable.
|
||||
* @param variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractVideoRenderer(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
public AbstractVideoRenderer(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
this.generator = generator;
|
||||
this.variable = variable;
|
||||
this.variables = variables;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the video generator that created the renderer.
|
||||
*
|
||||
*
|
||||
* @return The video generator.
|
||||
*/
|
||||
public VideoGenerator getGenerator() {
|
||||
return generator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the frame composer of the video generator.
|
||||
*
|
||||
*
|
||||
* @return The frame composer of the video generator.
|
||||
*/
|
||||
protected VideoFrameComposer getComposer() {
|
||||
return getGenerator().getComposer();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the image renderer of the video generator.
|
||||
*
|
||||
*
|
||||
* @return The image renderer.
|
||||
*/
|
||||
protected VideoImageRenderer getRenderer() {
|
||||
return getComposer().getGenerator();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the numeric prediction of the video generator.
|
||||
*
|
||||
*
|
||||
* @return The numeric prediction.
|
||||
*/
|
||||
protected NumericPrediction getPrediction() {
|
||||
return generator.getPrediction();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a cleared version of the temporary image.
|
||||
*
|
||||
*
|
||||
* @return A cleared version of the temporary image.
|
||||
*/
|
||||
protected BufferedImage getTempImage() {
|
||||
@@ -112,10 +112,10 @@ public abstract class AbstractVideoRenderer {
|
||||
getComposer().clearImage(tempImage);
|
||||
return tempImage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the base image.
|
||||
*
|
||||
*
|
||||
* @return The base image.
|
||||
* @throws IOException Thrown if the base image cannot be created.
|
||||
*/
|
||||
@@ -127,14 +127,14 @@ public abstract class AbstractVideoRenderer {
|
||||
getComposer().getGenerator().renderPlantCover(temp, getPrediction().getValues(getPrediction().getFile(Variable.PLCOV, time)));
|
||||
getComposer().renderImage(baseImage, temp);
|
||||
getComposer().getGenerator().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(baseImage, temp);
|
||||
getComposer().renderImage(baseImage, temp);
|
||||
}
|
||||
return baseImage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the overlay image.
|
||||
*
|
||||
*
|
||||
* @return The overlay image.
|
||||
* @throws IOException Thrown if the overlay image cannot be created.
|
||||
*/
|
||||
@@ -145,11 +145,11 @@ public abstract class AbstractVideoRenderer {
|
||||
}
|
||||
return overlayImage;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders the video from the first to the last hour.
|
||||
*
|
||||
*
|
||||
* @param video The video.
|
||||
* @param first The first hour.
|
||||
* @param last The last hour.
|
||||
@@ -158,20 +158,20 @@ public abstract class AbstractVideoRenderer {
|
||||
*/
|
||||
public abstract void renderVideo(File video, int first, int last, IProgressMonitor monitor) throws IOException;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders the data image for the specified hour.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected abstract void renderDataImage(BufferedImage image, int hour) throws IOException;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders a preview file from the data at the specified hour.
|
||||
*
|
||||
*
|
||||
* @param file The preview file.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
@@ -184,10 +184,10 @@ public abstract class AbstractVideoRenderer {
|
||||
renderFrame(output, data);
|
||||
ImageIO.write(output, format, file);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Tries to guess the preview format from the file name.
|
||||
*
|
||||
*
|
||||
* @param file The file.
|
||||
* @return The preview format.
|
||||
*/
|
||||
@@ -200,11 +200,11 @@ public abstract class AbstractVideoRenderer {
|
||||
return "jpeg";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the image stack consisting of the base layer, the specified data layer and
|
||||
* the overlay layer onto the destination image.
|
||||
*
|
||||
*
|
||||
* @param image The destination image.
|
||||
* @param dataImage The data image.
|
||||
* @throws IOException Thrown if something fails.
|
||||
@@ -217,10 +217,10 @@ public abstract class AbstractVideoRenderer {
|
||||
if (over != null) getComposer().renderImage(image, over);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the specified data image as a frame.
|
||||
*
|
||||
*
|
||||
* @param frame The frame to render to.
|
||||
* @param dataImage The data image.
|
||||
* @throws IOException thrown if something fails.
|
||||
@@ -230,6 +230,6 @@ public abstract class AbstractVideoRenderer {
|
||||
renderImage(temp, dataImage);
|
||||
getComposer().renderFrame(frame, temp);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -13,32 +13,32 @@ import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
/**
|
||||
* A video renderer for the cloud coverage that renders data images
|
||||
* from the cloud coverage and if available, cloud depth.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CloudVideoRenderer extends AbstractFrameVideoRenderer {
|
||||
|
||||
/**
|
||||
* Creates a new video renderer for the specified time.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public CloudVideoRenderer(VideoGenerator generator, Time time) throws IOException {
|
||||
super(generator, Variable.CLCT, time, Type.MOTION);
|
||||
super(generator, new Variable[] {Variable.CLCT, Variable.CLDEPTH }, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
File file = getPrediction().getFile(variable, time, hour);
|
||||
File file = getPrediction().getFile(Variable.CLCT, time, hour);
|
||||
if (file == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
DoubleArray data = getPrediction().getValues(file);
|
||||
file = getPrediction().getFile(Variable.CLDEPTH, time, hour);
|
||||
if (file != null) {
|
||||
getRenderer().renderCloudCoverage3D(image, data, getPrediction().getValues(file));
|
||||
} else {
|
||||
getRenderer().renderCloudCoverage(image, data);
|
||||
getRenderer().renderCloudCoverage(image, data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.mowesta.data.process.util.DoubleArray;
|
||||
/**
|
||||
* The renderer state of the data renderer that performs
|
||||
* a simple linear interpolation on the data.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LinearRendererState extends RendererState {
|
||||
@@ -16,10 +16,10 @@ public class LinearRendererState extends RendererState {
|
||||
/**
|
||||
* The loaded data hashed by hour.
|
||||
*/
|
||||
Map<Integer, DoubleArray> cache = new HashMap<>();
|
||||
|
||||
Map<Integer, DoubleArray[]> cache = new HashMap<>();
|
||||
|
||||
/** The double array with the interpolated data. */
|
||||
DoubleArray data;
|
||||
|
||||
|
||||
DoubleArray[] data;
|
||||
|
||||
|
||||
}
|
||||
|
||||
+8
-8
@@ -12,33 +12,33 @@ import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
|
||||
/**
|
||||
* A video renderer for precipitation videos.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PrecipitationVideoRenderer extends AbstractFrameVideoRenderer {
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new video renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public PrecipitationVideoRenderer(VideoGenerator generator, Time time) throws IOException {
|
||||
super(generator, Variable.PREC, time, Type.MOTION);
|
||||
super(generator, new Variable[] { Variable.PREC }, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
File f1 = getPrediction().getFile(variable, time, hour);
|
||||
File f2 = getPrediction().getFile(variable, time, hour + 1);
|
||||
File f1 = getPrediction().getFile(Variable.PREC, time, hour);
|
||||
File f2 = getPrediction().getFile(Variable.PREC, time, hour + 1);
|
||||
if (f1 == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
if (f2 == null) throw new IOException(String.format("No file for hour %d.", hour + 1));
|
||||
DoubleArray data = getPrediction().getValues(f2);
|
||||
DoubleArray base = getPrediction().getValues(f1);
|
||||
for (int i = 0, s = data.getSize(); i < s; i++) {
|
||||
data.setValue(i, data.getValue(i) - base.getValue(i));
|
||||
data.setValue(i, data.getValue(i) - base.getValue(i));
|
||||
}
|
||||
getRenderer().renderPrecipitation(image, data);
|
||||
}
|
||||
|
||||
@@ -8,23 +8,23 @@ import java.util.List;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.algorithm.GaussianBlur;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A video renderer for pressure videos.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
|
||||
public class PressureVideoRenderer extends AbstractLinearDataVideoRender<LinearRendererState> {
|
||||
|
||||
/**
|
||||
* The surface height image.
|
||||
*/
|
||||
protected BufferedImage surfaceImage;
|
||||
|
||||
|
||||
/**
|
||||
* The distance of the iso lines.
|
||||
*/
|
||||
@@ -34,7 +34,7 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
* A filter to apply a Gaussian blur.
|
||||
*/
|
||||
protected GaussianBlur blur = new GaussianBlur(2);
|
||||
|
||||
|
||||
/**
|
||||
* The filtered image.
|
||||
*/
|
||||
@@ -47,20 +47,25 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
|
||||
/**
|
||||
* Creates a new pressure video renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @param isoDistance The iso distance in pa (= hpa * 100).
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public PressureVideoRenderer(VideoGenerator generator, Time time, double isoDistance) throws IOException {
|
||||
super(generator, Variable.PMSL, time);
|
||||
super(generator, new Variable[] { Variable.PMSL }, time);
|
||||
this.isoDistance = isoDistance;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected LinearRendererState createState() {
|
||||
return new LinearRendererState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage() {
|
||||
@@ -72,7 +77,7 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage2() {
|
||||
@@ -81,10 +86,10 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
}
|
||||
return filterImage2;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
*
|
||||
* @return The surface height image.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
@@ -100,14 +105,14 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
getRenderer().renderPressure(image, state.data);
|
||||
getRenderer().renderPressure(image, state.data[0]);
|
||||
getComposer().renderImage(image, getSurfaceImage());
|
||||
if (isoDistance != 0) {
|
||||
// find the perimeters for the iso lines
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data);
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data[0]);
|
||||
IntArray converted = getRenderer().getIntValues(projected, (v) -> (int)((v - 100000) / isoDistance));
|
||||
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
@@ -123,23 +128,23 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, getFilterImage2(), temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
}
|
||||
getComposer().renderImage(image, filter);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
// don't render any overlay image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+21
-16
@@ -8,49 +8,54 @@ import java.util.List;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A renderer for temperature videos.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender<LinearRendererState> {
|
||||
|
||||
/**
|
||||
* The surface height image.
|
||||
*/
|
||||
protected BufferedImage surfaceImage;
|
||||
|
||||
|
||||
/**
|
||||
* The image with the borders.
|
||||
*/
|
||||
protected BufferedImage borderImage;
|
||||
|
||||
|
||||
/**
|
||||
* The distance of the isotherms in degree celsius.
|
||||
*/
|
||||
protected double isoDistance;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new video renderer.
|
||||
*
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @param isoDistance The iso distance in degree centigrade, set to 0 to not draw anything.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public TemperatureVideoRenderer(VideoGenerator generator, Time time, double isoDistance) throws IOException {
|
||||
super(generator, Variable.T2M, time);
|
||||
super(generator, new Variable[] { Variable.T2M }, time);
|
||||
this.isoDistance = isoDistance;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected LinearRendererState createState() {
|
||||
return new LinearRendererState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
*
|
||||
* @return The surface height image.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
@@ -66,13 +71,13 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
getRenderer().renderTemperature(image, state.data);
|
||||
getRenderer().renderTemperature(image, state.data[0]);
|
||||
getComposer().renderImage(image, getSurfaceImage());
|
||||
if (isoDistance != 0) {
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data);
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data[0]);
|
||||
IntArray converted = getRenderer().getIntValues(projected, (v) -> (int)((v - KelvinCelsiusConversion.ZERO) / isoDistance));
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
List<List<int[]>> result = new ArrayList<>(ps.size());
|
||||
@@ -94,19 +99,19 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
getComposer().renderImage(image, temp);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
// don't render any overlay image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.algorithm.MarchingSquares;
|
||||
import com.mowesta.data.process.color.BeaufortWindScaleScheme;
|
||||
import com.mowesta.data.process.color.CloudDepthColorScheme;
|
||||
import com.mowesta.data.process.color.IColorScheme;
|
||||
import com.mowesta.data.process.color.PlantCoverColorScheme;
|
||||
@@ -28,32 +29,32 @@ import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
/**
|
||||
* A utility class to render videos from DWD data. This class is responsible for rendering the data at a
|
||||
* (nearly) native resolution resulting from the contents of the grib files. The rescaling of images is
|
||||
* done using regular image functions in the frame composer. This way, we do not have to handle the
|
||||
* A utility class to render videos from DWD data. This class is responsible for rendering the data at a
|
||||
* (nearly) native resolution resulting from the contents of the grib files. The rescaling of images is
|
||||
* done using regular image functions in the frame composer. This way, we do not have to handle the
|
||||
* scaling of data at the rendering level. The drawback is an increased rendering time, however, cropping
|
||||
* can be done by adjusting the projection.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class VideoImageRenderer {
|
||||
|
||||
|
||||
/**
|
||||
* An interface used to convert a double value to
|
||||
* An interface used to convert a double value to
|
||||
* an integer.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IntConverter {
|
||||
/**
|
||||
* Returns the integer after conversion.
|
||||
*
|
||||
*
|
||||
* @param value The value.
|
||||
* @return The integer.
|
||||
*/
|
||||
int convert(double value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The latitude values.
|
||||
@@ -91,7 +92,7 @@ public class VideoImageRenderer {
|
||||
/**
|
||||
* Creates a renderer for the specified coordinates and projection that
|
||||
* is capable of generating frames with the specified width and height.
|
||||
*
|
||||
*
|
||||
* @param longitudes The longitudes.
|
||||
* @param latitudes The latitudes.
|
||||
* @param projection The projection.
|
||||
@@ -107,28 +108,28 @@ public class VideoImageRenderer {
|
||||
this.imageProjection = new ImageProjection(projection, longitudes, latitudes, width, height);
|
||||
this.imageFiller = new ImageFiller(longitudes, latitudes, projection, width, height);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the width.
|
||||
*
|
||||
*
|
||||
* @return The width.
|
||||
*/
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the height.
|
||||
*
|
||||
*
|
||||
* @return The height.
|
||||
*/
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a reference to the image filler.
|
||||
*
|
||||
*
|
||||
* @return The image filler.
|
||||
*/
|
||||
public ImageFiller getImageFiller() {
|
||||
@@ -137,7 +138,7 @@ public class VideoImageRenderer {
|
||||
|
||||
/**
|
||||
* Returns a reference to the boundary renderer.
|
||||
*
|
||||
*
|
||||
* @return The boundary renderer.
|
||||
*/
|
||||
public BoundaryRenderer getBoundaryRenderer() {
|
||||
@@ -146,10 +147,19 @@ public class VideoImageRenderer {
|
||||
}
|
||||
return boundaryRenderer;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the image project of the renderer.
|
||||
*
|
||||
* @return The image projection of the renderer.
|
||||
*/
|
||||
public ImageProjection getImageProjection() {
|
||||
return imageProjection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders an image from the air pressure.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param pmsl The pressure levels.
|
||||
*/
|
||||
@@ -159,11 +169,11 @@ public class VideoImageRenderer {
|
||||
renderer.renderData(pmsl, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders the perimeters onto the image.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param perimeters The perimeters.
|
||||
* @param swidth The width to render the outlines.
|
||||
@@ -188,16 +198,16 @@ public class VideoImageRenderer {
|
||||
if (y2 == 0) y2 = -offset;
|
||||
if (y1 == this.height - 1) y1 = this.height + offset - 1;
|
||||
if (y2 == this.height - 1) y2 = this.height + offset - 1;
|
||||
g.drawLine(x1, y1, x2, y2);
|
||||
g.drawLine(x1, y1, x2, y2);
|
||||
}
|
||||
}
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the perimeters in the picture.
|
||||
*
|
||||
*
|
||||
* @param values The values of the picture.
|
||||
* @return The perimeters found in the picture.
|
||||
*/
|
||||
@@ -216,11 +226,11 @@ public class VideoImageRenderer {
|
||||
int ny = Math.min(height - 1, Math.max(0, y + j));
|
||||
if (cmp > values.getValue(ny * width + nx)) {
|
||||
MarchingSquares algo = new MarchingSquares(width, height, (a, b) -> {
|
||||
return values.getValue(b * width + a) == cmp;
|
||||
return values.getValue(b * width + a) == cmp;
|
||||
});
|
||||
List<int[]> perimeter = algo.findPerimenter(x, y);
|
||||
for (int[] v: perimeter) {
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
}
|
||||
perimeters.add(perimeter);
|
||||
break i;
|
||||
@@ -231,12 +241,12 @@ public class VideoImageRenderer {
|
||||
}
|
||||
return perimeters;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the soil type.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param soilType The soil type.
|
||||
*/
|
||||
@@ -246,10 +256,10 @@ public class VideoImageRenderer {
|
||||
renderer.renderData(soilType, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the temperature.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param t2m The temperature.
|
||||
*/
|
||||
@@ -260,10 +270,22 @@ public class VideoImageRenderer {
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image with the wind speed.
|
||||
*
|
||||
* @param image The image.
|
||||
* @param u10m The u component.
|
||||
* @param v10m The v component.
|
||||
*/
|
||||
public void renderWindSpeed(BufferedImage image, DoubleArray u10m, DoubleArray v10m) {
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new BeaufortWindScaleScheme());
|
||||
renderer.renderData((i) -> Math.sqrt(u10m.getValue(i) * u10m.getValue(i) + v10m.getValue(i) * v10m.getValue(i)), Math.min(u10m.getSize(), v10m.getSize()), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the precipitation onto the image.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param prec The previous precipitation.
|
||||
*/
|
||||
@@ -274,10 +296,10 @@ public class VideoImageRenderer {
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the plant coverage.
|
||||
*
|
||||
*
|
||||
* @param image The image to render to.
|
||||
* @param plcov The plant coverage.
|
||||
*/
|
||||
@@ -287,11 +309,11 @@ public class VideoImageRenderer {
|
||||
renderer.renderData(plcov, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the integrated surface height to generate a light effect with
|
||||
* the sunlight coming from the upper left corner.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param hsurf The surface height.
|
||||
*/
|
||||
@@ -302,7 +324,7 @@ public class VideoImageRenderer {
|
||||
/**
|
||||
* Renders a 3D effect by computing the difference between (x,y) and (x-1,y-1)
|
||||
* and then applying the color scheme to the difference.
|
||||
*
|
||||
*
|
||||
* @param image The image to render to.
|
||||
* @param values The values to render.
|
||||
* @param scheme The color scheme.
|
||||
@@ -322,11 +344,11 @@ public class VideoImageRenderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values and transforms them into an integer.
|
||||
*
|
||||
*
|
||||
* @param base The base values.
|
||||
* @param converter The converter.
|
||||
* @return The converted values.
|
||||
@@ -338,11 +360,11 @@ public class VideoImageRenderer {
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values.
|
||||
*
|
||||
*
|
||||
* @param base The base.
|
||||
* @return The projected values.
|
||||
*/
|
||||
@@ -352,16 +374,16 @@ public class VideoImageRenderer {
|
||||
if (imageProjection.isVisible(i)) {
|
||||
int x = imageProjection.getX(i);
|
||||
int y = imageProjection.getY(i);
|
||||
projected.setValue(y * width + x, base.getValue(i));
|
||||
projected.setValue(y * width + x, base.getValue(i));
|
||||
}
|
||||
}
|
||||
imageFiller.apply(projected);
|
||||
return projected;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the cloud coverage.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param clcm The cloud coverage.
|
||||
*/
|
||||
@@ -371,10 +393,10 @@ public class VideoImageRenderer {
|
||||
renderer.renderData(clcm, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the cloud coverage and the cloud depth to generate a 3d effect of clouds.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param clct The cloud coverage.
|
||||
* @param cldepth The cloud depth.
|
||||
@@ -391,17 +413,17 @@ public class VideoImageRenderer {
|
||||
int py = imageProjection.getY(i);
|
||||
int depth = depthScheme.getColor(cldepth.getValue(i));
|
||||
int cover = cloudScheme.getColor(clct.getValue(i));
|
||||
image.setRGB(px, py, (cover & 0xFF000000) | (depth & 0x00FFFFFF));
|
||||
image.setRGB(px, py, (cover & 0xFF000000) | (depth & 0x00FFFFFF));
|
||||
}
|
||||
}
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the boundaries.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param color The color to draw the boundaries.
|
||||
*/
|
||||
@@ -413,14 +435,14 @@ public class VideoImageRenderer {
|
||||
|
||||
/**
|
||||
* Clears the image with a transparent color.
|
||||
*
|
||||
*
|
||||
* @param image The image to clear.
|
||||
*/
|
||||
private void clearImage(BufferedImage image) {
|
||||
private void clearImage(BufferedImage image) {
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setBackground(new Color(0x00000000, true));
|
||||
g.clearRect(0, 0, image.getWidth(), image.getHeight());
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.projection.ReverseImageProjection;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A renderer for wind flow videos which is using a custom data type for the {@link AbstractLinearDataVideoRender}
|
||||
* and the underlying {@link LinearRendererState} due to the fact that the calculation of the wind flow prediction
|
||||
* depends on two {@link com.mowesta.data.dwd.NumericPrediction.Variable}s the U10M and the V10M.
|
||||
*
|
||||
* The U10M and V10M {@link DoubleArray}s are forming a vector grid which is representing the zonal
|
||||
* (U10M; East-to-West direction) and meridional (V10M; North-to-South direction) wind flow.
|
||||
*
|
||||
* @see <a href="https://www.dwd.de/DE/service/lexikon/Functions/glossar.html?lv2=102936&lv3=636284"></a>
|
||||
*
|
||||
* @author Adriano
|
||||
*/
|
||||
public class WindVideoRenderer extends AbstractLinearDataVideoRender<WindVideoState> {
|
||||
|
||||
/**
|
||||
* Creates a new renderer for the specified time.
|
||||
*
|
||||
* @param generator The video generator.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public WindVideoRenderer(VideoGenerator generator, Time time) throws IOException {
|
||||
super(generator, new Variable[] { Variable.U10M, Variable.V10M }, time);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, WindVideoState state) throws IOException {
|
||||
getRenderer().renderWindSpeed(image, state.data[0], state.data[1]);
|
||||
if (state.particles == null) {
|
||||
state.particles = new WindVideoState.Particle[getRenderer().getWidth() * 2];
|
||||
ReverseImageProjection projection = new ReverseImageProjection(getRenderer().getImageProjection(), getRenderer().getImageFiller());
|
||||
for (int i = 0; i < state.particles.length; i++) {
|
||||
state.particles[i] = new WindVideoState.Particle(projection);
|
||||
}
|
||||
}
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setColor(new Color(0x88FFFFFF, true));
|
||||
g.setStroke(new BasicStroke(getRenderer().getWidth() / 800f));
|
||||
for (int i = 0; i < state.particles.length; i++) {
|
||||
state.particles[i].step(state.data[0], state.data[1]);
|
||||
state.particles[i].drawParticle(g);
|
||||
}
|
||||
g.dispose();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected WindVideoState createState() {
|
||||
return new WindVideoState();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Graphics2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
import com.mowesta.data.process.projection.ReverseImageProjection;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* The state of the wind video that also contains a number of particles in
|
||||
* addition to the interpolated data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class WindVideoState extends LinearRendererState {
|
||||
|
||||
/**
|
||||
* The particles that we are drawing.
|
||||
*/
|
||||
Particle[] particles;
|
||||
|
||||
/**
|
||||
* Represents a single particle drawn on the surface.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class Particle {
|
||||
|
||||
/**
|
||||
* The random number generator for particles.
|
||||
*/
|
||||
private static Random RND = new Random(0);
|
||||
|
||||
/**
|
||||
* The speed factor to translate mps into pixels.
|
||||
*/
|
||||
private static float SPD = 0.1f;
|
||||
|
||||
/**
|
||||
* The maximum number of steps.
|
||||
*/
|
||||
private static int STEPS = 45;
|
||||
|
||||
/**
|
||||
* The maximum tail length in pixels.
|
||||
*/
|
||||
private static int LENGTH = 20;
|
||||
|
||||
/**
|
||||
* The trail of the particle.
|
||||
*/
|
||||
List<float[]> trail = new ArrayList<>(STEPS);
|
||||
|
||||
/**
|
||||
* A cache for the x values when drawing the polyline.
|
||||
*/
|
||||
int[] x = new int[STEPS];
|
||||
/**
|
||||
* A cache for the y values when drawing the polyline.
|
||||
*/
|
||||
int[] y = new int[STEPS];
|
||||
|
||||
/**
|
||||
* The number of steps made with this particle.
|
||||
*/
|
||||
private int steps = -1;
|
||||
|
||||
/**
|
||||
* The reverse projection for the particle.
|
||||
*/
|
||||
private ReverseImageProjection projection;
|
||||
|
||||
/**
|
||||
* Creates a new particle for the projection.
|
||||
*
|
||||
* @param projection The projection.
|
||||
*/
|
||||
public Particle(ReverseImageProjection projection) {
|
||||
this.projection = projection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the particle with the specified moves.
|
||||
*
|
||||
* @param u10m The u data.
|
||||
* @param v10m The v data.
|
||||
* @param move The steps to make initially.
|
||||
*/
|
||||
public void init(DoubleArray u10m, DoubleArray v10m, int move) {
|
||||
steps = STEPS - 1;
|
||||
trail.clear();
|
||||
float[] start = new float[] { RND.nextInt(projection.getWidth()), RND.nextInt(projection.getHeight()) };
|
||||
trail.add(start);
|
||||
for (int i = 0; i < move; i++) {
|
||||
step(u10m, v10m);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a step on the specified data.
|
||||
*
|
||||
* @param u10m The u data.
|
||||
* @param v10m The v data.
|
||||
*/
|
||||
public void step(DoubleArray u10m, DoubleArray v10m) {
|
||||
if (steps > 0) {
|
||||
steps -= 1;
|
||||
float[] last = trail.get(trail.size() - 1);
|
||||
int x = Math.max(0, Math.min(projection.getWidth(), (int)last[0]));
|
||||
int y = Math.max(0, Math.min(projection.getHeight(), (int)last[1]));
|
||||
int idx = projection.getIndex(x, y);
|
||||
if (idx >= 0) {
|
||||
// move based on current point value
|
||||
double u = u10m.getValue(idx);
|
||||
double v = v10m.getValue(idx);
|
||||
float[] next = new float[] {
|
||||
last[0] + (float)(u * SPD),
|
||||
last[1] - (float)(v * SPD),
|
||||
};
|
||||
trail.add(next);
|
||||
} else if (trail.size() >= 2) {
|
||||
// keep on going in the same direction
|
||||
float[] before = trail.get(trail.size() - 2);
|
||||
float[] next = new float[] {
|
||||
last[0] + (last[0] - before[0]),
|
||||
last[1] + (last[1] - before[1]),
|
||||
};
|
||||
trail.add(next);
|
||||
}
|
||||
} else {
|
||||
init(u10m, v10m, RND.nextInt(STEPS / 2));
|
||||
}
|
||||
// limit the tail length
|
||||
double length = 0;
|
||||
for (int i = trail.size() - 2; i >= 0; i--) {
|
||||
float[] p1 = trail.get(i + 1);
|
||||
float[] p2 = trail.get(i);
|
||||
float dx = p1[0] - p2[0];
|
||||
float dy = p1[1] - p2[1];
|
||||
double d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
|
||||
if (d + length > LENGTH) {
|
||||
double excess = length + d - LENGTH;
|
||||
double fraction = (d - excess) / d;
|
||||
for (int j = 0; j <= i; j++) trail.remove(0);
|
||||
trail.add(0, new float[] { p1[0] + (float)(fraction * dx), p1[1] + (float)(fraction * dy) });
|
||||
break;
|
||||
} else {
|
||||
length += d;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a single particle.
|
||||
*
|
||||
* @param g The graphics context.
|
||||
*/
|
||||
public void drawParticle(Graphics2D g) {
|
||||
int p = 1;
|
||||
x[0] = (int)trail.get(0)[0];
|
||||
y[0] = (int)trail.get(0)[1];
|
||||
for (int i = 1; i < trail.size(); i++) {
|
||||
float[] p1 = trail.get(i - 1);
|
||||
float[] p2 = trail.get(i);
|
||||
int x1 = (int)p1[0];
|
||||
int y1 = (int)p1[1];
|
||||
int x2 = (int)p2[0];
|
||||
int y2 = (int)p2[1];
|
||||
if (x1 != x2 || y1 != y2) {
|
||||
x[p] = x2;
|
||||
y[p] = y2;
|
||||
p += 1;
|
||||
}
|
||||
}
|
||||
if (p > 1) {
|
||||
g.drawPolyline(x, y, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
package com.mowesta.data.grib2;
|
||||
|
||||
import com.mowesta.data.grib2.code.CodeTables;
|
||||
import com.mowesta.data.grib2.io.DataStream;
|
||||
import com.mowesta.data.grib2.io.LimitedStream;
|
||||
import com.mowesta.data.grib2.section.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import com.mowesta.data.grib2.code.CodeTables;
|
||||
import com.mowesta.data.grib2.io.DataStream;
|
||||
import com.mowesta.data.grib2.io.LimitedStream;
|
||||
import com.mowesta.data.grib2.section.BitmapSection;
|
||||
import com.mowesta.data.grib2.section.EndSection;
|
||||
import com.mowesta.data.grib2.section.GridSection;
|
||||
import com.mowesta.data.grib2.section.IdentificationSection;
|
||||
import com.mowesta.data.grib2.section.LocalSection;
|
||||
import com.mowesta.data.grib2.section.ProductSection;
|
||||
import com.mowesta.data.grib2.section.RepresentationSection;
|
||||
|
||||
/**
|
||||
* The basic abstraction to load data from grib2 files.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
@@ -19,22 +25,22 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
* The 4 byte magic number at the beginning of the file.
|
||||
*/
|
||||
public static final byte[] GRIB2_HEADER = {71, 82, 73, 66};
|
||||
|
||||
|
||||
/**
|
||||
* The 4 byte magic number at the end of the file.
|
||||
*/
|
||||
public static final byte[] GRIB2_FOOTER = {55, 55, 55, 55};
|
||||
|
||||
|
||||
/**
|
||||
* The grib version supported by this library.
|
||||
*/
|
||||
public static final int GRIB2_VERSION = 2;
|
||||
|
||||
|
||||
/**
|
||||
* The data input stream to read the data.
|
||||
*/
|
||||
private DataStream data;
|
||||
|
||||
|
||||
/**
|
||||
* The header bytes.
|
||||
*/
|
||||
@@ -56,34 +62,34 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
* read in the constructor.
|
||||
*/
|
||||
private long length;
|
||||
|
||||
|
||||
/**
|
||||
* The number of bytes read.
|
||||
*/
|
||||
private long read;
|
||||
|
||||
|
||||
/**
|
||||
* The start of the next section.
|
||||
*/
|
||||
private long start;
|
||||
|
||||
|
||||
/**
|
||||
* The last read sections 1 to 6. The sections 1 to 6
|
||||
* are used to pass to the data section upon creation.
|
||||
*/
|
||||
private Grib2Section[] sections = new Grib2Section[6];
|
||||
|
||||
|
||||
/**
|
||||
* The limited stream that we gave out to the last data
|
||||
* section. The stream is automatically closed and set
|
||||
* to 0, when the next section is read.
|
||||
*/
|
||||
private LimitedStream stream;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new grib file.
|
||||
*
|
||||
*
|
||||
* @param stream The stream.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
@@ -107,19 +113,19 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
read += 16;
|
||||
start += 16;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the discipline of the file.
|
||||
*
|
||||
*
|
||||
* @return The discipline.
|
||||
*/
|
||||
public Grib2Value getDiscipline() {
|
||||
return discipline;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether there is another section availabe.
|
||||
*
|
||||
*
|
||||
* @return True if there is another section.
|
||||
*/
|
||||
public boolean hasSection() {
|
||||
@@ -128,7 +134,7 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
|
||||
/**
|
||||
* Reads the next section.
|
||||
*
|
||||
*
|
||||
* @return The next section.
|
||||
* @throws IOException Thrown if the section cannot be read.
|
||||
*/
|
||||
@@ -146,7 +152,7 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
int skipped = data.skipBytes(remainder>Integer.MAX_VALUE?Integer.MAX_VALUE:(int)remainder);
|
||||
remainder -= skipped;
|
||||
read += skipped;
|
||||
}
|
||||
}
|
||||
} else if (read > start) {
|
||||
throw new IOException("Previous read operations exceeded section length.");
|
||||
}
|
||||
@@ -162,7 +168,7 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
return createSection(8, 0);
|
||||
} else {
|
||||
long length = data.readUnsignedInt();
|
||||
if (length > Integer.MAX_VALUE)
|
||||
if (length > Integer.MAX_VALUE)
|
||||
throw new IOException("Section length exceeds supported limit (" + length + ">" + Integer.MAX_VALUE + ")");
|
||||
int number = data.readUnsignedByte();
|
||||
read += 5;
|
||||
@@ -174,17 +180,17 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
throw new IOException("Section returned invalid read count (expected >= 0 was " + count + ")" );
|
||||
} else if (count > maximum) {
|
||||
throw new IOException("Section returned too high read count (expected " + maximum + " was " + count + ")");
|
||||
}
|
||||
}
|
||||
read += count;
|
||||
start += length;
|
||||
return section;
|
||||
return section;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the next data section available or
|
||||
* null, if all sections have been read.
|
||||
*
|
||||
*
|
||||
* @return The next data section or null, if
|
||||
* there are no more sections.
|
||||
* @throws IOException Thrown if the section cannot
|
||||
@@ -193,22 +199,23 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
public Grib2Data nextData() throws IOException {
|
||||
while (hasSection()) {
|
||||
Grib2Section next = nextSection();
|
||||
if (next instanceof Grib2Data)
|
||||
if (next instanceof Grib2Data)
|
||||
return (Grib2Data)next;
|
||||
}
|
||||
return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reads the section either directly or indirectly (for the data section).
|
||||
*
|
||||
*
|
||||
* @param number The number of the section.
|
||||
* @param length The total length starting at the current position.
|
||||
* @param section The section.
|
||||
* @return The amount of bytes read.
|
||||
* @throws IOException Thrown by the underlying stream.
|
||||
*/
|
||||
@SuppressWarnings("resource")
|
||||
private int readSection(int number, long length, Grib2Section section) throws IOException {
|
||||
if (number == 7) {
|
||||
stream = new LimitedStream(data, length);
|
||||
@@ -224,10 +231,10 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
return section.read(data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Store the section, if it is not the data or end section.
|
||||
*
|
||||
*
|
||||
* @param number The number of the section.
|
||||
* @param section The section to store.
|
||||
*/
|
||||
@@ -236,31 +243,31 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
sections[number - 1] = section;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the section with the specified number.
|
||||
*
|
||||
*
|
||||
* @param number The number to retrieve.
|
||||
* @return The section read last.
|
||||
*/
|
||||
private Grib2Section getSection(int number) {
|
||||
return sections[number - 1];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the section for the specified section number.
|
||||
*
|
||||
*
|
||||
* @param number The number of the section.
|
||||
* @param length The length of the section.
|
||||
* @return The section.
|
||||
*/
|
||||
private Grib2Section createSection(int number, int length) {
|
||||
if (number == 1) return new IdentificationSection(this, number, (int)length);
|
||||
if (number == 2) return new LocalSection(this, number, (int)length);
|
||||
if (number == 3) return new GridSection(this, number, (int)length);
|
||||
if (number == 4) return new ProductSection(this, number, (int)length);
|
||||
if (number == 5) return new RepresentationSection(this, number, (int)length);
|
||||
if (number == 6) return new BitmapSection(this, number, (int)length);
|
||||
if (number == 1) return new IdentificationSection(this, number, length);
|
||||
if (number == 2) return new LocalSection(this, number, length);
|
||||
if (number == 3) return new GridSection(this, number, length);
|
||||
if (number == 4) return new ProductSection(this, number, length);
|
||||
if (number == 5) return new RepresentationSection(this, number, length);
|
||||
if (number == 6) return new BitmapSection(this, number, length);
|
||||
if (number == 7) {
|
||||
Grib2Data data = new Grib2Data(this, number, length);
|
||||
data.setIdentificationSection((IdentificationSection)getSection(1));
|
||||
@@ -271,20 +278,20 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
data.setBitmapSection((BitmapSection)getSection(6));
|
||||
return data;
|
||||
}
|
||||
if (number == 8) return new EndSection(this, number, length);
|
||||
if (number == 8) return new EndSection(this, number, length);
|
||||
throw new RuntimeException("Invalid Grib2 section type (" + number + ").");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Closes the underlying input stream.
|
||||
*
|
||||
*
|
||||
* @throws IOException Thrown by the stream.
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
data.close();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void toString(StringBuilder builder, String delimiter) {
|
||||
super.toString(builder, delimiter);
|
||||
@@ -295,5 +302,5 @@ public class Grib2File extends Grib2Object implements AutoCloseable {
|
||||
builder.append(delimiter);
|
||||
builder.append("READ(" + read + ")");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.mowesta.data.grib2.decoder;
|
||||
|
||||
import com.mowesta.data.grib2.section.BitmapSection;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* Creates a new bitmap handler.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class BitmapInterpreter {
|
||||
|
||||
/**
|
||||
* The bitmap or null.
|
||||
*/
|
||||
private byte[] bitmap;
|
||||
|
||||
/**
|
||||
* The grid size.
|
||||
*/
|
||||
private long size;
|
||||
|
||||
/**
|
||||
* The current index.
|
||||
*/
|
||||
private int current = 0;
|
||||
|
||||
/**
|
||||
* Creates a new bitmap handler.
|
||||
*
|
||||
* @param section The section.
|
||||
* @param size The point count.
|
||||
*/
|
||||
public BitmapInterpreter(BitmapSection section, long size) {
|
||||
this.size = size;
|
||||
if (section.getBitmapIndicator().getValue() == 0) {
|
||||
bitmap = section.getBitmap();
|
||||
} else {
|
||||
bitmap = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if there is a bitmap.
|
||||
*
|
||||
* @return True if there is a bitmap.
|
||||
*/
|
||||
public boolean hasBitmap() {
|
||||
return bitmap != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The total point count which may include
|
||||
* invalid points.
|
||||
*
|
||||
* @return The total point count.
|
||||
*/
|
||||
public long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of valid points.
|
||||
*
|
||||
* @return The points.
|
||||
*/
|
||||
public long getPoints() {
|
||||
if (bitmap == null) {
|
||||
return size;
|
||||
} else {
|
||||
int points = 0;
|
||||
for (long i = 0, s = size; i < s; i++) {
|
||||
if (isSet(bitmap, i)) points += 1;
|
||||
}
|
||||
return points;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of bits in the bitmap.
|
||||
*
|
||||
* @return The number of bits in the bitmap.
|
||||
*/
|
||||
public int getBits() {
|
||||
return bitmap.length * 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the next value is present.
|
||||
*
|
||||
* @return True if the next value is present.
|
||||
*/
|
||||
public boolean hasNext() {
|
||||
if (current < size) {
|
||||
if (bitmap == null) {
|
||||
return true;
|
||||
} else {
|
||||
return isSet(this.bitmap, current);
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the next value.
|
||||
*
|
||||
* @return True if we moved.
|
||||
*/
|
||||
public boolean moveNext() {
|
||||
if (current < size) {
|
||||
current += 1;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters an existing array using the bitmap.
|
||||
*
|
||||
* @param input The input.
|
||||
* @return The filtered array.
|
||||
*/
|
||||
public DoubleArray filter(DoubleArray input) {
|
||||
if (input.getSize() != size) throw new RuntimeException("Unexpected filter input size.");
|
||||
DoubleArray result = new DoubleArray((int)getPoints());
|
||||
int next = 0;
|
||||
for (int i = 0, s = (int)size; i < s; i++) {
|
||||
if (bitmap == null || isSet(bitmap, i)) {
|
||||
result.setValue(next, input.getValue(i));
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether the i-th bit is set.
|
||||
*
|
||||
* @param bitmap The bitmap.
|
||||
* @param index The index of the bit.
|
||||
* @return True if the bit is set, false otherwise.
|
||||
*/
|
||||
public static boolean isSet(byte[] bitmap, long index) {
|
||||
int idx = (int)index / 8;
|
||||
if (idx < 0 || idx >= bitmap.length) return false;
|
||||
return ((0x80 & (bitmap[idx] & 0xff << index - idx * 8)) != 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,26 +6,26 @@ import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A decoder for regular grids.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class RegularGridDecoder {
|
||||
|
||||
|
||||
/**
|
||||
* The typical devider for latitudes and longitudes.
|
||||
* Grib2 recommendation is micro-degrees.
|
||||
*/
|
||||
private static final double DIVIDER = 1e6;
|
||||
|
||||
|
||||
/**
|
||||
* The grid template.
|
||||
*/
|
||||
private AbstractFixedLatLonGrid grid;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new decoder.
|
||||
*
|
||||
*
|
||||
* @param section The grid section defining the grid.
|
||||
* @throws IllegalArgumentException Thrown if the section does
|
||||
* not contain a regular grid or if the scanning mode is not supported.
|
||||
@@ -38,7 +38,7 @@ public class RegularGridDecoder {
|
||||
throw new IllegalArgumentException("Decoder requires fixed latitude longitude grid.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs a sanity check on the coordinates.
|
||||
*/
|
||||
@@ -54,10 +54,10 @@ public class RegularGridDecoder {
|
||||
if (Math.abs(dlon - grid.di) > 1) // allow minor rounding errors (present in dwd output)
|
||||
throw new IllegalArgumentException("Unsupported di specification, expected " + grid.di + " computed " + dlon + " (unsupported scan mode?).");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the latitudes.
|
||||
*
|
||||
*
|
||||
* @return The latitudes.
|
||||
*/
|
||||
public DoubleArray getLatitudes() {
|
||||
@@ -74,10 +74,10 @@ public class RegularGridDecoder {
|
||||
}
|
||||
return latitudes;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the longitude and corrects its values.
|
||||
*
|
||||
*
|
||||
* @param value The value.
|
||||
* @return The longitude.
|
||||
*/
|
||||
@@ -87,11 +87,11 @@ public class RegularGridDecoder {
|
||||
else if (result < -180) result += 360;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the longitudes.
|
||||
*
|
||||
*
|
||||
* @return The longitudes.
|
||||
*/
|
||||
public DoubleArray getLongitudes() {
|
||||
@@ -109,10 +109,10 @@ public class RegularGridDecoder {
|
||||
}
|
||||
return longitudes;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the latitude and corrects its values.
|
||||
*
|
||||
*
|
||||
* @param value The value.
|
||||
* @return The latitude.
|
||||
*/
|
||||
@@ -122,6 +122,6 @@ public class RegularGridDecoder {
|
||||
if (result < -90) result += 180;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import com.mowesta.data.grib2.io.DataStream;
|
||||
import com.mowesta.data.grib2.template.data.SimpleData;
|
||||
|
||||
/**
|
||||
* A streaming decoder for data with simple packing.
|
||||
*
|
||||
* A streaming decoder for data with simple packing.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class SimpleDataDecoder implements StreamDecoder {
|
||||
@@ -37,15 +37,21 @@ public class SimpleDataDecoder implements StreamDecoder {
|
||||
* The number of octets (= bits / 8).
|
||||
*/
|
||||
private int octets;
|
||||
|
||||
|
||||
/**
|
||||
* The bitmap interpreter.
|
||||
*/
|
||||
private BitmapInterpreter bitmap;
|
||||
|
||||
/**
|
||||
* Creates a simple decoder for the data.
|
||||
*
|
||||
*
|
||||
* @param data The data.
|
||||
* @throws RuntimeException Thrown if the decoder does not support the format.
|
||||
*/
|
||||
public SimpleDataDecoder(Grib2Data data) {
|
||||
SimpleData simpleData = (SimpleData)data.getRepresentationSection().getTemplate();
|
||||
this.bitmap = new BitmapInterpreter(data.getBitmapSection(), data.getGridSection().getPointCount());
|
||||
reference = simpleData.getReferenceValue();
|
||||
bscale = Math.pow(2, simpleData.getBinaryScaleFactor());
|
||||
dscale = Math.pow(10, -simpleData.getDecimalScaleFactor());
|
||||
@@ -54,9 +60,39 @@ public class SimpleDataDecoder implements StreamDecoder {
|
||||
if (bits % 8 != 0 || octets > 8) throw new RuntimeException("Unsupported bit count (" + bits + ")");
|
||||
stream = data.getStream();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the total number of valid and invalid points.
|
||||
*
|
||||
* @return The total number of points.
|
||||
*/
|
||||
public long getSize() {
|
||||
return bitmap.getSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of valid points.
|
||||
*
|
||||
* @return The number of valid points.
|
||||
*/
|
||||
public long getPoints() {
|
||||
return bitmap.getPoints();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the next value is valid.
|
||||
*
|
||||
* @return True if the next value is valid.
|
||||
*/
|
||||
public boolean hasNext() {
|
||||
return bitmap.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double readNext() throws IOException {
|
||||
boolean next = bitmap.hasNext();
|
||||
bitmap.moveNext();
|
||||
if (!next) return Double.NaN;
|
||||
// special case, if bits is 0, return only reference value
|
||||
if (bits == 0) return reference;
|
||||
long longBits = 0;
|
||||
@@ -68,5 +104,5 @@ public class SimpleDataDecoder implements StreamDecoder {
|
||||
}
|
||||
return (longBits * bscale + reference) * dscale;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -4,17 +4,18 @@ import java.io.IOException;
|
||||
|
||||
/**
|
||||
* An interface for streaming decoders.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface StreamDecoder {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reads the next value from the stream.
|
||||
*
|
||||
*
|
||||
* @return The next value.
|
||||
* @throws IOException Thrown by the stream.
|
||||
*/
|
||||
double readNext() throws IOException;
|
||||
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.mowesta.data.process.color;
|
||||
|
||||
/**
|
||||
* Represents the Beaufort Scale which relates wind speed to observed conditions
|
||||
* at sea or on land.
|
||||
*
|
||||
* @see <a href="https://en.wikipedia.org/wiki/Beaufort_scale">Beaufort
|
||||
* Scale</a>
|
||||
*
|
||||
* @author Adriano
|
||||
*/
|
||||
public class BeaufortWindScaleScheme implements IColorScheme {
|
||||
|
||||
/**
|
||||
* The colors for different wind speeds.
|
||||
*/
|
||||
private static final int[] BEAUFORT_SCALE = new int[13];
|
||||
|
||||
static { // Wind speed (m/s)
|
||||
BEAUFORT_SCALE[0] = 0xff7ec1d9; // < 0.5
|
||||
BEAUFORT_SCALE[1] = 0xff8ed1d9; // 0.5 - 1.5
|
||||
BEAUFORT_SCALE[2] = 0xff76d7bc; // 1.6 - 3.3
|
||||
BEAUFORT_SCALE[3] = 0xff76d794; // 3.4 - 5.5
|
||||
BEAUFORT_SCALE[4] = 0xff4fd44f; // 5.6 - 7.9
|
||||
BEAUFORT_SCALE[5] = 0xff53cd02; // 8.0 - 10.7
|
||||
BEAUFORT_SCALE[6] = 0xff84cd02; // 10.8 - 13.8
|
||||
BEAUFORT_SCALE[7] = 0xffbacd02; // 13.9 - 17.1
|
||||
BEAUFORT_SCALE[8] = 0xffcda202; // 17.2 - 20.7
|
||||
BEAUFORT_SCALE[9] = 0xffcd6f02; // 20.8 - 24.4
|
||||
BEAUFORT_SCALE[10] = 0xffcd4302; // 24.5 - 28.4
|
||||
BEAUFORT_SCALE[11] = 0xffcd0902; // 28.5 - 32.6
|
||||
BEAUFORT_SCALE[12] = 0xffb5000d; // > 32.7
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColor(double value) {
|
||||
if (value < 0.5d)
|
||||
return BEAUFORT_SCALE[0];
|
||||
else if (value < 1.6d)
|
||||
return BEAUFORT_SCALE[1];
|
||||
else if (value < 3.4d)
|
||||
return BEAUFORT_SCALE[2];
|
||||
else if (value < 5.6d)
|
||||
return BEAUFORT_SCALE[3];
|
||||
else if (value < 8.0d)
|
||||
return BEAUFORT_SCALE[4];
|
||||
else if (value < 10.8d)
|
||||
return BEAUFORT_SCALE[5];
|
||||
else if (value < 13.9d)
|
||||
return BEAUFORT_SCALE[6];
|
||||
else if (value < 17.2d)
|
||||
return BEAUFORT_SCALE[7];
|
||||
else if (value < 20.8d)
|
||||
return BEAUFORT_SCALE[8];
|
||||
else if (value < 24.5d)
|
||||
return BEAUFORT_SCALE[9];
|
||||
else if (value < 28.5d)
|
||||
return BEAUFORT_SCALE[10];
|
||||
else if (value < 32.7d)
|
||||
return BEAUFORT_SCALE[11];
|
||||
else
|
||||
return BEAUFORT_SCALE[12];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -128,7 +128,7 @@ public class ColorScaleRenderer {
|
||||
private void renderText(Graphics2D g, int x, int y, int width) {
|
||||
g.setColor(color);
|
||||
int shift = (int)(Math.abs(max - min) / (double)tick);
|
||||
double step = width / shift;
|
||||
double step = width / (double)shift;
|
||||
for (int i = 0; i < shift + 1; i++) {
|
||||
String s = provider.getLabel(min + i * tick);
|
||||
char[] t = s.toCharArray();
|
||||
|
||||
@@ -12,21 +12,21 @@ import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A class to generate an image from a data stream using a projection.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DataRenderer {
|
||||
|
||||
|
||||
/**
|
||||
* The image projection to speed up the projection process.
|
||||
*/
|
||||
protected ImageProjection projection;
|
||||
|
||||
|
||||
/**
|
||||
* The color scheme to apply to the pixels based on the values.
|
||||
*/
|
||||
protected IColorScheme scheme;
|
||||
|
||||
|
||||
/**
|
||||
* An optional list of data conversions.
|
||||
*/
|
||||
@@ -35,18 +35,18 @@ public class DataRenderer {
|
||||
/**
|
||||
* Creates a new image generator that uses the specified projection
|
||||
* and color scheme.
|
||||
*
|
||||
*
|
||||
* @param projection The projection to convert wgs84 into image coordinates.
|
||||
* @param scheme The color scheme to apply to the pixels based on the values.
|
||||
*/
|
||||
public DataRenderer(ImageProjection projection, IColorScheme scheme) {
|
||||
this(projection, scheme, Collections.emptyList());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new image generator that uses the specified projection
|
||||
* and color scheme with a certain set of data conversions.
|
||||
*
|
||||
*
|
||||
* @param projection The projection to convert wgs84 into image coordinates.
|
||||
* @param scheme The color scheme to apply to the pixels based on the values.
|
||||
* @param conversions An optional list of data conversions that is applied to
|
||||
@@ -58,11 +58,11 @@ public class DataRenderer {
|
||||
this.scheme = scheme;
|
||||
this.conversions = conversions;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the data source onto the specified image.
|
||||
*
|
||||
* @param source The data source.
|
||||
*
|
||||
* @param source The data source.
|
||||
* @param image The image to render to.
|
||||
*/
|
||||
public void renderData(DoubleArray source, BufferedImage image) {
|
||||
@@ -82,7 +82,32 @@ public class DataRenderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders the data of the provider onto the specified image.
|
||||
*
|
||||
* @param provider The provider.
|
||||
* @param size The size of the data.
|
||||
* @param image The image to draw to.
|
||||
*/
|
||||
public void renderData(IDataProvider provider, int size, BufferedImage image) {
|
||||
DataBufferInt r = (DataBufferInt)image.getRaster().getDataBuffer();
|
||||
int w = image.getWidth();
|
||||
int cs = conversions.size();
|
||||
for (int index = 0; index < size; index++) {
|
||||
if (projection.isVisible(index)) {
|
||||
int px = projection.getX(index);
|
||||
int py = projection.getY(index);
|
||||
double value = provider.getValue(index);
|
||||
for (int i = 0; i < cs; i++) {
|
||||
value = conversions.get(i).convert(value);
|
||||
}
|
||||
int color = scheme.getColor(value);
|
||||
r.setElem(py * w + px, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.mowesta.data.process.image;
|
||||
|
||||
/**
|
||||
* A functional interface to access data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IDataProvider {
|
||||
|
||||
/**
|
||||
* Returns the value at the index.
|
||||
*
|
||||
* @param index The index.
|
||||
* @return The value at the index.
|
||||
*/
|
||||
double getValue(int index);
|
||||
|
||||
|
||||
}
|
||||
+34
-23
@@ -5,35 +5,40 @@ import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
/**
|
||||
* A projection that is pre-computed to ensure that the angle functions are
|
||||
* not repeatedly called during the video generation process.
|
||||
*
|
||||
* not repeatedly called during the video generation process.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ImageProjection {
|
||||
|
||||
|
||||
/**
|
||||
* The projected x-coordinate of the associated wgs coordinate.
|
||||
*/
|
||||
private IntArray x;
|
||||
|
||||
|
||||
/**
|
||||
* The projected y-coordinate of the associated wgs coordinate.
|
||||
*/
|
||||
private IntArray y;
|
||||
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*/
|
||||
private int width;
|
||||
|
||||
|
||||
/**
|
||||
* The height of the image.
|
||||
*/
|
||||
private int height;
|
||||
|
||||
|
||||
/**
|
||||
* The number of elements.
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Applies to the projection to the longitude and latitue pairs and stores the results.
|
||||
*
|
||||
*
|
||||
* @param projection The projection.
|
||||
* @param longitudes The longitudes of coordinates.
|
||||
* @param latitudes The latitudes of coordinates.
|
||||
@@ -43,7 +48,7 @@ public class ImageProjection {
|
||||
public ImageProjection(IProjection projection, DoubleArray longitudes, DoubleArray latitudes, int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
int size = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
size = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
this.x = new IntArray(size);
|
||||
this.y = new IntArray(size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
@@ -58,58 +63,64 @@ public class ImageProjection {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*
|
||||
*
|
||||
* @return The width of the image.
|
||||
*/
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The height of the image.
|
||||
*
|
||||
*
|
||||
* @return The height of the image.
|
||||
*/
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of elements.
|
||||
*
|
||||
* @return The number of projected elements.
|
||||
*/
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the i-th coordinate is visible.
|
||||
*
|
||||
*
|
||||
* @param index The index.
|
||||
* @return True if visible, false otherwise.
|
||||
*/
|
||||
public boolean isVisible(int index) {
|
||||
return x.getValue(index) >= 0 && y.getValue(index) >= 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the x-coordinate of the i-th wgs coordinate
|
||||
* or -1, if it is not visible.
|
||||
*
|
||||
*
|
||||
* @param index The index.
|
||||
* @return The x coordinate or -1 if not visible.
|
||||
*/
|
||||
public int getX(int index) {
|
||||
return x.getValue(index);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the y-coordinate of the i-th wgs coordinate
|
||||
* or -1, if it is not visible.
|
||||
*
|
||||
*
|
||||
* @param index The index.
|
||||
* @return The y coordinate or -1 if not visible.
|
||||
*/
|
||||
public int getY(int index) {
|
||||
return y.getValue(index);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.mowesta.data.process.projection;
|
||||
|
||||
import com.mowesta.data.process.image.ImageFiller;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
/**
|
||||
* An reverse image projection that enables us to identify
|
||||
* the data point in the grib data that matches to a particular
|
||||
* image coordinate.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ReverseImageProjection {
|
||||
|
||||
/**
|
||||
* The indexes.
|
||||
*/
|
||||
private IntArray indexes;
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*/
|
||||
private int width;
|
||||
|
||||
/**
|
||||
* The height of the image.
|
||||
*/
|
||||
private int height;
|
||||
|
||||
/**
|
||||
* The size of the image.
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Returns the reverse image projection for a given image projection
|
||||
* thereby applying a specific filler.
|
||||
*
|
||||
* @param projection The projection.
|
||||
* @param filler The filler or null, if none should be applied.
|
||||
*/
|
||||
public ReverseImageProjection(ImageProjection projection, ImageFiller filler) {
|
||||
this.width = projection.getWidth();
|
||||
this.height = projection.getHeight();
|
||||
this.size = projection.getSize();
|
||||
indexes = new IntArray(width * height);
|
||||
for (int i = 0, s = width * height; i < s; i++) {
|
||||
indexes.setValue(i, -1);
|
||||
}
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (projection.isVisible(i)) {
|
||||
int x = projection.getX(i);
|
||||
int y = projection.getY(i);
|
||||
indexes.setValue(y * width + x, i);
|
||||
}
|
||||
}
|
||||
if (filler != null) filler.apply(indexes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the height of the image.
|
||||
*
|
||||
* @return The height of the image.
|
||||
*/
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the width of the image.
|
||||
*
|
||||
* @return The width of the image.
|
||||
*/
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of the image.
|
||||
*
|
||||
* @return The size.
|
||||
*/
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to find the index that populates the pixel.
|
||||
*
|
||||
* @param x The x value.
|
||||
* @param y The y value.
|
||||
* @return The index or -1 if the pixel cannot be reversed.
|
||||
*/
|
||||
public int getIndex(int x, int y) {
|
||||
return indexes.getValue(y * width + x);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
description = 'Mowesta Service Ejb'
|
||||
|
||||
configurations {
|
||||
// configuration to extract minimum dependencies that must be included
|
||||
// as jars in the testing jar (due to automatic service registration)
|
||||
testBundle
|
||||
testBundle.transitive = false
|
||||
testBundle.transitive = true
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +11,7 @@ dependencies {
|
||||
compile project(':service-data')
|
||||
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
|
||||
compile "org.infinispan:infinispan-query:${versionInfinispan}"
|
||||
|
||||
|
||||
compileOnly "org.hibernate:hibernate-search-orm:${versionHibernateSearch}"
|
||||
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
|
||||
@@ -34,13 +32,7 @@ dependencies {
|
||||
|
||||
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
|
||||
|
||||
testBundle "org.infinispan:infinispan-query:${versionInfinispan}"
|
||||
testBundle "org.infinispan:infinispan-query-dsl:${versionInfinispan}"
|
||||
testBundle "org.infinispan:infinispan-objectfilter:${versionInfinispan}"
|
||||
testBundle "org.infinispan:infinispan-directory-provider:${versionInfinispan}"
|
||||
testBundle "org.antlr:antlr-runtime:3.5.2"
|
||||
|
||||
|
||||
testBundle "org.infinispan:infinispan-query:${versionInfinispan}"
|
||||
}
|
||||
|
||||
// copy the jars required for testing into an output folder
|
||||
@@ -64,8 +56,8 @@ jar {
|
||||
'Build-Jdk' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})",
|
||||
'Build-OS' : "${System.properties['os.name']} ${System.properties['os.arch']} ${System.properties['os.version']}",
|
||||
'Implementation-Build' : "${System.properties['jenkins.build.number']}",
|
||||
'Dependencies': 'jdk.unsupported',
|
||||
'Implementation-Version' : project.version,
|
||||
'Dependencies' : 'org.hibernate.search.engine export, org.infinispan export, org.infinispan.commons export, org.antlr export'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@ import javax.persistence.PersistenceProperty;
|
||||
*
|
||||
*/
|
||||
public class Datasources {
|
||||
|
||||
|
||||
/**
|
||||
* The name of the datastore.
|
||||
*/
|
||||
public static final String MOWESTA_DATASTORE = "mowesta-datastore";
|
||||
|
||||
|
||||
/**
|
||||
* Defines the entity manager for the default database. This
|
||||
* definition sets some standard properties. More properties
|
||||
@@ -26,11 +26,11 @@ public class Datasources {
|
||||
*/
|
||||
@Produces
|
||||
@PersistenceContext(
|
||||
unitName=MOWESTA_DATASTORE,
|
||||
properties= {
|
||||
unitName=MOWESTA_DATASTORE,
|
||||
properties= {
|
||||
@PersistenceProperty(name="hibernate.connection.useUnicode", value="true"),
|
||||
@PersistenceProperty(name="hibernate.connection.characterEncoding", value="UTF-8"),
|
||||
})
|
||||
private EntityManager defaultEntityManager;
|
||||
|
||||
})
|
||||
private EntityManager createEntityManager;
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.mowesta.service.injection;
|
||||
|
||||
/**
|
||||
* A class with deployment constants, to create a central place for
|
||||
* configuration.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DeploymentConstants {
|
||||
|
||||
/**
|
||||
* The base folder to store lucene indexes. Note that this folder
|
||||
* is also contained in the persistence.xml as a property for
|
||||
* the hibernate search configuration.
|
||||
*/
|
||||
public static final String FOLDER_LUCENCE = "/var/lucene/mowesta";
|
||||
|
||||
/**
|
||||
* The folder that contains the nominatim data to import.
|
||||
*/
|
||||
public static final String FOLDER_NOMINATIM = "/opt/data/nominatim";
|
||||
|
||||
/**
|
||||
* The base folder that contains the data from the dwd that is downloaded
|
||||
* periodically and imported.
|
||||
*/
|
||||
public static final String FOLDER_DWD = "/opt/data/dwd";
|
||||
|
||||
/**
|
||||
* The base folder that contains the infinispan data cache on the machine.
|
||||
*/
|
||||
public static final String FOLDER_INFINISPAN = "/var/infinispan/mowesta";
|
||||
|
||||
/**
|
||||
* The folder that contains the generated video files.
|
||||
*/
|
||||
public static final String FOLDER_VIDEO = "/opt/data/video";
|
||||
|
||||
/**
|
||||
* The base url for videos.
|
||||
*/
|
||||
public static final String URL_VIDEO = "https://www.mowesta.com/data/video/";
|
||||
|
||||
/**
|
||||
* Prevent the instantiation of the class.
|
||||
*/
|
||||
private DeploymentConstants() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.mowesta.service.injection;
|
||||
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
import com.mowesta.data.dwd.VideoConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.enterprise.inject.Produces;
|
||||
import javax.inject.Inject;
|
||||
|
||||
/**
|
||||
* The produces for predictions and video configurations.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Predictions {
|
||||
|
||||
/**
|
||||
* The dwd folder.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.DwdFolder
|
||||
private String dwdFolder;
|
||||
|
||||
/**
|
||||
* A flag to limit the predictions.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.LimitPredictions
|
||||
private boolean limitPredictions;
|
||||
|
||||
/**
|
||||
* Produces the predictions to synchronize.
|
||||
*
|
||||
* @return The predictions.
|
||||
*/
|
||||
@Produces
|
||||
public NumericPrediction[] createPredictions() {
|
||||
List<NumericPrediction> predictions = new ArrayList<>();
|
||||
predictions.add(new NumericPrediction(NumericPrediction.PredictionType.COSMO_EUROPE, new File(dwdFolder, "cosmo-eu"))); // entries, 28 files per variable)
|
||||
if (!limitPredictions) {
|
||||
// process large predictions only if configured
|
||||
predictions.add(new NumericPrediction(NumericPrediction.PredictionType.ICON_EUROPE, new File(dwdFolder, "icon-eu"))); // 720K entries, 93 files per variable
|
||||
predictions.add(new NumericPrediction(NumericPrediction.PredictionType.ICON_GLOBAL, new File(dwdFolder, "icon-global"))); // 3mio entries, 113 files per variable
|
||||
}
|
||||
return predictions.toArray(new NumericPrediction[predictions.size()]);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the video configurations for the predictions.
|
||||
*
|
||||
* @return The video configurations.
|
||||
*/
|
||||
@Produces
|
||||
public VideoConfiguration[] createConfigurations() {
|
||||
NumericPrediction[] predictions = createPredictions();
|
||||
VideoConfiguration[] result = new VideoConfiguration[predictions.length];
|
||||
for (int i = 0; i < predictions.length; i++) {
|
||||
result[i] = VideoConfiguration.getConfiguration(predictions[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the weather sources that are used for the corresponding indexes.
|
||||
*
|
||||
* @return The weather sources.
|
||||
*/
|
||||
@Produces
|
||||
public WeatherSource[] createSources() {
|
||||
NumericPrediction[] predictions = createPredictions();
|
||||
List<WeatherSource> sources = new ArrayList<>();
|
||||
if (predictions.length > 0) sources.add(WeatherSource.COSMO_EUROPE);
|
||||
if (predictions.length > 1) sources.add(WeatherSource.ICON_EUROPE);
|
||||
if (predictions.length > 2) sources.add(WeatherSource.ICON_GLOBAL);
|
||||
return sources.toArray(new WeatherSource[sources.size()]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.mowesta.service.injection;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.enterprise.inject.Produces;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Qualifier;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
|
||||
/**
|
||||
* A class producing strings that can be configured using entries
|
||||
* in the naming system.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Settings {
|
||||
|
||||
/**
|
||||
* The annotation to fetch the lucene base folder.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface LuceneFolder { }
|
||||
|
||||
/**
|
||||
* The annotation to fetch the nominatim base folder.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface NominatimFolder { }
|
||||
|
||||
/**
|
||||
* The annotation to fetch the nominatim base folder.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface DwdFolder { }
|
||||
|
||||
/**
|
||||
* The annotation to fetch the infinispan base folder.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface InfinispanFolder { }
|
||||
|
||||
/**
|
||||
* The annotation to fetch the video base folder.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface VideoFolder { }
|
||||
|
||||
/**
|
||||
* The annotation to fetch the video url.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface VideoUrl { }
|
||||
|
||||
|
||||
/**
|
||||
* The annotation to fetch the prediction setting.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target({ElementType.METHOD, ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface LimitPredictions { }
|
||||
|
||||
|
||||
/**
|
||||
* The base folder to store lucene indexes. Note that this folder
|
||||
* is also contained in the persistence.xml as a property for
|
||||
* the hibernate search configuration.
|
||||
*/
|
||||
private static final NameValuePair<String> FOLDER_LUCENCE = new NameValuePair<>("java:global/mowesta/folderLucene", "/var/lucene/mowesta");
|
||||
|
||||
/**
|
||||
* The folder that contains the nominatim data to import.
|
||||
*/
|
||||
private static final NameValuePair<String> FOLDER_NOMINATIM = new NameValuePair<>("java:global/mowesta/folderNominatim", "/opt/data/nominatim");
|
||||
|
||||
/**
|
||||
* The base folder that contains the data from the dwd that is downloaded
|
||||
* periodically and imported.
|
||||
*/
|
||||
private static final NameValuePair<String> FOLDER_DWD = new NameValuePair<>("java:global/mowesta/folderDwd", "/opt/data/dwd");
|
||||
|
||||
/**
|
||||
* The base folder that contains the infinispan data cache on the machine.
|
||||
*/
|
||||
private static final NameValuePair<String> FOLDER_INFINISPAN = new NameValuePair<>("java:global/mowesta/folderInfinispan", "/var/infinispan/mowesta");
|
||||
|
||||
/**
|
||||
* The folder that contains the generated video files.
|
||||
*/
|
||||
private static final NameValuePair<String> FOLDER_VIDEO = new NameValuePair<>("java:global/mowesta/folderVideo", "/opt/data/video");
|
||||
|
||||
/**
|
||||
* The base url for videos.
|
||||
*/
|
||||
private static final NameValuePair<String> URL_VIDEO = new NameValuePair<>("java:global/mowesta/urlVideo", "https://www.mowesta.com/data/video/");
|
||||
|
||||
/**
|
||||
* A boolean flag to limit the amount of predictions to process.
|
||||
*/
|
||||
private static final NameValuePair<Boolean> LIMIT_PREDICTIONS = new NameValuePair<>("java:global/mowesta/limitPredictions", Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
@Inject
|
||||
private Logger logger;
|
||||
|
||||
/**
|
||||
* Produces the video url.
|
||||
*
|
||||
* @return The video url.
|
||||
*/
|
||||
@Produces
|
||||
@VideoUrl
|
||||
public String getVideoURL() {
|
||||
return lookup(URL_VIDEO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the infinspan folder.
|
||||
*
|
||||
* @return The infinispan folder.
|
||||
*/
|
||||
@Produces
|
||||
@InfinispanFolder
|
||||
public String getInfinispanFolder() { return lookup(FOLDER_INFINISPAN); }
|
||||
|
||||
/**
|
||||
* Produces the lucene folder.
|
||||
*
|
||||
* @return The lucene folder.
|
||||
*/
|
||||
@Produces
|
||||
@LuceneFolder
|
||||
public String getLuceneFolder() { return lookup(FOLDER_LUCENCE); }
|
||||
|
||||
/**
|
||||
* Produces the video folder.
|
||||
*
|
||||
* @return The video folder.
|
||||
*/
|
||||
@Produces
|
||||
@VideoFolder
|
||||
public String getVideoFolder() { return lookup(FOLDER_VIDEO); }
|
||||
|
||||
/**
|
||||
* Produces the dwd folder.
|
||||
*
|
||||
* @return The dwd folder.
|
||||
*/
|
||||
@Produces
|
||||
@DwdFolder
|
||||
public String getDwdFolder() { return lookup(FOLDER_DWD); }
|
||||
|
||||
/**
|
||||
* Produces the nominatim folder.
|
||||
*
|
||||
* @return The nominatim folder.
|
||||
*/
|
||||
@Produces
|
||||
@NominatimFolder
|
||||
public String getNominatimFolder() { return lookup(FOLDER_NOMINATIM); }
|
||||
|
||||
/**
|
||||
* A flag to reduce the amount of predictions to process.
|
||||
* This is useful to limit the amount of data that is downloaded
|
||||
* and processed for local testing and debugging.
|
||||
*
|
||||
* @return True to limit the predictions, false to process all data.
|
||||
*/
|
||||
@Produces
|
||||
@LimitPredictions
|
||||
public boolean isLimitPredicitons() { return lookup(LIMIT_PREDICTIONS); }
|
||||
|
||||
/**
|
||||
* Performs a lookup of a name using JNDI and returns
|
||||
* a value, or the default value if not present.
|
||||
*
|
||||
* @param nameValuePair The name value pair.
|
||||
* @return The value bound to the name or the default value.
|
||||
* @throws RuntimeException Thrown if something fails.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> T lookup(NameValuePair<T> nameValuePair) {
|
||||
try {
|
||||
InitialContext context = new InitialContext();
|
||||
try {
|
||||
return (T)context.lookup(nameValuePair.name);
|
||||
} catch (NamingException e) {
|
||||
// may happen, if name is not bound
|
||||
} catch (RuntimeException e) {
|
||||
logger.log(Level.SEVERE, "Found an unexpected data type when resolving " + nameValuePair.name + ". Consider adjusting it.");
|
||||
}
|
||||
logger.log(Level.INFO, "Using default value to resolve " + nameValuePair.name + ". Consider setting it explicitly.");
|
||||
return nameValuePair.value;
|
||||
} catch (NamingException e) {
|
||||
throw new RuntimeException("Failed to resolve initial context.", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* An internal class to represent a name with a default value.
|
||||
*/
|
||||
private static final class NameValuePair<T> {
|
||||
/**
|
||||
* The name.
|
||||
*/
|
||||
final String name;
|
||||
/**
|
||||
* The value.
|
||||
*/
|
||||
final T value;
|
||||
|
||||
/**
|
||||
* Creates a new name value pair.
|
||||
*
|
||||
* @param name The name.
|
||||
* @param value The value.
|
||||
*/
|
||||
private NameValuePair(String name, T value) {
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -30,7 +30,7 @@ import org.infinispan.manager.DefaultCacheManager;
|
||||
import org.infinispan.transaction.TransactionMode;
|
||||
|
||||
import com.mowesta.service.entity.WeatherForecastContainer;
|
||||
import com.mowesta.service.injection.DeploymentConstants;
|
||||
import com.mowesta.service.injection.Settings;
|
||||
|
||||
/**
|
||||
* A session bean to manage all infinispan caches. Note that the cache must
|
||||
@@ -74,6 +74,20 @@ public class InfinispanSessionBean {
|
||||
*/
|
||||
@Resource
|
||||
protected SessionContext context;
|
||||
|
||||
/**
|
||||
* The folder containing the infinispan caches.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.InfinispanFolder
|
||||
protected String infinispanFolder;
|
||||
|
||||
/**
|
||||
* The folder containing the lucene indexes.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.LuceneFolder
|
||||
protected String luceneFolder;
|
||||
|
||||
/**
|
||||
* Creates the cache manager on startup.
|
||||
@@ -153,7 +167,7 @@ public class InfinispanSessionBean {
|
||||
* @return The file system location.
|
||||
*/
|
||||
protected String getLocation(String cacheName) {
|
||||
return new File(DeploymentConstants.FOLDER_INFINISPAN, cacheName).getAbsolutePath();
|
||||
return new File(infinispanFolder, cacheName).getAbsolutePath();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,7 +176,7 @@ public class InfinispanSessionBean {
|
||||
* @return The index base.
|
||||
*/
|
||||
protected String getIndexBase() {
|
||||
return new File(DeploymentConstants.FOLDER_LUCENCE).getAbsolutePath();
|
||||
return new File(luceneFolder).getAbsolutePath();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -40,32 +40,32 @@ import com.mowesta.service.session.sync.WeatherVideoSyncSessionBean;
|
||||
|
||||
/**
|
||||
* The session bean that handles weather reports.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Stateless
|
||||
public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
|
||||
|
||||
/**
|
||||
* The maximum age of weather reports included in weather conditions.
|
||||
*/
|
||||
private static final long MAX_REPORT_AGE = 60*60*1000;
|
||||
|
||||
|
||||
/**
|
||||
* The infinispan session bean.
|
||||
*/
|
||||
@Inject
|
||||
private InfinispanSessionBean infinispanSession;
|
||||
|
||||
|
||||
/**
|
||||
* The session bean to access video metadata.
|
||||
*/
|
||||
@Inject
|
||||
private WeatherVideoSyncSessionBean videoSession;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the best and longest forecast for a given coordinate.
|
||||
*
|
||||
*
|
||||
* @param location The coordinate.
|
||||
* @return The best forecast for the coordinate or null, if there is none.
|
||||
*/
|
||||
@@ -74,11 +74,22 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
public WeatherForecast getForecast(Coordinate location) {
|
||||
SearchManager manager = Search.getSearchManager(infinispanSession.getDataCache());
|
||||
List<WeatherForecastContainer> containers = WeatherForecastContainer.findByLocation(manager, location, 10);
|
||||
// compute the map of forecasts
|
||||
// compute the map of forecasts (distance is considered since list is ordered)
|
||||
Map<WeatherSource, WeatherForecast> forecasts = new HashMap<>();
|
||||
for (int i = containers.size() - 1; i >= 0; i--) {
|
||||
forecasts.put(containers.get(i).getSource(), containers.get(i).getForecast());
|
||||
}
|
||||
// find the most recent prediction time from all sources
|
||||
long threshold = 0;
|
||||
for (WeatherForecast forecast: forecasts.values()) {
|
||||
if (forecast.getConditions().size() > 0) {
|
||||
long time = forecast.getConditions().get(0).getTime();
|
||||
for (int i = 1, s = forecast.getConditions().size(); i < s; i++) {
|
||||
time = Math.min(forecast.getConditions().get(i).getTime(), time);
|
||||
}
|
||||
threshold = Math.max(threshold, time);
|
||||
}
|
||||
}
|
||||
// compute the set of "best" conditions from all sources
|
||||
Map<Long, WeatherCondition> conditions = new HashMap<>();
|
||||
WeatherForecast result = null;
|
||||
@@ -88,7 +99,11 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
if (next != null) {
|
||||
result = next;
|
||||
for (WeatherCondition c: next.getConditions()) {
|
||||
conditions.put(c.getTime(), c);
|
||||
// only keep data that is fresher than the latest
|
||||
// prediction, in case some prediction is not updated
|
||||
if (c.getTime() >= threshold) {
|
||||
conditions.put(c.getTime(), c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,22 +118,22 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
|
||||
/**
|
||||
* Returns the forecast with the specified id.
|
||||
*
|
||||
*
|
||||
* @param id The id of the forecast.
|
||||
* @return The forecast with the id or null, if the id is invalid.
|
||||
*/
|
||||
@PermitAll
|
||||
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
|
||||
public WeatherForecast getForecast(long id){
|
||||
WeatherForecastContainer container = (WeatherForecastContainer)infinispanSession.getDataCache().get(id);
|
||||
WeatherForecastContainer container = infinispanSession.getDataCache().get(id);
|
||||
if (container == null) return null;
|
||||
else return container.getForecast();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of weather stations that match the term. If the
|
||||
* Returns a page of weather stations that match the term. If the
|
||||
* term is null or the empty string, all stations will be returned.
|
||||
*
|
||||
*
|
||||
* @param term The search term.
|
||||
* @param config The page config.
|
||||
* @param filtered True to filter deleted.
|
||||
@@ -138,10 +153,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
page.setTotal(count);
|
||||
return page;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the weather station with the specified id.
|
||||
*
|
||||
*
|
||||
* @param id The id of the station.
|
||||
* @return The weather station.
|
||||
* @throws EntityNotFoundException
|
||||
@@ -151,10 +166,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
WeatherStationEntity station = getStationEntity(id);
|
||||
return Convert.with(WeatherStationConverter.class).apply(station, false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the weather station entity with the specified id.
|
||||
*
|
||||
*
|
||||
* @param id The id to search.
|
||||
* @return The entity.
|
||||
* @throws EntityNotFoundException Thrown if not found.
|
||||
@@ -165,20 +180,20 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
throw new EntityNotFoundException(WeatherStationEntity.class, id);
|
||||
return station;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the last modification date over all stations.
|
||||
*
|
||||
*
|
||||
* @return The last modification date over all stations.
|
||||
*/
|
||||
@PermitAll
|
||||
public long getLastModifiedStation() {
|
||||
return AbstractEntity.getLastModified(em, WeatherStationEntity.class);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the last modification time stamp for the station.
|
||||
*
|
||||
*
|
||||
* @param id The station id.
|
||||
* @return The last modification time stamp.
|
||||
* @throws EntityNotFoundException Thrown if the entity does not exist.
|
||||
@@ -188,10 +203,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
WeatherStationEntity station = getStationEntity(id);
|
||||
return WeatherReportEntity.getLastModifiedForStation(em, station);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a report page for a specific station and time range.
|
||||
*
|
||||
*
|
||||
* @param id The station id.
|
||||
* @param range The time range.
|
||||
* @param config The page configuration.
|
||||
@@ -214,10 +229,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the latest report from the station.
|
||||
*
|
||||
*
|
||||
* @param id The id of the station.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The weather report.
|
||||
@@ -228,10 +243,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
WeatherStationEntity station = getStationEntity(id);
|
||||
return Convert.with(WeatherReportConverter.class).apply(getLatestReportEntity(station, filtered), filtered);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the latest report from the station.
|
||||
*
|
||||
*
|
||||
* @param station The weather station.
|
||||
* @param filtered True to filter deleted, false otherwise.
|
||||
* @return The weather report.
|
||||
@@ -241,12 +256,12 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
if (time == 0) return null;
|
||||
else return WeatherReportEntity.findByTime(em, station, time);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the nearest weather station for the coordinate or
|
||||
* null, if there is no nearby station.
|
||||
*
|
||||
*
|
||||
* @param coordinate The coordinate.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The weather station.
|
||||
@@ -255,10 +270,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
public WeatherStation getStation(Coordinate coordinate, boolean filtered) {
|
||||
return Convert.with(WeatherStationConverter.class).apply(getStationEntity(coordinate, filtered), filtered);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the closest station to the entity.
|
||||
*
|
||||
*
|
||||
* @param coordinate The coordinate.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The station entity.
|
||||
@@ -270,13 +285,13 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the weather conditions for the coordinate.
|
||||
*
|
||||
*
|
||||
* @param coordinate The coordinate.
|
||||
*
|
||||
*
|
||||
* @return The weather condition or null.
|
||||
*/
|
||||
@PermitAll
|
||||
@@ -307,32 +322,32 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the last modification timestamp of the weather video metadata.
|
||||
*
|
||||
*
|
||||
* @return The last modification timestamp.
|
||||
*/
|
||||
@PermitAll
|
||||
public long getLastModifiedVideo() {
|
||||
return videoSession.getMetadata().getModificationTime();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of all videos.
|
||||
*
|
||||
*
|
||||
* @param config The page config.
|
||||
* @return The video page.
|
||||
*/
|
||||
@PermitAll
|
||||
public WeatherVideoPage getVideos(PageConfig config) {
|
||||
return getVideoPage(videoSession.getMetadata().getVideos(false), config);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of videos that are relevant for the coordinate.
|
||||
*
|
||||
*
|
||||
* @param c The coordinate.
|
||||
* @param config The page config.
|
||||
* @return The video page.
|
||||
@@ -341,10 +356,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
public WeatherVideoPage getVideos(Coordinate c, PageConfig config) {
|
||||
return getVideoPage(videoSession.getMetadata().getVideos(c, false), config);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a page of videos using the list of videos and the page config.
|
||||
*
|
||||
*
|
||||
* @param videos The videos to select from.
|
||||
* @param config The page configuration.
|
||||
* @return The video page with contents from the list as defined by the config.
|
||||
@@ -363,7 +378,7 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
|
||||
/**
|
||||
* Returns only the latest videos.
|
||||
*
|
||||
*
|
||||
* @return The latest videos.
|
||||
*/
|
||||
@PermitAll
|
||||
@@ -373,7 +388,7 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
|
||||
/**
|
||||
* Returns the latest videos for the coordinate.
|
||||
*
|
||||
*
|
||||
* @param c The coordinate.
|
||||
* @return The list of latest videos for the coordinate.
|
||||
*/
|
||||
@@ -381,6 +396,6 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
|
||||
public List<WeatherVideo> getLatestVideos(Coordinate c) {
|
||||
return videoSession.getMetadata().getVideos(c, true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
+16
-4
@@ -15,6 +15,7 @@ import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
||||
import org.geojson.Geometry;
|
||||
@@ -37,7 +38,7 @@ import com.mowesta.service.entity.CountryEntity;
|
||||
import com.mowesta.service.entity.EmbeddedCoordinate;
|
||||
import com.mowesta.service.entity.EmbeddedName;
|
||||
import com.mowesta.service.entity.StateEntity;
|
||||
import com.mowesta.service.injection.DeploymentConstants;
|
||||
import com.mowesta.service.injection.Settings;
|
||||
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
|
||||
/**
|
||||
@@ -129,7 +130,14 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
|
||||
* The name of the file containing the cities to remove.
|
||||
*/
|
||||
public static final String FILE_NOMINATIM_DUPLICATES = "duplicates.json.bz2";
|
||||
|
||||
|
||||
/**
|
||||
* The base folder name with the nominatim files.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.NominatimFolder
|
||||
private String nominatimFolder;
|
||||
|
||||
/**
|
||||
* Synchronizes all locations.
|
||||
*
|
||||
@@ -351,6 +359,10 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
|
||||
StateEntity state = null;
|
||||
if (city.getState() != null) state = AbstractLocationEntity.findByExternalId(em, StateEntity.class, city.getState());
|
||||
CountryEntity country = AbstractLocationEntity.findByExternalId(em, CountryEntity.class, city.getCountry());
|
||||
if (country == null) {
|
||||
log.log(Level.INFO, "City " + getName(city) + " does not have a known country, skipping.");
|
||||
continue;
|
||||
}
|
||||
if (e == null) {
|
||||
log.log(Level.FINE, "City " + getName(city) + " does not exist, creating.");
|
||||
e = new CityEntity();
|
||||
@@ -538,7 +550,7 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
|
||||
* @throws IOException Thrown if the input stream cannot be opened.
|
||||
*/
|
||||
protected InputStream getNominatimInputStream(String file) throws IOException {
|
||||
File f = new File(DeploymentConstants.FOLDER_NOMINATIM, file);
|
||||
File f = new File(nominatimFolder, file);
|
||||
if (f.exists() && f.canRead()) return new FileInputStream(f);
|
||||
else return null;
|
||||
}
|
||||
@@ -551,7 +563,7 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
|
||||
* @return The last modification time or 0, if the file does not exist.
|
||||
*/
|
||||
protected long getLastModified(String file) {
|
||||
File f = new File(DeploymentConstants.FOLDER_NOMINATIM, file);
|
||||
File f = new File(nominatimFolder, file);
|
||||
return f.lastModified();
|
||||
}
|
||||
|
||||
|
||||
+24
-30
@@ -20,6 +20,7 @@ import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import org.infinispan.Cache;
|
||||
|
||||
@@ -31,7 +32,6 @@ 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.PredictionType;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
@@ -42,7 +42,6 @@ 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.injection.DeploymentConstants;
|
||||
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
|
||||
/**
|
||||
@@ -52,24 +51,7 @@ import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
*/
|
||||
@Stateless
|
||||
public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
/**
|
||||
* The predictions that are synchronized. Note that this must be held
|
||||
* in sync with the sources definition.
|
||||
*/
|
||||
public static final NumericPrediction[] PREDICTIONS = new NumericPrediction[] {
|
||||
new NumericPrediction(PredictionType.COSMO_EUROPE, new File(DeploymentConstants.FOLDER_DWD, "cosmo-eu")), // entries, 28 files per variable
|
||||
new NumericPrediction(PredictionType.ICON_EUROPE, new File(DeploymentConstants.FOLDER_DWD, "icon-eu")), // 720K entries, 93 files per variable
|
||||
new NumericPrediction(PredictionType.ICON_GLOBAL, new File(DeploymentConstants.FOLDER_DWD, "icon-global")) // 3mio entries, 113 files per variable
|
||||
};
|
||||
/**
|
||||
* The weather sources that are used for the corresponding indexes.
|
||||
*/
|
||||
public static final WeatherSource[] SOURCES = new WeatherSource[] {
|
||||
WeatherSource.COSMO_EUROPE,
|
||||
WeatherSource.ICON_EUROPE,
|
||||
WeatherSource.ICON_GLOBAL,
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The class with the metadata about the imported forecast.
|
||||
@@ -160,7 +142,19 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
|
||||
* The maximum hour to import during testing.
|
||||
*/
|
||||
private static final int MAX_HOUR = 200;
|
||||
|
||||
|
||||
/**
|
||||
* The numeric predictions to process.
|
||||
*/
|
||||
@Inject
|
||||
private NumericPrediction[] predictions;
|
||||
|
||||
/**
|
||||
* The weather sources for the predicitons.
|
||||
*/
|
||||
@Inject
|
||||
private WeatherSource[] sources;
|
||||
|
||||
/**
|
||||
* Updates the prediction for the current time.
|
||||
*
|
||||
@@ -189,26 +183,26 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
|
||||
log.log(Level.INFO, "Checking predictions for " + time);
|
||||
ForecastMetadata meta = getMetadata(MetadataType.FORECAST, ForecastMetadata.class);
|
||||
if (meta == null) meta = new ForecastMetadata();
|
||||
for (int i = 0; i < PREDICTIONS.length; i++) {
|
||||
if (time.equals(meta.getTime(SOURCES[i])) && isDataAvailable(SOURCES[i])) {
|
||||
log.log(Level.INFO, "Skipping update for " + SOURCES[i] + " since it is already imported for " + time + ".");
|
||||
for (int i = 0; i < predictions.length; i++) {
|
||||
if (time.equals(meta.getTime(sources[i])) && isDataAvailable(sources[i])) {
|
||||
log.log(Level.INFO, "Skipping update for " + sources[i] + " since it is already imported for " + time + ".");
|
||||
continue;
|
||||
} else {
|
||||
log.log(Level.INFO, "Starting update for " + SOURCES[i] + " at time " + time + ".");
|
||||
log.log(Level.INFO, "Starting update for " + sources[i] + " at time " + time + ".");
|
||||
}
|
||||
// check if already available (avoid request), if not download and check again
|
||||
if (PREDICTIONS[i].isAvailable(time) || (downloadData(PREDICTIONS[i], time) && PREDICTIONS[i].isAvailable(time))) {
|
||||
if (predictions[i].isAvailable(time) || (downloadData(predictions[i], time) && predictions[i].isAvailable(time))) {
|
||||
try {
|
||||
Set<Integer> hours = prepareData(PREDICTIONS[i], SOURCES[i], time);
|
||||
importData(PREDICTIONS[i], SOURCES[i], time, hours);
|
||||
Set<Integer> hours = prepareData(predictions[i], sources[i], time);
|
||||
importData(predictions[i], sources[i], time, hours);
|
||||
// store the successful import
|
||||
meta.setTime(SOURCES[i], time);
|
||||
meta.setTime(sources[i], time);
|
||||
setMetadata(MetadataType.FORECAST, meta);
|
||||
} catch (IOException e) {
|
||||
log.log(Level.SEVERE, "Data import failed.", e);
|
||||
}
|
||||
} else {
|
||||
log.log(Level.INFO, "Skipping import for " + SOURCES[i] + " since data is not complete.");
|
||||
log.log(Level.INFO, "Skipping import for " + sources[i] + " since data is not complete.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-3
@@ -41,7 +41,7 @@ import com.mowesta.data.grib2.io.CsvReader;
|
||||
import com.mowesta.service.entity.EmbeddedCoordinate;
|
||||
import com.mowesta.service.entity.WeatherReportEntity;
|
||||
import com.mowesta.service.entity.WeatherStationEntity;
|
||||
import com.mowesta.service.injection.DeploymentConstants;
|
||||
import com.mowesta.service.injection.Settings;
|
||||
import com.mowesta.service.session.AbstractSessionBean;
|
||||
import com.mowesta.service.session.ShutdownSessionBean;
|
||||
|
||||
@@ -84,9 +84,23 @@ public class WeatherReportSyncSessionBean extends AbstractSessionBean {
|
||||
|
||||
protected static final String SERVER_PATH = "/climate_environment/CDC/observations_germany/climate/10_minutes/air_temperature/now/";
|
||||
protected static final String SERVER_NAME = "opendata.dwd.de";
|
||||
|
||||
|
||||
/**
|
||||
* The folder containing the dwd data.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.DwdFolder
|
||||
private String dwdFolder;
|
||||
|
||||
/**
|
||||
* The session context.
|
||||
*/
|
||||
@Resource
|
||||
private SessionContext context;
|
||||
|
||||
/**
|
||||
* The reference to detect shutdowns.
|
||||
*/
|
||||
@Inject
|
||||
protected ShutdownSessionBean shutdownSessionBean;
|
||||
|
||||
@@ -389,7 +403,7 @@ public class WeatherReportSyncSessionBean extends AbstractSessionBean {
|
||||
*/
|
||||
@PermitAll
|
||||
public File getTempFolder() {
|
||||
return new File(DeploymentConstants.FOLDER_DWD);
|
||||
return new File(dwdFolder);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+81
-69
@@ -19,6 +19,7 @@ import javax.annotation.security.PermitAll;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.ejb.TransactionAttribute;
|
||||
import javax.ejb.TransactionAttributeType;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -31,56 +32,56 @@ import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoConfiguration;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.service.injection.DeploymentConstants;
|
||||
import com.mowesta.service.injection.Settings;
|
||||
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
|
||||
|
||||
/**
|
||||
* A bean that generates videos and manages the video metadata. Note that this
|
||||
* bean does not download the data itself. Instead it relies on the forecast
|
||||
* sync to do the job.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Stateless
|
||||
public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
|
||||
/**
|
||||
* The class to store video metadata.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class VideoMetadata extends Metadata {
|
||||
|
||||
|
||||
/**
|
||||
* The serialization version
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
|
||||
/**
|
||||
* The object mapper to write the videos.
|
||||
*/
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
|
||||
/**
|
||||
* The weather videos.
|
||||
*/
|
||||
private List<WeatherVideo> videos = new ArrayList<>();
|
||||
|
||||
|
||||
/**
|
||||
* Returns all videos available. Sorted by time,
|
||||
* prediction and variable.
|
||||
*
|
||||
*
|
||||
* @param filterOld True to filter the old videos.
|
||||
* @return The videos that are available.
|
||||
*/
|
||||
public synchronized List<WeatherVideo> getVideos(boolean filterOld) {
|
||||
return getFiltered(new ArrayList<>(videos), filterOld);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns all videos that cover the coordinate. Sorted
|
||||
* by time, prediction and variable.
|
||||
*
|
||||
*
|
||||
* @param c The coordinate.
|
||||
* @param filterOld True to only return the latest videos.
|
||||
* @return The videos for the coordinate.
|
||||
@@ -95,10 +96,10 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
}
|
||||
return getFiltered(result, filterOld);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the old videos from the list and returns it.
|
||||
*
|
||||
*
|
||||
* @param videos The videos.
|
||||
* @param filter True to filter the old videos and only return the latest, false
|
||||
* to simply return the list as is.
|
||||
@@ -113,35 +114,35 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
map = new EnumMap<>(VideoType.class);
|
||||
latest.put(v.getSource(), map);
|
||||
}
|
||||
Long ts = map.get(v.getType());
|
||||
Long ts = map.get(v.getType());
|
||||
if (ts == null || ts < v.getTime()) {
|
||||
map.put(v.getType(), v.getTime());
|
||||
}
|
||||
}
|
||||
for (int i = videos.size() - 1; i >= 0; i--) {
|
||||
WeatherVideo v = videos.get(i);
|
||||
Map<VideoType, Long> map = latest.get(v.getSource());
|
||||
Map<VideoType, Long> map = latest.get(v.getSource());
|
||||
Long ts = map.get(v.getType());
|
||||
if (v.getTime() < ts) {
|
||||
videos.remove(i);
|
||||
}
|
||||
}
|
||||
return videos;
|
||||
return videos;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds the video and sorts the list.
|
||||
*
|
||||
*
|
||||
* @param video The video to add.
|
||||
*/
|
||||
public synchronized void addVideo(WeatherVideo video) {
|
||||
videos.add(video);
|
||||
sortVideos();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Replaces the videos with the videos and sorts them.
|
||||
*
|
||||
*
|
||||
* @param videos The videos to add.
|
||||
*/
|
||||
public synchronized void setVideos(List<WeatherVideo> videos) {
|
||||
@@ -149,9 +150,9 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
this.videos.addAll(videos);
|
||||
sortVideos();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sorts the videos by name which corresponds to sorting
|
||||
* Sorts the videos by name which corresponds to sorting
|
||||
* them by time, prediction type and variable.
|
||||
*/
|
||||
private void sortVideos() {
|
||||
@@ -162,10 +163,10 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Custom serializer for videos.
|
||||
*
|
||||
*
|
||||
* @param ois The input stream.
|
||||
* @throws IOException Thrown by the stream.
|
||||
* @throws ClassNotFoundException Never thrown.
|
||||
@@ -175,16 +176,16 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
int length = ois.readInt();
|
||||
byte[] in = new byte[length];
|
||||
ois.read(in);
|
||||
videos = mapper.readValue(in, new TypeReference<List<WeatherVideo>>(){});
|
||||
videos = mapper.readValue(in, new TypeReference<List<WeatherVideo>>(){});
|
||||
} catch (IOException e) {
|
||||
// ignore for temporary backward compatibility
|
||||
videos = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Custom serializer for videos.
|
||||
*
|
||||
*
|
||||
* @param oos The output stream.
|
||||
* @throws IOException Thrown by the stream.
|
||||
*/
|
||||
@@ -192,33 +193,41 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
byte[] out = mapper.writeValueAsBytes(videos);
|
||||
oos.writeInt(out.length);
|
||||
oos.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The period to keep videos in days.
|
||||
*/
|
||||
public static final int DELETION_DAYS = 7;
|
||||
|
||||
/**
|
||||
* The video configurations.
|
||||
*/
|
||||
public static final VideoConfiguration[] CONFIGURATIONS = new VideoConfiguration[WeatherForecastSyncSessionBean.PREDICTIONS.length];
|
||||
|
||||
|
||||
static {
|
||||
for (int i = 0; i < CONFIGURATIONS.length; i++) {
|
||||
CONFIGURATIONS[i] = VideoConfiguration.getConfiguration(WeatherForecastSyncSessionBean.PREDICTIONS[i]);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The base url to access the videos.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.VideoUrl
|
||||
private String videoUrl;
|
||||
|
||||
/**
|
||||
* The folder containing the videos.
|
||||
*/
|
||||
@Inject
|
||||
@Settings.VideoFolder
|
||||
private String videoFolder;
|
||||
|
||||
/**
|
||||
* The video configurations to produce.
|
||||
*/
|
||||
@Inject
|
||||
private VideoConfiguration[] videoConfigurations;
|
||||
|
||||
/**
|
||||
* Synchronizes the videos on disk and puts their metadata into the store for
|
||||
* the first run. On consecutive runs, this process checks whether new videos
|
||||
* must be generated and generates them.
|
||||
*
|
||||
*
|
||||
* @param first
|
||||
* True to indicate the first execution.
|
||||
* @throws Exception
|
||||
@@ -235,7 +244,7 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
/**
|
||||
* Updates the videos for the specified time.
|
||||
*
|
||||
*
|
||||
* @param first
|
||||
* A flag to indicate whether this is the first execution.
|
||||
* @param time
|
||||
@@ -248,7 +257,7 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
public void syncVideos(boolean first, Time time) throws Exception {
|
||||
if (first) rebuildMetadata();
|
||||
log.log(Level.INFO, "Updating videos for " + time);
|
||||
for (VideoConfiguration c: CONFIGURATIONS) {
|
||||
for (VideoConfiguration c: videoConfigurations) {
|
||||
if (! c.getPrediction().isAvailable(time)) {
|
||||
log.log(Level.INFO, "Skipping video update for " + c.getPrediction().getType() + " since data is not available.");
|
||||
continue; // data not available
|
||||
@@ -287,7 +296,7 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
} catch (IOException e) {
|
||||
log.log(Level.SEVERE, "Failed to generate weather video (" + videoName + ").", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// expire videos and rebuild metadata, if necessary
|
||||
if (deleteVideos(time)) {
|
||||
@@ -297,14 +306,14 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
/**
|
||||
* Returns the video configuration for the source.
|
||||
*
|
||||
*
|
||||
* @param type The prediction type.
|
||||
* @return The configuration.
|
||||
*/
|
||||
protected VideoConfiguration getVideoConfiguration(PredictionType type) {
|
||||
for (int i = 0; i < WeatherForecastSyncSessionBean.PREDICTIONS.length; i++) {
|
||||
if (type == WeatherForecastSyncSessionBean.PREDICTIONS[i].getType()) {
|
||||
return CONFIGURATIONS[i];
|
||||
for (VideoConfiguration c: videoConfigurations) {
|
||||
if (type == c.getPrediction().getType()) {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -335,14 +344,14 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
if (meta == null) meta = new VideoMetadata();
|
||||
meta.setVideos(videos);
|
||||
setMetadata(MetadataType.VIDEO, meta);
|
||||
log.log(Level.INFO, "Reloaded video metadata has " + getMetadata().videos.size() + " videos.");
|
||||
log.log(Level.INFO, "Reloaded video metadata has " + getMetadata().videos.size() + " videos.");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Finds old videos to delete and removes them from disk and from the
|
||||
* metadata entry.
|
||||
*
|
||||
*
|
||||
* @param time The current time to compute the threshold.
|
||||
* @return True if at least one video has been deleted.
|
||||
*/
|
||||
@@ -367,11 +376,11 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the video metadata.
|
||||
*
|
||||
*
|
||||
* @return The video metadata.
|
||||
*/
|
||||
@PermitAll
|
||||
@@ -381,20 +390,20 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
log.log(Level.INFO, "Retrieving video metadata with " + meta.videos.size() + " videos.");
|
||||
return meta;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the video folder.
|
||||
*
|
||||
*
|
||||
* @return The video folder.
|
||||
*/
|
||||
protected File getVideoFolder() {
|
||||
return new File(DeploymentConstants.FOLDER_VIDEO);
|
||||
return new File(videoFolder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the filename based on the time, prediction type and variable.
|
||||
*
|
||||
*
|
||||
* @param time The time.
|
||||
* @param type The prediction type.
|
||||
* @param v The variable.
|
||||
@@ -404,10 +413,10 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
// time - prediction type - variable
|
||||
return time.toString() + "-" + type.name().toLowerCase() + "-" + v.name().toLowerCase();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parses the weather video metadata from a file name.
|
||||
*
|
||||
*
|
||||
* @param name The name.
|
||||
* @return The metadata or null, if the file name is not a valid video file.
|
||||
*/
|
||||
@@ -443,20 +452,20 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
v.setStart(vc.getFirstHour());
|
||||
v.setDuration(vc.getLastHour() - vc.getFirstHour());
|
||||
v.setTime(getTime(time, type.getHour()));
|
||||
v.setUrl(DeploymentConstants.URL_VIDEO + name);
|
||||
v.setPreview(DeploymentConstants.URL_VIDEO + base + ".jpg");
|
||||
v.setScale(DeploymentConstants.URL_VIDEO + "scale_" + vt.name().toLowerCase() + ".png");
|
||||
v.setUrl(videoUrl + name);
|
||||
v.setPreview(videoUrl + base + ".jpg");
|
||||
v.setScale(videoUrl + "scale_" + vt.name().toLowerCase() + ".png");
|
||||
return v;
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.log(Level.INFO, "Failed to parse video from file name (" + name + ").", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the time based on a time stamp and an offset hour.
|
||||
*
|
||||
*
|
||||
* @param time The time.
|
||||
* @param hour The offset hour.
|
||||
* @return The time in epoch milliseconds.
|
||||
@@ -464,10 +473,10 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
protected long getTime(Time time, int hour) {
|
||||
return OffsetDateTime.of(time.year, time.month, time.day, 0, 0, 0, 0, ZoneOffset.UTC).plusHours(hour).toEpochSecond() * 1000;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the weather source for the prediction type.
|
||||
*
|
||||
*
|
||||
* @param type The type.
|
||||
* @return The source, or null.
|
||||
*/
|
||||
@@ -486,7 +495,7 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
|
||||
/**
|
||||
* Returns the video type for the variable.
|
||||
*
|
||||
*
|
||||
* @param v The variable.
|
||||
* @return The video type or null.
|
||||
*/
|
||||
@@ -502,6 +511,9 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
return VideoType.CLOUD;
|
||||
case T2M:
|
||||
return VideoType.TEMPERATURE;
|
||||
case U10M:
|
||||
case V10M:
|
||||
return VideoType.WIND;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import com.mowesta.service.session.DataSessionBean;
|
||||
* An extended implementation of the data session
|
||||
* bean that initializes the database in a more
|
||||
* complete state for testing.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Alternative
|
||||
@@ -90,9 +90,9 @@ public class DataTestBean extends DataSessionBean {
|
||||
* @return the entity object of the created device.
|
||||
*/
|
||||
private DeviceEntity createTestDevice(String userLogin) {
|
||||
final UserEntity userEntity = UserEntity.findByLogin(em, userLogin);
|
||||
DeviceEntity deviceEntity = null;
|
||||
if (userEntity != null) {
|
||||
final UserEntity userEntity = UserEntity.findByLogin(em, userLogin);
|
||||
DeviceEntity deviceEntity = null;
|
||||
if (userEntity != null) {
|
||||
deviceEntity = new DeviceEntity();
|
||||
deviceEntity.setUser(userEntity);
|
||||
deviceEntity.setDevice(userLogin + "-device");
|
||||
@@ -103,20 +103,9 @@ public class DataTestBean extends DataSessionBean {
|
||||
em.persist(deviceEntity);
|
||||
em.flush();
|
||||
}
|
||||
return deviceEntity;
|
||||
return deviceEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a batch of measurements with a timestamp difference of one millisecond.
|
||||
*
|
||||
* @param device The device which was "creating" the measurements.
|
||||
* @param timestamp The beginning timestamp.
|
||||
* @param count The amount of measurements to create.
|
||||
*/
|
||||
private void createBatchTestMeasurements(DeviceEntity device, long timestamp, int count) {
|
||||
for (int i = 0; i < count; i++)
|
||||
createTestMeasurements(device, null,timestamp + count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a batch of measurements with a timestamp difference of one millisecond
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
|
||||
version="2.1">
|
||||
<persistence-unit name="mowesta-datastore" transaction-type="JTA">
|
||||
<provider>com.mowesta.service.injection.PersistenceProvider</provider>
|
||||
<jta-data-source>java:jboss/datasources/mowesta</jta-data-source>
|
||||
<class>com.mowesta.service.entity.AbstractEntity</class>
|
||||
<class>com.mowesta.service.entity.AbstractLocationEntity</class>
|
||||
@@ -26,11 +27,11 @@
|
||||
<class>com.mowesta.service.entity.WeatherStationEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="jboss.as.jpa.providerModule" value="application"></property>
|
||||
<property name="jboss.entity.manager.jndi.name" value="java:app/mowesta/datastore"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="update"/>
|
||||
<property name="hibernate.show_sql" value="false" />
|
||||
<property name="hibernate.search.default.directory_provider" value="filesystem"/>
|
||||
<property name="hibernate.search.default.indexBase" value="/var/lucene/mowesta"/>
|
||||
<property name="hibernate.search.lucene_version" value="LUCENE_CURRENT"/>
|
||||
<property name="hibernate.jdbc.batch_size" value="1000"/>
|
||||
</properties>
|
||||
|
||||
@@ -65,8 +65,8 @@ public class EjbDeployment {
|
||||
b.append("Manifest-Version: 1.0\n");
|
||||
b.append("Implementation-Version: version\n");
|
||||
b.append("Implementation-Build: build\n");
|
||||
b.append("Dependencies: org.hibernate.search.engine export, org.infinispan export, org.infinispan.commons export, org.antlr export\n");
|
||||
b.append("Built-By: creator\n\n");
|
||||
b.append("Dependencies: jdk.unsupported\n");
|
||||
b.append("Built-By: creator\n\n");
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.mowesta.service.test.login;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.security.acl.Group;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -11,11 +11,15 @@ import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.security.auth.Subject;
|
||||
import javax.security.auth.callback.Callback;
|
||||
import javax.security.auth.callback.CallbackHandler;
|
||||
import javax.security.auth.callback.NameCallback;
|
||||
import javax.security.auth.callback.PasswordCallback;
|
||||
import javax.security.auth.login.LoginException;
|
||||
|
||||
import org.jboss.security.SecurityContextAssociation;
|
||||
import org.jboss.security.SimpleGroup;
|
||||
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
|
||||
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.service.entity.DeviceEntity;
|
||||
@@ -32,140 +36,204 @@ import com.mowesta.service.principal.MowestaPrincipal;
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LoginModule extends UsernamePasswordLoginModule {
|
||||
|
||||
/**
|
||||
* The roles that we will assign to the user.
|
||||
*/
|
||||
private List<String> roles = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private Logger log = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
public boolean login() throws LoginException {
|
||||
if (super.login()) {
|
||||
Principal p = getIdentity();
|
||||
if (p instanceof MowestaPrincipal) {
|
||||
MowestaPrincipal mp = (MowestaPrincipal)p;
|
||||
// abort the login if device and user are not set (!)
|
||||
return mp.getUser() != null || mp.getUser() != null;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean logout() throws LoginException {
|
||||
boolean result = super.logout();
|
||||
for (Group g: getRoleSets()) {
|
||||
subject.getPrincipals().remove(g);
|
||||
}
|
||||
// this is probably hacky: clear the security context
|
||||
SecurityContextAssociation.clearSecurityContext();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected Principal createIdentity(String username) throws Exception {
|
||||
String[] loginDevice = getLoginDevice(username);
|
||||
Long user = null;
|
||||
Long device = null;
|
||||
String name1 = "";
|
||||
String name2 = "";
|
||||
// this will be running inside the application's current
|
||||
// transaction which could potentially be problematic
|
||||
EntityManager em = getEntityManager();
|
||||
UserEntity ue = UserEntity.findByLogin(em, loginDevice[0]);
|
||||
if (ue != null) {
|
||||
user = ue.getId();
|
||||
name1 = ue.getLogin();
|
||||
for (RoleEntity re : ue.getRoles()) {
|
||||
roles.add(re.getName());
|
||||
}
|
||||
}
|
||||
DeviceEntity de = DeviceEntity.findByToken(em, loginDevice[1]);
|
||||
if (de != null) {
|
||||
name2 = de.getToken();
|
||||
device = de.getId();
|
||||
roles.add(Roles.DEVICE);
|
||||
}
|
||||
return new MowestaPrincipal(name1 + ":" + name2, user, device);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the login name and the device token from the
|
||||
* username string provided to the auth module.
|
||||
*
|
||||
* @param username The username (consisting of login:token).
|
||||
* @return An array with the login and the token.
|
||||
*/
|
||||
private String[] getLoginDevice(String username) {
|
||||
String[] loginAndDevice = new String[] { "", "" };
|
||||
if (username != null) {
|
||||
int idx = username.indexOf(':');
|
||||
if (idx != -1) {
|
||||
loginAndDevice[0] = username.substring(0, idx);
|
||||
loginAndDevice[1] = username.substring(idx + 1, username.length());
|
||||
} else {
|
||||
loginAndDevice[0] = username;
|
||||
}
|
||||
}
|
||||
return loginAndDevice;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean commit() throws LoginException {
|
||||
System.out.println("Login ok is: " + loginOk);
|
||||
if (loginOk) {
|
||||
subject.getPrincipals().clear();
|
||||
}
|
||||
return super.commit();
|
||||
}
|
||||
public class LoginModule implements javax.security.auth.spi.LoginModule {
|
||||
|
||||
@Override
|
||||
protected Group[] getRoleSets() throws LoginException {
|
||||
SimpleGroup group = new SimpleGroup("Roles");
|
||||
for (final String r: roles) {
|
||||
group.addMember(new Principal() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return r;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return r;
|
||||
}
|
||||
});
|
||||
}
|
||||
return new Group[] { group };
|
||||
}
|
||||
/**
|
||||
* The group name that wildfly uses to identify the caller principal.
|
||||
*/
|
||||
private static final String GROUP_NAME_CALLER = "CallerPrincipal";
|
||||
|
||||
@Override
|
||||
protected String getUsersPassword() throws LoginException {
|
||||
return "password";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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");
|
||||
} catch (NamingException e) {
|
||||
log.log(Level.SEVERE, "Failed to resolve entity manager.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The group name that wildfly uses to identify the roles of the caller.
|
||||
*/
|
||||
private static final String GROUP_NAME_ROLES = "Roles";
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private Logger log = Logger.getLogger(getClass().getName());
|
||||
|
||||
/**
|
||||
* The callback handler to fetch the username and password during login.
|
||||
*/
|
||||
private CallbackHandler callbackHandler;
|
||||
|
||||
/**
|
||||
* The subject to update with the caller and roles.
|
||||
*/
|
||||
private Subject subject;
|
||||
|
||||
/**
|
||||
* The user name that we fetched or were initialized with.
|
||||
*/
|
||||
private String username;
|
||||
/**
|
||||
* The password that we fetched or where initialized with.
|
||||
*/
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* The list of roles to assign.
|
||||
*/
|
||||
private List<String> roles = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
|
||||
Map<String, ?> options) {
|
||||
this.subject = subject;
|
||||
this.callbackHandler = callbackHandler;
|
||||
Object username = sharedState.get("javax.security.auth.login.name");
|
||||
this.username = asString(username);
|
||||
Object password = sharedState.get("javax.security.auth.login.password");
|
||||
this.password = asString(password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to convert a parameter into a string.
|
||||
*
|
||||
* @param object
|
||||
* The object.
|
||||
* @return The string.
|
||||
*/
|
||||
private String asString(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
} else if (object instanceof char[]) {
|
||||
return new String((char[]) object);
|
||||
} else if (object instanceof String) {
|
||||
return (String) object;
|
||||
} else if (object instanceof Principal) {
|
||||
return ((Principal) object).getName();
|
||||
} else {
|
||||
log.log(Level.SEVERE, "Unknown data type during login: " + object.getClass());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entity manager for the maptology 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");
|
||||
} catch (NamingException e) {
|
||||
log.log(Level.SEVERE, "Failed to resolve entity manager.", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the login name and the device token from the username string provided
|
||||
* to the auth module.
|
||||
*
|
||||
* @return An array with the login and the token.
|
||||
*/
|
||||
private String[] getLoginDevice() {
|
||||
String[] loginAndDevice = new String[] { "", "" };
|
||||
if (username != null) {
|
||||
int idx = username.indexOf(':');
|
||||
if (idx != -1) {
|
||||
loginAndDevice[0] = username.substring(0, idx);
|
||||
loginAndDevice[1] = username.substring(idx + 1, username.length());
|
||||
} else {
|
||||
loginAndDevice[0] = username;
|
||||
}
|
||||
}
|
||||
return loginAndDevice;
|
||||
}
|
||||
|
||||
protected MowestaPrincipal createPrincipal() {
|
||||
String[] loginDevice = getLoginDevice();
|
||||
Long user = null;
|
||||
Long device = null;
|
||||
String name1 = "";
|
||||
String name2 = "";
|
||||
// this will be running inside the application's current
|
||||
// transaction which could potentially be problematic
|
||||
EntityManager em = getEntityManager();
|
||||
UserEntity ue = UserEntity.findByLogin(em, loginDevice[0]);
|
||||
if (ue != null) {
|
||||
user = ue.getId();
|
||||
name1 = ue.getLogin();
|
||||
for (RoleEntity re : ue.getRoles()) {
|
||||
roles.add(re.getName());
|
||||
}
|
||||
}
|
||||
DeviceEntity de = DeviceEntity.findByToken(em, loginDevice[1]);
|
||||
if (de != null) {
|
||||
name2 = de.getToken();
|
||||
device = de.getId();
|
||||
roles.add(Roles.DEVICE);
|
||||
}
|
||||
return new MowestaPrincipal(name1 + ":" + name2, user, device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean login() throws LoginException {
|
||||
requestCredentials();
|
||||
return username != null && password != null && password.equals("password");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to request the login credentials using the callback handler.
|
||||
*/
|
||||
private void requestCredentials() {
|
||||
if (callbackHandler == null) {
|
||||
log.log(Level.SEVERE, "No callback handler request credentials.");
|
||||
} else {
|
||||
NameCallback nc = new NameCallback("Login: ", "-");
|
||||
PasswordCallback pc = new PasswordCallback("Password: ", false);
|
||||
try {
|
||||
callbackHandler.handle(new Callback[] { nc, pc });
|
||||
String name = nc.getName();
|
||||
if (name != null)
|
||||
username = name;
|
||||
char[] pass = pc.getPassword();
|
||||
if (pass != null)
|
||||
password = new String(pass);
|
||||
} catch (Exception e) {
|
||||
log.log(Level.SEVERE, "Failed to request credentials via callbacks.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean commit() throws LoginException {
|
||||
// throw away all state held for the principal
|
||||
subject.getPrincipals().clear();
|
||||
// get the principal form the result and create the groups
|
||||
MowestaPrincipal principal = createPrincipal();
|
||||
subject.getPrincipals().add(principal);
|
||||
// add the caller principal group
|
||||
SimpleGroup principalGroup = new SimpleGroup(GROUP_NAME_CALLER);
|
||||
principalGroup.addMember(principal);
|
||||
subject.getPrincipals().add(principalGroup);
|
||||
SimpleGroup rolesGroup = new SimpleGroup(GROUP_NAME_ROLES);
|
||||
subject.getPrincipals().add(rolesGroup);
|
||||
// add the caller groups
|
||||
for (String role : roles) {
|
||||
SimpleGroup group = new SimpleGroup(role);
|
||||
group.addMember(principal);
|
||||
rolesGroup.addMember(group);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean abort() throws LoginException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean logout() throws LoginException {
|
||||
// throw away all state held for the principal
|
||||
subject.getPrincipals().clear();
|
||||
// this is probably hacky: clear the security context
|
||||
SecurityContextAssociation.clearSecurityContext();
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-31
@@ -1,39 +1,23 @@
|
||||
package com.mowesta.service.test.session;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.location.*;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.jboss.vfs.VFS;
|
||||
import org.jboss.vfs.VirtualFile;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Tests whether the forcasts can be imported.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
//@SuppressWarnings({"serial", "ResultOfMethodCallIgnored"})
|
||||
//@RunWith(Arquillian.class)
|
||||
public class CurrentWeatherSessionTest extends AbstractSessionTest {
|
||||
//
|
||||
//
|
||||
// @EJB
|
||||
// protected TestWeatherSyncSessionBean weatherSyncSessionBean;
|
||||
//
|
||||
//
|
||||
// @EJB
|
||||
// protected CurrentWeatherSessionBean currentWeatherSessionBean;
|
||||
//
|
||||
//
|
||||
// @EJB
|
||||
// protected LocationSessionBean locationSessionBean;
|
||||
//
|
||||
//
|
||||
// @Before
|
||||
// public void setUp() throws Exception {
|
||||
// tearDown();
|
||||
@@ -53,7 +37,7 @@ public class CurrentWeatherSessionTest extends AbstractSessionTest {
|
||||
// weatherSyncSessionBean.syncCurrentWeather();
|
||||
// weatherSyncSessionBean.syncWeatherForecast();
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @After
|
||||
// public void tearDown() throws IOException {
|
||||
// final File tempFolder = weatherSyncSessionBean.getTempFolder();
|
||||
@@ -65,27 +49,27 @@ public class CurrentWeatherSessionTest extends AbstractSessionTest {
|
||||
// }
|
||||
// tempFolder.getParentFile().delete();
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @Test
|
||||
// public void testCurrentWeatherSession() {
|
||||
// final PageConfig pageConfig = new PageConfig(0, 5);
|
||||
// final CityPage cityPage = locationSessionBean.getAllCities(pageConfig, false);
|
||||
// final StatePage statePage = locationSessionBean.getAllStates(pageConfig, false);
|
||||
// final CountryPage countryPage = locationSessionBean.getAllCountries(pageConfig, false);
|
||||
//
|
||||
//
|
||||
// final List<City> cities = cityPage.getElements();
|
||||
// final List<State> states = statePage.getElements();
|
||||
// final List<Country> countries = countryPage.getElements();
|
||||
//
|
||||
//
|
||||
// final Random random = new Random();
|
||||
// final City city = cities.get(random.nextInt(cities.size()));
|
||||
// final State state = states.get(random.nextInt(states.size()));
|
||||
// final Country country = countries.get(random.nextInt(countries.size()));
|
||||
//
|
||||
//
|
||||
// final CurrentWeather currentWeatherCity = currentWeatherSessionBean.findByCity(city, false);
|
||||
// final CurrentWeather currentWeatherState = currentWeatherSessionBean.findByState(state, false);
|
||||
// final CurrentWeather currentWeatherCountry = currentWeatherSessionBean.findByCountry(country, false);
|
||||
//
|
||||
//
|
||||
// Assert.assertNotNull("Should contain a CurrentWeather Entity.", currentWeatherCity);
|
||||
// Assert.assertNotNull("Should contain a CurrentWeather Entity.", currentWeatherState);
|
||||
// Assert.assertNotNull("Should contain a CurrentWeather Entity.", currentWeatherCountry);
|
||||
|
||||
+6
-7
@@ -16,8 +16,6 @@ import java.util.stream.Collectors;
|
||||
import javax.ejb.EJB;
|
||||
import javax.ejb.EJBAccessException;
|
||||
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -29,12 +27,14 @@ import com.mowesta.api.device.DeviceHandle;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
|
||||
/**
|
||||
* Runs tests on the measurement session.
|
||||
*
|
||||
*
|
||||
* @author Sebastian
|
||||
*/
|
||||
@SuppressWarnings("javadoc")
|
||||
@@ -77,7 +77,7 @@ public class MeasurementSessionTest extends AbstractSessionTest {
|
||||
if (count % 2 == 0) {
|
||||
measurementSession.addCurrentDeviceMeasurement(createMeasurement(time + i));
|
||||
} else {
|
||||
measurementSession.addCurrentDeviceMeasurements(Collections.singletonList(createMeasurement(time + i)));
|
||||
measurementSession.addCurrentDeviceMeasurements(Collections.singletonList(createMeasurement(time + i)));
|
||||
}
|
||||
}
|
||||
MeasurementPage p = null;
|
||||
@@ -90,7 +90,7 @@ public class MeasurementSessionTest extends AbstractSessionTest {
|
||||
}
|
||||
if (!success)
|
||||
fail();
|
||||
|
||||
|
||||
assertEquals("Should have correct number of entries.", count, p.getTotal());
|
||||
for (int i = 0; i < count; i++) {
|
||||
checkMeasurement(p.getElements().get(i), time + (count - 1 - i));
|
||||
@@ -249,8 +249,7 @@ public class MeasurementSessionTest extends AbstractSessionTest {
|
||||
initRangedMeasurementsForUser("friend", time, entryCount);
|
||||
executeAs("handte", () -> {
|
||||
try {
|
||||
final MeasurementPage page = measurementSession
|
||||
.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 10), false);
|
||||
measurementSession.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 10), false);
|
||||
} catch (EJBAccessException e) {
|
||||
assertNotNull("Should deny access to ordinary user.", e);
|
||||
}
|
||||
|
||||
+63
-48
@@ -1,21 +1,14 @@
|
||||
package com.mowesta.service.test.session;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.weather.WeatherSource;
|
||||
import com.mowesta.api.weather.WeatherReportPage;
|
||||
import com.mowesta.api.weather.WeatherStation;
|
||||
import com.mowesta.api.weather.WeatherStationPage;
|
||||
import com.mowesta.api.weather.WeatherType;
|
||||
import com.mowesta.api.weather.WindDirection;
|
||||
import com.mowesta.service.entity.*;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
import com.mowesta.service.session.sync.PeriodicSyncSessionBean;
|
||||
import com.mowesta.service.session.sync.PeriodicSyncSessionBean.JobType;
|
||||
import com.mowesta.service.session.sync.WeatherReportSyncSessionBean;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
import org.hibernate.search.jpa.Search;
|
||||
import org.hibernate.search.spatial.impl.Point;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.jboss.vfs.VFS;
|
||||
import org.jboss.vfs.VirtualFile;
|
||||
@@ -25,37 +18,44 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.weather.WeatherReportPage;
|
||||
import com.mowesta.api.weather.WeatherStation;
|
||||
import com.mowesta.api.weather.WeatherStationPage;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
import com.mowesta.service.session.sync.PeriodicSyncSessionBean;
|
||||
import com.mowesta.service.session.sync.PeriodicSyncSessionBean.JobType;
|
||||
import com.mowesta.service.session.sync.WeatherReportSyncSessionBean;
|
||||
|
||||
@SuppressWarnings({"serial", "ResultOfMethodCallIgnored"})
|
||||
/**
|
||||
* Tests the import of data from weather stations.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@RunWith(Arquillian.class)
|
||||
//TODO check expected values and split the test in smaller parts
|
||||
public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
/**
|
||||
* The entity manager
|
||||
*/
|
||||
@Inject
|
||||
protected EntityManager em;
|
||||
|
||||
|
||||
@Inject
|
||||
protected PeriodicSyncSessionBean periodicSyncSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected WeatherReportSyncSessionBean reportSyncSession;
|
||||
|
||||
|
||||
@Inject
|
||||
protected WeatherSessionBean weatherSession;
|
||||
|
||||
|
||||
/**
|
||||
* Unpacks files in a temp folder.
|
||||
*
|
||||
* @throws Exception Thrown if something fails.
|
||||
*/
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
tearDown();
|
||||
@@ -75,7 +75,12 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
}
|
||||
periodicSyncSession.executeSync(JobType.REPORT);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deletes the files from the temp folder.
|
||||
*
|
||||
* @throws IOException Should not be thrown.
|
||||
*/
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
final File tempFolder = reportSyncSession.getTempFolder();
|
||||
@@ -87,7 +92,12 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
tempFolder.delete();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks that all data is imported.
|
||||
*
|
||||
* @throws EntityNotFoundException Should not be thrown.
|
||||
*/
|
||||
@Test
|
||||
public void testCorrectAmountOfData() throws EntityNotFoundException {
|
||||
WeatherStationPage stations = weatherSession.getStations(null, new PageConfig(0, 20), false);
|
||||
@@ -99,9 +109,14 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
Assert.assertEquals("Should have " + expect + " reports.", expect, reports.getTotal());
|
||||
Assert.assertEquals("Should retrieve " + expect + " reports.", expect, reports.getElements().size());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that importing the same data twice does not result in duplicate data.
|
||||
*
|
||||
* @throws EntityNotFoundException Should not be thrown.
|
||||
*/
|
||||
@Test
|
||||
public void testDuplicateImportDoesNotAddData() throws EntityNotFoundException {
|
||||
WeatherStationPage stations1 = weatherSession.getStations("", new PageConfig(0, 20), false);
|
||||
@@ -113,56 +128,56 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
WeatherReportPage reports2 = weatherSession.getReports(stations1.getElements().get(0).getId(), new TimeRange(0, Long.MAX_VALUE), new PageConfig(0, 20), false);
|
||||
Assert.assertEquals("No measurements should be added.", reports1.getTotal(), reports2.getTotal());
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
//
|
||||
// @Test
|
||||
// public void testWeatherSync() throws IOException, InterruptedException {
|
||||
// final EmbeddedCoordinate coordiante = new EmbeddedCoordinate(7.0158171d,51.4582235d);
|
||||
// final AbstractLocationEntity location = new AbstractLocationEntity(){{setCoordinate(coordiante);}};
|
||||
//
|
||||
//
|
||||
// final WeatherReportEntity currentWeatherForLocation = testCurrentWeatherInDB(coordiante, location);
|
||||
// final List<WeatherForecastEntity> currentWeatherForecastsForLocation = testWeatherForecastInDB(coordiante, location);
|
||||
//
|
||||
//
|
||||
// weatherSyncSessionBean.syncCurrentWeather();
|
||||
// weatherSyncSessionBean.syncWeatherForecast();
|
||||
// Search.getFullTextEntityManager(em).createIndexer().startAndWait();
|
||||
//
|
||||
//
|
||||
// final WeatherReportEntity newCurrentWeatherForLocation = testCurrentWeatherInDB(coordiante, location);
|
||||
// final List<WeatherForecastEntity> newCurrentWeatherForecastsForLocation = testWeatherForecastInDB(coordiante, location);
|
||||
//
|
||||
//
|
||||
// Assert.assertNotEquals("The previous current weather was not deleted", currentWeatherForLocation.getId(), newCurrentWeatherForLocation.getId());
|
||||
// for (WeatherForecastEntity newCurrentWeatherForecastForLocation : newCurrentWeatherForecastsForLocation) {
|
||||
// final boolean foundWithSameId = currentWeatherForecastsForLocation.stream().mapToLong(AbstractEntity::getId).anyMatch(l -> newCurrentWeatherForecastForLocation.getId() == l);
|
||||
// Assert.assertFalse("The previous weather forecast was not deleted", foundWithSameId);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private WeatherReportEntity testCurrentWeatherInDB(EmbeddedCoordinate coordiante, AbstractLocationEntity location) {
|
||||
// int countCurrent = WeatherReportEntity.getCount(em, WeatherReportEntity.class, false);
|
||||
// Assert.assertNotEquals("No current weather entity found in DB", 0, countCurrent);
|
||||
// Assert.assertEquals("Wrong number of current weather entites found in DB", 6, countCurrent);
|
||||
//
|
||||
//
|
||||
// long a = System.currentTimeMillis();
|
||||
// final WeatherReportEntity currentWeatherForLocation = AbstractPositionEntity.findEntityNearPosition(em, WeatherReportEntity.class, location);
|
||||
// long b = System.currentTimeMillis();
|
||||
// log.log(Level.INFO, "Loading nearest current weather took " + (b-a) + "ms");
|
||||
//
|
||||
//
|
||||
// Assert.assertNotNull("No nearest weather found", currentWeatherForLocation);
|
||||
// Assert.assertEquals("Wrong nearest weather returned", new EmbeddedCoordinate(7.9126d, 52.4853d), currentWeatherForLocation.getCoordinate());
|
||||
// Assert.assertEquals("Wrong temperature", 8.8f, currentWeatherForLocation.getTemperature(), 0.05f);
|
||||
// return currentWeatherForLocation;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private List<WeatherForecastEntity> testWeatherForecastInDB(EmbeddedCoordinate coordiante, AbstractLocationEntity location) {
|
||||
// int countForecast = WeatherForecastEntity.getCount(em, WeatherForecastEntity.class, false);
|
||||
// Assert.assertNotEquals("No weather forecast entity found in DB", 0, countForecast);
|
||||
// Assert.assertEquals("Wrong number of weather forecast entities found in DB", 34, countForecast);
|
||||
//
|
||||
//
|
||||
// long a = System.currentTimeMillis();
|
||||
// final List<WeatherForecastEntity> weatherForecastEntities = AbstractPositionEntity.findEntitiesNearPosition(em, WeatherForecastEntity.class, location);
|
||||
// long b = System.currentTimeMillis();
|
||||
// log.log(Level.INFO, "Loading nearest weather foreacst took " + (b-a) + "ms");
|
||||
//
|
||||
//
|
||||
// Assert.assertNotNull("No weather forecasts found", weatherForecastEntities);
|
||||
// Assert.assertNotEquals("No weather forecasts found", 0, weatherForecastEntities.size());
|
||||
// final WeatherForecastEntity weatherForecastEntity = weatherForecastEntities.get(0);
|
||||
@@ -185,7 +200,7 @@ public class WeatherReportSyncTest extends AbstractSessionTest {
|
||||
// Assert.assertEquals("System type wrong", ForecastSource.ICON_GLOBAL, weatherForecastEntity.getPredictionSystemType());
|
||||
// Assert.assertEquals("Prediction start timestamp wrong", 1575936000L, weatherForecastEntity.getPredictionStartTimestamp());
|
||||
// Assert.assertEquals("Prediction duration wrong", TimeUnit.HOURS.toSeconds(1), weatherForecastEntity.getPredictionDuration());
|
||||
//
|
||||
//
|
||||
// return weatherForecastEntities;
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<!-- <property name="javaVmArguments">-Djboss.socket.binding.port-offset=1000 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y</property> -->
|
||||
<property name="javaVmArguments">-Djboss.socket.binding.port-offset=1000</property>
|
||||
<!-- configure the wildfly location and the logger -->
|
||||
<property name="jbossHome">../service-wildfly/wildfly-17.0.1.Final</property>
|
||||
<property name="jbossHome">../service-wildfly/wildfly-21.0.0.Final</property>
|
||||
<!-- <property name="java.util.logging.manager">org.jboss.logmanager.LogManager</property> -->
|
||||
<property name="serverConfig">../../../../service-ejb/src/test/resources/wildfly.xml</property>
|
||||
</configuration>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version='1.0' encoding='UTF-8'?>
|
||||
<server xmlns="urn:jboss:domain:10.0">
|
||||
|
||||
<server xmlns="urn:jboss:domain:14.0">
|
||||
<extensions>
|
||||
<extension module="org.jboss.as.clustering.infinispan"/>
|
||||
<extension module="org.jboss.as.connector"/>
|
||||
@@ -31,6 +32,7 @@
|
||||
<extension module="org.wildfly.extension.io"/>
|
||||
<extension module="org.wildfly.extension.microprofile.config-smallrye"/>
|
||||
<extension module="org.wildfly.extension.microprofile.health-smallrye"/>
|
||||
<extension module="org.wildfly.extension.microprofile.jwt-smallrye"/>
|
||||
<extension module="org.wildfly.extension.microprofile.metrics-smallrye"/>
|
||||
<extension module="org.wildfly.extension.microprofile.opentracing-smallrye"/>
|
||||
<extension module="org.wildfly.extension.request-controller"/>
|
||||
@@ -93,7 +95,7 @@
|
||||
</access-control>
|
||||
</management>
|
||||
<profile>
|
||||
<subsystem xmlns="urn:jboss:domain:logging:7.0">
|
||||
<subsystem xmlns="urn:jboss:domain:logging:8.0">
|
||||
<console-handler name="CONSOLE">
|
||||
<level name="INFO"/>
|
||||
<formatter>
|
||||
@@ -147,7 +149,7 @@
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:bean-validation:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:core-management:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:datasources:5.0">
|
||||
<subsystem xmlns="urn:jboss:domain:datasources:6.0">
|
||||
<datasources>
|
||||
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true" statistics-enabled="${wildfly.datasources.statistics-enabled:${wildfly.statistics-enabled:false}}">
|
||||
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
|
||||
@@ -168,14 +170,14 @@
|
||||
<deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:discovery:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:distributable-web:1.0" default-session-management="default" default-single-sign-on-management="default">
|
||||
<infinispan-session-management name="default" granularity="SESSION" cache-container="web">
|
||||
<subsystem xmlns="urn:jboss:domain:distributable-web:2.0" default-session-management="default" default-single-sign-on-management="default">
|
||||
<infinispan-session-management name="default" cache-container="web" granularity="SESSION">
|
||||
<primary-owner-affinity/>
|
||||
</infinispan-session-management>
|
||||
<infinispan-single-sign-on-management name="default" cache-container="web" cache="sso"/>
|
||||
<infinispan-routing cache-container="web" cache="routing"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:ee:4.0">
|
||||
<subsystem xmlns="urn:jboss:domain:ee:5.0">
|
||||
<spec-descriptor-property-replacement>false</spec-descriptor-property-replacement>
|
||||
<concurrent>
|
||||
<context-services>
|
||||
@@ -194,7 +196,7 @@
|
||||
<default-bindings context-service="java:jboss/ee/concurrency/context/default" datasource="java:jboss/datasources/ExampleDS" managed-executor-service="java:jboss/ee/concurrency/executor/default" managed-scheduled-executor-service="java:jboss/ee/concurrency/scheduler/default" managed-thread-factory="java:jboss/ee/concurrency/factory/default"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:ee-security:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:ejb3:5.0">
|
||||
<subsystem xmlns="urn:jboss:domain:ejb3:8.0">
|
||||
<session-bean>
|
||||
<stateless>
|
||||
<bean-instance-pool-ref pool-name="slsb-strict-max-pool"/>
|
||||
@@ -221,7 +223,7 @@
|
||||
<file-data-store name="default-file-store" path="timer-service-data" relative-to="jboss.server.data.dir"/>
|
||||
</data-stores>
|
||||
</timer-service>
|
||||
<remote connector-ref="http-remoting-connector" thread-pool-name="default">
|
||||
<remote cluster="ejb" connectors="http-remoting-connector" thread-pool-name="default">
|
||||
<channel-creation-options>
|
||||
<option name="MAX_OUTBOUND_MESSAGES" value="1234" type="remoting"/>
|
||||
</channel-creation-options>
|
||||
@@ -229,7 +231,7 @@
|
||||
<thread-pools>
|
||||
<thread-pool name="default">
|
||||
<max-threads count="10"/>
|
||||
<keepalive-time time="100" unit="milliseconds"/>
|
||||
<keepalive-time time="60" unit="seconds"/>
|
||||
</thread-pool>
|
||||
</thread-pools>
|
||||
<default-security-domain value="test"/>
|
||||
@@ -237,7 +239,7 @@
|
||||
<statistics enabled="${wildfly.ejb3.statistics-enabled:${wildfly.statistics-enabled:false}}"/>
|
||||
<log-system-exceptions value="true"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:wildfly:elytron:7.0" final-providers="combined-providers" disallowed-providers="OracleUcrypto">
|
||||
<subsystem xmlns="urn:wildfly:elytron:11.0" final-providers="combined-providers" disallowed-providers="OracleUcrypto">
|
||||
<providers>
|
||||
<aggregate-providers name="combined-providers">
|
||||
<providers name="elytron"/>
|
||||
@@ -337,48 +339,42 @@
|
||||
<provider-sasl-server-factory name="global"/>
|
||||
</sasl>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:infinispan:8.0">
|
||||
<subsystem xmlns="urn:jboss:domain:infinispan:11.0">
|
||||
<cache-container name="web" default-cache="passivation" module="org.wildfly.clustering.web.infinispan">
|
||||
<local-cache name="passivation">
|
||||
<locking isolation="REPEATABLE_READ"/>
|
||||
<transaction mode="BATCH"/>
|
||||
<file-store passivation="true" purge="false"/>
|
||||
</local-cache>
|
||||
<local-cache name="sso">
|
||||
<locking isolation="REPEATABLE_READ"/>
|
||||
<transaction mode="BATCH"/>
|
||||
</local-cache>
|
||||
<local-cache name="sso"/>
|
||||
<local-cache name="routing"/>
|
||||
</cache-container>
|
||||
<cache-container name="server" default-cache="default" module="org.wildfly.clustering.server">
|
||||
<local-cache name="default">
|
||||
<transaction mode="BATCH"/>
|
||||
</local-cache>
|
||||
</cache-container>
|
||||
<cache-container name="ejb" aliases="sfsb" default-cache="passivation" module="org.wildfly.clustering.ejb.infinispan">
|
||||
<local-cache name="passivation">
|
||||
<locking isolation="REPEATABLE_READ"/>
|
||||
<transaction mode="BATCH"/>
|
||||
<file-store passivation="true" purge="false"/>
|
||||
</local-cache>
|
||||
</cache-container>
|
||||
<cache-container name="server" default-cache="default" module="org.wildfly.clustering.server">
|
||||
<local-cache name="default"/>
|
||||
</cache-container>
|
||||
<cache-container name="hibernate" module="org.infinispan.hibernate-cache">
|
||||
<local-cache name="entity">
|
||||
<object-memory size="10000"/>
|
||||
<heap-memory size="10000"/>
|
||||
<expiration max-idle="100000"/>
|
||||
</local-cache>
|
||||
<local-cache name="local-query">
|
||||
<object-memory size="10000"/>
|
||||
<heap-memory size="10000"/>
|
||||
<expiration max-idle="100000"/>
|
||||
</local-cache>
|
||||
<local-cache name="timestamps"/>
|
||||
<local-cache name="pending-puts">
|
||||
<expiration max-idle="60000"/>
|
||||
</local-cache>
|
||||
</cache-container>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:io:3.0">
|
||||
<worker name="default"/>
|
||||
<buffer-pool name="default"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:jaxrs:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:jaxrs:2.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:jca:5.0">
|
||||
<archive-validation enabled="true" fail-on-error="true" fail-on-warn="false"/>
|
||||
<bean-validation enabled="true"/>
|
||||
@@ -408,15 +404,20 @@
|
||||
<jpa default-datasource="" default-extended-persistence-inheritance="DEEP"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:jsf:1.1"/>
|
||||
<subsystem xmlns="urn:jboss:domain:mail:3.0">
|
||||
<subsystem xmlns="urn:jboss:domain:mail:4.0">
|
||||
<mail-session name="default" jndi-name="java:jboss/mail/Default">
|
||||
<smtp-server outbound-socket-binding-ref="mail-smtp"/>
|
||||
</mail-session>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-config-smallrye:1.0"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-health-smallrye:1.0" security-enabled="false"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-health-smallrye:2.0" security-enabled="false" empty-liveness-checks-status="${env.MP_HEALTH_EMPTY_LIVENESS_CHECKS_STATUS:UP}" empty-readiness-checks-status="${env.MP_HEALTH_EMPTY_READINESS_CHECKS_STATUS:UP}"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-jwt-smallrye:1.0"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-metrics-smallrye:2.0" security-enabled="false" exposed-subsystems="*" prefix="${wildfly.metrics.prefix:wildfly}"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-opentracing-smallrye:1.0"/>
|
||||
<subsystem xmlns="urn:wildfly:microprofile-opentracing-smallrye:3.0" default-tracer="jaeger">
|
||||
<jaeger-tracer name="jaeger">
|
||||
<sampler-configuration sampler-type="const" sampler-param="1.0"/>
|
||||
</jaeger-tracer>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:naming:2.0">
|
||||
<remote-naming/>
|
||||
</subsystem>
|
||||
@@ -425,30 +426,21 @@
|
||||
<http-connector name="http-remoting-connector" connector-ref="default" security-realm="ApplicationRealm"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:request-controller:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:resource-adapters:5.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:resource-adapters:6.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:sar:1.0"/>
|
||||
<subsystem xmlns="urn:jboss:domain:security:2.0">
|
||||
<security-domains>
|
||||
<security-domain name="test">
|
||||
<authentication>
|
||||
<!--
|
||||
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
|
||||
<module-option name="dsJndiName" value="java:jboss/datasources/ExampleDS"/>
|
||||
<module-option name="principalsQuery" value="select 'password' from user where login=?"/>
|
||||
<module-option name="rolesQuery" value="select r.name,'Roles' from user as u, user_role as ur, role as r where u.login=? and u.id = ur.user_id and ur.role_id = r.id"/>
|
||||
</login-module>
|
||||
-->
|
||||
<login-module code="com.mowesta.service.test.login.LoginModule" flag="required" />
|
||||
<login-module code="org.jboss.security.ClientLoginModule" flag="required">
|
||||
<module-option name="password-stacking" value="true"/>
|
||||
</login-module>
|
||||
|
||||
</authentication>
|
||||
<authorization>
|
||||
<authentication>
|
||||
<login-module code="com.mowesta.service.test.login.LoginModule" flag="required" />
|
||||
<login-module code="org.jboss.security.ClientLoginModule" flag="required">
|
||||
<module-option name="password-stacking" value="true"/>
|
||||
</login-module>
|
||||
</authentication>
|
||||
<authorization>
|
||||
<policy-module code="JACC" flag="required"/>
|
||||
</authorization>
|
||||
</security-domain>
|
||||
|
||||
</authorization>
|
||||
</security-domain>
|
||||
<security-domain name="other" cache-type="default">
|
||||
<authentication>
|
||||
<login-module code="Remoting" flag="optional">
|
||||
@@ -496,7 +488,7 @@
|
||||
<coordinator-environment statistics-enabled="${wildfly.transactions.statistics-enabled:${wildfly.statistics-enabled:false}}"/>
|
||||
<object-store path="tx-object-store" relative-to="jboss.server.data.dir"/>
|
||||
</subsystem>
|
||||
<subsystem xmlns="urn:jboss:domain:undertow:9.0" default-server="default-server" default-virtual-host="default-host" default-servlet-container="default" default-security-domain="other" statistics-enabled="${wildfly.undertow.statistics-enabled:${wildfly.statistics-enabled:false}}">
|
||||
<subsystem xmlns="urn:jboss:domain:undertow:11.0" default-server="default-server" default-virtual-host="default-host" default-servlet-container="default" default-security-domain="other" statistics-enabled="${wildfly.undertow.statistics-enabled:${wildfly.statistics-enabled:false}}">
|
||||
<buffer-cache name="default"/>
|
||||
<server name="default-server">
|
||||
<http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
|
||||
@@ -535,15 +527,15 @@
|
||||
</interface>
|
||||
</interfaces>
|
||||
<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
|
||||
<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
|
||||
<socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
|
||||
<socket-binding name="ajp" port="${jboss.ajp.port:8009}"/>
|
||||
<socket-binding name="http" port="${jboss.http.port:8080}"/>
|
||||
<socket-binding name="https" port="${jboss.https.port:8443}"/>
|
||||
<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
|
||||
<socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
|
||||
<socket-binding name="txn-recovery-environment" port="4712"/>
|
||||
<socket-binding name="txn-status-manager" port="4713"/>
|
||||
<outbound-socket-binding name="mail-smtp">
|
||||
<remote-destination host="localhost" port="25"/>
|
||||
<remote-destination host="${jboss.mail.server.host:localhost}" port="${jboss.mail.server.port:25}"/>
|
||||
</outbound-socket-binding>
|
||||
</socket-binding-group>
|
||||
</server>
|
||||
</server>
|
||||
@@ -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;
|
||||
@@ -0,0 +1,21 @@
|
||||
description = 'Mowesta Service Jpa'
|
||||
|
||||
dependencies {
|
||||
compileOnly "org.hibernate:hibernate-core:${versionHibernate}"
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes(
|
||||
'Built-By' : System.properties['user.name'],
|
||||
'Build-Timestamp': new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()),
|
||||
'Created-By' : "Gradle ${gradle.gradleVersion}",
|
||||
'Build-Jdk' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})",
|
||||
'Build-OS' : "${System.properties['os.name']} ${System.properties['os.arch']} ${System.properties['os.version']}",
|
||||
'Implementation-Build' : "${System.properties['jenkins.build.number']}",
|
||||
'Dependencies': 'org.hibernate',
|
||||
'Implementation-Version' : project.version,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.mowesta.service.injection;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
|
||||
import org.hibernate.jpa.HibernatePersistenceProvider;
|
||||
|
||||
/**
|
||||
* This class implements a wrapper around the hibernate persistence provider
|
||||
* that automatically sets the hibernate search file index base using an
|
||||
* entry in the naming service of the container. Note that this functionality
|
||||
* cannot be implemented at a higher level of abstraction since hibernate search
|
||||
* will initialize itself as soon as the entity manager factory is created.
|
||||
* This means that we actually need to replace the provider to ensure that
|
||||
* the property is set at an early stage during the application startup.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PersistenceProvider extends HibernatePersistenceProvider {
|
||||
|
||||
/**
|
||||
* The hibernate search property to set the index base.
|
||||
*/
|
||||
private static final String KEY_LUCENE = "hibernate.search.default.indexBase";
|
||||
|
||||
/**
|
||||
* The name entry used to find the configuration of the lucene folder.
|
||||
*/
|
||||
private static final String NAME_LUCENE = "java:global/mowesta/folderLucene";
|
||||
|
||||
/**
|
||||
* The default value for the configuration of the lucene folder.
|
||||
*/
|
||||
private static final String VALUE_LUCENE = "/var/lucene/mowesta";
|
||||
|
||||
/**
|
||||
* The logger to generate debug output.
|
||||
*/
|
||||
private Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
|
||||
logger.log(Level.INFO, "Creating entity manager factory.");
|
||||
if (! properties.containsKey(KEY_LUCENE)) {
|
||||
properties.put(KEY_LUCENE, getLuceneFolder());
|
||||
}
|
||||
logger.log(Level.INFO, "Setting lucene folder to: " + properties.get(KEY_LUCENE));
|
||||
return super.createContainerEntityManagerFactory(info, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lucene folder from the name service
|
||||
* or the default value, if the name is not bound.
|
||||
*
|
||||
* @return The lucene folder used as index base.
|
||||
*/
|
||||
private String getLuceneFolder() {
|
||||
try {
|
||||
InitialContext ctx = new InitialContext();
|
||||
Object v = ctx.lookup(NAME_LUCENE);
|
||||
if (v instanceof String) {
|
||||
return (String)v;
|
||||
}
|
||||
} catch (NamingException e) {
|
||||
// ignore unbound value
|
||||
}
|
||||
return VALUE_LUCENE;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user