Compare commits
175
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84ce2ebbdf | ||
|
|
67b6344b2e | ||
|
|
36a888474c | ||
|
|
17fcbd3cd8 | ||
|
|
d5617a3a0d | ||
|
|
4bc4b05991 | ||
|
|
59eec77e07 | ||
|
|
cffe16e153 | ||
|
|
dc40ec2e5b | ||
|
|
a11656b7b7 | ||
|
|
1ab99c816d | ||
|
|
01d60700ec | ||
|
|
5100a320c4 | ||
|
|
1c7d7e48e0 | ||
|
|
348b46681f | ||
|
|
792a67e6dd | ||
|
|
782c759fb8 | ||
|
|
c69fb5dfdc | ||
|
|
f5b49e2ca3 | ||
|
|
29fcc0fe8f | ||
|
|
f0231235f8 | ||
|
|
46cc9f83ac | ||
|
|
c10871016e | ||
|
|
5a3b0a62f6 | ||
|
|
ecd2119da9 | ||
|
|
d34a88943a | ||
|
|
6a611d57d3 | ||
|
|
9588da3454 | ||
|
|
c0106a720d | ||
|
|
12168e5dc4 | ||
|
|
ed050db16a | ||
|
|
9d0989afb1 | ||
|
|
eb593c8aed | ||
|
|
10aa8a25e6 | ||
|
|
a3e213eea2 | ||
|
|
7b81e8a3ec | ||
|
|
99456ddbf6 | ||
|
|
9849d7c51e | ||
|
|
6de6599924 | ||
|
|
53938dbde8 | ||
|
|
7cd403bc4c | ||
|
|
a2233f477a | ||
|
|
e3d0122fb0 | ||
|
|
327a6eb9e4 | ||
|
|
92eb61828f | ||
|
|
393f2a6304 | ||
|
|
c14c243043 | ||
|
|
a9863fa495 | ||
|
|
532a7cf35e | ||
|
|
751544c0df | ||
|
|
549c4b559b | ||
|
|
c4b92b734c | ||
|
|
ff763ec44c | ||
|
|
912151ef2d | ||
|
|
f341e8eb10 | ||
|
|
64af6ae5aa | ||
|
|
1d64d0bd23 | ||
|
|
bc19ba5fd0 | ||
|
|
aea6edd08b | ||
|
|
9b62b46e0e | ||
|
|
dcad963c7c | ||
|
|
6749700b34 | ||
|
|
f66a6e8a49 | ||
|
|
51931b979f | ||
|
|
d863b0927e | ||
|
|
bfaf634148 | ||
|
|
e8760938af | ||
|
|
5bb3275a54 | ||
|
|
d5362ff41d | ||
|
|
949a0d2770 | ||
|
|
8af818ffbe | ||
|
|
ac8b771ecf | ||
|
|
3f25520284 | ||
|
|
2ef558894f | ||
|
|
b68b63a110 | ||
|
|
9f2ec5fb38 | ||
|
|
9564586f97 | ||
|
|
4fdfeec9a5 | ||
|
|
ffb4b56073 | ||
|
|
b0d71102f3 | ||
|
|
c784c85909 | ||
|
|
b977a80ecc | ||
|
|
f3251a4139 | ||
|
|
d5b82cddc8 | ||
|
|
7ad855a4aa | ||
|
|
9826392819 | ||
|
|
9e8a519bc7 | ||
|
|
2029d47b29 | ||
|
|
0622b4cbc5 | ||
|
|
474432d2a7 | ||
|
|
135afc064b | ||
|
|
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 | ||
|
|
84fd69dfdb | ||
|
|
8c174f8581 | ||
|
|
6bd040272b | ||
|
|
2d2caaed09 | ||
|
|
cf99d87a66 | ||
|
|
778677ec40 | ||
|
|
485f56e547 | ||
|
|
13080b113b | ||
|
|
d1fc3bee96 | ||
|
|
8bd0cf7bc2 | ||
|
|
c306987b63 | ||
|
|
84beb97a73 | ||
|
|
82b7b5544d | ||
|
|
942e42ae76 | ||
|
|
ed8846d950 | ||
|
|
6bd27b2eff | ||
|
|
ef86399ba3 | ||
|
|
6b5f85fe5f | ||
|
|
822f4044f7 | ||
|
|
7414860ace | ||
|
|
582c1c6468 | ||
|
|
192836a763 | ||
|
|
5539048c54 | ||
|
|
61bb009959 | ||
|
|
843b52b468 | ||
|
|
1487957ea4 | ||
|
|
daf517bc6a | ||
|
|
c45b14d35a | ||
|
|
4734c0f7b7 | ||
|
|
0272fb770e | ||
|
|
0b357be701 | ||
|
|
de8a4b8360 | ||
|
|
83dc34fb53 | ||
|
|
8a306727a7 | ||
|
|
3a2eadad70 | ||
|
|
6017db7599 | ||
|
|
bc29648790 | ||
|
|
0ba90a0bb2 | ||
|
|
3ec70113e6 | ||
|
|
0c3b968aee |
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 == "feature/auth") {
|
||||
echo "Deploying to beta server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-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-alpha01'
|
||||
versionAndroidXSecurity = '1.1.0-alpha03'
|
||||
versionAndroidXViewpager = '1.0.0'
|
||||
versionGoogleMaterial = '1.1.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 8
|
||||
versionCode 12
|
||||
versionName "${version}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
@@ -148,6 +149,7 @@ android {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
+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
|
||||
|
||||
@@ -45,13 +45,7 @@ public class CityInfoFragment extends CityFragment.ChildFragment {
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
FragmentCityInfoBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_city_info, container, false);
|
||||
MapView mapView = binding.getRoot().findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
// reduce brightness of map (technically, we should generate a night mode in leafless but this needs to be fixed in the library)
|
||||
if (getResources().getBoolean(R.bool.dark_mode)) {
|
||||
mapView.setAlpha(0.5f);
|
||||
} else {
|
||||
mapView.setAlpha(1f);
|
||||
}
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
CityViewModel model = new ViewModelProvider(getParentFragment().getParentFragment()).get(CityViewModel.class);
|
||||
ConditionViewModel condition = new ViewModelProvider(this).get(ConditionViewModel.class);
|
||||
Runnable updateCondition = () -> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -109,7 +109,7 @@ public class CountryFragment extends AbstractPlaceFragment {
|
||||
model.getCities().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
MapViewUtil.removePolylines(mapView, polylines);
|
||||
polylines.clear();
|
||||
|
||||
@@ -52,7 +52,16 @@ public class LoginFragment extends Fragment {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_devices, null, b.build());
|
||||
break;
|
||||
case COLLECTION:
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
try {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// this is most likely bug in the navigation library, since it cannot find the
|
||||
// node in the xml file which is technically impossible (probably a race during loading)
|
||||
NavOptions.Builder builder = new NavOptions.Builder().setPopUpTo(R.id.destination_login, true);
|
||||
builder.setEnterAnim(R.anim.slide_in_right);
|
||||
builder.setExitAnim(R.anim.slide_out_left);
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_collection, null, builder.build());
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -108,7 +108,7 @@ public class StateFragment extends AbstractPlaceFragment {
|
||||
model.getCities().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
MapViewUtil.removePolylines(mapView, polylines);
|
||||
polylines.clear();
|
||||
|
||||
@@ -122,7 +122,7 @@ public class StationFragment extends AbstractDiagramFragment {
|
||||
model.getReports().observe(getViewLifecycleOwner(), (list) -> adapter.submitList(list));
|
||||
recyclerView.setAdapter(adapter);
|
||||
MapView mapView = view.findViewById(R.id.map_detail);
|
||||
MapViewUtil.setupInteractiveMap(mapView);
|
||||
MapViewUtil.setupInteractiveMap(mapView, getResources().getBoolean(R.bool.dark_mode));
|
||||
Runnable updateMap = () -> {
|
||||
if (model.getStation().getValue() != null) {
|
||||
WeatherStation s = model.getStation().getValue();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -34,9 +34,14 @@ import java.util.List;
|
||||
public class MapViewUtil {
|
||||
|
||||
/**
|
||||
* The url.
|
||||
* The url for a light mode tile map.
|
||||
*/
|
||||
private static final String URL = "https://cloud.locoslab.com/carta/get/{z}/{x}/{y}.png";
|
||||
private static final String URL_LIGHT = "https://www.mowesta.com/carta/tile/{z}/{x}/{y}.png";
|
||||
|
||||
/**
|
||||
* The url for a dark mode tile map.
|
||||
*/
|
||||
private static final String URL_DARK = "https://www.mowesta.com/carta/tile/dark/{z}/{x}/{y}.png";
|
||||
|
||||
|
||||
/**
|
||||
@@ -153,7 +158,7 @@ public class MapViewUtil {
|
||||
*/
|
||||
public static void setupNonInteractiveMap(MapView mapView) {
|
||||
setupInteraction(mapView, false);
|
||||
setupTileLayer(mapView);
|
||||
setupTileLayer(mapView, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,19 +181,21 @@ public class MapViewUtil {
|
||||
* Configures an interactive map view.
|
||||
*
|
||||
* @param mapView The map view.
|
||||
* @param darkMode True to enable dark mode, false otherwise
|
||||
*/
|
||||
public static void setupInteractiveMap(MapView mapView) {
|
||||
public static void setupInteractiveMap(MapView mapView, boolean darkMode) {
|
||||
setupInteraction(mapView, true);
|
||||
setupTileLayer(mapView);
|
||||
setupTileLayer(mapView, darkMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a tile layer to the map.
|
||||
*
|
||||
* @param mapView The map view.
|
||||
* @param darkMode True to use dark mode.
|
||||
*/
|
||||
private static void setupTileLayer(MapView mapView) {
|
||||
TileLayerOptions options = new TileLayerOptions(URL);
|
||||
private static void setupTileLayer(MapView mapView, boolean darkMode) {
|
||||
TileLayerOptions options = new TileLayerOptions(darkMode?URL_DARK:URL_LIGHT);
|
||||
options.minZoom = 4;
|
||||
options.maxZoom = 18;
|
||||
TileLayer layer = new TileLayer(options);
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -177,10 +177,10 @@
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="1.1.2000 11:00"
|
||||
tools:text="Donnerstag | 11:00"
|
||||
android:id="@+id/gradient_time"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:singleLine="true"
|
||||
android:ellipsize="middle"
|
||||
android:gravity="center_horizontal|bottom"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
|
||||
@@ -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,14 +218,15 @@ 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();
|
||||
repository = SdkRepository.getInstance(this.getApplication());
|
||||
capabilityManager = new CapabilityManager(getApplication());
|
||||
channelManager = new ChannelManager(getApplication());
|
||||
channelManager.createChannel();
|
||||
startForeground(channelManager.getNotificationId(), channelManager.createNotification(R.string.mowesta_sdk_notification_content_idle));
|
||||
repository = SdkRepository.getInstance(this.getApplication());
|
||||
capabilityManager = new CapabilityManager(getApplication());
|
||||
repository.getUploading().observeForever(uploadListener);
|
||||
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
|
||||
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
|
||||
@@ -635,6 +637,10 @@ public abstract class SdkService extends Service {
|
||||
// cleanup based on type
|
||||
if (currentState == State.GPS) cleanupGps();
|
||||
if (currentState == State.NET) cleanupNet();
|
||||
// workaround locations that might be buffered already
|
||||
// in the location listeners buffer which can cause
|
||||
// two locations to be sent despite deactivation
|
||||
if (measurement == null) return;
|
||||
Coordinate c = new Coordinate();
|
||||
c.setLatitude(location.getLatitude());
|
||||
c.setLongitude(location.getLongitude());
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+34
-39
@@ -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.8'
|
||||
version = '1.0.12-SNAPSHOT'
|
||||
|
||||
// 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,12 +50,13 @@ allprojects {
|
||||
// other frameworks
|
||||
mapstructVersion = '1.3.1.Final'
|
||||
// shared android dependencies
|
||||
versionAndroidXTest = '1.2.0'
|
||||
versionAndroidXAppcompat = '1.1.0'
|
||||
versionAndroidXRoom = '2.2.5'
|
||||
versionAndroidXTest = '1.3.0'
|
||||
versionAndroidXAppcompat = '1.2.0'
|
||||
versionAndroidXRoom = '2.2.6'
|
||||
versionAndroidXPreference = '1.1.1'
|
||||
versionRobolectric = '4.3.1'
|
||||
|
||||
versionRobolectric = '4.5'
|
||||
//oauth dependencies
|
||||
versionJWT = '0.11.2'
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +80,7 @@ subprojects {
|
||||
publications {
|
||||
maven(MavenPublication) {
|
||||
artifact file('build/outputs/aar/android-sdk-release.aar')
|
||||
version = project.version
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,32 +118,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") { }
|
||||
|
||||
@@ -32,6 +32,7 @@ swagger {
|
||||
'com.mowesta.api.measurement.IMeasurementService',
|
||||
'com.mowesta.api.settings.ISettingsService',
|
||||
'com.mowesta.api.user.IUserService',
|
||||
'com.mowesta.api.oauth2.IOAuth2Service',
|
||||
'com.mowesta.api.version.IVersionService',
|
||||
'com.mowesta.api.weather.IWeatherService',
|
||||
]
|
||||
|
||||
@@ -43,6 +43,11 @@ public class Tags {
|
||||
*/
|
||||
public static final String SETTINGS = "Settings";
|
||||
|
||||
/**
|
||||
* Tag for OAuth.
|
||||
*/
|
||||
public static final String OAUTH = "OAuth";
|
||||
|
||||
|
||||
/**
|
||||
* Prevent instantiation.
|
||||
|
||||
@@ -2,61 +2,66 @@ package com.mowesta.api.access;
|
||||
|
||||
/**
|
||||
* The user roles used by the application.
|
||||
*
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Roles {
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the admin role.
|
||||
*/
|
||||
public static final String ADMIN = "admin";
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the user role.
|
||||
*/
|
||||
public static final String USER = "user";
|
||||
|
||||
|
||||
/**
|
||||
* The string value of the device role.
|
||||
*/
|
||||
public static final String DEVICE = "device";
|
||||
|
||||
/**
|
||||
* The role granted to valid services that may
|
||||
* use oauth to authenticate for a user.
|
||||
*/
|
||||
public static final String SERVICE = "service";
|
||||
|
||||
/**
|
||||
* Prevents accidential instantiation.
|
||||
*/
|
||||
private Roles() { }
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of roles used for human
|
||||
* subjects.
|
||||
*
|
||||
*
|
||||
* @return The roles used for humans.
|
||||
*/
|
||||
public static String[] getHumanRoles() {
|
||||
return new String[] { ADMIN, USER };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of roles used for machines.
|
||||
*
|
||||
*
|
||||
* @return The roles used for machines.
|
||||
*/
|
||||
public static String[] getMachineRoles() {
|
||||
return new String[] { DEVICE };
|
||||
return new String[] { DEVICE, SERVICE };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the names of all roles.
|
||||
*
|
||||
*
|
||||
* @return The names of all roles.
|
||||
*/
|
||||
public static String[] getAllRoles() {
|
||||
return new String[] { ADMIN, USER, DEVICE };
|
||||
return new String[] { ADMIN, USER, DEVICE, SERVICE };
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -104,7 +104,7 @@ public interface IMeasurementService {
|
||||
*/
|
||||
@GET
|
||||
@Path("devices/{id: ([0-9])+}/measurements")
|
||||
@ApiOperation(value = "Returns a page of measurements of a specific device from a certain time range.", authorizations = {
|
||||
@ApiOperation(value = "Returns a page of measurements of a specific device from a certain time range.",authorizations = {
|
||||
@Authorization(Authorizations.USER), @Authorization(Authorizations.ADMIN) }, tags = { Tags.DEFAULT, Tags.DEVICE })
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Measurements retrieved successfully.", response = MeasurementPage.class),
|
||||
@@ -113,4 +113,21 @@ public interface IMeasurementService {
|
||||
@RolesAllowed({ Roles.USER, Roles.ADMIN })
|
||||
Response getDeviceMeasurements(@ApiParam(value = "The device id.", required = true) @PathParam("id") long id, @BeanParam @Valid TimeRange timeRange, @BeanParam @Valid PageConfig pageConfig);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a page of measurements of all devices within a certain time range.
|
||||
*
|
||||
* @param timeRange The time range.
|
||||
* @param pageConfig The page config.
|
||||
* @return The page of measurements.
|
||||
*/
|
||||
@GET
|
||||
@Path("devices/measurements")
|
||||
@ApiOperation(value = "Returns a page of measurements of all devices within a certain time range.",
|
||||
authorizations = { @Authorization(Authorizations.ADMIN) }, tags = { Tags.DEFAULT, Tags.DEVICE })
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Measurements retrieved successfully.", response = MeasurementPage.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges to retrieve the measurements.") })
|
||||
@RolesAllowed({ Roles.ADMIN })
|
||||
Response getAllMeasurementsByRange(@BeanParam @Valid TimeRange timeRange, @BeanParam @Valid PageConfig pageConfig);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@XmlRootElement
|
||||
@ApiModel(description="Represents an authorization grant. The AccessCode is only used once to get an AuthorizationToken/RequestToken pair.")
|
||||
public class AuthorizationResponse {
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="The Access Code.", required=true)
|
||||
private String accessCode;
|
||||
|
||||
public String getAccessCode() {
|
||||
return accessCode;
|
||||
}
|
||||
|
||||
public void setAccessCode(String accessCode) {
|
||||
this.accessCode = accessCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.mowesta.api.Tags;
|
||||
import com.mowesta.api.access.Authorizations;
|
||||
import com.mowesta.api.access.Roles;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Authorization;
|
||||
|
||||
/**
|
||||
* A service to authenticate with the oauth2 protocol.
|
||||
*
|
||||
* @author Tobias Stottrop
|
||||
*/
|
||||
@Api
|
||||
@Produces({ MediaType.APPLICATION_JSON })
|
||||
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON })
|
||||
@Path("/")
|
||||
public interface IOAuth2Service {
|
||||
|
||||
|
||||
@GET
|
||||
@Path("oauth2/authorize")
|
||||
@ApiOperation(value = "Use this endpoint to authenticate a user with a social provider. Will return an Access- and Refreshtoken.", authorizations = { @Authorization(Authorizations.USER)}, tags = {Tags.DEFAULT, Tags.OAUTH})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Access token created successfully.", response = AuthorizationResponse.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message = "Error creating AccessCode."),
|
||||
@ApiResponse(code = HttpServletResponse.SC_UNAUTHORIZED, message = "User was not authorized.")
|
||||
})
|
||||
@RolesAllowed({Roles.USER})
|
||||
Response getAccessCode(
|
||||
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
|
||||
@ApiParam(value = "Endpoint to which should be redirected.", required = true) @QueryParam(value = "redirect_uri") URI redirect_uri,
|
||||
@ApiParam(value = "Indicates the type of response that should be returned.", required = true) @QueryParam(value="response_type") String response_type,
|
||||
@ApiParam(value = "Internal state of service which wants to authenticate.", required = true) @QueryParam(value="state") String state,
|
||||
@ApiParam(value = "Scope of access.", required = true) @QueryParam(value="scope") String scope
|
||||
);
|
||||
|
||||
|
||||
@POST
|
||||
@Path("oauth2/token")
|
||||
@ApiOperation(value = "Use this endpoint to get an Access Token.", tags = {Tags.DEFAULT, Tags.OAUTH})
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = HttpServletResponse.SC_FOUND, message = "Access token created successfully.", response = TokenResponse.class),
|
||||
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request.")
|
||||
})
|
||||
@RolesAllowed({Roles.SERVICE})
|
||||
Response getAccessRefreshTokenPair(
|
||||
@ApiParam(value = "Grant Type.", required = true) @QueryParam(value = "grant_type") String grant_type,
|
||||
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
|
||||
@ApiParam(value = "Client secret.", required = true) @QueryParam(value = "client_secret") String client_secret,
|
||||
@ApiParam(value = "Access Code.", required = false) @QueryParam(value="code") String code,
|
||||
@ApiParam(value = "Refresh Token.", required = false) @QueryParam(value = "refresh_token") String refresh_token
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.mowesta.api.oauth2;
|
||||
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@XmlRootElement
|
||||
@ApiModel(description="Represents a token response.")
|
||||
public class TokenResponse {
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="type of token", required=true)
|
||||
private String token_type;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="expiration in seconds", required=false)
|
||||
private long expires_in;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=true)
|
||||
@ApiModelProperty(value="The access token", required=true)
|
||||
private String access_token;
|
||||
|
||||
@NotNull
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="The refresh token.", required=false)
|
||||
private String refresh_token;
|
||||
|
||||
@XmlAttribute(required=false)
|
||||
@ApiModelProperty(value="The granted scope.", required=false)
|
||||
private String scope;
|
||||
|
||||
public long getExpires_in() {
|
||||
return expires_in;
|
||||
}
|
||||
|
||||
public void setExpires_in(long expires_in) {
|
||||
this.expires_in = expires_in;
|
||||
}
|
||||
|
||||
public String getAccess_token() {
|
||||
return access_token;
|
||||
}
|
||||
|
||||
public void setAccess_token(String access_token) {
|
||||
this.access_token = access_token;
|
||||
}
|
||||
|
||||
public String getRefresh_token() {
|
||||
return refresh_token;
|
||||
}
|
||||
|
||||
public void setRefresh_token(String refresh_token) {
|
||||
this.refresh_token = refresh_token;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
public String getToken_type() {
|
||||
return token_type;
|
||||
}
|
||||
|
||||
public void setToken_type(String token_type) {
|
||||
this.token_type = token_type;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package com.mowesta.api.weather;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
@@ -80,6 +80,13 @@ public class WeatherCondition {
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value="The wind speed at ten meters above the ground in meters per second.", required=true)
|
||||
private double windSpeed;
|
||||
|
||||
/**
|
||||
* The maximal wind speed 10 meter above the ground.
|
||||
*/
|
||||
@XmlAttribute(required = true)
|
||||
@ApiModelProperty(value="The maximal wind speed at ten meters above the ground in meters per second.", required=true)
|
||||
private double maxWindSpeed;
|
||||
|
||||
/**
|
||||
* The cloud cover in percent from 0 (no clouds) to 1 (just clouds).
|
||||
@@ -403,5 +410,19 @@ public class WeatherCondition {
|
||||
public void setSnowDepth(double snowDepth) {
|
||||
this.snowDepth = snowDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maxWindSpeed.
|
||||
*
|
||||
* @return The maxWindSpeed.
|
||||
*/
|
||||
public double getMaxWindSpeed() { return maxWindSpeed; }
|
||||
|
||||
/**
|
||||
* Sets the maxWindSpeed.
|
||||
*
|
||||
* @param maxWindSpeed The maxWindSpeed to set.
|
||||
*/
|
||||
public void setMaxWindSpeed(double maxWindSpeed) { this.maxWindSpeed = maxWindSpeed; }
|
||||
|
||||
}
|
||||
|
||||
+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
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
2C2CA271237304E200529274 /* MowestaApi in Frameworks */ = {isa = PBXBuildFile; productRef = 2C2CA270237304E200529274 /* MowestaApi */; };
|
||||
2C32C47524B355A500B69113 /* SwiftUICharts in Frameworks */ = {isa = PBXBuildFile; productRef = 2C32C47424B355A500B69113 /* SwiftUICharts */; };
|
||||
2C7846D52372F44300766694 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D42372F44300766694 /* AppDelegate.swift */; };
|
||||
2C7846D72372F44300766694 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D62372F44300766694 /* SceneDelegate.swift */; };
|
||||
2C7846D92372F44300766694 /* MainTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D82372F44300766694 /* MainTabView.swift */; };
|
||||
@@ -303,6 +304,7 @@
|
||||
9E6D641223CCC2600002CBCF /* Socket in Frameworks */,
|
||||
9E0D267223AD2E7D00BE14F5 /* AuthenticationServices.framework in Frameworks */,
|
||||
9E6D640623CC73320002CBCF /* NetworkExtension.framework in Frameworks */,
|
||||
2C32C47524B355A500B69113 /* SwiftUICharts in Frameworks */,
|
||||
9E3BCD3623ACED50002F2D8F /* KeychainSwift in Frameworks */,
|
||||
2C2CA271237304E200529274 /* MowestaApi in Frameworks */,
|
||||
);
|
||||
@@ -695,6 +697,7 @@
|
||||
2C2CA270237304E200529274 /* MowestaApi */,
|
||||
9E3BCD3523ACED50002F2D8F /* KeychainSwift */,
|
||||
9E6D641123CCC2600002CBCF /* Socket */,
|
||||
2C32C47424B355A500B69113 /* SwiftUICharts */,
|
||||
);
|
||||
productName = app;
|
||||
productReference = 2C7846D12372F44300766694 /* MoWeSta.app */;
|
||||
@@ -772,6 +775,7 @@
|
||||
packageReferences = (
|
||||
9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */,
|
||||
9E6D641023CCC2600002CBCF /* XCRemoteSwiftPackageReference "BlueSocket" */,
|
||||
2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */,
|
||||
);
|
||||
productRefGroup = 2C7846D22372F44300766694 /* Products */;
|
||||
projectDirPath = "";
|
||||
@@ -1294,6 +1298,14 @@
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/AppPear/ChartView";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 1.5.3;
|
||||
};
|
||||
};
|
||||
9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/evgenyneu/keychain-swift.git";
|
||||
@@ -1321,6 +1333,11 @@
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = MowestaApi;
|
||||
};
|
||||
2C32C47424B355A500B69113 /* SwiftUICharts */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */;
|
||||
productName = SwiftUICharts;
|
||||
};
|
||||
9E3BCD3523ACED50002F2D8F /* KeychainSwift */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import os
|
||||
import Foundation
|
||||
import KeychainSwift
|
||||
import UIKit
|
||||
import MowestaApi
|
||||
|
||||
/*
|
||||
@@ -83,7 +84,8 @@ class UserData: ObservableObject {
|
||||
if !DeviceData.shared.created {
|
||||
resetDeviceForPairing()
|
||||
} else {
|
||||
DeviceAPI.setCurrentDeviceUser(completion: { d, err in
|
||||
let d = Device(_id: DeviceData.shared.idInt64, creationTime: 0, modificationTime: 0, deleted: false, user: nil, os: .ios, manufacturer: "Apple Inc.", device: UIDevice.current.modelName, model: UIDevice.current.model)
|
||||
DeviceAPI.setCurrentDeviceUser(body: d, completion: { d, err in
|
||||
if let error = err {
|
||||
switch(error as! ErrorResponse) {
|
||||
case .error(let statusCode, _, _):
|
||||
|
||||
@@ -47,7 +47,7 @@ class MeasurementService {
|
||||
if let c = coordinate {
|
||||
let measurement = MowestaApi.Measurement(coordinate: c, time: timestamp, measurements: measurementData, deviceId: DeviceData.shared.idInt64)
|
||||
|
||||
DeviceAPI.addCurrentDeviceMeasurements(body: MeasurementBatch(elements: [measurement]), completion: { _,err in
|
||||
DeviceAPI.addCurrentDeviceMeasurements(body: [measurement], completion: { _,err in
|
||||
if let error = err {
|
||||
NSLog("\(error)")
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
plugins {
|
||||
id 'war'
|
||||
}
|
||||
|
||||
description = 'Mowesta Alexa Service'
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation project(path: ':service-war')
|
||||
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}"
|
||||
|
||||
compile "io.jsonwebtoken:jjwt-api:0.11.2"
|
||||
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
|
||||
compile "org.bouncycastle:bcprov-jdk15on:1.60"
|
||||
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
|
||||
|
||||
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = true
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.mowesta.service.alexa;
|
||||
|
||||
import com.amazon.ask.Skills;
|
||||
import com.amazon.ask.servlet.SkillServlet;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.service.alexa.impl.CancelandStopIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.ClothingRecommendationIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.CurrentWeatherIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.HelpIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.LaunchRequestHandler;
|
||||
import com.mowesta.service.alexa.impl.SessionEndedRequestHandler;
|
||||
import com.mowesta.service.alexa.impl.WeatherForecastIntentHandler;
|
||||
import com.mowesta.service.alexa.impl.WeatherstationIntentHandler;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.LocationSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
import com.mowesta.service.session.WeatherSessionBean;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
|
||||
@RequestScoped
|
||||
public class AlexaServlet extends HttpServlet {
|
||||
|
||||
private HttpServlet servlet;
|
||||
|
||||
|
||||
@Inject
|
||||
LocationSessionBean locationSessionBean;
|
||||
|
||||
@Inject
|
||||
WeatherSessionBean weatherSessionBean;
|
||||
|
||||
@Inject
|
||||
UserSessionBean userSessionBean;
|
||||
|
||||
@Inject
|
||||
DeviceSessionBean deviceSessionBean;
|
||||
|
||||
@Inject
|
||||
MeasurementSessionBean measurementSessionBean;
|
||||
|
||||
@Inject
|
||||
protected EntityManager entityManager;
|
||||
|
||||
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 WeatherstationIntentHandler(userSessionBean, deviceSessionBean, measurementSessionBean, entityManager),
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package com.mowesta.service.alexa.impl;
|
||||
|
||||
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
|
||||
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
|
||||
import com.amazon.ask.model.IntentRequest;
|
||||
import com.amazon.ask.model.Response;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.DevicePage;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import com.mowesta.service.entity.OAuthSecretEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.session.DeviceSessionBean;
|
||||
import com.mowesta.service.session.MeasurementSessionBean;
|
||||
import com.mowesta.service.session.UserSessionBean;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.TypedQuery;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
|
||||
import static com.amazon.ask.request.Predicates.intentName;
|
||||
|
||||
public class WeatherstationIntentHandler implements IntentRequestHandler {
|
||||
|
||||
UserSessionBean userSessionBean;
|
||||
DeviceSessionBean deviceSessionBean;
|
||||
MeasurementSessionBean measurementSessionBean;
|
||||
EntityManager entityManager;
|
||||
|
||||
Logger logger = Logger.getLogger(getClass().getName());
|
||||
|
||||
public WeatherstationIntentHandler(UserSessionBean userSessionBean,
|
||||
DeviceSessionBean deviceSessionBean,
|
||||
MeasurementSessionBean measurementSessionBean,
|
||||
EntityManager entityManager) {
|
||||
this.userSessionBean = userSessionBean;
|
||||
this.deviceSessionBean = deviceSessionBean;
|
||||
this.measurementSessionBean = measurementSessionBean;
|
||||
this.entityManager = entityManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
|
||||
return input.matches(intentName("WeatherstationIntent"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
|
||||
logger.log(Level.INFO, "WeatherStationIntent started");
|
||||
String accessToken = input.getRequestEnvelope().getContext().getSystem().getUser().getAccessToken();
|
||||
logger.log(Level.INFO, "AccessToken: " + accessToken);
|
||||
|
||||
|
||||
|
||||
|
||||
if (accessToken == null) {
|
||||
String errorText = "Du musst mit angemeldet sein, um diesen Service nutzen zu können. " +
|
||||
"Bitte gehe in die Alexa App und melde dich an.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withLinkAccountCard()
|
||||
.build();
|
||||
} else {
|
||||
|
||||
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
|
||||
if (secretKey.isPresent()) {
|
||||
OAuthSecretEntity secretEntity = secretKey.get();
|
||||
Claims claims = Jwts
|
||||
.parserBuilder()
|
||||
.setSigningKey(secretEntity.getSecret().getBytes())
|
||||
.build()
|
||||
.parseClaimsJws(accessToken)
|
||||
.getBody();
|
||||
String userId = claims.getId();
|
||||
logger.log(Level.INFO, "UserID: " + userId);
|
||||
|
||||
UserEntity userEntity = userSessionBean.findUser(userId);
|
||||
|
||||
if (userEntity != null) {
|
||||
logger.log(Level.INFO, "UserEntity: " + userEntity.getName());
|
||||
DevicePage devicePage = null;
|
||||
try {
|
||||
devicePage = deviceSessionBean.getAllDevicesForCurrentUser(new PageConfig(0, 60), true);
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "device at 0: " + devicePage.getElements().get(0));
|
||||
|
||||
if (devicePage == null) {
|
||||
String errorText = "Es konnten keine Geräte gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
Device device = devicePage.getElements().get(0);
|
||||
Measurement measurement = null;
|
||||
try {
|
||||
measurement = measurementSessionBean.getDeviceMeasurements(device.getId(), new TimeRange(System.currentTimeMillis(), System.currentTimeMillis() + 10),
|
||||
new PageConfig(0, 1), false).getElements().get(0);
|
||||
|
||||
logger.log(Level.INFO, "measurement: " + measurement.getTemperature());
|
||||
} catch (EntityNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (EntityForbiddenException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
String measurementString = "";
|
||||
if (measurement != null) {
|
||||
measurementString += "Die Temperatur beträgt " + measurement.getTemperature() + " Grad.";
|
||||
} else measurementString += "Es wurde keine Messung gefunden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(measurementString)
|
||||
.withSimpleCard("Measurement", measurementString)
|
||||
.build();
|
||||
|
||||
} else {
|
||||
String errorText = "Der Nutzer konnte nicht gefunden werden.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
|
||||
} else {
|
||||
String errorText = "Es ist ein Fehler aufgetreten. Bitte versuche es später nochmal.";
|
||||
return input.getResponseBuilder()
|
||||
.withSpeech(errorText)
|
||||
.withSimpleCard("Error", errorText)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
|
||||
TypedQuery<OAuthSecretEntity> query = entityManager.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
|
||||
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
|
||||
|
||||
return oAuthSecretEntityList.stream()
|
||||
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
|
||||
.findAny();
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -1,5 +1,19 @@
|
||||
package com.mowesta.data.dwd;
|
||||
|
||||
import com.mowesta.data.ftp.FileStatus;
|
||||
import com.mowesta.data.ftp.FileStatusListener;
|
||||
import com.mowesta.data.ftp.FtpFolderSync;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.grib2.template.product.ForecastProduct;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.FileNameComparator;
|
||||
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
@@ -13,20 +27,6 @@ import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
||||
|
||||
import com.mowesta.data.ftp.FileStatus;
|
||||
import com.mowesta.data.ftp.FileStatusListener;
|
||||
import com.mowesta.data.ftp.FtpFolderSync;
|
||||
import com.mowesta.data.grib2.Grib2Data;
|
||||
import com.mowesta.data.grib2.Grib2File;
|
||||
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
|
||||
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
|
||||
import com.mowesta.data.grib2.template.product.ForecastProduct;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.FileNameComparator;
|
||||
|
||||
/**
|
||||
* Represents a numeric weather prediction from DWD.
|
||||
*/
|
||||
@@ -284,6 +284,11 @@ public class NumericPrediction {
|
||||
* The meridional wind at 10m height.
|
||||
*/
|
||||
V10M("v_10m", false),
|
||||
|
||||
/**
|
||||
* The maximum wind speed at 10m height.
|
||||
*/
|
||||
VMAX_10M("vmax_10m", false),
|
||||
|
||||
/**
|
||||
* The weather interpretation type.
|
||||
@@ -443,7 +448,7 @@ public class NumericPrediction {
|
||||
type.getSystem().isComputed()?Variable.RLAT:Variable.CLAT,
|
||||
type.getSystem().isComputed()?Variable.RLON:Variable.CLON,
|
||||
Variable.HSURF, Variable.PLCOV, Variable.SOILTYP, Variable.PREC, Variable.T2M, Variable.CLCT, Variable.CLDEPTH,
|
||||
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
|
||||
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.VMAX_10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.render.VideoFrameComposer;
|
||||
import com.mowesta.data.dwd.render.VideoImageRenderer;
|
||||
import com.mowesta.data.process.projection.CroppedProjection;
|
||||
import com.mowesta.data.process.projection.CroppedProjection.CropType;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
@@ -82,8 +84,8 @@ public class VideoConfiguration {
|
||||
public static VideoConfiguration getConfiguration(NumericPrediction prediction) {
|
||||
VideoConfiguration c = new VideoConfiguration();
|
||||
c.prediction = prediction;
|
||||
c.frameWidth = 1280;
|
||||
c.frameHeight = 720;
|
||||
c.frameWidth = 1600;
|
||||
c.frameHeight = 900;
|
||||
c.firstHour = 1;
|
||||
switch (prediction.getType()) {
|
||||
case ICON_EUROPE:
|
||||
@@ -124,11 +126,10 @@ public class VideoConfiguration {
|
||||
* @return The frame composer.
|
||||
* @throws IOException Thrown if the longitudes or latitudes cannot be loaded.
|
||||
*/
|
||||
public FrameComposer createComposer(Time time) throws IOException {
|
||||
public VideoFrameComposer createComposer(Time time) throws IOException {
|
||||
IProjection projection = new CroppedProjection(new MercatorProjection(), CropType.COORDINATE, minLongitude, maxLatitude, maxLongitude, minLatitude);
|
||||
ImageGenerator generator = new ImageGenerator(prediction.getLongitues(time), prediction.getLatitudes(time), projection, imageWidth, imageHeight);
|
||||
generator.getBoundaryRenderer().setColor(new Color(0xC0f9a825, true));
|
||||
FrameComposer result = new FrameComposer(generator, createOverlay(generator), frameWidth, frameHeight);
|
||||
VideoImageRenderer generator = new VideoImageRenderer(prediction.getLongitues(time), prediction.getLatitudes(time), projection, imageWidth, imageHeight);
|
||||
VideoFrameComposer result = new VideoFrameComposer(generator, createOverlay(generator), frameWidth, frameHeight);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -138,20 +139,36 @@ public class VideoConfiguration {
|
||||
* @param generator The generator.
|
||||
* @return The overlay image.
|
||||
*/
|
||||
private BufferedImage createOverlay(ImageGenerator generator) {
|
||||
private BufferedImage createOverlay(VideoImageRenderer generator) {
|
||||
switch (prediction.getType()) {
|
||||
case COSMO_EUROPE:
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setColor(new Color(0xFF47859c, true));
|
||||
g.fillRect(0, 0, imageWidth, imageHeight);
|
||||
// generator.getBoundaryRenderer().setColor(new Color(0xfff9a825, true));
|
||||
generator.getBoundaryRenderer().setColor(new Color(0x00695c));
|
||||
generator.getBoundaryRenderer().renderLand(image, true);
|
||||
generator.getBoundaryRenderer().setColor(new Color(0xC0f9a825, true));
|
||||
generator.getBoundaryRenderer().setColor(new Color(0x44000000, true));
|
||||
|
||||
|
||||
generator.getBoundaryRenderer().renderBoundaries(image, false);
|
||||
g.setComposite(AlphaComposite.Src);
|
||||
g.setColor(new Color(0x00FFFFFF, true));
|
||||
g.fillRect(175, 0, imageWidth - 350, imageHeight);
|
||||
for (int i = 0; i < imageHeight; i++) {
|
||||
image.setRGB(170, i, image.getRGB(172, i) & 0xD0ffffff);
|
||||
image.setRGB(171, i, image.getRGB(172, i) & 0xB0ffffff);
|
||||
image.setRGB(172, i, image.getRGB(172, i) & 0x80ffffff);
|
||||
image.setRGB(173, i, image.getRGB(173, i) & 0x40ffffff);
|
||||
image.setRGB(174, i, image.getRGB(174, i) & 0x20ffffff);
|
||||
|
||||
image.setRGB(imageWidth - 175, i, image.getRGB(imageWidth - 175, i) & 0x20ffffff);
|
||||
image.setRGB(imageWidth - 174, i, image.getRGB(imageWidth - 174, i) & 0x40ffffff);
|
||||
image.setRGB(imageWidth - 173, i, image.getRGB(imageWidth - 173, i) & 0x80ffffff);
|
||||
image.setRGB(imageWidth - 172, i, image.getRGB(imageWidth - 172, i) & 0xB0ffffff);
|
||||
image.setRGB(imageWidth - 171, i, image.getRGB(imageWidth - 171, i) & 0xD0ffffff);
|
||||
}
|
||||
g.dispose();
|
||||
return image;
|
||||
default:
|
||||
|
||||
@@ -1,96 +1,112 @@
|
||||
package com.mowesta.data.dwd;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.video.PixelFormat;
|
||||
import com.mowesta.data.process.video.VideoEncoder;
|
||||
import com.mowesta.data.dwd.render.AbstractVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.CloudVideoRenderer;
|
||||
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;
|
||||
import com.mowesta.data.process.video.VideoFrame;
|
||||
import com.mowesta.data.process.video.VideoInterpolator;
|
||||
import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
|
||||
/**
|
||||
* 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 FrameComposer 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 bitrate.
|
||||
* The video encoder crf value between 0 (lossless) and 51 (compressed).
|
||||
*/
|
||||
protected int bitRate = 750;
|
||||
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.
|
||||
*/
|
||||
public VideoGenerator(NumericPrediction prediction, FrameComposer composer) {
|
||||
public VideoGenerator(NumericPrediction prediction, VideoFrameComposer composer) {
|
||||
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.
|
||||
*
|
||||
@@ -110,21 +126,21 @@ public class VideoGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the bitRate.
|
||||
* Returns the crf.
|
||||
*
|
||||
* @return The bitRate.
|
||||
* @return The crf.
|
||||
*/
|
||||
public int getBitRate() {
|
||||
return bitRate;
|
||||
public int getCrf() {
|
||||
return crf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the bitRate.
|
||||
* Sets the crf.
|
||||
*
|
||||
* @param bitRate The bitRate to set.
|
||||
* @param crf The crf to set.
|
||||
*/
|
||||
public void setBitRate(int bitRate) {
|
||||
this.bitRate = bitRate;
|
||||
public void setCrf(int crf) {
|
||||
this.crf = crf;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,148 +161,22 @@ public class VideoGenerator {
|
||||
this.fps = fps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a base layer using the soil type, plant cover and surface height.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @return The base layer.
|
||||
* @throws IOException Thrown if something cannot be loaded.
|
||||
*/
|
||||
protected BufferedImage getBaseLayer(Variable variable, Time time) throws IOException {
|
||||
BufferedImage result = composer.createImage();
|
||||
switch (variable) {
|
||||
case T2M:
|
||||
case PMSL:
|
||||
break;
|
||||
default:
|
||||
composer.getGenerator().renderSoilType(result, prediction.getValues(prediction.getFile(Variable.SOILTYP, time)));
|
||||
BufferedImage temp = composer.createImage();
|
||||
composer.getGenerator().renderPlantCover(temp, prediction.getValues(prediction.getFile(Variable.PLCOV, time)));
|
||||
composer.renderImage(result, temp);
|
||||
composer.getGenerator().renderSurfaceHeight(temp, prediction.getValues(prediction.getFile(Variable.HSURF, time)));
|
||||
composer.renderImage(result, temp);
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a data layer for a particular hour, if the data is available.
|
||||
*
|
||||
* @param image The image used for rendering.
|
||||
* @param time The time.
|
||||
* @param hour The hour.
|
||||
* @param variable The variable.
|
||||
* @return True if the image has been created, false if the data is not available.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected boolean getDataLayer(BufferedImage image, Variable variable, Time time, int hour) throws IOException {
|
||||
DoubleArray data = null;
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
case T2M:
|
||||
case CLCT:
|
||||
File f = prediction.getFile(variable, time, hour);
|
||||
if (f != null) data = prediction.getValues(f);
|
||||
break;
|
||||
case PREC:
|
||||
File f1 = prediction.getFile(variable, time, hour);
|
||||
File f2 = prediction.getFile(variable, time, hour + 1);
|
||||
if (f1 != null && f2 != null) {
|
||||
data = prediction.getValues(f2);
|
||||
DoubleArray base = prediction.getValues(f1);
|
||||
for (int i = 0, s = data.getSize(); i < s; i++) {
|
||||
data.setValue(i, data.getValue(i) - base.getValue(i));
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (data != null) {
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
composer.getGenerator().renderPressure(image, data);
|
||||
return true;
|
||||
case T2M:
|
||||
composer.getGenerator().renderTemperature(image, data);
|
||||
return true;
|
||||
case CLCT:
|
||||
File f = prediction.getFile(Variable.CLDEPTH, time, hour);
|
||||
if (f != null) {
|
||||
composer.getGenerator().renderCloudCoverage3D(image, data, prediction.getValues(f));
|
||||
} else {
|
||||
composer.getGenerator().renderCloudCoverage(image, data);
|
||||
}
|
||||
return true;
|
||||
case PREC:
|
||||
composer.getGenerator().renderPrecipitation(image, data);
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an overlay layer using the boundary renderer.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @return The overlay layer.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected BufferedImage getOverlayLayer(Variable variable, Time time) throws IOException {
|
||||
BufferedImage result = composer.createImage();
|
||||
composer.getGenerator().renderBoundaries(result, false);
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
case T2M:
|
||||
BufferedImage temp = composer.createImage();
|
||||
composer.getGenerator().renderSurfaceHeight(temp, prediction.getValues(prediction.getFile(Variable.HSURF, time)));
|
||||
composer.renderImage(result, temp);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interpolation type for the variable.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @return The interpolation type for the variable.
|
||||
*/
|
||||
protected VideoInterpolator.Type getInterpolation(Variable variable) {
|
||||
switch (variable) {
|
||||
case CLCT:
|
||||
case PREC:
|
||||
return Type.MOTION;
|
||||
default:
|
||||
return Type.BLEND;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -294,127 +184,49 @@ 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 {
|
||||
final IProgressMonitor m = monitor==null?MONITOR_NULL:monitor;
|
||||
// initialize all the buffers that we need
|
||||
BufferedImage baseLayer = getBaseLayer(variable, time);
|
||||
BufferedImage overlayLayer = getOverlayLayer(variable, time);
|
||||
BufferedImage input = composer.createImage();
|
||||
BufferedImage image = composer.createImage();
|
||||
BufferedImage frame = composer.createFrame(BufferedImage.TYPE_INT_ARGB);
|
||||
BufferedImage dataLayer = composer.createImage();
|
||||
int[] counter = new int[2]; // key frame, interpolate frame
|
||||
boolean[] canceled = new boolean[1];
|
||||
byte[] imageBuffer = VideoFrame.createBuffer(composer.getGenerator().getWidth(), composer.getGenerator().getHeight(), PixelFormat.ARGB);
|
||||
byte[] frameBuffer = VideoFrame.createBuffer(composer.getWidth(), composer.getHeight(), PixelFormat.ARGB);
|
||||
// create the encoder and interpolator
|
||||
VideoEncoder encoder = new VideoEncoder(composer.getWidth(), composer.getHeight(), PixelFormat.ARGB, 30, bitRate, quality);
|
||||
try {
|
||||
VideoInterpolator interpolator = new VideoInterpolator(composer.getGenerator().getWidth(), composer.getGenerator().getHeight(), PixelFormat.ARGB, 1, 32, getInterpolation(variable));
|
||||
try {
|
||||
// create a frame callback that forwards frames from interpolator to encoder
|
||||
VideoInterpolator.FrameCallback handler = (source, pts, data) -> {
|
||||
if (canceled[0]) return;
|
||||
logger.log(Level.FINE, "Received interpolated frame of " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.decodeImage(PixelFormat.ARGB, data, dataLayer);
|
||||
composer.renderImage(image, baseLayer);
|
||||
composer.renderImage(image, dataLayer);
|
||||
composer.renderImage(image, overlayLayer);
|
||||
composer.renderFrame(frame, image);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, frameBuffer);
|
||||
try {
|
||||
// drop 1 frame at the beginning and one at the end for smoother motion
|
||||
int f = (int)(pts % 32);
|
||||
if (f < 31 && f > 0) {
|
||||
counter[1] += 1;
|
||||
logger.log(Level.FINE, "Encoding interpolated frame for pts " + counter[1] + " of " + prediction.getType() + "-" + variable + ".");
|
||||
encoder.addFrame(frameBuffer);
|
||||
canceled[0] = canceled[0] || m.onFrameProcessed(counter[0], counter[1]);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to encode image.", e);
|
||||
}
|
||||
};
|
||||
for (int i = first; i <= last; i++) {
|
||||
logger.log(Level.INFO, "Generating key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
if (getDataLayer(input, variable, time, i)) {
|
||||
if (counter[0] == 0) {
|
||||
String format = guessPreviewFormat(preview);
|
||||
logger.log(Level.INFO, "Generating preview image as '" + format + "' in '" + preview.getAbsolutePath() + "'.");
|
||||
BufferedImage output = format.equals("png")?frame:composer.createFrame(BufferedImage.TYPE_INT_RGB);
|
||||
composer.renderImage(image, baseLayer);
|
||||
composer.renderImage(image, input);
|
||||
composer.renderImage(image, overlayLayer);
|
||||
composer.renderFrame(output, image);
|
||||
ImageIO.write(output, format , preview);
|
||||
}
|
||||
counter[0] += 1;
|
||||
canceled[0] = canceled[0] || m.onFrameProcessed(counter[0], counter[1]);
|
||||
if (canceled[0]) throw new IOException("Video generation canceled.");
|
||||
logger.log(Level.FINE, "Interpolating key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.encodeImage(input, PixelFormat.ARGB, imageBuffer);
|
||||
interpolator.addFrame(i, imageBuffer, handler);
|
||||
if (canceled[0]) throw new IOException("Video generation canceled.");
|
||||
} else {
|
||||
logger.log(Level.SEVERE, "Failed to generate key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
}
|
||||
}
|
||||
if (canceled[0]) throw new IOException("Video generation canceled for " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.encodeImage(input, PixelFormat.ARGB, imageBuffer);
|
||||
interpolator.addFrame(last + 1, imageBuffer, handler);
|
||||
interpolator.release();
|
||||
logger.log(Level.INFO, "Remultiplexing video of " + prediction.getType() + "-" + variable + ".");
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
interpolator.release();
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
AbstractVideoRenderer renderer;
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
renderer = new PressureVideoRenderer(this, time, getIsobars());
|
||||
break;
|
||||
case T2M:
|
||||
renderer = new TemperatureVideoRenderer(this, time, getIsotherms());
|
||||
break;
|
||||
case CLCT:
|
||||
renderer = new CloudVideoRenderer(this, time);
|
||||
break;
|
||||
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:
|
||||
return 250;
|
||||
default:
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to guess the preview format from the file name.
|
||||
*
|
||||
* @param file The file.
|
||||
* @return The preview format.
|
||||
*/
|
||||
public String guessPreviewFormat(File file) {
|
||||
if (file.getName().toLowerCase().endsWith("png")) {
|
||||
return "png";
|
||||
} else {
|
||||
return "jpeg";
|
||||
|
||||
private double getIsotherms() {
|
||||
switch (prediction.getType()) {
|
||||
default:
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a image and stores it in the destination.
|
||||
*
|
||||
* @param image The destination for the video image.
|
||||
* @param format The output format, e.g. "png" or "jpeg".
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public void createImage(Variable variable, Time time, int hour, String format, File image) throws IOException {
|
||||
BufferedImage baseLayer = getBaseLayer(variable, time);
|
||||
BufferedImage overlayLayer = getOverlayLayer(variable, time);
|
||||
BufferedImage dataLayer = composer.createImage();
|
||||
BufferedImage frame = composer.createFrame(format.equals("png")?BufferedImage.TYPE_INT_ARGB:BufferedImage.TYPE_INT_RGB);
|
||||
if (getDataLayer(dataLayer, variable, time, hour)) {
|
||||
composer.renderImage(baseLayer, dataLayer);
|
||||
composer.renderImage(baseLayer, overlayLayer);
|
||||
composer.renderFrame(frame, baseLayer);
|
||||
ImageIO.write(frame, format, image);
|
||||
} else {
|
||||
throw new IOException("Failed to render data layer.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A video render that operates on data interpolation.
|
||||
*
|
||||
* @param <T> The state of the renderer.
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractDataVideoRenderer<T extends RendererState> extends AbstractVideoRenderer {
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractDataVideoRenderer(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
super(generator, variables, time);
|
||||
}
|
||||
|
||||
@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);
|
||||
// the buffered for the key frame
|
||||
BufferedImage keyImage = getComposer().createImage();
|
||||
byte[] keyFrame = VideoFrame.createBuffer(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB);
|
||||
T state = createState();
|
||||
int fps = getGenerator().getFps();
|
||||
// create the encoder and interpolator
|
||||
VideoEncoder encoder = new VideoEncoder(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB, fps, getGenerator().getCrf(), getGenerator().getQuality());
|
||||
try {
|
||||
for (int i = first; i <= last; i++) {
|
||||
state.keyCount += 1;
|
||||
for (int j = 0; j < fps; j++) {
|
||||
state.interpolationCount += 1;
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
renderDataImage(keyImage, i, i + 1, j/(double)fps, state);
|
||||
renderFrame(frame, keyImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, keyFrame);
|
||||
encoder.addFrame(keyFrame);
|
||||
}
|
||||
}
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
try {
|
||||
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.
|
||||
* @param fraction The fraction between start and end.
|
||||
* @param state The rendering state.
|
||||
* @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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* interpolator which works well for moving objects such as clouds or precipitation.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
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 variables The variables.
|
||||
* @param time The time.
|
||||
* @param interpolation The interpolation type.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
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);
|
||||
// the buffered for the key frame
|
||||
BufferedImage keyImage = getComposer().createImage();
|
||||
byte[] keyFrame = VideoFrame.createBuffer(getRenderer().getWidth(), getRenderer().getHeight(), PixelFormat.ARGB);
|
||||
// the buffer for the interpolated frames
|
||||
BufferedImage interpolatedImage = getComposer().createImage();
|
||||
byte[] interpolatedFrame = VideoFrame.createBuffer(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB);
|
||||
// key frame, interpolate frame
|
||||
RendererState state = new RendererState();
|
||||
int fps = getGenerator().getFps();
|
||||
// create the encoder and interpolator
|
||||
System.out.println(getComposer().getWidth() + " " + getComposer().getHeight() + " - " + getRenderer().getWidth() + " " + getRenderer().getHeight());
|
||||
VideoEncoder encoder = new VideoEncoder(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB, fps, getGenerator().getCrf(), getGenerator().getQuality());
|
||||
try {
|
||||
VideoInterpolator interpolator = new VideoInterpolator(getRenderer().getWidth(), getRenderer().getHeight(), PixelFormat.ARGB, 1, fps + 2, interpolation);
|
||||
try {
|
||||
// create a frame callback that forwards frames from interpolator to encoder
|
||||
VideoInterpolator.FrameCallback handler = (source, pts, data) -> {
|
||||
try {
|
||||
if (state.canceled) return;
|
||||
// drop 1 frame at the beginning and one at the end for smoother motion
|
||||
int f = (int)(pts % (fps + 2));
|
||||
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);
|
||||
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);
|
||||
}
|
||||
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);
|
||||
} finally {
|
||||
interpolator.release();
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
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.interpolation.LinearInterpolation;
|
||||
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<State extends LinearRendererState> extends AbstractDataVideoRenderer<State> {
|
||||
|
||||
/**
|
||||
* The interpolator.
|
||||
*/
|
||||
protected LinearInterpolation interpolation = new LinearInterpolation();
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractLinearDataVideoRender(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
super(generator, variables, time);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
if (a == null) a = getData(h);
|
||||
state.cache.put(h, a);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
state.data[i] = new DoubleArray(a[i].getSize());
|
||||
}
|
||||
}
|
||||
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);
|
||||
state.cache.put(start, s);
|
||||
if (e == null) e = getData(end);
|
||||
state.cache.put(end, e);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray[s.length];
|
||||
for (int i = 0; i < s.length; i++) {
|
||||
state.data[i] = new DoubleArray(s[i].getSize());
|
||||
}
|
||||
}
|
||||
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, 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 {
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
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.
|
||||
*/
|
||||
protected VideoGenerator generator;
|
||||
/**
|
||||
* The variable that we want to render.
|
||||
*/
|
||||
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 variables The variables to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractVideoRenderer(VideoGenerator generator, Variable[] variables, Time time) throws IOException {
|
||||
this.generator = generator;
|
||||
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() {
|
||||
if (tempImage == null) {
|
||||
tempImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(tempImage);
|
||||
return tempImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base image.
|
||||
*
|
||||
* @return The base image.
|
||||
* @throws IOException Thrown if the base image cannot be created.
|
||||
*/
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
if (baseImage == null) {
|
||||
BufferedImage temp = getTempImage();
|
||||
baseImage = getComposer().createImage();
|
||||
getRenderer().renderSoilType(baseImage, getPrediction().getValues(getPrediction().getFile(Variable.SOILTYP, time)));
|
||||
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);
|
||||
}
|
||||
return baseImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the overlay image.
|
||||
*
|
||||
* @return The overlay image.
|
||||
* @throws IOException Thrown if the overlay image cannot be created.
|
||||
*/
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
if (overlayImage == null) {
|
||||
overlayImage = getComposer().createImage();
|
||||
getRenderer().renderBoundaries(overlayImage, new Color(0x44000000, true));
|
||||
}
|
||||
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.
|
||||
* @param monitor The progress monitor.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
public void renderPreview(File file, int hour) throws IOException {
|
||||
String format = getPreviewFormat(file);
|
||||
BufferedImage output = getComposer().createFrame( format.equals("jpeg") ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
|
||||
BufferedImage data = getComposer().createImage();
|
||||
renderDataImage(data, hour);
|
||||
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.
|
||||
*/
|
||||
private String getPreviewFormat(File file) {
|
||||
if (file.getName().toLowerCase().endsWith("png")) {
|
||||
return "png";
|
||||
} else if (file.getName().toLowerCase().endsWith("gif")) {
|
||||
return "gif";
|
||||
} else {
|
||||
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.
|
||||
*/
|
||||
protected void renderImage(BufferedImage image, BufferedImage dataImage) throws IOException {
|
||||
BufferedImage base = getBaseImage();
|
||||
if (base != null) getComposer().renderImage(image, base);
|
||||
getComposer().renderImage(image, dataImage);
|
||||
BufferedImage over = getOverlayImage();
|
||||
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.
|
||||
*/
|
||||
protected void renderFrame(BufferedImage frame, BufferedImage dataImage) throws IOException {
|
||||
BufferedImage temp = getTempImage();
|
||||
renderImage(temp, dataImage);
|
||||
getComposer().renderFrame(frame, temp);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
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.util.DoubleArray;
|
||||
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, new Variable[] {Variable.CLCT, Variable.CLDEPTH }, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
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 {
|
||||
|
||||
/**
|
||||
* The loaded data hashed by hour.
|
||||
*/
|
||||
Map<Integer, DoubleArray[]> cache = new HashMap<>();
|
||||
|
||||
/** The double array with the interpolated data. */
|
||||
DoubleArray[] data;
|
||||
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
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.util.DoubleArray;
|
||||
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, new Variable[] { Variable.PREC }, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
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));
|
||||
}
|
||||
getRenderer().renderPrecipitation(image, data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A video renderer for pressure videos.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PressureVideoRenderer extends AbstractLinearDataVideoRender<LinearRendererState> {
|
||||
|
||||
/**
|
||||
* The surface height image.
|
||||
*/
|
||||
protected BufferedImage surfaceImage;
|
||||
|
||||
/**
|
||||
* The distance of the iso lines.
|
||||
*/
|
||||
protected double isoDistance;
|
||||
|
||||
/**
|
||||
* A filter to apply a Gaussian blur.
|
||||
*/
|
||||
protected GaussianBlur blur = new GaussianBlur(2);
|
||||
|
||||
/**
|
||||
* The filtered image.
|
||||
*/
|
||||
protected BufferedImage filterImage;
|
||||
|
||||
/**
|
||||
* The filtered image.
|
||||
*/
|
||||
protected BufferedImage filterImage2;
|
||||
|
||||
/**
|
||||
* 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, 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() {
|
||||
if (filterImage == null) {
|
||||
filterImage = getComposer().createImage();
|
||||
}
|
||||
return filterImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage2() {
|
||||
if (filterImage2 == null) {
|
||||
filterImage2 = getComposer().createImage();
|
||||
}
|
||||
return filterImage2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
* @return The surface height image.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
public BufferedImage getSurfaceImage() throws IOException {
|
||||
if (surfaceImage == null) {
|
||||
surfaceImage = getComposer().createImage();
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, new Color(0x44000000, true));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
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[0]);
|
||||
IntArray converted = getRenderer().getIntValues(projected, (v) -> (int)((v - 100000) / isoDistance));
|
||||
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
List<List<int[]>> result = new ArrayList<>();
|
||||
// remove the short lines
|
||||
for (List<int[]> p : ps) {
|
||||
if (p.size() > 30) result.add(p);
|
||||
}
|
||||
// render onto temp image
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 2f, 0xffffffff);
|
||||
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, getFilterImage2(), temp);
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
/**
|
||||
* The internal state of the renderer.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class RendererState {
|
||||
/** The number of key frames generated so far. */
|
||||
int keyCount;
|
||||
/** The number of interpolated frames generated so far. */
|
||||
int interpolationCount;
|
||||
/** A flag to determine whether the process is canceled. */
|
||||
boolean canceled;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A renderer for temperature videos.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
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, 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.
|
||||
*/
|
||||
public BufferedImage getSurfaceImage() throws IOException {
|
||||
if (surfaceImage == null) {
|
||||
surfaceImage = getComposer().createImage();
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, new Color(0x44000000, true));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
getRenderer().renderTemperature(image, state.data[0]);
|
||||
getComposer().renderImage(image, getSurfaceImage());
|
||||
if (isoDistance != 0) {
|
||||
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());
|
||||
for (List<int[]> p : ps) {
|
||||
if (p.size() > 25) {
|
||||
result.add(p);
|
||||
}
|
||||
}
|
||||
// render onto temp image (without transparency, since it is too expensive)
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 1f, 0xff000000);
|
||||
// compute the transparency effect in a simplified version
|
||||
for (int i = 0, w = getRenderer().getWidth(); i < w; i++) {
|
||||
for (int j = 0, h = getRenderer().getHeight(); j < h; j++) {
|
||||
temp.setRGB(i, j, temp.getRGB(i, j) & 0x33ffffff);
|
||||
}
|
||||
}
|
||||
// compose the rest
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+15
-14
@@ -1,4 +1,4 @@
|
||||
package com.mowesta.data.dwd;
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.AlphaComposite;
|
||||
import java.awt.Color;
|
||||
@@ -11,12 +11,13 @@ import com.mowesta.data.process.image.ImageRenderer.Dimension;
|
||||
import com.mowesta.data.process.image.ImageRenderer.Logo;
|
||||
|
||||
/**
|
||||
* A utility class to resize and extend the a data frame generated
|
||||
* by the frame generator.
|
||||
* A utility class to resize and extend the a data frame generated by the frame generator
|
||||
* using an optional. At the present time, this overlay is used to cover the non-existing
|
||||
* regions in the cosmo-d2 model, if we generate a 16x9 video from the data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class FrameComposer {
|
||||
public class VideoFrameComposer {
|
||||
|
||||
/**
|
||||
* The output width.
|
||||
@@ -31,7 +32,7 @@ public class FrameComposer {
|
||||
/**
|
||||
* The frame generator.
|
||||
*/
|
||||
protected ImageGenerator generator;
|
||||
protected VideoImageRenderer renderer;
|
||||
|
||||
/**
|
||||
* The overlay to render on top of the image.
|
||||
@@ -53,25 +54,25 @@ public class FrameComposer {
|
||||
* Creates a new frame composer that rescales images to the
|
||||
* framesize.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param renderer The generator.
|
||||
* @param width The width of the output frame.
|
||||
* @param height The height of the output frame.
|
||||
*/
|
||||
public FrameComposer(ImageGenerator generator, int width, int height) {
|
||||
this(generator, null, width, height);
|
||||
public VideoFrameComposer(VideoImageRenderer renderer, int width, int height) {
|
||||
this(renderer, null, width, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new frame composer rescales images to the framesize
|
||||
* and adds the specified overlay image.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param renderer The generator.
|
||||
* @param overlay The overlay to render on top of a frame.
|
||||
* @param width The width of the output frame.
|
||||
* @param height The height of the output frame.
|
||||
*/
|
||||
public FrameComposer(ImageGenerator generator, BufferedImage overlay, int width, int height) {
|
||||
this.generator = generator;
|
||||
public VideoFrameComposer(VideoImageRenderer renderer, BufferedImage overlay, int width, int height) {
|
||||
this.renderer = renderer;
|
||||
this.overlay = overlay;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
@@ -100,8 +101,8 @@ public class FrameComposer {
|
||||
*
|
||||
* @return The frame generator.
|
||||
*/
|
||||
public ImageGenerator getGenerator() {
|
||||
return generator;
|
||||
public VideoImageRenderer getGenerator() {
|
||||
return renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,7 +159,7 @@ public class FrameComposer {
|
||||
* @return The image for the image generator.
|
||||
*/
|
||||
public BufferedImage createImage() {
|
||||
return new BufferedImage(generator.getWidth(), generator.getHeight(), BufferedImage.TYPE_INT_ARGB);
|
||||
return new BufferedImage(renderer.getWidth(), renderer.getHeight(), BufferedImage.TYPE_INT_ARGB);
|
||||
}
|
||||
|
||||
/**
|
||||
+210
-94
@@ -1,10 +1,15 @@
|
||||
package com.mowesta.data.dwd;
|
||||
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.util.ArrayList;
|
||||
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;
|
||||
@@ -19,18 +24,37 @@ import com.mowesta.data.process.image.BoundaryRenderer;
|
||||
import com.mowesta.data.process.image.DataRenderer;
|
||||
import com.mowesta.data.process.image.ImageFiller;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
import com.mowesta.data.process.source.DoubleArraySource;
|
||||
import com.mowesta.data.process.projection.ImageProjection;
|
||||
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.
|
||||
*
|
||||
* 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 ImageGenerator {
|
||||
public class VideoImageRenderer {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -41,7 +65,11 @@ public class ImageGenerator {
|
||||
*/
|
||||
protected DoubleArray longitudes;
|
||||
/**
|
||||
* The projection to use.
|
||||
* The precomputed projection to use.
|
||||
*/
|
||||
protected ImageProjection imageProjection;
|
||||
/**
|
||||
* The projection.
|
||||
*/
|
||||
protected IProjection projection;
|
||||
/**
|
||||
@@ -64,43 +92,44 @@ public class ImageGenerator {
|
||||
/**
|
||||
* 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.
|
||||
* @param width The image width.
|
||||
* @param height The image height.
|
||||
*/
|
||||
public ImageGenerator(DoubleArray longitudes, DoubleArray latitudes, IProjection projection, int width, int height) {
|
||||
public VideoImageRenderer(DoubleArray longitudes, DoubleArray latitudes, IProjection projection, int width, int height) {
|
||||
this.projection = projection;
|
||||
this.longitudes = longitudes;
|
||||
this.latitudes = latitudes;
|
||||
this.projection = projection;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
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() {
|
||||
@@ -109,7 +138,7 @@ public class ImageGenerator {
|
||||
|
||||
/**
|
||||
* Returns a reference to the boundary renderer.
|
||||
*
|
||||
*
|
||||
* @return The boundary renderer.
|
||||
*/
|
||||
public BoundaryRenderer getBoundaryRenderer() {
|
||||
@@ -118,98 +147,173 @@ public class ImageGenerator {
|
||||
}
|
||||
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.
|
||||
*/
|
||||
public void renderPressure(BufferedImage image, DoubleArray pmsl) {
|
||||
double min = 0, max = 0, avg = 0;
|
||||
boolean first = true;
|
||||
int s = Math.min(longitudes.getSize(), Math.min(latitudes.getSize(), pmsl.getSize()));
|
||||
for (int i = 0; i < s; i++) {
|
||||
double longitude = longitudes.getValue(i);
|
||||
double latitude = latitudes.getValue(i);
|
||||
double value = pmsl.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
if (first) {
|
||||
min = value;
|
||||
max = value;
|
||||
first = false;
|
||||
} else {
|
||||
min = Math.min(min, value);
|
||||
max = Math.max(max, value);
|
||||
}
|
||||
}
|
||||
avg += value;
|
||||
}
|
||||
avg /= s;
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PressureColorScheme(avg, min, max));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, pmsl), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PressureColorScheme(101325, 99825, 102825));
|
||||
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.
|
||||
* @param color The color to render with.
|
||||
*/
|
||||
public void renderPerimeters(BufferedImage image, List<List<int[]>> perimeters, float swidth, int color) {
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setColor(new Color(color, true));
|
||||
g.setStroke(new BasicStroke(swidth));
|
||||
int offset = (int)Math.ceil(swidth);
|
||||
for (List<int[]> perimeter: perimeters) {
|
||||
for (int i = 1; i < perimeter.size(); i++) {
|
||||
int x1 = perimeter.get(i - 1)[0];
|
||||
int x2 = perimeter.get(i)[0];
|
||||
int y1 = perimeter.get(i - 1)[1];
|
||||
int y2 = perimeter.get(i)[1];
|
||||
if (x1 == 0) x1 = -offset;
|
||||
if (x2 == 0) x2 = -offset;
|
||||
if (x1 == this.width - 1) x1 = this.width + offset - 1;
|
||||
if (x2 == this.width - 1) x2 = this.width + offset - 1;
|
||||
if (y1 == 0) y1 = -offset;
|
||||
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.dispose();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the perimeters in the picture.
|
||||
*
|
||||
* @param values The values of the picture.
|
||||
* @return The perimeters found in the picture.
|
||||
*/
|
||||
public List<List<int[]>> getPerimeters(IntArray values) {
|
||||
IntArray found = new IntArray(width * height);
|
||||
List<List<int[]>> perimeters = new ArrayList<>();
|
||||
for (int x = 1; x < width - 1; x++) {
|
||||
for (int y = 1; y < height - 1; y++) {
|
||||
int index = y * width + x;
|
||||
if (found.getValue(index) != 0)
|
||||
continue;
|
||||
int cmp = values.getValue(index);
|
||||
i: for (int i = -1; i <= 1; i++) {
|
||||
for (int j = -1; j <= 1; j++) {
|
||||
int nx = Math.min(width - 1, Math.max(0, x + i));
|
||||
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;
|
||||
});
|
||||
List<int[]> perimeter = algo.findPerimenter(x, y);
|
||||
for (int[] v: perimeter) {
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
}
|
||||
perimeters.add(perimeter);
|
||||
break i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return perimeters;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the soil type.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param soilType The soil type.
|
||||
*/
|
||||
public void renderSoilType(BufferedImage image, DoubleArray soilType) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new SoilTypeColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, soilType), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new SoilTypeColorScheme());
|
||||
renderer.renderData(soilType, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the temperature.
|
||||
*
|
||||
*
|
||||
* @param image The image.
|
||||
* @param t2m The temperature.
|
||||
*/
|
||||
public void renderTemperature(BufferedImage image, DoubleArray t2m) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new ScientificTemperatureColorScheme(), Collections.singletonList(new KelvinCelsiusConversion()));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, t2m), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new ScientificTemperatureColorScheme(), Collections.singletonList(new KelvinCelsiusConversion()));
|
||||
renderer.renderData(t2m, image);
|
||||
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.
|
||||
*/
|
||||
public void renderPrecipitation(BufferedImage image, DoubleArray prec) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PrecipitationColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, prec), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PrecipitationColorScheme());
|
||||
renderer.renderData(prec, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the plant coverage.
|
||||
*
|
||||
*
|
||||
* @param image The image to render to.
|
||||
* @param plcov The plant coverage.
|
||||
*/
|
||||
public void renderPlantCover(BufferedImage image, DoubleArray plcov) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PlantCoverColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, plcov), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PlantCoverColorScheme());
|
||||
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.
|
||||
*/
|
||||
@@ -220,7 +324,7 @@ public class ImageGenerator {
|
||||
/**
|
||||
* 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.
|
||||
@@ -240,44 +344,59 @@ public class ImageGenerator {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values and transforms them into an integer.
|
||||
*
|
||||
* @param base The base values.
|
||||
* @param converter The converter.
|
||||
* @return The converted values.
|
||||
*/
|
||||
public IntArray getIntValues(DoubleArray base, IntConverter converter) {
|
||||
IntArray projected = new IntArray(base.getSize());
|
||||
for (int i = 0, s = base.getSize(); i < s; i++) {
|
||||
projected.setValue(i, converter.convert(base.getValue(i)));
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values.
|
||||
*
|
||||
*
|
||||
* @param base The base.
|
||||
* @return The projected values.
|
||||
*/
|
||||
protected DoubleArray getProjectedValues(DoubleArray base) {
|
||||
public DoubleArray getProjectedValues(DoubleArray base) {
|
||||
DoubleArray projected = new DoubleArray(width * height);
|
||||
for (int i = 0, s = Math.min(longitudes.getSize(), Math.min(latitudes.getSize(), base.getSize())); i < s; i++) {
|
||||
double longitude = longitudes.getValue(i);
|
||||
double latitude = latitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int x = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int y = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
projected.setValue(y * width + x, base.getValue(i));
|
||||
if (imageProjection.isVisible(i)) {
|
||||
int x = imageProjection.getX(i);
|
||||
int y = imageProjection.getY(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.
|
||||
*/
|
||||
public void renderCloudCoverage(BufferedImage image, DoubleArray clcm) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new WhiteCloudColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, clcm), image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new WhiteCloudColorScheme());
|
||||
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.
|
||||
@@ -286,40 +405,37 @@ public class ImageGenerator {
|
||||
clearImage(image);
|
||||
IColorScheme cloudScheme = new WhiteCloudColorScheme();
|
||||
IColorScheme depthScheme = new CloudDepthColorScheme();
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
int s = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
s = Math.min(cldepth.getSize(), Math.min(clct.getSize(), s));
|
||||
for (int i = 0; i < s; i++) {
|
||||
double latitude = latitudes.getValue(i);
|
||||
double longitude = longitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int px = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int py = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
if (imageProjection.isVisible(i)) {
|
||||
int px = imageProjection.getX(i);
|
||||
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 fill True to fill, false to draw the outline.
|
||||
* @param color The color to draw the boundaries.
|
||||
*/
|
||||
public void renderBoundaries(BufferedImage image, boolean fill) {
|
||||
public void renderBoundaries(BufferedImage image, Color color) {
|
||||
clearImage(image);
|
||||
getBoundaryRenderer().renderBoundaries(image, fill);
|
||||
getBoundaryRenderer().setColor(color);
|
||||
getBoundaryRenderer().renderBoundaries(image, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the image with a transparent color.
|
||||
*
|
||||
*
|
||||
* @param image The image to clear.
|
||||
*/
|
||||
private void clearImage(BufferedImage image) {
|
||||
@@ -328,5 +444,5 @@ public class ImageGenerator {
|
||||
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 + ")");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -28,7 +28,19 @@ public class NominatimCity extends NominatimObject {
|
||||
* The country that contains this city.
|
||||
*/
|
||||
private long country;
|
||||
|
||||
|
||||
/**
|
||||
* This string contains the is_in relation used to disambiguate
|
||||
* cities during the import.
|
||||
*/
|
||||
private String inside;
|
||||
|
||||
/**
|
||||
* This string is the first name of a parent used to disambiguate
|
||||
* cities during import.
|
||||
*/
|
||||
private String parent;
|
||||
|
||||
/**
|
||||
* Returns the capital.
|
||||
*
|
||||
@@ -101,4 +113,42 @@ public class NominatimCity extends NominatimObject {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the parent.
|
||||
*
|
||||
* @return The parent.
|
||||
*/
|
||||
public String getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the parent.
|
||||
*
|
||||
* @param parent The parent to set.
|
||||
*/
|
||||
public void setParent(String parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the inside.
|
||||
*
|
||||
* @return The inside.
|
||||
*/
|
||||
public String getInside() {
|
||||
return inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the inside.
|
||||
*
|
||||
* @param inside The inside to set.
|
||||
*/
|
||||
public void setInside(String inside) {
|
||||
this.inside = inside;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An implementation of the Douglas Peucker polyline simplification algorithm.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DouglasPeucker {
|
||||
|
||||
/**
|
||||
* An interface for a distance metric.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Metric {
|
||||
|
||||
/**
|
||||
* Computes the distance between two points.
|
||||
*
|
||||
* @param a The first point.
|
||||
* @param b The second point.
|
||||
* @return The distance.
|
||||
*/
|
||||
double getDistance(double[] a, int[] b);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The distance threshold used during simplification.
|
||||
*/
|
||||
private double distance;
|
||||
|
||||
/**
|
||||
* The metric.
|
||||
*/
|
||||
private Metric metric;
|
||||
|
||||
/**
|
||||
* Creates a new algorithm using the specified distance threshold
|
||||
* and a Euclidean distance metric.
|
||||
*
|
||||
* @param distance The threshold distance.
|
||||
*/
|
||||
public DouglasPeucker(double distance) {
|
||||
this((a, b) -> Math.sqrt(Math.pow(a[0] - b[0] ,2) + Math.pow(a [1] - b[1], 2)), distance);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new algorithm using the specified distance threshold
|
||||
* and the specified distance metric.
|
||||
*
|
||||
* @param metric The distance metric.
|
||||
* @param distance The distance threshold..
|
||||
*/
|
||||
public DouglasPeucker(Metric metric, double distance) {
|
||||
this.metric = metric;
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the distance threshold for simplification.
|
||||
*
|
||||
* @return The distance threshold
|
||||
*/
|
||||
public double getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the distance threshold for simplification.
|
||||
*
|
||||
* @param distance The distance to set.
|
||||
*/
|
||||
public void setDistance(double distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplifies a polyline by removing points. The resulting line will not deviate
|
||||
* more than the specified distance as defined by the specified metric.
|
||||
* The algorithm implemented here is the so-called Douglas-Peucker algorithm.
|
||||
*
|
||||
* @param polyline The polyline to simplify.
|
||||
* @return The list with the simplified coordinates.
|
||||
*/
|
||||
public List<int[]> simplify(List<int[]> polyline) {
|
||||
List<int[]> input = new ArrayList<>(polyline);
|
||||
if (input.size() > 2 && metric != null) {
|
||||
List<int[]> result = new ArrayList<>();
|
||||
List<List<int[]>> backlog = new ArrayList<>();
|
||||
backlog.add(input);
|
||||
while (!backlog.isEmpty()) {
|
||||
List<int[]> next = backlog.remove(0);
|
||||
double dmax = 0;
|
||||
int split = -1;
|
||||
for (int i = 1; i < next.size() - 1; i++) {
|
||||
int[] p = next.get(i);
|
||||
double[] c = getClosestPointOnSlope(next.get(0), next.get(next.size() - 1), p);
|
||||
if (c == null) {
|
||||
// special case that the first and last point are identical
|
||||
int[] n = next.get(0);
|
||||
c = new double[] { n[0], n[1] };
|
||||
}
|
||||
double d = metric.getDistance(c, p);
|
||||
if (d > dmax || split == -1) {
|
||||
dmax = d;
|
||||
split = i;
|
||||
}
|
||||
}
|
||||
if (split != -1 && dmax > distance) {
|
||||
List<int[]> first = new ArrayList<>();
|
||||
for (int i = 0; i <= split; i++) {
|
||||
first.add(next.get(i));
|
||||
}
|
||||
List<int[]> second = new ArrayList<>();
|
||||
for (int i = split; i < next.size(); i++) {
|
||||
second.add(next.get(i));
|
||||
}
|
||||
// add the last element twice, again
|
||||
backlog.add(0, second);
|
||||
backlog.add(0, first);
|
||||
} else {
|
||||
result.add(next.get(0));
|
||||
result.add(next.get(next.size() - 1));
|
||||
}
|
||||
}
|
||||
// it is possible that the list will contain duplicates due to
|
||||
// the removal, so lets remove the ones which are really close
|
||||
return deduplicate(result);
|
||||
} else {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes duplicate adjacent coordinates form the polyline. Identical
|
||||
* coordinates are identified by the epsilon.
|
||||
*
|
||||
* @param polyline The polyline.
|
||||
* @return The deduplicated polyline.
|
||||
*/
|
||||
public List<int[]> deduplicate(List<int[]> polyline) {
|
||||
List<int[]> result = new ArrayList<>();
|
||||
if (!polyline.isEmpty()) {
|
||||
result.add(polyline.get(0));
|
||||
for (int i = 1; i < polyline.size(); i++) {
|
||||
int[] prev = result.get(result.size() - 1);
|
||||
int[] next = polyline.get(i);
|
||||
if (prev[0] != next[0] || prev[1] != next[1]) {
|
||||
result.add(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the closest point on a linear slope that is defined
|
||||
* by two points.
|
||||
*
|
||||
* @param line1
|
||||
* The first coordinate of the linear slope.
|
||||
* @param line2
|
||||
* The second coordinate of the linear slope.
|
||||
* @param point
|
||||
* The point to start from.
|
||||
* @return The point that is closest on the linear slope or null
|
||||
* if line1 and line2 are not spanning a linear slope.
|
||||
*/
|
||||
private double[] getClosestPointOnSlope(int[] line1, int[] line2, int[] point) {
|
||||
double line1x = line1[0];
|
||||
double line1y = line1[1];
|
||||
double apx = point[0] - line1x;
|
||||
double apy = point[1] - line1y;
|
||||
double abx = line2[0] - line1x;
|
||||
double aby = line2[1] - line1y;
|
||||
double ab2 = abx * abx + aby * aby;
|
||||
double ap_ab = apx * abx + apy * aby;
|
||||
double t = ap_ab / ab2;
|
||||
if (Double.isInfinite(t) || Double.isNaN(t)) {
|
||||
return null;
|
||||
}
|
||||
return new double[] { line1x + abx * t, line1y + aby * t };
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.ConvolveOp;
|
||||
import java.awt.image.Kernel;
|
||||
|
||||
/**
|
||||
* A class to apply a Gaussian blur filter.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class GaussianBlur {
|
||||
|
||||
/**
|
||||
* The radius.
|
||||
*/
|
||||
private int radius;
|
||||
|
||||
private ConvolveOp horizontal;
|
||||
|
||||
private ConvolveOp vertical;
|
||||
|
||||
/**
|
||||
* Creates a new gaussian blur filter
|
||||
* using the specified radius.
|
||||
*
|
||||
* @param radius The radius.;
|
||||
*/
|
||||
public GaussianBlur(int radius) {
|
||||
if (radius < 1) throw new IllegalArgumentException("Invalid radius.");
|
||||
this.radius = radius;
|
||||
float[] data = getCoefficients(radius);
|
||||
horizontal = new ConvolveOp(new Kernel(data.length, 1, data), ConvolveOp.EDGE_NO_OP, null);
|
||||
vertical = new ConvolveOp(new Kernel(1, data.length, data), ConvolveOp.EDGE_NO_OP, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the radius.
|
||||
*
|
||||
* @return The radius.
|
||||
*/
|
||||
public int getRadius() {
|
||||
return radius;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Applies the filter to the image.
|
||||
*
|
||||
* @param result The result.
|
||||
* @param temp A temporary image.
|
||||
* @param image The image.
|
||||
*/
|
||||
public void apply(BufferedImage result, BufferedImage temp, BufferedImage image) {
|
||||
vertical.filter(horizontal.filter(image, temp), result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the coefficients for the blur with the specified radius.
|
||||
*
|
||||
* @param radius The radius.
|
||||
* @return The coefficients.
|
||||
*/
|
||||
private float[] getCoefficients(int radius) {
|
||||
if (radius < 1) throw new IllegalArgumentException("Invalid radius.");
|
||||
int size = radius * 2 + 1;
|
||||
float[] data = new float[size];
|
||||
|
||||
float sigma = radius / 3.0f;
|
||||
float twoSigmaSquare = 2.0f * sigma * sigma;
|
||||
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
|
||||
float total = 0.0f;
|
||||
|
||||
for (int i = -radius; i <= radius; i++) {
|
||||
float distance = i * i;
|
||||
int index = i + radius;
|
||||
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
|
||||
total += data[index];
|
||||
}
|
||||
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
data[i] /= total;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An implementation of a marching square algorithm mostly stolen from
|
||||
* Phill Spiess development blog. This implementation is modified
|
||||
* to walk off the image by 1 pixel such that the polygons are not
|
||||
* cut off directly at the border which would result in many white
|
||||
* border pixels.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MarchingSquares {
|
||||
|
||||
/**
|
||||
* A raster to search through.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Raster {
|
||||
|
||||
/**
|
||||
* Determines whether the point in the raster
|
||||
* is inside or outside of the area whose
|
||||
* perimeter shall be found.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @return True if x and y are part of the area.
|
||||
*/
|
||||
boolean isArea(int x, int y);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The width of the raster.
|
||||
*/
|
||||
private int width;
|
||||
|
||||
/**
|
||||
* The height of the raster.
|
||||
*/
|
||||
private int height;
|
||||
|
||||
/**
|
||||
* The raster to search through.
|
||||
*/
|
||||
private Raster raster;
|
||||
|
||||
/**
|
||||
* Creates a new marching squares algorithm.
|
||||
*
|
||||
* @param width The width of the image.
|
||||
* @param height The height of the image.
|
||||
* @param data The raster data.
|
||||
*/
|
||||
public MarchingSquares(int width, int height, Raster data) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.raster = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a starting point if there is one.
|
||||
*
|
||||
* @return The starting point [x, y] or null.
|
||||
*/
|
||||
public int[] findStart() {
|
||||
for (int i = 0; i < height; i++) {
|
||||
for (int j = 0; j < width; j++) {
|
||||
if (isArea(j, i)) {
|
||||
return new int[] { j, i };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes an int that encodes the
|
||||
* fill state of 4 pixels.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @return The encoded state.
|
||||
*/
|
||||
private int getState(int x, int y) {
|
||||
int state = 0;
|
||||
if (isArea(x - 1, y - 1))
|
||||
state |= 1;
|
||||
if (isArea(x, y - 1))
|
||||
state |= 2;
|
||||
if (isArea(x - 1, y))
|
||||
state |= 4;
|
||||
if (isArea(x, y))
|
||||
state |= 8;
|
||||
return state;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines the direction for the next step based on
|
||||
* the state of the area around the pixel. The previous
|
||||
* step direction is used for disambiguation.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @param previous The previous step.
|
||||
* @return The next direction.
|
||||
*/
|
||||
private Direction getDirection(int x, int y, Direction previous) {
|
||||
// compute the state based on the fill of 4 points
|
||||
switch (getState(x, y)) {
|
||||
case 1:
|
||||
return Direction.UP;
|
||||
case 2:
|
||||
return Direction.RIGHT;
|
||||
case 3:
|
||||
return Direction.RIGHT;
|
||||
case 4:
|
||||
return Direction.LEFT;
|
||||
case 5:
|
||||
return Direction.UP;
|
||||
case 6:
|
||||
if (previous == Direction.UP)
|
||||
return Direction.LEFT;
|
||||
else
|
||||
return Direction.RIGHT;
|
||||
case 7:
|
||||
return Direction.RIGHT;
|
||||
case 8:
|
||||
return Direction.DOWN;
|
||||
case 9:
|
||||
if (previous == Direction.RIGHT)
|
||||
return Direction.UP;
|
||||
else
|
||||
return Direction.DOWN;
|
||||
case 10:
|
||||
return Direction.DOWN;
|
||||
case 11:
|
||||
return Direction.DOWN;
|
||||
case 12:
|
||||
return Direction.LEFT;
|
||||
case 13:
|
||||
return Direction.UP;
|
||||
case 14:
|
||||
return Direction.LEFT;
|
||||
default:
|
||||
return Direction.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the value at x and y is part of the target area. Pixels
|
||||
* outside the image are considered to be not part of the area to avoid walking
|
||||
* outside of the image.
|
||||
*
|
||||
* @param x
|
||||
* The x coordinate.
|
||||
* @param y
|
||||
* The y coordinate.
|
||||
* @return True if the coordinate
|
||||
*/
|
||||
private boolean isArea(int x, int y) {
|
||||
if (x < 0 || y < 0 || x >= width || y >= height) {
|
||||
return false;
|
||||
} else {
|
||||
return raster.isArea(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the perimeter of the area starting at x and y. Note that the input x
|
||||
* and y must already lie on the perimeter for this method to function properly.
|
||||
*
|
||||
* @param startX
|
||||
* The x coordinate.
|
||||
* @param startY
|
||||
* The y coordinate.
|
||||
* @return The list of coordinates on the perimeter.
|
||||
*/
|
||||
public List<int[]> findPerimenter(int startX, int startY) {
|
||||
// sanity checking
|
||||
startX = Math.max(0, Math.min(width - 1, startX));
|
||||
startY = Math.max(0, Math.min(height - 1, startY));
|
||||
// result list
|
||||
List<int[]> result = new ArrayList<int[]>();
|
||||
// current point
|
||||
int x = startX;
|
||||
int y = startY;
|
||||
Direction previous = Direction.NONE;
|
||||
Direction current = Direction.NONE;
|
||||
do {
|
||||
// Evaluate our state, and set up our next direction
|
||||
current = getDirection(x, y, previous);
|
||||
// If our current point is within our image
|
||||
// add it to the list of points
|
||||
result.add(new int[] { Math.max(0, Math.min(width - 1, x)), Math.max(0, Math.min(height - 1, y)) });
|
||||
switch (current) {
|
||||
case UP:
|
||||
y--;
|
||||
break;
|
||||
case LEFT:
|
||||
x--;
|
||||
break;
|
||||
case DOWN:
|
||||
y++;
|
||||
break;
|
||||
case RIGHT:
|
||||
x++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
previous = current;
|
||||
} while (x != startX || y != startY);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The direction to follow the perimeter.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private enum Direction {
|
||||
NONE, UP, DOWN, LEFT, RIGHT
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A class to apply morphological operations on rectangular masks.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Morphology {
|
||||
|
||||
/**
|
||||
* An interface for operators.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Operator {
|
||||
/**
|
||||
* Applies the operator to to the value.
|
||||
*
|
||||
* @param value The value.
|
||||
* @param previous The previous value.
|
||||
* @return The result of the operation.
|
||||
*/
|
||||
double apply(double value, Double previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* An operator to apply erosion.
|
||||
*/
|
||||
public static final Operator ERODE = (v, p) -> { if (p == null) return v; else return Math.min(v, p); };
|
||||
|
||||
/**
|
||||
* An operator to apply dilation.
|
||||
*/
|
||||
public static final Operator DILATE = (v, p) -> { if (p == null) return v; else return Math.max(v, p); };
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*/
|
||||
private int width;
|
||||
/**
|
||||
* The height of the image.
|
||||
*/
|
||||
private int height;
|
||||
/**
|
||||
* The size of the mask in pixels.
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Creates a new class to run morphological operations on the
|
||||
* image with the specified dimensions using a mask of the specified size.
|
||||
*
|
||||
* @param width The width.
|
||||
* @param height The height.
|
||||
* @param size The size.
|
||||
*/
|
||||
public Morphology(int width, int height, int size) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.size = Math.abs(size);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Applies the operator to the values inside the result.
|
||||
*
|
||||
* @param result The result.
|
||||
* @param values The values.
|
||||
* @param operator The operator.
|
||||
*/
|
||||
public void apply(DoubleArray result, DoubleArray values, Operator operator) {
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
for (int j = size, hs = height - size; j < hs; j++) {
|
||||
Double current = null;
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
int x = (i + k);
|
||||
int y = (j + l);
|
||||
current = operator.apply(values.getValue(y * width + x), current);
|
||||
}
|
||||
}
|
||||
result.setValue(j * width + i, current);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the local minima in the values.
|
||||
*
|
||||
* @param values The values.
|
||||
* @return The local minima.
|
||||
*/
|
||||
public List<int[]> getMinima(DoubleArray values) {
|
||||
|
||||
List<int[]> results = new ArrayList<>();
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
j: for (int j = size, hs = height - size; j < hs; j++) {
|
||||
double current = values.getValue(j * width + i);
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
double v = values.getValue((j + l) * width + (i + k));
|
||||
if (v < current) continue j;
|
||||
}
|
||||
}
|
||||
results.add(new int[] { i, j });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the local maxima in the values.
|
||||
*
|
||||
* @param values The values.
|
||||
* @return The local maxima.
|
||||
*/
|
||||
public List<int[]> getMaxima(DoubleArray values) {
|
||||
List<int[]> results = new ArrayList<>();
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
j: for (int j = size, hs = height - size; j < hs; j++) {
|
||||
double current = values.getValue(j * width + i);
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
double v = values.getValue((j + l) * width + (i + k));
|
||||
if (v > current) continue j;
|
||||
}
|
||||
}
|
||||
results.add(new int[] { i, j });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
+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];
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ public class KelvinCelsiusConversion implements IDataConversion {
|
||||
/**
|
||||
* The constant to convert Kelvin to degree's Celsius.
|
||||
*/
|
||||
private static final double ZERO = -273.15;
|
||||
public static final double ZERO = -273.15;
|
||||
|
||||
|
||||
@Override
|
||||
|
||||
@@ -61,6 +61,7 @@ public class ColorScaleRenderer {
|
||||
* Creates a new color scale renderer.
|
||||
*
|
||||
* @param colorScheme The scheme to render.
|
||||
* @param provider A label provider.
|
||||
*/
|
||||
public ColorScaleRenderer(IColorScheme colorScheme, LabelProvider provider) {
|
||||
this.colorScheme = colorScheme;
|
||||
@@ -127,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();
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
package com.mowesta.data.process.image;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.DataBufferInt;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.color.IColorScheme;
|
||||
import com.mowesta.data.process.conversion.IDataConversion;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
import com.mowesta.data.process.source.IDataSource;
|
||||
import com.mowesta.data.process.projection.ImageProjection;
|
||||
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 projection to convert wgs84 into image coordinates.
|
||||
* The image projection to speed up the projection process.
|
||||
*/
|
||||
protected IProjection projection;
|
||||
protected ImageProjection projection;
|
||||
|
||||
/**
|
||||
* The color scheme to apply to the pixels based on the values.
|
||||
*/
|
||||
protected IColorScheme scheme;
|
||||
|
||||
/**
|
||||
* An optional list of data conversions.
|
||||
*/
|
||||
@@ -32,55 +35,79 @@ 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(IProjection projection, IColorScheme scheme) {
|
||||
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
|
||||
* each data value before passing it to the color scheme in the order in which
|
||||
* it appears in the list.
|
||||
*/
|
||||
public DataRenderer(IProjection projection, IColorScheme scheme, List<IDataConversion> conversions) {
|
||||
public DataRenderer(ImageProjection projection, IColorScheme scheme, List<IDataConversion> conversions) {
|
||||
this.projection = projection;
|
||||
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(IDataSource source, BufferedImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
while (source.moveNext()) {
|
||||
double latitude = source.getLatitude();
|
||||
double longitude = source.getLongitude();
|
||||
double value = source.getValue();
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int px = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int py = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
for (int i = 0; i < conversions.size(); i++) {
|
||||
public void renderData(DoubleArray source, BufferedImage image) {
|
||||
DataBufferInt r = (DataBufferInt)image.getRaster().getDataBuffer();
|
||||
int w = image.getWidth();
|
||||
int cs = conversions.size();
|
||||
for (int index = 0, s = source.getSize(); index < s; index++) {
|
||||
if (projection.isVisible(index)) {
|
||||
int px = projection.getX(index);
|
||||
int py = projection.getY(index);
|
||||
double value = source.getValue(index);
|
||||
for (int i = 0; i < cs; i++) {
|
||||
value = conversions.get(i).convert(value);
|
||||
}
|
||||
int color = scheme.getColor(value);
|
||||
image.setRGB(px, py, color);
|
||||
r.setElem(py * w + px, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.mowesta.data.process.projection;
|
||||
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
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.
|
||||
*
|
||||
* @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.
|
||||
* @param width The width of the image.
|
||||
* @param height The height of the image.
|
||||
*/
|
||||
public ImageProjection(IProjection projection, DoubleArray longitudes, DoubleArray latitudes, int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
size = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
this.x = new IntArray(size);
|
||||
this.y = new IntArray(size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
double latitude = latitudes.getValue(i);
|
||||
double longitude = longitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
x.setValue(i,Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width))));
|
||||
y.setValue(i, Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height))));
|
||||
} else {
|
||||
x.setValue(i, -1);
|
||||
y.setValue(i, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -165,9 +165,9 @@ public class VideoEncoder {
|
||||
*/
|
||||
private int height;
|
||||
/**
|
||||
* The bitrate.
|
||||
* The constant rate factor to set the target quality.
|
||||
*/
|
||||
private int bitrate;
|
||||
private int crf;
|
||||
/**
|
||||
* The quality preset of the encoder.
|
||||
*/
|
||||
@@ -207,17 +207,17 @@ public class VideoEncoder {
|
||||
* @param height The height of the video and the input images.
|
||||
* @param format The image format that defines the pixel layout and the number of bytes per pixel.
|
||||
* @param fps The play back speed in frames per second.
|
||||
* @param bitrate The target bitrate in kbs.
|
||||
* @param crf The constant rate factor between 0 (no compression) to 51 (high loss, small size).
|
||||
* @param quality The quality preset to balance the encoder quality and processing effort.
|
||||
*
|
||||
* @throws IOException Thrown if the allocation of the various objects fails.
|
||||
* @throws NullPointerException Thrown if the quality preset or image format is null.
|
||||
* @throws IllegalArgumentException Thrown if the width, height, fps or bitrate is not positive.
|
||||
*/
|
||||
public VideoEncoder(int width, int height, PixelFormat format, int fps, int bitrate, Quality quality) throws IOException {
|
||||
public VideoEncoder(int width, int height, PixelFormat format, int fps, int crf, Quality quality) throws IOException {
|
||||
if (width <= 0) throw new IllegalArgumentException("Invalid image width (" + width + "), must be positive.");
|
||||
if (height <= 0) throw new IllegalArgumentException("Invalid image height (" + height + "), must be positive.");
|
||||
if (bitrate <= 0) throw new IllegalArgumentException("Invalid bitrate (" + bitrate + "), must be positive.");
|
||||
if (crf < 0 || crf > 51) throw new IllegalArgumentException("Invalid crf (" + crf + "), must be (good) 0-51 (bad).");
|
||||
if (fps <= 0) throw new IllegalArgumentException("Invalid fps (" + fps + "), must be positive.");
|
||||
if (format == null) throw new NullPointerException("Image format must not be null.");
|
||||
if (quality == null) throw new NullPointerException("Quality preset must not be null.");
|
||||
@@ -227,7 +227,7 @@ public class VideoEncoder {
|
||||
this.format = format;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.bitrate = bitrate;
|
||||
this.crf = crf;
|
||||
this.quality = quality;
|
||||
|
||||
logger.log(Level.FINEST, "Configuring log level.");
|
||||
@@ -256,7 +256,6 @@ public class VideoEncoder {
|
||||
videoStream.codecpar().width(width);
|
||||
videoStream.codecpar().height(height);
|
||||
videoStream.codecpar().format(avutil.AV_PIX_FMT_YUV420P); // change format
|
||||
videoStream.codecpar().bit_rate(bitrate * 1000);
|
||||
AVRational timeBase = avutil.av_make_q(1, fps);
|
||||
codecContext.time_base(timeBase);
|
||||
videoStream.time_base(timeBase);
|
||||
@@ -271,6 +270,8 @@ public class VideoEncoder {
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
error = avutil.av_opt_set(codecContext, "b_strategy", "2", avutil.AV_OPT_SEARCH_CHILDREN);
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
error = avutil.av_opt_set(codecContext, "crf", Integer.toString(crf), avutil.AV_OPT_SEARCH_CHILDREN);
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
}
|
||||
logger.log(Level.FINEST, "Setting format header flags.");
|
||||
if ((formatContext.oformat().flags() & avformat.AVFMT_GLOBALHEADER) != 0) {
|
||||
@@ -392,12 +393,12 @@ public class VideoEncoder {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the target bitrate of the encoder.
|
||||
* Returns the constant rate factor of the encoder.
|
||||
*
|
||||
* @return The target bitrate of the encoder.
|
||||
* @return The constant rate factor of the encoder.
|
||||
*/
|
||||
public int getBitrate() {
|
||||
return bitrate;
|
||||
public int getCrf() {
|
||||
return crf;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user