Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84fd69dfdb | ||
|
|
8c174f8581 | ||
|
|
6bd040272b | ||
|
|
2d2caaed09 | ||
|
|
cf99d87a66 | ||
|
|
778677ec40 | ||
|
|
485f56e547 | ||
|
|
13080b113b | ||
|
|
d1fc3bee96 | ||
|
|
8bd0cf7bc2 | ||
|
|
c306987b63 | ||
|
|
84beb97a73 | ||
|
|
82b7b5544d | ||
|
|
942e42ae76 | ||
|
|
ed8846d950 | ||
|
|
6bd27b2eff | ||
|
|
ef86399ba3 | ||
|
|
6b5f85fe5f | ||
|
|
822f4044f7 | ||
|
|
7414860ace | ||
|
|
61bb009959 |
Vendored
+1
-1
@@ -59,7 +59,7 @@ node {
|
||||
|
||||
// deploy the build output on the server
|
||||
stage ('Deploy') {
|
||||
//release = true; // uncomment to temporary enable snapshot deployments
|
||||
// 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"
|
||||
|
||||
@@ -16,9 +16,9 @@ ext {
|
||||
versionAndroidXConstraint = '1.1.3'
|
||||
versionAndroidXNavigation = '2.3.0'
|
||||
versionAndroidXLifecycle = '2.2.0'
|
||||
versionAndroidXSecurity = '1.1.0-alpha01'
|
||||
versionAndroidXSecurity = '1.1.0-alpha02'
|
||||
versionAndroidXViewpager = '1.0.0'
|
||||
versionGoogleMaterial = '1.1.0'
|
||||
versionGoogleMaterial = '1.2.0'
|
||||
versionAndroidXSwipeRefresh = '1.1.0'
|
||||
versionExoPlayer = '2.11.5'
|
||||
}
|
||||
@@ -88,7 +88,7 @@ android {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 29
|
||||
versionCode 9
|
||||
versionCode 10
|
||||
versionName "${version}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -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 = () -> {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
+2
-2
@@ -29,7 +29,7 @@ allprojects {
|
||||
|
||||
// set version for our project
|
||||
group = 'com.mowesta'
|
||||
version = '1.0.9'
|
||||
version = '1.0.10'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
@@ -57,7 +57,7 @@ allprojects {
|
||||
mapstructVersion = '1.3.1.Final'
|
||||
// shared android dependencies
|
||||
versionAndroidXTest = '1.2.0'
|
||||
versionAndroidXAppcompat = '1.1.0'
|
||||
versionAndroidXAppcompat = '1.2.0'
|
||||
versionAndroidXRoom = '2.2.5'
|
||||
versionAndroidXPreference = '1.1.1'
|
||||
versionRobolectric = '4.3.1'
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -84,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:
|
||||
@@ -129,7 +129,6 @@ public class VideoConfiguration {
|
||||
public VideoFrameComposer createComposer(Time time) throws IOException {
|
||||
IProjection projection = new CroppedProjection(new MercatorProjection(), CropType.COORDINATE, minLongitude, maxLatitude, maxLongitude, minLatitude);
|
||||
VideoImageRenderer generator = new VideoImageRenderer(prediction.getLongitues(time), prediction.getLatitudes(time), projection, imageWidth, imageHeight);
|
||||
generator.getBoundaryRenderer().setColor(new Color(0xC0f9a825, true));
|
||||
VideoFrameComposer result = new VideoFrameComposer(generator, createOverlay(generator), frameWidth, frameHeight);
|
||||
return result;
|
||||
}
|
||||
@@ -147,13 +146,29 @@ public class VideoConfiguration {
|
||||
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:
|
||||
|
||||
@@ -64,6 +64,7 @@ public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
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);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -140,7 +141,7 @@ public abstract class AbstractVideoRenderer {
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
if (overlayImage == null) {
|
||||
overlayImage = getComposer().createImage();
|
||||
getRenderer().renderBoundaries(overlayImage, false);
|
||||
getRenderer().renderBoundaries(overlayImage, new Color(0x44000000, true));
|
||||
}
|
||||
return overlayImage;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -38,7 +39,12 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
* The filtered image.
|
||||
*/
|
||||
protected BufferedImage filterImage;
|
||||
|
||||
|
||||
/**
|
||||
* The filtered image.
|
||||
*/
|
||||
protected BufferedImage filterImage2;
|
||||
|
||||
/**
|
||||
* Creates a new pressure video renderer.
|
||||
*
|
||||
@@ -61,9 +67,20 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
if (filterImage == null) {
|
||||
filterImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(filterImage);
|
||||
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.
|
||||
@@ -78,7 +95,7 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, false);
|
||||
getRenderer().renderBoundaries(temp, new Color(0x44000000, true));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
@@ -92,6 +109,7 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
// find the perimeters for the iso lines
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data);
|
||||
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
|
||||
@@ -100,14 +118,17 @@ public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
}
|
||||
// render onto temp image
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 1.5f, 0xffffffff);
|
||||
getRenderer().renderPerimeters(temp, result, 2f, 0xffffffff);
|
||||
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
blur.apply(filter, getFilterImage2(), temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
|
||||
+14
-33
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -7,7 +8,6 @@ import java.util.List;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.process.algorithm.GaussianBlur;
|
||||
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
@@ -30,16 +30,6 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
*/
|
||||
protected BufferedImage borderImage;
|
||||
|
||||
/**
|
||||
* The image for the filter.
|
||||
*/
|
||||
protected BufferedImage filterImage;
|
||||
|
||||
/**
|
||||
* A filter to apply a Gaussian blur.
|
||||
*/
|
||||
protected GaussianBlur blur = new GaussianBlur(2);
|
||||
|
||||
/**
|
||||
* The distance of the isotherms in degree celsius.
|
||||
*/
|
||||
@@ -57,20 +47,7 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
super(generator, Variable.T2M, time);
|
||||
this.isoDistance = isoDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage() {
|
||||
if (filterImage == null) {
|
||||
filterImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(filterImage);
|
||||
return filterImage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
@@ -84,7 +61,7 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, false);
|
||||
getRenderer().renderBoundaries(temp, new Color(0x44000000, true));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
@@ -100,17 +77,21 @@ public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
List<List<int[]>> result = new ArrayList<>(ps.size());
|
||||
for (List<int[]> p : ps) {
|
||||
if (p.size() > 30) {
|
||||
if (p.size() > 25) {
|
||||
result.add(p);
|
||||
}
|
||||
}
|
||||
// render onto temp image
|
||||
// render onto temp image (without transparency, since it is too expensive)
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 0.25f, 0xcc444444);
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.mowesta.data.dwd.render;
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
@@ -25,7 +24,6 @@ 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.projection.ImageProjection;
|
||||
import com.mowesta.data.process.source.DoubleArraySource;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
@@ -158,7 +156,7 @@ public class VideoImageRenderer {
|
||||
public void renderPressure(BufferedImage image, DoubleArray pmsl) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PressureColorScheme(101325, 99825, 102825));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, pmsl), image);
|
||||
renderer.renderData(pmsl, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -174,21 +172,24 @@ public class VideoImageRenderer {
|
||||
public void renderPerimeters(BufferedImage image, List<List<int[]>> perimeters, float swidth, int color) {
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setColor(new Color(color, true));
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setStroke(new BasicStroke(swidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
g.setStroke(new BasicStroke(swidth));
|
||||
int offset = (int)Math.ceil(swidth);
|
||||
for (List<int[]> perimeter: perimeters) {
|
||||
int[] x = new int[perimeter.size()];
|
||||
int[] y = new int[perimeter.size()];
|
||||
for (int i = 0; i < perimeter.size(); i++) {
|
||||
x[i] = perimeter.get(i)[0];
|
||||
if (x[i] == 0) x[i] = -offset;
|
||||
if (x[i] == this.width - 1) x[i] = this.width + offset - 1;
|
||||
y[i] = perimeter.get(i)[1];
|
||||
if (y[i] == 0) y[i] = -offset;
|
||||
if (y[i] == height - 1) y[i] = this.height + offset - 1;
|
||||
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.drawPolyline(x, y, x.length);
|
||||
}
|
||||
g.dispose();
|
||||
}
|
||||
@@ -205,9 +206,10 @@ public class VideoImageRenderer {
|
||||
List<List<int[]>> perimeters = new ArrayList<>();
|
||||
for (int x = 1; x < width - 1; x++) {
|
||||
for (int y = 1; y < height - 1; y++) {
|
||||
if (found.getValue(y * width + x) != 0)
|
||||
int index = y * width + x;
|
||||
if (found.getValue(index) != 0)
|
||||
continue;
|
||||
int cmp = values.getValue(y * width + x);
|
||||
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));
|
||||
@@ -218,12 +220,7 @@ public class VideoImageRenderer {
|
||||
});
|
||||
List<int[]> perimeter = algo.findPerimenter(x, y);
|
||||
for (int[] v: perimeter) {
|
||||
try {
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
} catch (ArrayIndexOutOfBoundsException e) {
|
||||
System.out.println(v[1] + " " + v[0] + " " + width + " " + height);
|
||||
throw e;
|
||||
}
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
}
|
||||
perimeters.add(perimeter);
|
||||
break i;
|
||||
@@ -246,7 +243,7 @@ public class VideoImageRenderer {
|
||||
public void renderSoilType(BufferedImage image, DoubleArray soilType) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new SoilTypeColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, soilType), image);
|
||||
renderer.renderData(soilType, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -259,7 +256,7 @@ public class VideoImageRenderer {
|
||||
public void renderTemperature(BufferedImage image, DoubleArray t2m) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new ScientificTemperatureColorScheme(), Collections.singletonList(new KelvinCelsiusConversion()));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, t2m), image);
|
||||
renderer.renderData(t2m, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -273,7 +270,7 @@ public class VideoImageRenderer {
|
||||
public void renderPrecipitation(BufferedImage image, DoubleArray prec) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PrecipitationColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, prec), image);
|
||||
renderer.renderData(prec, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -287,7 +284,7 @@ public class VideoImageRenderer {
|
||||
public void renderPlantCover(BufferedImage image, DoubleArray plcov) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PlantCoverColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, plcov), image);
|
||||
renderer.renderData(plcov, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -371,7 +368,7 @@ public class VideoImageRenderer {
|
||||
public void renderCloudCoverage(BufferedImage image, DoubleArray clcm) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new WhiteCloudColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, clcm), image);
|
||||
renderer.renderData(clcm, image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
@@ -406,11 +403,12 @@ public class VideoImageRenderer {
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -418,7 +416,7 @@ public class VideoImageRenderer {
|
||||
*
|
||||
* @param image The image to clear.
|
||||
*/
|
||||
private void clearImage(BufferedImage image) {
|
||||
private void clearImage(BufferedImage image) {
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setBackground(new Color(0x00000000, true));
|
||||
g.clearRect(0, 0, image.getWidth(), image.getHeight());
|
||||
|
||||
@@ -49,10 +49,11 @@ public class GaussianBlur {
|
||||
* 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 image) {
|
||||
vertical.filter(horizontal.filter(image, null), result);
|
||||
public void apply(BufferedImage result, BufferedImage temp, BufferedImage image) {
|
||||
vertical.filter(horizontal.filter(image, temp), result);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
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.ImageProjection;
|
||||
import com.mowesta.data.process.source.IDataSource;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A class to generate an image from a data stream using a projection.
|
||||
@@ -64,20 +65,21 @@ public class DataRenderer {
|
||||
* @param source The data source.
|
||||
* @param image The image to render to.
|
||||
*/
|
||||
public void renderData(IDataSource source, BufferedImage image) {
|
||||
int index = 0;
|
||||
while (source.moveNext()) {
|
||||
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();
|
||||
for (int i = 0; i < conversions.size(); i++) {
|
||||
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);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ public class VideoInterpolator {
|
||||
/**
|
||||
* Motion interpolation.
|
||||
*/
|
||||
MOTION("minterpolate='mi_mode=mci:me=ds:me_mode=bilat:search_param=64:scd=none:fps=%d',format=pix_fmts=%d"),
|
||||
MOTION("minterpolate='mi_mode=mci:me=ds:me_mode=bilat:search_param=64:vsbmc=1:scd=none:fps=%d',format=pix_fmts=%d"),
|
||||
/**
|
||||
* Motion interpolation mixed with blending.
|
||||
*/
|
||||
|
||||
@@ -242,6 +242,8 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
|
||||
/**
|
||||
* Returns the maximum modification time stamp for a particular device.
|
||||
* If device is null the maximum modification time stamp for all measurements
|
||||
* of all devices is returned.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param device The device to search.
|
||||
@@ -252,17 +254,47 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class); // from MeasurementEntity e
|
||||
cq.select(cb.max(r.get("modificationTime").as(Long.class))); // max modification time
|
||||
cq.where(cb.equal(r.get("device"), device)); // e.device=:device
|
||||
if (device != null) {
|
||||
cq.where(cb.equal(r.get("device"), device)); // e.device=:device
|
||||
}
|
||||
TypedQuery<Long> q = em.createQuery(cq);
|
||||
return getSingleResultOrZero(q).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the number of measurement whose start and duration time matches and
|
||||
* belongs to device.
|
||||
/**
|
||||
* Counts the number of measurement whose start and duration time matches.
|
||||
* The data set can contain measurements of more than one particular device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param timeRange The time range.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The number of results.
|
||||
*/
|
||||
public static int countByTimeRange(EntityManager em, TimeRange timeRange, boolean filtered) {
|
||||
return countByDeviceAndTimeRange(em, null, timeRange, filtered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all measurement by start and duration time.
|
||||
* The data set can contain measurements of more than one particular device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param config The page configuration.
|
||||
* @param timeRange The time range.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The list to fill the page.
|
||||
*/
|
||||
public static List<MeasurementEntity> findAllByTimeRange(EntityManager em, PageConfig config,
|
||||
TimeRange timeRange, boolean filtered) {
|
||||
return findAllByDeviceAndTimeRange(em, config, null, timeRange, filtered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the number of measurement whose start and duration time matches.
|
||||
* If device is not null it only filters for the specified device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param device The device to search measurements for.
|
||||
* @param device The device to search measurements for or null.
|
||||
* @param timeRange The time range.
|
||||
* @param filtered True to filter deleted.
|
||||
* @return The number of results.
|
||||
@@ -272,8 +304,10 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class); // from MeasurementEntity e
|
||||
cq.select(cb.count(r)); // select count(e)
|
||||
Predicate is = cb.and(cb.equal(r.get("device"), device), // e.device_id=:device_id
|
||||
cb.between(r.get("time"), timeRange.getStart(), timeRange.getEnd())); // and e.time between start and end
|
||||
Predicate is = cb.between(r.get("time"), timeRange.getStart(), timeRange.getEnd()); // e.time between start and end
|
||||
if (device != null) {
|
||||
is = cb.and(cb.equal(r.get("device"), device), is); // e.device_id=:device_id and (e.time between start and end)
|
||||
}
|
||||
if (filtered) {
|
||||
cq.where(cb.and(cb.equal(r.get("deleted"), false), is)); // and not deleted
|
||||
} else {
|
||||
@@ -284,10 +318,11 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all measurement by start and duration time and belongs to device.
|
||||
* Finds all measurement by start and duration time.
|
||||
* If device is not null it only filters for the specified device.
|
||||
*
|
||||
* @param em The entity manager.
|
||||
* @param device The device to search measurements for.
|
||||
* @param device The device to search measurements for or null.
|
||||
* @param config The page configuration.
|
||||
* @param timeRange The time range.
|
||||
* @param filtered True to filter deleted.
|
||||
@@ -299,18 +334,21 @@ public class MeasurementEntity extends AbstractSpatialEntity {
|
||||
CriteriaQuery<MeasurementEntity> cq = cb.createQuery(MeasurementEntity.class);
|
||||
Root<MeasurementEntity> r = cq.from(MeasurementEntity.class); // from MeasuementEntity e
|
||||
cq.select(r); // select E
|
||||
Predicate is = cb.and(cb.equal(r.get("device"), device), // e.device=:device
|
||||
cb.between(r.get("time"), timeRange.getStart(), timeRange.getEnd() )); // and e.time between start and end
|
||||
Predicate is = cb.between(r.get("time"), timeRange.getStart(), timeRange.getEnd()); // e.time between start and end
|
||||
if (device != null){
|
||||
is = cb.and(cb.equal(r.get("device"), device), is); // e.device=:device and (e.time between start and end)
|
||||
cq.orderBy(cb.desc(r.get("time")));
|
||||
} else {
|
||||
cq.orderBy(cb.asc(r.get("device")), cb.desc(r.get("time")));
|
||||
}
|
||||
if (filtered) {
|
||||
cq.where(cb.and(cb.equal(r.get("deleted"), false), is)); // and not deleted
|
||||
} else {
|
||||
cq.where(is); // ignore deleted
|
||||
}
|
||||
cq.orderBy(cb.desc(r.get("time")));
|
||||
TypedQuery<MeasurementEntity> q = em.createQuery(cq);
|
||||
q.setFirstResult(config.getOffset());
|
||||
q.setMaxResults(config.getSize());
|
||||
return q.getResultList();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -41,7 +41,20 @@ public class DataSessionBean {
|
||||
|
||||
@Inject
|
||||
protected WeatherSessionBean forecastSession;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Initializes the database with the default roles and users.
|
||||
* Can be overridden by subclasses to be flexible and add more
|
||||
* data at start up, e.g. for testing purposes.
|
||||
*/
|
||||
@PermitAll
|
||||
@TransactionAttribute(TransactionAttributeType.REQUIRED)
|
||||
public void initData() {
|
||||
initRoles();
|
||||
initUsers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the database with the default roles.
|
||||
*/
|
||||
@@ -76,8 +89,7 @@ public class DataSessionBean {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Initializes a default set of users.
|
||||
*/
|
||||
|
||||
@@ -4,6 +4,8 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.annotation.security.DeclareRoles;
|
||||
@@ -53,6 +55,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
MeasurementEntity existing = MeasurementEntity.findByDeviceAndTime(em, device, m.getTime());
|
||||
if (existing == null) {
|
||||
MeasurementEntity e = createMeasurement(device, m);
|
||||
device.touch(); // update device modification time stamp
|
||||
if (e.getCoordinate() == null) {
|
||||
log.log(Level.WARNING, "Ignoring measurement without (valid) gps position.", e);
|
||||
} else {
|
||||
@@ -82,6 +85,7 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
MeasurementEntity existing = MeasurementEntity.findByDeviceAndTime(em, device, m.getTime());
|
||||
if (existing == null) {
|
||||
MeasurementEntity e = createMeasurement(device, m);
|
||||
device.touch(); // update device modification time stamp
|
||||
em.persist(e);
|
||||
em.flush();
|
||||
return Convert.with(MeasurementConverter.class).apply(e, true);
|
||||
@@ -231,12 +235,11 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
* @return The last modification time stamp.
|
||||
* @throws EntityNotFoundException Thrown if there is no caller principal.
|
||||
*/
|
||||
@RolesAllowed({Roles.DEVICE })
|
||||
@RolesAllowed({ Roles.DEVICE })
|
||||
public long getLastModifiedMeasurement() throws EntityNotFoundException {
|
||||
DeviceEntity principal = getPrincipalDevice();
|
||||
if (principal == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot access principal device.");
|
||||
return MeasurementEntity.getLastModifiedForDevice(em, principal);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,6 +256,34 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
return MeasurementEntity.getLastModifiedForDevice(em, device);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last modification timestamp of all measurements.
|
||||
*
|
||||
* @return The last modification time stamp.
|
||||
*/
|
||||
@RolesAllowed({ Roles.ADMIN })
|
||||
public long getLastModifiedMeasurementForAllDevices() {
|
||||
return MeasurementEntity.getLastModifiedForDevice(em, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a measurement page for a specific time range. The page can
|
||||
* contain measurements from more than one device.
|
||||
*
|
||||
* @param range The time range.
|
||||
* @param config The page configuration.
|
||||
* @param filtered True to filter deleted, false otherwise.
|
||||
* @return The measurement page.
|
||||
*/
|
||||
@RolesAllowed({ Roles.ADMIN })
|
||||
public MeasurementPage getMeasurements(TimeRange range, PageConfig config, boolean filtered) {
|
||||
return createMeasurementPage(config,
|
||||
() -> MeasurementEntity.countByTimeRange(em, range, filtered),
|
||||
(page) -> page.setElements(Convert.with(MeasurementConverter.class).apply(
|
||||
MeasurementEntity.findAllByTimeRange(em, config, range, filtered),
|
||||
filtered)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a measurement page for a specific device and time range.
|
||||
*
|
||||
@@ -263,15 +294,30 @@ public class MeasurementSessionBean extends AbstractUserSpecificSessionBean {
|
||||
* @return The measurement page.
|
||||
*/
|
||||
protected MeasurementPage getDeviceMeasurements(DeviceEntity device, TimeRange range, PageConfig config, boolean filtered) {
|
||||
return createMeasurementPage(config,
|
||||
() -> MeasurementEntity.countByDeviceAndTimeRange(em, device, range, filtered),
|
||||
(page) -> page.setElements(Convert.with(MeasurementConverter.class).apply(
|
||||
MeasurementEntity.findAllByDeviceAndTimeRange(em, config, device, range, filtered),
|
||||
filtered)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a measurement page.
|
||||
*
|
||||
* @param config The page configuration.
|
||||
* @param measurementCount Supplies the total amount of measurements for this call.
|
||||
* @param findAll Retrieves the actual measurements and adds it to the given page.
|
||||
* @return The measurement page.
|
||||
*/
|
||||
private MeasurementPage createMeasurementPage(PageConfig config, IntSupplier measurementCount,
|
||||
Consumer<MeasurementPage> findAll) {
|
||||
MeasurementPage page = new MeasurementPage();
|
||||
page.setOffset(config.getOffset());
|
||||
page.setSize(config.getSize());
|
||||
int count = MeasurementEntity.countByDeviceAndTimeRange(em, device, range, filtered);
|
||||
int count = measurementCount.getAsInt();
|
||||
page.setTotal(count);
|
||||
if (count > config.getOffset()) {
|
||||
page.setElements(Convert.with(MeasurementConverter.class).apply(
|
||||
MeasurementEntity.findAllByDeviceAndTimeRange(em, config, device, range, filtered),
|
||||
filtered));
|
||||
findAll.accept(page);
|
||||
// temporary hack to show the ambient or battery temperature, if there is no other temperature source
|
||||
if (page.getElements() != null) {
|
||||
for (Measurement m: page.getElements()) {
|
||||
|
||||
@@ -34,8 +34,7 @@ public class StartupSessionBean {
|
||||
@PostConstruct
|
||||
@TransactionAttribute(TransactionAttributeType.NEVER)
|
||||
public void onConstruct() {
|
||||
dataSession.initRoles();
|
||||
dataSession.initUsers();
|
||||
dataSession.initData();
|
||||
syncSession.startTimer();
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -58,17 +58,17 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
|
||||
* in sync with the sources definition.
|
||||
*/
|
||||
public static final NumericPrediction[] PREDICTIONS = new NumericPrediction[] {
|
||||
new NumericPrediction(PredictionType.ICON_GLOBAL, new File(DeploymentConstants.FOLDER_DWD, "icon-global")), // 3mio entries, 113 files per variable
|
||||
new NumericPrediction(PredictionType.COSMO_EUROPE, new File(DeploymentConstants.FOLDER_DWD, "cosmo-eu")), // entries, 28 files per variable
|
||||
new NumericPrediction(PredictionType.ICON_EUROPE, new File(DeploymentConstants.FOLDER_DWD, "icon-eu")), // 720K entries, 93 files per variable
|
||||
new NumericPrediction(PredictionType.COSMO_EUROPE, new File(DeploymentConstants.FOLDER_DWD, "cosmo-eu")) // entries, 28 files per variable
|
||||
new NumericPrediction(PredictionType.ICON_GLOBAL, new File(DeploymentConstants.FOLDER_DWD, "icon-global")) // 3mio entries, 113 files per variable
|
||||
};
|
||||
/**
|
||||
* The weather sources that are used for the corresponding indexes.
|
||||
*/
|
||||
public static final WeatherSource[] SOURCES = new WeatherSource[] {
|
||||
WeatherSource.ICON_GLOBAL,
|
||||
WeatherSource.COSMO_EUROPE,
|
||||
WeatherSource.ICON_EUROPE,
|
||||
WeatherSource.COSMO_EUROPE
|
||||
WeatherSource.ICON_GLOBAL,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mowesta.service.session.test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.annotation.security.PermitAll;
|
||||
@@ -7,9 +8,17 @@ import javax.ejb.Stateless;
|
||||
import javax.enterprise.inject.Alternative;
|
||||
|
||||
import com.mowesta.api.access.Roles;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.service.crypto.SecureToken;
|
||||
import com.mowesta.service.crypto.TokenType;
|
||||
import com.mowesta.service.entity.DeviceEntity;
|
||||
import com.mowesta.service.entity.EmbeddedCoordinate;
|
||||
import com.mowesta.service.entity.MeasurementEntity;
|
||||
import com.mowesta.service.entity.UserEntity;
|
||||
import com.mowesta.service.session.DataSessionBean;
|
||||
|
||||
|
||||
/**
|
||||
* An extended implementation of the data session
|
||||
* bean that initializes the database in a more
|
||||
@@ -20,15 +29,28 @@ import com.mowesta.service.session.DataSessionBean;
|
||||
@Alternative
|
||||
@Stateless
|
||||
public class DataTestBean extends DataSessionBean {
|
||||
|
||||
@Override
|
||||
|
||||
private static final long ONE_WEEK = 604_800_000;
|
||||
private static final long ONE_DAY = 86_400_000;
|
||||
/** Approximation of one degree of latitude in kilometers. */
|
||||
private static final double LAT_ONE_DEGREE_IN_KM = 111.32d;
|
||||
|
||||
@Override
|
||||
@PermitAll
|
||||
public void initData() {
|
||||
// No call to super to prevent clash of initializing roles and users twice.
|
||||
initRoles();
|
||||
initUsers();
|
||||
initTestDevicesAndMeasurements();
|
||||
}
|
||||
|
||||
@Override
|
||||
@PermitAll
|
||||
public void initUsers() {
|
||||
super.initUsers();
|
||||
createUser("friend", "The friend", "secure", "no-reply@handte.org", new String[] { Roles.USER });
|
||||
createUser("intruder", "The intruder", "secure", "no-reply@handte.org", new String[] { Roles.USER });
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected UserEntity createUser(String login, String name, String password, String email, String[] roles) {
|
||||
@@ -39,6 +61,114 @@ public class DataTestBean extends DataSessionBean {
|
||||
createEmail(u, "dummyEmailVerified@trash.mail", true,false);
|
||||
}
|
||||
return u;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes some devices and measurements for testing.
|
||||
*/
|
||||
private void initTestDevicesAndMeasurements() {
|
||||
final long time = System.currentTimeMillis();
|
||||
final EmbeddedCoordinate geoCenter = new EmbeddedCoordinate(7.011555, 51.455643); // Essen
|
||||
DeviceEntity device = createTestDevice("handte");
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time - ONE_DAY, 8);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time - ONE_WEEK, 17);
|
||||
createBatchTestMeasurements(device, geoCenter, 200, time, 10);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_DAY, 45);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_WEEK, 28);
|
||||
device = createTestDevice("friend");
|
||||
createBatchTestMeasurements(device, geoCenter, 200, time - ONE_DAY, 22);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time - ONE_WEEK, 9);
|
||||
createBatchTestMeasurements(device, geoCenter, 200, time, 7);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_DAY, 34);
|
||||
createBatchTestMeasurements(device, geoCenter, 200,time + ONE_WEEK, 57);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test device.
|
||||
*
|
||||
* @param userLogin User name associated with the device.
|
||||
* @return the entity object of the created device.
|
||||
*/
|
||||
private DeviceEntity createTestDevice(String userLogin) {
|
||||
final UserEntity userEntity = UserEntity.findByLogin(em, userLogin);
|
||||
DeviceEntity deviceEntity = null;
|
||||
if (userEntity != null) {
|
||||
deviceEntity = new DeviceEntity();
|
||||
deviceEntity.setUser(userEntity);
|
||||
deviceEntity.setDevice(userLogin + "-device");
|
||||
deviceEntity.setManufacturer(userLogin + "-manufacture");
|
||||
deviceEntity.setModel(userLogin + "-model");
|
||||
deviceEntity.setOs(OperatingSystem.ANDROID);
|
||||
deviceEntity.setToken(SecureToken.createToken(TokenType.INTERNAL));
|
||||
em.persist(deviceEntity);
|
||||
em.flush();
|
||||
}
|
||||
return deviceEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a batch of measurements with a timestamp difference of one millisecond.
|
||||
*
|
||||
* @param device The device which was "creating" the measurements.
|
||||
* @param timestamp The beginning timestamp.
|
||||
* @param count The amount of measurements to create.
|
||||
*/
|
||||
private void createBatchTestMeasurements(DeviceEntity device, long timestamp, int count) {
|
||||
for (int i = 0; i < count; i++)
|
||||
createTestMeasurements(device, null,timestamp + count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a batch of measurements with a timestamp difference of one millisecond
|
||||
* and randomly calculated coordinates within a range and a fixed point.
|
||||
*
|
||||
* @param device The device which was "creating" the measurements.
|
||||
* @param geoCenter The geo center of all created measurements.
|
||||
* @param range The range where the measurements are created from within the center in kilometers.
|
||||
* @param timestamp The beginning timestamp.
|
||||
* @param count The amount of measurements to create.
|
||||
*/
|
||||
private void createBatchTestMeasurements(DeviceEntity device, EmbeddedCoordinate geoCenter,
|
||||
int range, long timestamp, int count) {
|
||||
final double latDegreeRange = range / LAT_ONE_DEGREE_IN_KM;
|
||||
final double latDegreeRadius = latDegreeRange / 2d;
|
||||
for (int i = 0; i < count; i++) {
|
||||
final double randomLatOffset = (Math.random() * latDegreeRange) - latDegreeRadius;
|
||||
final double latitude = geoCenter.getLatitude() + randomLatOffset;
|
||||
final double lngOneDegreeInKM = 40075 * Math.cos(latitude) / 360;
|
||||
final double lngDegreeRange = range / lngOneDegreeInKM;
|
||||
final double randomLngOffset = (Math.random() * lngDegreeRange) - (lngDegreeRange / 2d);
|
||||
final double longitude = geoCenter.getLongitude() + randomLngOffset;
|
||||
createTestMeasurements(device, new EmbeddedCoordinate(longitude, latitude), timestamp + count);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test measurement.
|
||||
*
|
||||
* @param device The device which was "creating" the measurements.
|
||||
* @param coords The coordinates.
|
||||
* @param timestamp The timestamp.
|
||||
*/
|
||||
private void createTestMeasurements(DeviceEntity device, EmbeddedCoordinate coords, long timestamp) {
|
||||
MeasurementEntity measurement = new MeasurementEntity();
|
||||
measurement.setDevice(device);
|
||||
measurement.setVersion(1);
|
||||
if (coords == null) {
|
||||
measurement.setCoordinate(new EmbeddedCoordinate(1, 2));
|
||||
} else {
|
||||
measurement.setCoordinate(coords);
|
||||
}
|
||||
measurement.setTime(timestamp);
|
||||
measurement.setData(new HashMap<>());
|
||||
for (MeasurementType t : MeasurementType.values()) {
|
||||
if (t.getType() == Boolean.class) {
|
||||
measurement.getData().put(t, Boolean.TRUE.toString());
|
||||
} else if (t.getType() == Double.class) {
|
||||
measurement.getData().put(t, Double.valueOf(1.1).toString());
|
||||
}
|
||||
}
|
||||
em.persist(measurement);
|
||||
em.flush();
|
||||
}
|
||||
}
|
||||
|
||||
+123
-1
@@ -9,9 +9,15 @@ import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.ejb.EJB;
|
||||
import javax.ejb.EJBAccessException;
|
||||
|
||||
import com.mowesta.service.entity.EntityForbiddenException;
|
||||
import com.mowesta.service.entity.EntityNotFoundException;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -167,5 +173,121 @@ public class MeasurementSessionTest extends AbstractSessionTest {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, "handte");
|
||||
executeAs("handte", deviceHandle.getToken(), new AddMeasurementTest(deviceHandle, true, 0));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets up measurements with a timestamp range from today and from one week ago.
|
||||
*/
|
||||
private class RangedMeasurementsSetup implements Runnable {
|
||||
|
||||
private static final long ONE_WEEK = 604_800_000;
|
||||
private final DeviceHandle handle;
|
||||
private final long time;
|
||||
private final int count;
|
||||
|
||||
public RangedMeasurementsSetup(DeviceHandle handle, long time, int count) {
|
||||
this.handle = handle;
|
||||
this.time = time;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
// Create entries one week ago
|
||||
for (int i = 0; i < count; i++)
|
||||
measurementSession.addCurrentDeviceMeasurement(createMeasurement(time + i - ONE_WEEK));
|
||||
// Create entries today
|
||||
for (int i = 0; i < count; i++)
|
||||
measurementSession.addCurrentDeviceMeasurement(createMeasurement(time + i));
|
||||
|
||||
final MeasurementPage p = measurementSession
|
||||
.getDeviceMeasurements(handle.getId(), new TimeRange(time - ONE_WEEK, time + count),
|
||||
new PageConfig(0, 10), false);
|
||||
assertEquals("Should have correct number of entries.", count * 2, p.getTotal());
|
||||
} catch (EntityForbiddenException | EntityNotFoundException e) {
|
||||
fail("Failed due to: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private DeviceHandle initRangedMeasurementsForUser(String user, long time, int count) {
|
||||
final DeviceHandle deviceHandle = DeviceSessionTest.createDevice(this, deviceSession, user);
|
||||
executeAs(user, deviceHandle.getToken(), new RangedMeasurementsSetup(deviceHandle, time, count));
|
||||
return deviceHandle;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessAllMeasurementsWithAdminRole() {
|
||||
final long time = System.currentTimeMillis();
|
||||
final int entryCount = 10;
|
||||
final long duration = time + entryCount + 50;
|
||||
|
||||
AtomicInteger dbTotalBefore = new AtomicInteger();
|
||||
executeAs("admin", () -> {
|
||||
final MeasurementPage page = measurementSession
|
||||
.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 1000), false);
|
||||
dbTotalBefore.set(page.getTotal());
|
||||
});
|
||||
|
||||
initRangedMeasurementsForUser("handte", time, entryCount);
|
||||
initRangedMeasurementsForUser("friend", time, entryCount);
|
||||
|
||||
executeAs("admin", () -> {
|
||||
final MeasurementPage page = measurementSession
|
||||
.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 1000), false);
|
||||
assertEquals("Should have retrieved all entries within the range.",
|
||||
entryCount * 2 + dbTotalBefore.get(), page.getTotal());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessAllMeasurementsWithUserRole() {
|
||||
final long time = System.currentTimeMillis();
|
||||
final int entryCount = 10;
|
||||
final long duration = time + entryCount + 50;
|
||||
initRangedMeasurementsForUser("handte", time, entryCount);
|
||||
initRangedMeasurementsForUser("friend", time, entryCount);
|
||||
executeAs("handte", () -> {
|
||||
try {
|
||||
final MeasurementPage page = measurementSession
|
||||
.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 10), false);
|
||||
} catch (EJBAccessException e) {
|
||||
assertNotNull("Should deny access to ordinary user.", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllMeasurementsResults() {
|
||||
final long time = System.currentTimeMillis();
|
||||
final int entryCount = 10;
|
||||
final long duration = time + entryCount + 50;
|
||||
|
||||
final DeviceHandle handteDeviceHandle = initRangedMeasurementsForUser("handte", time, entryCount);
|
||||
final DeviceHandle friendDeviceHandle = initRangedMeasurementsForUser("friend", time, entryCount);
|
||||
|
||||
executeAs("admin", () -> {
|
||||
final MeasurementPage page = measurementSession
|
||||
.getMeasurements(new TimeRange(time, duration), new PageConfig(0, 1000), false);
|
||||
final List<Measurement> measurements = page.getElements();
|
||||
|
||||
if (measurements.size() != 0) {
|
||||
List<Measurement> handteMeasurements = measurements.stream()
|
||||
.filter(e -> e.getDevice() == handteDeviceHandle.getId()
|
||||
&& time <= e.getTime() && e.getTime() < duration)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals("Should contain all measurements from handte within time range.",
|
||||
entryCount, handteMeasurements.size());
|
||||
|
||||
List<Measurement> friendMeasurements = measurements.stream()
|
||||
.filter(e -> e.getDevice() == friendDeviceHandle.getId()
|
||||
&& time <= e.getTime() && e.getTime() < duration)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals("Should contain all measurements from friend within time range.",
|
||||
entryCount, friendMeasurements.size());
|
||||
} else {
|
||||
fail("No measurements retrieved.");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,14 +36,14 @@ public class ExportShapes {
|
||||
/**
|
||||
* The url of the Locoslab service.
|
||||
*/
|
||||
public static final String API_URL = "https://cloud.locoslab.com";
|
||||
public static final String API_URL = "https://www.mowesta.com/carta";
|
||||
|
||||
/**
|
||||
* The tile service to fetch the tiles.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@Path("/carta/restful-services/")
|
||||
@Path("/")
|
||||
public interface ITileService {
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,10 +10,8 @@ import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -26,7 +24,6 @@ import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
|
||||
@@ -139,6 +136,7 @@ public class MeasurementAnalyzer {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the values as a seperated string.
|
||||
*
|
||||
* @param separator The separator.
|
||||
* @return The values.
|
||||
@@ -160,19 +158,41 @@ public class MeasurementAnalyzer {
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A utility class to analyze the distribution of a set of values.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Aggregate {
|
||||
|
||||
/**
|
||||
* The values to analyze.
|
||||
*/
|
||||
private List<Double> values = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Adds a value to the aggregate.
|
||||
*
|
||||
* @param value The value to add.
|
||||
*/
|
||||
private void add(double value) {
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the values.
|
||||
*
|
||||
* @return The values.
|
||||
*/
|
||||
public int count() {
|
||||
return values.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the average of the values.
|
||||
*
|
||||
* @return The average or null, if the count is 0.
|
||||
*/
|
||||
public Double average() {
|
||||
if (values.isEmpty()) return null;
|
||||
double sum = 0;
|
||||
@@ -182,6 +202,11 @@ public class MeasurementAnalyzer {
|
||||
return sum / values.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the variance of the values.
|
||||
*
|
||||
* @return The variance or null, if the count is 0.
|
||||
*/
|
||||
public Double variance() {
|
||||
Double average = average();
|
||||
if (average == null)
|
||||
@@ -194,6 +219,11 @@ public class MeasurementAnalyzer {
|
||||
return Math.sqrt(var / values.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the maximum value.
|
||||
*
|
||||
* @return The maximum value.
|
||||
*/
|
||||
public Double max() {
|
||||
Double max = null;
|
||||
for (Double v: values)
|
||||
@@ -202,6 +232,11 @@ public class MeasurementAnalyzer {
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the minimum value.
|
||||
*
|
||||
* @return The minimum value.
|
||||
*/
|
||||
public Double min() {
|
||||
Double min = null;
|
||||
for (Double v: values)
|
||||
@@ -210,6 +245,13 @@ public class MeasurementAnalyzer {
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the percentiles for the specified number of
|
||||
* segments.
|
||||
*
|
||||
* @param numbers The number of segments.
|
||||
* @return The percentiles.
|
||||
*/
|
||||
public Double[] percentiles(int numbers) {
|
||||
if (values.isEmpty()) return null;
|
||||
List<Double> sorted = new ArrayList<>(values);
|
||||
@@ -480,12 +522,34 @@ public class MeasurementAnalyzer {
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* An interface to extract some data.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
private interface Extractor {
|
||||
/**
|
||||
* Returns the extracted value from an item.
|
||||
*
|
||||
* @param item The item.
|
||||
* @return The extracted value.
|
||||
*/
|
||||
Double getValue(MeasurementItem item);
|
||||
}
|
||||
|
||||
/**
|
||||
* An interface to filter some data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private interface Filter {
|
||||
/**
|
||||
* Determines whether to include the item.
|
||||
*
|
||||
* @param item The item to check.
|
||||
* @return True to include, false to filter out.
|
||||
*/
|
||||
boolean include(MeasurementItem item);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ public class VideoGeneratorExample {
|
||||
if (p.isAvailable(time)) {
|
||||
VideoGenerator videoGenerator = new VideoGenerator(p, c.createComposer(time));
|
||||
long start = System.currentTimeMillis();
|
||||
Variable variable = Variable.T2M;
|
||||
Variable variable = Variable.PREC;
|
||||
String name = "video-" + prefixes[i] + "-" + variable.getFolder();
|
||||
videoGenerator.createVideo(variable, time, 8, 10, new File(name + ".mp4"), new File(name + ".jpg"), (kfr, ifr) -> {
|
||||
System.out.println("Key: " + kfr + " Int:" + ifr);
|
||||
|
||||
@@ -125,7 +125,8 @@ public class CorsResponseFilter implements ContainerResponseFilter {
|
||||
final Path calledUrlEndpoint = calledMethod.getAnnotation(Path.class);
|
||||
final Class<?> declaringClass = calledMethod.getDeclaringClass();
|
||||
final String[] annotations = Arrays.stream(declaringClass.getMethods())
|
||||
.filter(method -> method.getDeclaredAnnotation(Path.class).value().equals(calledUrlEndpoint.value())
|
||||
.filter(method -> method.getDeclaredAnnotation(Path.class) != null
|
||||
&& method.getDeclaredAnnotation(Path.class).value().equals(calledUrlEndpoint.value())
|
||||
&& method.getDeclaredAnnotation(PermitAll.class) != null)
|
||||
.map(Method::getDeclaredAnnotations)
|
||||
.flatMap(Arrays::stream)
|
||||
|
||||
@@ -95,7 +95,7 @@ public class MeasurementResource implements IMeasurementService {
|
||||
} catch (EntityForbiddenException e) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
} catch (EntityNotFoundException e) {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
return Response.status(Status.NOT_FOUND).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,4 +115,16 @@ public class MeasurementResource implements IMeasurementService {
|
||||
return Response.status(Status.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response getAllMeasurementsByRange(@Valid TimeRange timeRange, @Valid PageConfig pageConfig) {
|
||||
log.log(Level.INFO, "Received a get request for all measurements for a time range from {0} to {1}.",
|
||||
new Object[]{ timeRange.getStart(), timeRange.getDuration()});
|
||||
EntityTag tag = new EntityTag(Long.toString(measurementSession.getLastModifiedMeasurementForAllDevices()));
|
||||
ResponseBuilder r = request.evaluatePreconditions(tag);
|
||||
if (r == null) {
|
||||
r = Response.ok(measurementSession.getMeasurements(timeRange, pageConfig, true));
|
||||
}
|
||||
return r.tag(tag).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.mowesta.service.test.rest;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.IMeasurementService;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
import org.jboss.arquillian.junit.Arquillian;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* Tests against the measurement resource.
|
||||
*
|
||||
* @author Adriano
|
||||
*/
|
||||
@RunWith(Arquillian.class)
|
||||
public class MeasurementResourceTest extends AbstractResourceTest {
|
||||
|
||||
@Test
|
||||
public void testAccessingAllDevicesMeasurementsAsAnonymous() {
|
||||
final IMeasurementService measurementService = getTarget().proxy(IMeasurementService.class);
|
||||
long time = System.currentTimeMillis();
|
||||
Response r = measurementService.getAllMeasurementsByRange(new TimeRange(time, time + 1000), new PageConfig(0, 10));
|
||||
assertEquals("Should result in HTTP Status - 403 Forbidden", 403, r.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessingAllDevicesMeasurementsAsUserRole() {
|
||||
final IMeasurementService measurementService = getTarget("handte", "secure").proxy(IMeasurementService.class);
|
||||
long time = System.currentTimeMillis();
|
||||
Response r = measurementService.getAllMeasurementsByRange(new TimeRange(time, time + 1000), new PageConfig(0, 10));
|
||||
assertEquals("Should result in HTTP Status - 403 Forbidden", 403, r.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessingAllDevicesMeasurementsAsAdminRole() {
|
||||
final IMeasurementService measurementService = getTarget("admin", "admin").proxy(IMeasurementService.class);
|
||||
long time = System.currentTimeMillis();
|
||||
Response r = measurementService.getAllMeasurementsByRange(new TimeRange(time, time + 1000), new PageConfig(0, 10));
|
||||
MeasurementPage page = r.readEntity(MeasurementPage.class);
|
||||
assertEquals("Should result in HTTP Status - 200 OK", 200, r.getStatus());
|
||||
assertNotNull("Measurement page should not be null", page);
|
||||
}
|
||||
}
|
||||
@@ -22,4 +22,4 @@
|
||||
</configuration>
|
||||
</container>
|
||||
|
||||
</arquillian>
|
||||
</arquillian>
|
||||
|
||||
Generated
+8
@@ -9844,6 +9844,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"saturn-datepicker": {
|
||||
"version": "8.0.5",
|
||||
"resolved": "https://registry.npmjs.org/saturn-datepicker/-/saturn-datepicker-8.0.5.tgz",
|
||||
"integrity": "sha512-LEJftfa/mDNYFLdOZRETU4SEjXPtd5xve8hjyUHmxmc/znYD4PqBfS044+C1uekN4M92YZlsLUXWKmPKSdAQbg==",
|
||||
"requires": {
|
||||
"tslib": "^1.9.0"
|
||||
}
|
||||
},
|
||||
"saucelabs": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/saucelabs/-/saucelabs-1.5.0.tgz",
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
"leaflet": "1.6.0",
|
||||
"ngx-gauge": "^1.1.0",
|
||||
"rxjs": "^6.5.4",
|
||||
"saturn-datepicker": "^8.0.5",
|
||||
"tslib": "^1.10.0",
|
||||
"zone.js": "~0.10.2"
|
||||
},
|
||||
|
||||
@@ -32,7 +32,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||
import { LocationStrategy, PathLocationStrategy, registerLocaleData, DatePipe } from '@angular/common';
|
||||
import LocaleDE from '@angular/common/locales/de';
|
||||
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
|
||||
|
||||
import { SatDatepickerModule, SatNativeDateModule } from "saturn-datepicker";
|
||||
|
||||
import { AppRoutingModule } from './app.routing';
|
||||
import { AppComponent } from './app.component';
|
||||
@@ -71,6 +71,7 @@ import { HumidityPipe, CloudPipe, PressurePipe, TemperaturePipe, SpeedPipe, Snow
|
||||
WeatherPipe, DirectionPipe, SourcePipe, LocalTimePipe, LocalDatePipe, LocalNamePipe, BingMapsPipe,
|
||||
GoogleMapsPipe, WikipediaPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe, LocationIconPipe, WeatherIconPipe,
|
||||
DirectionIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe, OsIconPipe } from './pipes';
|
||||
import { ManageMeasurementsMapComponent } from './views-manage/manage-measurements-map.component';
|
||||
|
||||
|
||||
/**
|
||||
@@ -115,7 +116,7 @@ registerLocaleData(LocaleDE);
|
||||
WeatherPipe, DirectionPipe, SourcePipe, BingMapsPipe, GoogleMapsPipe, WikipediaPipe, LocalTimePipe,
|
||||
LocalDatePipe, LocalNamePipe, LocationIconPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe,
|
||||
WeatherIconPipe, DirectionIconPipe, OsIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe,
|
||||
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent, LocationAutocompleteComponent,
|
||||
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent, LocationAutocompleteComponent, ManageMeasurementsMapComponent,
|
||||
],
|
||||
imports: [
|
||||
BrowserModule, BrowserAnimationsModule,
|
||||
@@ -134,6 +135,7 @@ registerLocaleData(LocaleDE);
|
||||
MatDatepickerModule, MatNativeDateModule,
|
||||
MatTabsModule, MatGridListModule,
|
||||
AppRoutingModule, MatAutocompleteModule,
|
||||
SatDatepickerModule, SatNativeDateModule
|
||||
],
|
||||
providers: [
|
||||
// injection token for http client
|
||||
|
||||
@@ -10,6 +10,8 @@ import { UserDevicesComponent, UserAccountComponent, UserFavoritesComponent, Use
|
||||
import { ManageLogComponent, ManageSystemComponent, ManageUsersComponent } from './views-manage';
|
||||
import { CityResolver, StateResolver, CountryResolver, UserResolver, StationResolver, LanguageResolver,
|
||||
BootstrapResolver, DeviceResolver } from './resolvers';
|
||||
import { CanDeactivateGuard } from "./guards/can-deactivate.guard";
|
||||
import { ManageMeasurementsMapComponent } from "./views-manage/manage-measurements-map.component";
|
||||
|
||||
|
||||
export const routes: Routes = [
|
||||
@@ -24,6 +26,7 @@ export const routes: Routes = [
|
||||
{ path: 'logs', component: ManageLogComponent },
|
||||
{ path: 'system', component: ManageSystemComponent },
|
||||
{ path: 'users', component: ManageUsersComponent },
|
||||
{ path: 'measurements', component: ManageMeasurementsMapComponent },
|
||||
{ path: '**', redirectTo: '/manage/system' }
|
||||
]},
|
||||
// user functions
|
||||
@@ -32,7 +35,7 @@ export const routes: Routes = [
|
||||
{ path: ':id', component: UserDeviceComponent, resolve: { device: DeviceResolver } },
|
||||
{ path: '**', component: UserDevicesComponent },
|
||||
] },
|
||||
{ path: 'account', component: UserAccountComponent },
|
||||
{ path: 'account', component: UserAccountComponent, canDeactivate: [CanDeactivateGuard] },
|
||||
{ path: 'favorites', component: UserFavoritesComponent },
|
||||
{ path: '**', redirectTo: '/user/account' }
|
||||
]},
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { HostListener, Injectable } from '@angular/core';
|
||||
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Abstract class which can be extended by components which need confirmation from the user if the tab
|
||||
* should be closed or the navigation should proceed to another page of the webapp.
|
||||
*/
|
||||
export abstract class AbstractCanDeactivate {
|
||||
|
||||
abstract canDeactivate(): boolean;
|
||||
abstract processDeactivation(currentRoute: ActivatedRouteSnapshot,
|
||||
currentState: RouterStateSnapshot,
|
||||
nextState?: RouterStateSnapshot): void;
|
||||
|
||||
@HostListener('window:beforeunload', ['$event'])
|
||||
onBeforeUnload(event: any) {
|
||||
if (this.canDeactivate()) { event.returnValue = true; }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic Guard which resolves if the router navigation can proceed.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CanDeactivateGuard implements CanDeactivate<AbstractCanDeactivate> {
|
||||
|
||||
canDeactivate(component: AbstractCanDeactivate, currentRoute: ActivatedRouteSnapshot,
|
||||
currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot)
|
||||
: Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
||||
if (component.canDeactivate()) {
|
||||
component.processDeactivation(currentRoute, currentState, nextState);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -58,6 +58,12 @@
|
||||
<span class="mat-button">{{ res.strings('manage_users_title') }}</span>
|
||||
</a>
|
||||
</mat-list-item>
|
||||
<mat-list-item>
|
||||
<a mat-list-item [routerLink]="'/' + res.getLanguage() + '/manage/measurements'">
|
||||
<mat-icon class="icon-button">assessment</mat-icon>
|
||||
<span class="mat-button">{{ res.strings('manage_measurements_map_title') }}</span>
|
||||
</a>
|
||||
</mat-list-item>
|
||||
</ng-container>
|
||||
<h3 mat-subheader>{{res.strings('drawer_account')}}</h3>
|
||||
<ng-container *ngIf="user; else login">
|
||||
|
||||
@@ -9,7 +9,6 @@ export class BootstrapResolver implements Resolve<string> {
|
||||
constructor(private router: Router, private consoleService: ConsoleService, private res: ResourceService) {}
|
||||
|
||||
resolve(route: ActivatedRouteSnapshot) {
|
||||
console.dir(route);
|
||||
const url = route.pathFromRoot.map(v => v.url.map(segment => segment.toString()).join('/')).join('/');
|
||||
this.consoleService.log(`Bootstrapping url ${url}.`);
|
||||
if (url.startsWith('/reset') || url.startsWith('/activate') || url === '/') {
|
||||
|
||||
@@ -0,0 +1,635 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { formatDate } from '@angular/common';
|
||||
import { BehaviorSubject, Observable, Subject } from 'rxjs';
|
||||
import { takeUntil } from 'rxjs/operators';
|
||||
import { SatDatepickerRangeValue } from 'saturn-datepicker';
|
||||
import * as JSZip from 'jszip';
|
||||
import { DefaultService, Device, DevicePage, Measurement, MeasurementPage } from '../api';
|
||||
import { Page } from '../utils';
|
||||
import { HumidityPipe, PressurePipe, TemperaturePipe } from '../pipes'
|
||||
|
||||
|
||||
export interface MeasurementMsg {
|
||||
data: Array<Measurement>;
|
||||
partialData?: boolean;
|
||||
}
|
||||
|
||||
/** Current status of the fetching progress. */
|
||||
export enum ProgressStatus {
|
||||
DONE, // Fetching is done.
|
||||
FETCHING, // Fetching.
|
||||
NO_DEVICES, // No devices found.
|
||||
NO_MEASUREMENTS, // No measurements found.
|
||||
EXPORTING // Exporting.
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback function type to get some feedback on the fetching progress.
|
||||
*
|
||||
* @param status Current progress status.
|
||||
* @param fetched Number of already fetched data.
|
||||
* @param total Total amount of data to be fetched.
|
||||
*/
|
||||
export type ProgressFn = (status: ProgressStatus, current?: number, total?: number) => void;
|
||||
|
||||
/**
|
||||
* Handles bulk fetching operations on the measurement resource for exporting and caching purposes.
|
||||
* The amount of data fetched from the resource by this service is determined by the specified
|
||||
* time range and the user privilege.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BulkMeasurementService {
|
||||
|
||||
private static readonly COLUMN_SEPARATOR = ';';
|
||||
private static readonly LINE_SEPARATOR = '\r\n';
|
||||
|
||||
private exportHandler: AbstractExportHandler | null;
|
||||
private cachingHandler: AdminCachingHandler | null;
|
||||
|
||||
constructor(
|
||||
private readonly defaultService: DefaultService,
|
||||
private readonly humidityPipe: HumidityPipe,
|
||||
private readonly temperaturePipe: TemperaturePipe,
|
||||
private readonly pressurePipe: PressurePipe
|
||||
) { }
|
||||
|
||||
exportMeasurements(range: SatDatepickerRangeValue<Date>, filename: string, isAdmin: boolean, progressFn?: ProgressFn): void {
|
||||
this.initServiceForExport(isAdmin);
|
||||
this.exportHandler.progressFn = progressFn;
|
||||
this.exportHandler.start(range, filename);
|
||||
}
|
||||
|
||||
fetchMeasurements(range: SatDatepickerRangeValue<Date>, progressFn?: ProgressFn): Observable<MeasurementMsg> {
|
||||
this.initServiceForCaching();
|
||||
this.cachingHandler.progressFn = progressFn;
|
||||
this.cachingHandler.start(range);
|
||||
return this.cachingHandler.observeMeasurementChanges();
|
||||
}
|
||||
|
||||
saveFetchedMeasurements(filename: string, progressFn?: ProgressFn): boolean {
|
||||
if (this.cachingHandler && !this.cachingHandler.fetching) {
|
||||
this.cachingHandler.progressFn = progressFn;
|
||||
this.cachingHandler.exportMeasurements(filename);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.exportHandler) {
|
||||
this.exportHandler.stop();
|
||||
} else if (this.cachingHandler) {
|
||||
this.exportHandler.stop();
|
||||
}
|
||||
}
|
||||
|
||||
createReadme(): string {
|
||||
let result = '';
|
||||
result += 'This zip contains for every measuring device a single file in CSV format:' + BulkMeasurementService.LINE_SEPARATOR;
|
||||
result += BulkMeasurementService.LINE_SEPARATOR;
|
||||
result += 'Files that would contain no data are removed automatically.' + BulkMeasurementService.LINE_SEPARATOR;
|
||||
result += 'Columns are separated by semi-colons (";"), lines are separated by carriage return followed by line feed ("CRLF").';
|
||||
result += BulkMeasurementService.LINE_SEPARATOR;
|
||||
return result;
|
||||
}
|
||||
|
||||
createCSV(measurements: Array<Measurement>): string {
|
||||
let result = '';
|
||||
result += 'ID' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'CREATION_TIME' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'MODIFICATION_TIME' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'DELETED' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'LATITUDE' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'LONGITUDE' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'TIME' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'DEVICE' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'VERSION' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'TEMPERATURE' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'PRESSURE' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += 'HUMIDITY' + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += BulkMeasurementService.LINE_SEPARATOR;
|
||||
measurements.forEach(m => {
|
||||
result += m.id + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += formatDate(new Date(m.creationTime),
|
||||
'dd.MM.yyyy H:mm:ss', 'de') + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += formatDate(new Date(m.modificationTime),
|
||||
'dd.MM.yyyy H:mm:ss', 'de') + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += m.deleted + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += m.coordinate?.latitude + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += m.coordinate?.longitude + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += formatDate(new Date(m.time),
|
||||
'dd.MM.yyyy H:mm:ss', 'de') + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += m.device + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += m.version + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += this.temperaturePipe.transform(m.temperature) + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += this.pressurePipe.transform(m.pressure) + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += this.humidityPipe.transform(m.humidity) + BulkMeasurementService.COLUMN_SEPARATOR;
|
||||
result += BulkMeasurementService.LINE_SEPARATOR;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private initServiceForExport(isAdmin: boolean): void {
|
||||
if (isAdmin) {
|
||||
if (!this.exportHandler || (this.exportHandler && !(this.exportHandler instanceof AdminExportHandler))) {
|
||||
this.exportHandler = new AdminExportHandler(this.defaultService, this);
|
||||
}
|
||||
} else {
|
||||
if (!this.exportHandler || (this.exportHandler && !(this.exportHandler instanceof UserExportHandler))) {
|
||||
this.exportHandler = new UserExportHandler(this.defaultService, this);
|
||||
}
|
||||
}
|
||||
this.cachingHandler = null;
|
||||
}
|
||||
|
||||
private initServiceForCaching(): void {
|
||||
if (!this.cachingHandler) {
|
||||
this.cachingHandler = new AdminCachingHandler(this.defaultService, this);
|
||||
this.exportHandler = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface DeviceMeasurements {
|
||||
id: number;
|
||||
page?: MeasurementPage;
|
||||
}
|
||||
|
||||
interface TimeRange {
|
||||
start: number;
|
||||
end: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract class which offers common functionalities for bulk fetching data from the measurement
|
||||
* resource and saving it to a .zip file containing all measurements for a particular device each
|
||||
* separately written to a .csv file.
|
||||
*/
|
||||
abstract class AbstractExportHandler {
|
||||
|
||||
protected static readonly DAY_IN_MILLI = 86_400_000;
|
||||
protected static readonly BATCH_SIZE = 500;
|
||||
protected static readonly NULL_PROGRESS_FN = (status, current, total) => null;
|
||||
/** Creates an empty page. */
|
||||
protected static emptyPage<T>() {
|
||||
return { elements: [], offset: 0, total: -1, size: 0 } as Page<T>;
|
||||
}
|
||||
|
||||
fetching: boolean;
|
||||
protected abortRequests$: Subject<void>;
|
||||
protected fetchedMeasurements: number;
|
||||
protected totalMeasurements: number;
|
||||
protected _progressFn: ProgressFn;
|
||||
protected dateRange: TimeRange | null | undefined;
|
||||
protected archiveName: string | null | undefined;
|
||||
protected zip: JSZip | null | undefined;
|
||||
|
||||
set progressFn(fn: ProgressFn | undefined) {
|
||||
this._progressFn = fn ? fn : AbstractExportHandler.NULL_PROGRESS_FN;
|
||||
}
|
||||
|
||||
constructor(
|
||||
protected readonly defaultService: DefaultService,
|
||||
protected readonly bulkMeasurementService: BulkMeasurementService
|
||||
) {
|
||||
this.fetching = false;
|
||||
this.abortRequests$ = new Subject();
|
||||
this.fetchedMeasurements = 0;
|
||||
this.totalMeasurements = 0;
|
||||
this._progressFn = AbstractExportHandler.NULL_PROGRESS_FN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the bulk fetching process. Needs to be overridden by the derived class with a call to the super method.
|
||||
*
|
||||
* @param range The specified time range.
|
||||
* @param filename The filename to export to or null.
|
||||
*/
|
||||
abstract start(range: SatDatepickerRangeValue<Date>, filename?: string): void;
|
||||
|
||||
stop(): void {
|
||||
this._progressFn(ProgressStatus.DONE);
|
||||
this.abortRequests$.next();
|
||||
this.reset();
|
||||
}
|
||||
|
||||
exportMeasurements(filename?: string): void {
|
||||
this.zip.generateAsync({ type: 'blob' }).then(content => {
|
||||
if (this.fetching === true) {
|
||||
this.saveAs(`mowesta-export-${this.archiveName}.zip`, content);
|
||||
this._progressFn(ProgressStatus.DONE);
|
||||
this.reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected init(range: SatDatepickerRangeValue<Date>, filename?: string): void {
|
||||
this.fetching = true;
|
||||
this.archiveName = filename;
|
||||
this.abortRequests$.next();
|
||||
this.dateRange = this.satDatepickerRangeToTimeRange(range);
|
||||
}
|
||||
|
||||
protected reset(): void {
|
||||
this.fetching = false;
|
||||
this.archiveName = null;
|
||||
this.dateRange = null;
|
||||
this.zip = null;
|
||||
this._progressFn = AbstractExportHandler.NULL_PROGRESS_FN;
|
||||
}
|
||||
|
||||
protected initZipArchive(): void {
|
||||
this.zip = new JSZip();
|
||||
// '\ufeff' -> UTF-8 Header Byte prepended for encoding purposes.
|
||||
const content = '\ufeff' + this.bulkMeasurementService.createReadme();
|
||||
this.zip.file(`Readme.txt`, content);
|
||||
}
|
||||
|
||||
protected addMeasurementsToZipArchive(deviceId: number, measurements: Array<Measurement>): void {
|
||||
if (measurements.length === 0) { return; }
|
||||
const content = '\ufeff' + this.bulkMeasurementService.createCSV(measurements);
|
||||
this.zip.file(`device-${deviceId}.csv`, content);
|
||||
}
|
||||
|
||||
protected saveAs(name: string, blob: Blob): void {
|
||||
if (navigator.msSaveBlob) {
|
||||
navigator.msSaveBlob(blob, name);
|
||||
} else {
|
||||
const link = document.createElement('a');
|
||||
(<any>link).download = name;
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.click();
|
||||
setTimeout(() => {
|
||||
URL.revokeObjectURL(link.href);
|
||||
link.remove();
|
||||
}, 10);
|
||||
}
|
||||
}
|
||||
|
||||
protected satDatepickerRangeToTimeRange(range: SatDatepickerRangeValue<Date>): TimeRange {
|
||||
const endTime = new Date(range.end.getTime() + AbstractExportHandler.DAY_IN_MILLI).getTime();
|
||||
return {
|
||||
start: range.begin.getTime(),
|
||||
end: endTime,
|
||||
duration: endTime - range.begin.getTime()
|
||||
};
|
||||
}
|
||||
|
||||
protected isPageIncomplete(page: Page<any>): boolean {
|
||||
return page.total < 0 || page.total > page.offset;
|
||||
}
|
||||
|
||||
protected mergePages<T>(source: Page<T>, destination: Page<T>): void {
|
||||
destination.total = source.total;
|
||||
destination.elements = destination.elements.concat(source.elements);
|
||||
destination.size = destination.elements.length;
|
||||
destination.offset = destination.offset + source.elements.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the bulk fetching of measurements as a user with simple user privileges within a specified time range.
|
||||
* Only the measurements of devices which belong to the user are fetched and automatically exported to a .zip file.
|
||||
*/
|
||||
class UserExportHandler extends AbstractExportHandler {
|
||||
|
||||
private deviceMeasurements: Array<DeviceMeasurements>;
|
||||
|
||||
start(range: SatDatepickerRangeValue<Date>, filename: string): void {
|
||||
this.init(range, filename);
|
||||
this.fetchAllUserDevices(AbstractExportHandler.emptyPage<Device>());
|
||||
}
|
||||
|
||||
protected reset() {
|
||||
super.reset();
|
||||
this.deviceMeasurements = null;
|
||||
}
|
||||
|
||||
private fetchAllUserDevices(devicesPage: DevicePage): void {
|
||||
if (this.isPageIncomplete(devicesPage)) {
|
||||
this.defaultService.getCurrentUserDevices(devicesPage.offset, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
this.mergePages(page, devicesPage);
|
||||
this.fetchAllUserDevices(devicesPage);
|
||||
});
|
||||
} else {
|
||||
if (devicesPage.elements.length > 0) {
|
||||
this.peekMeasurementsTotal(devicesPage.elements);
|
||||
} else {
|
||||
this._progressFn(ProgressStatus.NO_DEVICES);
|
||||
this.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private peekMeasurementsTotal(devices: Array<Device>): void {
|
||||
let peekCount = 0;
|
||||
this.fetchedMeasurements = this.totalMeasurements = 0;
|
||||
this.deviceMeasurements = new Array<DeviceMeasurements>();
|
||||
devices.forEach(device => {
|
||||
this.defaultService.getDeviceMeasurements(device.id, this.dateRange.start, this.dateRange.duration,
|
||||
0, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
peekCount++;
|
||||
if (page.total > 0) {
|
||||
this.fetchedMeasurements += page.elements.length;
|
||||
this.totalMeasurements += page.total;
|
||||
page.offset += page.elements.length;
|
||||
this.deviceMeasurements.push({ id: device.id, page });
|
||||
}
|
||||
if (peekCount === devices.length) {
|
||||
if (this.deviceMeasurements.length > 0) {
|
||||
this.initZipArchive();
|
||||
this.fetchRemainingMeasurements(0, this.copyDeviceMeasurements(this.deviceMeasurements[0]));
|
||||
} else {
|
||||
this._progressFn(ProgressStatus.NO_MEASUREMENTS);
|
||||
this.reset();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private copyDeviceMeasurements(dm: DeviceMeasurements): DeviceMeasurements | null {
|
||||
if (!dm) { return null; }
|
||||
return {
|
||||
id: dm.id,
|
||||
page: {
|
||||
size: dm.page.size,
|
||||
offset: dm.page.offset,
|
||||
total: dm.page.total,
|
||||
elements: dm.page.elements
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private fetchRemainingMeasurements(idx: number, dmBuffer?: DeviceMeasurements): void {
|
||||
this._progressFn(ProgressStatus.FETCHING, this.fetchedMeasurements, this.totalMeasurements);
|
||||
if (dmBuffer && this.isPageIncomplete(dmBuffer.page)) {
|
||||
this.defaultService.getDeviceMeasurements(dmBuffer.id, this.dateRange.start, this.dateRange.duration,
|
||||
dmBuffer.page.offset, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
this.fetchedMeasurements += page.elements.length;
|
||||
this.mergePages(page, dmBuffer.page);
|
||||
this.fetchRemainingMeasurements(idx, dmBuffer);
|
||||
});
|
||||
} else if (idx < this.deviceMeasurements.length) {
|
||||
this.addMeasurementsToZipArchive(dmBuffer.id, dmBuffer.page.elements);
|
||||
this.fetchRemainingMeasurements(++idx, this.copyDeviceMeasurements(this.deviceMeasurements[idx]));
|
||||
} else {
|
||||
this.exportMeasurements();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the bulk fetching of measurements as a user with administrator privileges within a specified
|
||||
* time range. All measurements of all devices are fetched and automatically exported to a .zip file.
|
||||
*/
|
||||
class AdminExportHandler extends AbstractExportHandler {
|
||||
|
||||
start(range: SatDatepickerRangeValue<Date>, filename: string): void {
|
||||
this.init(range, filename);
|
||||
this.peekMeasurementsTotal();
|
||||
}
|
||||
|
||||
protected peekMeasurementsTotal(): void {
|
||||
this.fetchedMeasurements = this.totalMeasurements = 0;
|
||||
this.defaultService.getAllMeasurementsByRange(this.dateRange.start, this.dateRange.duration,
|
||||
0, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
if (page.total > 0) {
|
||||
page.offset += page.elements.length;
|
||||
this.fetchedMeasurements = page.elements.length;
|
||||
this.totalMeasurements = page.total;
|
||||
this.initZipArchive();
|
||||
this.fetchRemainingMeasurements({ id: page.elements[0].device, page });
|
||||
} else {
|
||||
this._progressFn(ProgressStatus.NO_MEASUREMENTS);
|
||||
this.reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected fetchRemainingMeasurements(dmBuffer: DeviceMeasurements): void {
|
||||
this._progressFn(ProgressStatus.FETCHING, this.fetchedMeasurements, this.totalMeasurements);
|
||||
dmBuffer = this.splitDmIfRequiredAndStore(dmBuffer);
|
||||
if (this.isPageIncomplete(dmBuffer.page)) {
|
||||
this.defaultService.getAllMeasurementsByRange(this.dateRange.start, this.dateRange.duration,
|
||||
dmBuffer.page.offset, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
this.fetchedMeasurements += page.elements.length;
|
||||
this.mergePages(page, dmBuffer.page);
|
||||
this.fetchRemainingMeasurements(dmBuffer);
|
||||
});
|
||||
} else {
|
||||
this.addMeasurementsToZipArchive(dmBuffer.id, dmBuffer.page.elements);
|
||||
this.exportMeasurements();
|
||||
}
|
||||
}
|
||||
|
||||
private splitDmIfRequiredAndStore(dm: DeviceMeasurements): DeviceMeasurements {
|
||||
const measurements = dm.page.elements, last = measurements.length - 1;
|
||||
if (measurements[0].device !== measurements[last].device) {
|
||||
let i = 0;
|
||||
while (i < measurements.length) {
|
||||
const deviceId = measurements[i].device;
|
||||
const filteredMeasurements = measurements.filter(m => m.device === deviceId);
|
||||
if (measurements[last].device === deviceId) {
|
||||
dm.id = deviceId;
|
||||
dm.page.size = filteredMeasurements.length;
|
||||
dm.page.elements = filteredMeasurements;
|
||||
break;
|
||||
}
|
||||
this.addMeasurementsToZipArchive(deviceId, filteredMeasurements)
|
||||
i += filteredMeasurements.length;
|
||||
}
|
||||
}
|
||||
return dm;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the bulk fetching of measurements as a user with administrator privileges within a
|
||||
* specified time range. All measurements of all devices are fetched and cached in memory.
|
||||
* The concrete export of the fetched measurements has to be triggered externally.
|
||||
* If the fetching process is triggered again with a new time range the already cached
|
||||
* measurements falling into the new time range are not fetched again.
|
||||
*/
|
||||
class AdminCachingHandler extends AbstractExportHandler {
|
||||
|
||||
private readonly measurementChanges$: BehaviorSubject<MeasurementMsg>;
|
||||
// private readonly tempSplitCache: { front: Array<Measurement> | null, tail: Array<Measurement> | null };
|
||||
private cachedMeasurements: Array<Measurement>;
|
||||
private timeRanges: Array<TimeRange> | null;
|
||||
private exporting: boolean;
|
||||
|
||||
constructor(
|
||||
protected readonly defaultService: DefaultService,
|
||||
protected readonly bulkMeasurementService: BulkMeasurementService
|
||||
) {
|
||||
super(defaultService, bulkMeasurementService);
|
||||
this.measurementChanges$ = new BehaviorSubject<MeasurementMsg>(null);
|
||||
// this.tempSplitCache = { front: null, tail: null };
|
||||
this.exporting = false;
|
||||
}
|
||||
|
||||
observeMeasurementChanges(): Observable<MeasurementMsg> {
|
||||
return this.measurementChanges$;
|
||||
}
|
||||
|
||||
start(range: SatDatepickerRangeValue<Date>, filename?: string): void {
|
||||
const fetch = this.checkIfDataNeedsToBeFetched(range);
|
||||
this.init(range);
|
||||
if (fetch) {
|
||||
this.peekMeasurementsTotal();
|
||||
} else {
|
||||
this._progressFn(ProgressStatus.DONE);
|
||||
this.fetching = false;
|
||||
}
|
||||
}
|
||||
|
||||
exportMeasurements(filename?: string) {
|
||||
this.exporting = true
|
||||
this.archiveName = filename;
|
||||
this.initZipArchive();
|
||||
this.splitCacheByDevicesAndAddToZip();
|
||||
this.zip.generateAsync({ type: 'blob' }).then(content => {
|
||||
if (this.exporting) {
|
||||
this.saveAs(`mowesta-export-${this.archiveName}.zip`, content);
|
||||
this._progressFn(ProgressStatus.DONE);
|
||||
this.exporting = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected reset(): void {
|
||||
super.reset();
|
||||
this.measurementChanges$.next(null);
|
||||
// this.tempSplitCache.front = null;
|
||||
// this.tempSplitCache.tail = null;
|
||||
this.cachedMeasurements = null;
|
||||
this.timeRanges = null;
|
||||
}
|
||||
|
||||
private checkIfDataNeedsToBeFetched(satRange: SatDatepickerRangeValue<Date>): boolean {
|
||||
let fetch: boolean;
|
||||
this.timeRanges = new Array<TimeRange>();
|
||||
const newRange = this.satDatepickerRangeToTimeRange(satRange);
|
||||
if (!this.dateRange || newRange.start > this.dateRange.end || newRange.end < this.dateRange.start) {
|
||||
// No temporal overlap, cache can be released completely.
|
||||
this.timeRanges.push(newRange);
|
||||
this.cachedMeasurements = new Array<Measurement>();
|
||||
fetch = true;
|
||||
} else {
|
||||
const start = this.mustFetchDataOrReleaseCachePartially(newRange.start, this.dateRange.start,
|
||||
m => m.time >= newRange.start);
|
||||
const end = this.mustFetchDataOrReleaseCachePartially(this.dateRange.end, newRange.end,
|
||||
m => m.time <= newRange.end);
|
||||
fetch = start || end;
|
||||
}
|
||||
return fetch;
|
||||
}
|
||||
|
||||
private mustFetchDataOrReleaseCachePartially(range1: number, range2: number,
|
||||
isWithinRange: (m: Measurement) => boolean): boolean {
|
||||
const diff = range1 - range2;
|
||||
if (diff > 0) {
|
||||
// No fetching data, only release cache partially.
|
||||
const copiedCache = new Array<Measurement>();
|
||||
this.cachedMeasurements = this.cachedMeasurements.filter(m => {
|
||||
if (isWithinRange(m)) {
|
||||
copiedCache.push(m);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
console.log(this.cachedMeasurements);
|
||||
this.measurementChanges$.next({ data: copiedCache });
|
||||
return false;
|
||||
} else if (diff < 0) {
|
||||
// Fetching data, expand cache.
|
||||
this.timeRanges.push({
|
||||
start: range1,
|
||||
end: range2,
|
||||
duration: Math.abs(diff)
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
// No changes, time range equal.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private peekMeasurementsTotal(): void {
|
||||
let peekCount = 0;
|
||||
this.fetchedMeasurements = this.totalMeasurements = 0;
|
||||
this.timeRanges.forEach(range => {
|
||||
this.defaultService.getAllMeasurementsByRange(range.start, range.duration,
|
||||
0, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
peekCount++;
|
||||
if (page.total > 0) {
|
||||
page.offset += page.elements.length;
|
||||
this.fetchedMeasurements += page.elements.length;
|
||||
this.totalMeasurements += page.total;
|
||||
this.measurementChanges$.next({ data: page.elements, partialData: true });
|
||||
}
|
||||
if (peekCount === this.timeRanges.length) {
|
||||
if (this.fetchedMeasurements > 0) {
|
||||
this.fetchRemainingMeasurements(0, { id: -1, page });
|
||||
} else {
|
||||
this._progressFn(ProgressStatus.NO_MEASUREMENTS);
|
||||
this.reset();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private fetchRemainingMeasurements(idx: number, dmBuffer: DeviceMeasurements): void {
|
||||
this._progressFn(ProgressStatus.FETCHING, this.fetchedMeasurements, this.totalMeasurements);
|
||||
if (this.isPageIncomplete(dmBuffer.page)) {
|
||||
this.defaultService.getAllMeasurementsByRange(this.timeRanges[idx].start, this.timeRanges[idx].duration,
|
||||
dmBuffer.page.offset, AbstractExportHandler.BATCH_SIZE)
|
||||
.pipe(takeUntil(this.abortRequests$))
|
||||
.subscribe(page => {
|
||||
this.fetchedMeasurements += page.elements.length;
|
||||
// this.cachedMeasurements.push(...page.elements)
|
||||
this.measurementChanges$.next({ data: page.elements, partialData: true });
|
||||
this.mergePages(page, dmBuffer.page);
|
||||
this.fetchRemainingMeasurements(idx, dmBuffer);
|
||||
});
|
||||
} else if (idx < this.timeRanges.length) {
|
||||
this.fetchRemainingMeasurements(++idx, dmBuffer);
|
||||
} else {
|
||||
this.fetching = false;
|
||||
this.cachedMeasurements.push(...dmBuffer.page.elements);
|
||||
this.cachedMeasurements.sort((a, b) => a.device - b.device);
|
||||
this._progressFn(ProgressStatus.DONE);
|
||||
}
|
||||
}
|
||||
|
||||
private splitCacheByDevicesAndAddToZip(): void {
|
||||
let i = 0;
|
||||
const measurements = this.cachedMeasurements,
|
||||
len = this.cachedMeasurements.length;
|
||||
while (i < len) {
|
||||
const deviceId = measurements[i].device;
|
||||
const filteredMeasurements = measurements.filter(m => m.device === deviceId);
|
||||
filteredMeasurements.sort((a, b) => a.time - b.time);
|
||||
this.addMeasurementsToZipArchive(deviceId, filteredMeasurements);
|
||||
i += filteredMeasurements.length;
|
||||
this._progressFn(ProgressStatus.EXPORTING, i, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,4 +13,3 @@ export * from './reports.service';
|
||||
export * from './measurements.service';
|
||||
export * from './settings.service';
|
||||
export * from './city-forecast.service';
|
||||
|
||||
|
||||
@@ -152,6 +152,7 @@ export class ResourceService {
|
||||
'label_local_time' : 'Ortszeit',
|
||||
'label_source' : 'Quelle',
|
||||
|
||||
'label_device' : 'Gerät',
|
||||
'label_time' : 'Zeit',
|
||||
'label_date' : 'Datum',
|
||||
'label_temperature' : 'Temperatur',
|
||||
@@ -223,6 +224,24 @@ export class ResourceService {
|
||||
'user_account_password_wrong_title' : 'Passwort falsch',
|
||||
'user_account_password_wrong_message' : 'Dein derzeitiges Passwort stimmt nicht mit Deiner Eingabe überein.'
|
||||
+ ' Bitte prüfe Deine Eingabe und versuchs nochmal.',
|
||||
'user_account_export_measurements_title' : 'Gerätemessdaten exportieren',
|
||||
'user_account_export_measurements_subtitle' : 'Hier kannst Du die Messdaten, die von Deinen Geräten gesammelt wurden, exportieren.',
|
||||
'export_measurements_input_placeholder' : 'Zeitraum wählen...',
|
||||
'fetch_measurements_fetch_btn' : 'Laden',
|
||||
'export_measurements_export_btn' : 'Exportieren',
|
||||
'export_measurements_cancel_btn' : 'Abbrechen',
|
||||
'fetch_measurements_export_aborted' : 'Laden abgebrochen!',
|
||||
'export_measurements_export_aborted' : 'Export abgebrochen!',
|
||||
'export_measurements_no_devices' : 'Es sind keine Geräte vorhanden.',
|
||||
'export_measurements_no_measurements' : 'Es existieren keine Messungen für den angegebenen Zeitraum.',
|
||||
'export_measurements_abort_process_confirmation_title' : 'Vorgang abbrechen',
|
||||
'export_measurements_abort_process_confirmation_message' : 'Mit dem Verlassen dieser Seite wird der Vorgang automatisch abgebrochen! Möchten Sie fortfahren?',
|
||||
'export_measurements_abort_process_confirmation_positive' : 'Ja',
|
||||
'export_measurements_abort_process_confirmation_negative' : 'Nein',
|
||||
'export_measurements_export_failed_title' : 'Export fehlgeschlagen!',
|
||||
'export_measurements_export_failed_msg' : 'Der Export konnte leider nicht durchgeführt werden.',
|
||||
'export_measurements_tooltip_title' : 'Messung',
|
||||
|
||||
'reset_confirm_title' : 'Passwort zurückgesetzt',
|
||||
'reset_confirm_message' : 'Wir haben Dir einen Link an Deine Kontaktemailadresse versandt, '
|
||||
+ 'mit dem Du Dein Passwort ändern kannst. Falls Dir Dein Passwort wieder einfällt, kannst Du die Email einfach löschen.',
|
||||
@@ -332,6 +351,8 @@ export class ResourceService {
|
||||
'manage_logs_trace_tooltip': 'Stacktrace vorhanden',
|
||||
'manage_logs_actions': 'Aktionen',
|
||||
'manage_logs_details_tooltip': 'Details anzeigen',
|
||||
'manage_measurements_map_title': 'Messdaten',
|
||||
|
||||
'login_login_title': 'Anmelden',
|
||||
'login_login_subtitle': 'Mit Deinem Konto kannst Du hier auf Deine Daten zugreifen.',
|
||||
'login_login_reset': 'Passwort vergessen?',
|
||||
@@ -594,6 +615,7 @@ export class ResourceService {
|
||||
'label_local_time' : 'Local Time',
|
||||
'label_source' : 'Source',
|
||||
|
||||
'label_device' : 'Device',
|
||||
'label_time' : 'Time',
|
||||
'label_date' : 'Date',
|
||||
'label_temperature' : 'Temperature',
|
||||
@@ -665,6 +687,24 @@ export class ResourceService {
|
||||
'user_account_password_wrong_title' : 'Password invalid',
|
||||
'user_account_password_wrong_message' : 'Your current password does not match the one you provided.'
|
||||
+ 'Please validate your input and try again.',
|
||||
'user_account_export_measurements_title' : 'Export device measurement data',
|
||||
'user_account_export_measurements_subtitle' : 'Here you can export the measurement data collected by your devices.',
|
||||
'export_measurements_input_placeholder' : 'Select time period...',
|
||||
'fetch_measurements_fetch_btn' : 'Fetch',
|
||||
'export_measurements_export_btn' : 'Export',
|
||||
'export_measurements_cancel_btn' : 'Cancel',
|
||||
'fetch_measurements_export_aborted' : 'Fetching aborted!',
|
||||
'export_measurements_export_aborted' : 'Export aborted!',
|
||||
'export_measurements_no_devices' : 'There are no devices available.',
|
||||
'export_measurements_no_measurements' : 'There are no measurements for the specified time period.',
|
||||
'export_measurements_abort_process_confirmation_title' : 'Cancel Process',
|
||||
'export_measurements_abort_process_confirmation_message' : 'If you leave this page, the process will be automatically aborted! Do you want to continue?',
|
||||
'export_measurements_abort_process_confirmation_positive' : 'Yes',
|
||||
'export_measurements_abort_process_confirmation_negative' : 'No',
|
||||
'export_measurements_export_failed_title' : 'Export failed!',
|
||||
'export_measurements_export_failed_msg' : 'Unfortunately the export could not be carried out.',
|
||||
'export_measurements_tooltip_title' : 'Measurement',
|
||||
|
||||
'reset_confirm_title' : 'Password reset',
|
||||
'reset_confirm_message' : 'We just sent an email to your primary email address that contains a password reset link. '
|
||||
+ 'If you remember your password again, you can simply delete the email.',
|
||||
@@ -773,6 +813,8 @@ export class ResourceService {
|
||||
'manage_logs_trace_tooltip': 'Stacktrace available',
|
||||
'manage_logs_actions': 'Actions',
|
||||
'manage_logs_details_tooltip': 'Show details',
|
||||
'manage_measurements_map_title': 'Measurements',
|
||||
|
||||
'login_login_title': 'Login',
|
||||
'login_login_subtitle': 'Here you can access your data with your account',
|
||||
'login_login_reset': 'Forgot password?',
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* The initial bounds of the map when the users language setting is german showing Central Europe.
|
||||
*/
|
||||
import { Coordinate } from "../../api/model/coordinate";
|
||||
|
||||
export const DACH_BOUNDS: Array<Coordinate> = [
|
||||
{ latitude: 52.5170365, longitude: 13.3888599 }, // Berlin
|
||||
{ latitude: 53.550341, longitude: 10.000654 }, // Hamburg
|
||||
{ latitude: 46.9482713, longitude: 7.4514512 }, // Bern
|
||||
{ latitude: 46.2017559, longitude: 6.1466014 }, // Genf
|
||||
{ latitude: 48.2083537, longitude: 16.3725042 }, // Wien
|
||||
{ latitude: 46.6228162, longitude: 14.3079604 } // Klagenfurt
|
||||
];
|
||||
/**
|
||||
* The initial bounds of the map when the users language setting is english showing a world map.
|
||||
*/
|
||||
export const WORLD_BOUNDS: Array<Coordinate> = [
|
||||
{ latitude: 35.6828387, longitude: 139.7594549 }, // Tokyo
|
||||
{ latitude: -12.0621065, longitude: -77.0365256 }, // Lima
|
||||
{ latitude: -6.1753942, longitude: 106.827183 }, // Jakarta
|
||||
{ latitude: -33.918861, longitude: 18.423300 }, // Kapstadt
|
||||
{ latitude: 68.9791718, longitude: 33.0925102 } // Murmansk
|
||||
];
|
||||
@@ -0,0 +1,43 @@
|
||||
<mat-accordion class="top-right-overflow ">
|
||||
<mat-expansion-panel expanded>
|
||||
<mat-expansion-panel-header>
|
||||
<mat-panel-title>{{ res.strings('manage_measurements_map_title') }}</mat-panel-title>
|
||||
</mat-expansion-panel-header>
|
||||
<div class="fx-column">
|
||||
<mat-form-field class="mb-sm">
|
||||
<input matInput
|
||||
[placeholder]="res.strings('export_measurements_input_placeholder')"
|
||||
[disabled]="fetchInProgress"
|
||||
[satDatepicker]="picker"
|
||||
[value]="dateRange"
|
||||
(click)="picker.open()"
|
||||
(dateChange)="dateRange = $event.target.value">
|
||||
<sat-datepicker #picker [rangeMode]="true" orderPeriodLabel="month"></sat-datepicker>
|
||||
<sat-datepicker-toggle matSuffix [for]="picker"></sat-datepicker-toggle>
|
||||
</mat-form-field>
|
||||
<button mat-raised-button color="primary" (click)="fetchMeasurements()" [disabled]="!dateRange || fetchInProgress">
|
||||
<mat-icon class="icon-button">get_app</mat-icon>
|
||||
<span>{{ res.strings('fetch_measurements_fetch_btn') }}</span>
|
||||
</button>
|
||||
<div class="mt-sm"></div>
|
||||
<button mat-raised-button color="accent" (click)="exportMeasurements()"
|
||||
[disabled]="fetchedMeasurements.length === 0 || fetchInProgress">
|
||||
<mat-icon class="icon-button">import_export</mat-icon>
|
||||
<span>{{ res.strings('export_measurements_export_btn') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</mat-expansion-panel>
|
||||
</mat-accordion>
|
||||
|
||||
<app-map #map [bounds]="initialBounds" [maxZoom]="16" draggable="true"></app-map>
|
||||
|
||||
<mat-card *ngIf="fetchInProgress" class="bottom-overflow">
|
||||
<mat-label class="fx-row fx-center progress-label" matLine>Fortschritt: {{ progress }}%</mat-label>
|
||||
<div class="fx-row fx-center mt-sm">
|
||||
<mat-progress-bar class="mr-md" mode="determinate" [value]="progress" matLine></mat-progress-bar>
|
||||
<button mat-raised-button color="warn" (click)="stop()">
|
||||
<mat-icon class="icon-button">cancel_icon</mat-icon>
|
||||
<span style="padding-right: 20px">{{ res.strings('export_measurements_cancel_btn') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</mat-card>
|
||||
@@ -0,0 +1,207 @@
|
||||
import { Component, OnInit, ViewChild } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from "@angular/router";
|
||||
import { formatDate } from "@angular/common";
|
||||
import { MatDialog } from "@angular/material/dialog";
|
||||
import { SatDatepickerRangeValue } from "saturn-datepicker";
|
||||
import * as L from 'leaflet';
|
||||
import * as MapUtils from '../utils/map-utilities'
|
||||
import { ConfirmationDialogComponent, MessageDialogComponent } from "../dialogs";
|
||||
import { ResourceService, UserService } from "../services";
|
||||
import { BulkMeasurementService, ProgressFn, ProgressStatus } from "../services/bulk-measurement.service";
|
||||
import { MapComponent } from "../widgets-common";
|
||||
import { HumidityPipe, PressurePipe, TemperaturePipe } from "../pipes";
|
||||
import { AbstractCanDeactivate } from "../guards/can-deactivate.guard";
|
||||
import { Coordinate } from "../../api/model/coordinate";
|
||||
import { Measurement } from "../../api/model/measurement";
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'app-measurements-map',
|
||||
templateUrl: './manage-measurements-map.component.html',
|
||||
styles: [`
|
||||
.top-right-overflow { position: absolute; top: 10px; right: 50px; z-index: 10000; }
|
||||
.bottom-overflow { position: absolute; right: 50px; bottom: 25px; left: 50px; z-index: 10000; }
|
||||
`]
|
||||
})
|
||||
export class ManageMeasurementsMapComponent extends AbstractCanDeactivate implements OnInit {
|
||||
|
||||
@ViewChild('map') appMap: MapComponent;
|
||||
|
||||
progress: number;
|
||||
fetchInProgress: boolean;
|
||||
exportInProgress: boolean;
|
||||
fetchedMeasurements: Array<Measurement>;
|
||||
initialBounds: Array<Coordinate>;
|
||||
dateRange: SatDatepickerRangeValue<Date>;
|
||||
|
||||
private readonly markers = new Array<L.Circle>();
|
||||
|
||||
constructor(
|
||||
public readonly res: ResourceService,
|
||||
private readonly router: Router,
|
||||
private readonly dialog: MatDialog,
|
||||
private readonly userService: UserService,
|
||||
private readonly bulkService: BulkMeasurementService,
|
||||
private readonly temperaturePipe: TemperaturePipe,
|
||||
private readonly pressurePipe: PressurePipe,
|
||||
private readonly humidityPipe: HumidityPipe
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.progress = 0;
|
||||
this.fetchInProgress = false;
|
||||
this.fetchedMeasurements = new Array<Measurement>();
|
||||
this.initialBounds = this.res.getLanguage() === 'de' ? MapUtils.DACH_BOUNDS : MapUtils.WORLD_BOUNDS;
|
||||
}
|
||||
|
||||
canDeactivate(): boolean {
|
||||
return this.exportInProgress || this.fetchInProgress;
|
||||
}
|
||||
|
||||
processDeactivation(currentRoute: ActivatedRouteSnapshot,
|
||||
currentState: RouterStateSnapshot,
|
||||
nextState?: RouterStateSnapshot): void {
|
||||
ConfirmationDialogComponent.open(this.dialog, {
|
||||
title: this.res.strings('export_measurements_abort_process_confirmation_title'),
|
||||
message: this.res.strings('export_measurements_abort_process_confirmation_message'),
|
||||
positive: this.res.strings('export_measurements_abort_process_confirmation_positive'),
|
||||
negative: this.res.strings('export_measurements_abort_process_confirmation_negative')
|
||||
}).subscribe(value => {
|
||||
if (value.confirmed === true) {
|
||||
this.exportInProgress = this.fetchInProgress = false;
|
||||
if (nextState) { this.router.navigateByUrl(nextState.url).then(); }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fetchMeasurements(): void {
|
||||
if (this.dateRange && !this.fetchInProgress && !this.exportInProgress) {
|
||||
this.fetchInProgress = true;
|
||||
this.bulkService.fetchMeasurements(this.dateRange, this.getProgressFn(ProgressStatus.FETCHING))
|
||||
.subscribe(msg => {
|
||||
if (!msg) {
|
||||
this.resetMap();
|
||||
} else if (msg.partialData) {
|
||||
this.addNewMeasurementsToMap(msg.data);
|
||||
} else {
|
||||
this.resetMap();
|
||||
this.addNewMeasurementsToMap(msg.data);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
exportMeasurements(): void {
|
||||
if (this.fetchedMeasurements.length !== 0 && !this.exportInProgress && !this.fetchInProgress) {
|
||||
this.exportInProgress = true;
|
||||
const success = this.bulkService
|
||||
.saveFetchedMeasurements(this.userService.getLogin(), this.getProgressFn(ProgressStatus.EXPORTING));
|
||||
if (!success) {
|
||||
MessageDialogComponent.open(this.dialog, {
|
||||
title: this.res.strings('export_measurements_export_failed_title'),
|
||||
message: this.res.strings('export_measurements_export_failed_msg')
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.fetchInProgress || this.exportInProgress) {
|
||||
this.bulkService.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private getProgressFn(statusOnWhichToModifyProgress: ProgressStatus): ProgressFn {
|
||||
return (status, fetched, total) => {
|
||||
if (status === statusOnWhichToModifyProgress) {
|
||||
this.progress = Math.floor((Math.min(fetched, total) / total) * 100);
|
||||
} else {
|
||||
this.fetchInProgress = this.exportInProgress = false;
|
||||
this.progress = 0;
|
||||
// @ts-ignore
|
||||
if (status !== ProgressStatus.DONE) {
|
||||
const pre = statusOnWhichToModifyProgress === ProgressStatus.EXPORTING ? 'export' : 'fetch';
|
||||
const title = this.res.strings(pre + '_measurements_export_aborted');
|
||||
let message;
|
||||
if (status === ProgressStatus.NO_DEVICES) {
|
||||
message = this.res.strings('export_measurements_no_devices');
|
||||
} else if (status === ProgressStatus.NO_MEASUREMENTS) {
|
||||
message = this.res.strings('export_measurements_no_measurements');
|
||||
}
|
||||
MessageDialogComponent.open(this.dialog, { title, message });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private resetMap(): void {
|
||||
this.fetchedMeasurements.length = 0;
|
||||
this.markers.forEach(m => m.remove());
|
||||
}
|
||||
|
||||
private addNewMeasurementsToMap(newData: Array<Measurement>): void {
|
||||
this.fetchedMeasurements = this.fetchedMeasurements.concat(newData);
|
||||
newData.forEach(m => {
|
||||
const tooltip = L.tooltip({
|
||||
direction: 'top',
|
||||
className: 'forecast-tooltip',
|
||||
}).setContent(this.createTooltipContent(m));
|
||||
const marker = L.circle([m.coordinate?.latitude, m.coordinate?.longitude], {
|
||||
radius: 32,
|
||||
color: '#00695c',
|
||||
fillColor: '#f9a825'
|
||||
}).addTo(this.appMap.map);
|
||||
marker.on({
|
||||
mouseover: _ => marker.openTooltip().bindTooltip(tooltip),
|
||||
mouseout: _ => marker.closeTooltip()
|
||||
})
|
||||
this.markers.push(marker);
|
||||
});
|
||||
}
|
||||
|
||||
private createTooltipContent(m: Measurement): string {
|
||||
const date = this.res.getLanguage() === 'de' ?
|
||||
formatDate(new Date(m.time), 'dd.MM.yyyy H:mm:ss', 'de')
|
||||
: formatDate(new Date(m.time), 'MM/dd/yyyy H:mm:ss', 'en');
|
||||
let content = `
|
||||
<div class="fx-column" style="width: 185px;">
|
||||
<div class="fx-row" style="margin-right: 5px; margin-left: 5px;">
|
||||
<div class="fx-column fx-stretch">
|
||||
<div style="margin-bottom: 4px; text-align: center; font-size: 16px;">
|
||||
<b>${this.res.strings('export_measurements_tooltip_title')}</b>
|
||||
</div>
|
||||
<div style="text-overflow: ellipsis; overflow: hidden; width: 120px;">
|
||||
${this.res.strings('label_device')}: <b>${m.device}</b>
|
||||
</div>
|
||||
<div style="width: 120px;">
|
||||
${this.res.strings('label_date')}: <b>${date}</b>
|
||||
</div>
|
||||
`;
|
||||
const contentTail = `
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const temperature = this.temperaturePipe.transform(m.temperature);
|
||||
const humidity = this.humidityPipe.transform(m.humidity);
|
||||
const pressure = this.pressurePipe.transform(m.pressure);
|
||||
if (temperature) {
|
||||
content += `
|
||||
<div>${this.res.strings('label_temperature')}: <b>${temperature}</b></div>
|
||||
`;
|
||||
}
|
||||
if (humidity) {
|
||||
content += `
|
||||
<div>${this.res.strings('label_humidity')}: <b>${humidity}</b></div>
|
||||
`;
|
||||
}
|
||||
if (pressure) {
|
||||
content += `
|
||||
<div>${this.res.strings('label_pressure')}: <b>${pressure}</b></div>
|
||||
`;
|
||||
}
|
||||
return content + contentTail;
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,44 @@
|
||||
</mat-list>
|
||||
</div>
|
||||
</mat-tab>
|
||||
<mat-tab>
|
||||
<ng-template mat-tab-label>
|
||||
<mat-icon>import_export</mat-icon>
|
||||
</ng-template>
|
||||
<div class="m-lg">
|
||||
<h2>{{ res.strings('user_account_export_measurements_title') }}</h2>
|
||||
<h4>{{ res.strings('user_account_export_measurements_subtitle') }}</h4>
|
||||
<div class="fx-column">
|
||||
<mat-form-field class="mb-sm">
|
||||
<input matInput
|
||||
[placeholder]="res.strings('export_measurements_input_placeholder')"
|
||||
[disabled]="exportInProgress"
|
||||
[satDatepicker]="picker"
|
||||
[value]="dateRange"
|
||||
(click)="picker.open()"
|
||||
(dateChange)="dateRange = $event.target.value">
|
||||
<sat-datepicker #picker [rangeMode]="true" orderPeriodLabel="month"></sat-datepicker>
|
||||
<sat-datepicker-toggle matSuffix [for]="picker"></sat-datepicker-toggle>
|
||||
</mat-form-field>
|
||||
<div class="fx-row fx-center mb-md">
|
||||
<button mat-raised-button color="primary" (click)="onExportMeasurements()" [disabled]="!dateRange || exportInProgress">
|
||||
<mat-icon class="icon-button">import_export</mat-icon>
|
||||
<span>{{ res.strings('export_measurements_export_btn') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div *ngIf="exportInProgress">
|
||||
<mat-label class="progress-label" matLine><div style="float: right;">{{ exportProgress }}%</div></mat-label>
|
||||
<mat-progress-bar mode="determinate" [value]="exportProgress" matLine></mat-progress-bar>
|
||||
<div class="fx-row fx-center mt-md">
|
||||
<button mat-raised-button color="warn" (click)="onCancelExportMeasurements()">
|
||||
<mat-icon class="icon-button">cancel_icon</mat-icon>
|
||||
<span>{{ res.strings('export_measurements_cancel_btn') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mat-tab>
|
||||
<mat-tab>
|
||||
<ng-template mat-tab-label>
|
||||
<mat-icon [matTooltip]="res.strings('user_account_delete_title')">delete_forever</mat-icon>
|
||||
@@ -115,4 +153,4 @@
|
||||
<div fxFlexFill fxLayoutAlign="space-around center">
|
||||
<mat-spinner [diameter]="100"></mat-spinner>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ng-template>
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
import { Component, OnInit, OnDestroy, ViewChild, HostListener } from '@angular/core';
|
||||
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
|
||||
import { BehaviorSubject, Subscription } from 'rxjs';
|
||||
import { Router } from '@angular/router';
|
||||
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { SatDatepickerRangeValue } from "saturn-datepicker";
|
||||
import { Snackbars } from '../utils';
|
||||
import { User, Email } from '../api';
|
||||
import { ResourceService, UserService, UserRole } from '../services';
|
||||
import { NameFieldComponent, EmailFieldComponent, PasswordFieldComponent } from '../widgets-common';
|
||||
import { MessageDialogComponent, ConfirmationDialogComponent } from '../dialogs';
|
||||
import { style } from '@angular/animations';
|
||||
import { Email, User } from '../api';
|
||||
import { ResourceService, UserRole, UserService } from '../services';
|
||||
import { EmailFieldComponent, NameFieldComponent, PasswordFieldComponent } from '../widgets-common';
|
||||
import { ConfirmationDialogComponent, MessageDialogComponent } from '../dialogs';
|
||||
import { BulkMeasurementService, ProgressStatus } from '../services/bulk-measurement.service'
|
||||
import { AbstractCanDeactivate } from "../guards/can-deactivate.guard";
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-account',
|
||||
templateUrl: './user-account.component.html',
|
||||
styles: [ ':host { flex: 1 1 100%; }' ]
|
||||
})
|
||||
export class UserAccountComponent implements OnInit, OnDestroy {
|
||||
export class UserAccountComponent extends AbstractCanDeactivate implements OnInit, OnDestroy {
|
||||
|
||||
@ViewChild(NameFieldComponent) nameField: NameFieldComponent;
|
||||
@ViewChild(MatSelect) emailSelect: MatSelect;
|
||||
@@ -37,11 +39,22 @@ export class UserAccountComponent implements OnInit, OnDestroy {
|
||||
correspondence: Email;
|
||||
emails: Email[] = [];
|
||||
|
||||
exportInProgress = false;
|
||||
exportProgress = 0;
|
||||
dateRange: SatDatepickerRangeValue<Date>;
|
||||
|
||||
user: BehaviorSubject<User>;
|
||||
private userSubscription: Subscription;
|
||||
|
||||
constructor(public res: ResourceService, private userService: UserService,
|
||||
private snackbar: MatSnackBar, private dialog: MatDialog, private router: Router) {
|
||||
constructor(
|
||||
public readonly res: ResourceService,
|
||||
public readonly exportService: BulkMeasurementService,
|
||||
private readonly userService: UserService,
|
||||
private readonly snackbar: MatSnackBar,
|
||||
private readonly dialog: MatDialog,
|
||||
private readonly router: Router
|
||||
) {
|
||||
super();
|
||||
this.user = userService.user;
|
||||
}
|
||||
|
||||
@@ -55,6 +68,7 @@ export class UserAccountComponent implements OnInit, OnDestroy {
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.userSubscription.unsubscribe();
|
||||
this.exportService.stop();
|
||||
}
|
||||
|
||||
private getEmails(): Email[] {
|
||||
@@ -123,6 +137,36 @@ export class UserAccountComponent implements OnInit, OnDestroy {
|
||||
this.userService.changeUser(u);
|
||||
}
|
||||
|
||||
onExportMeasurements(): void {
|
||||
if (this.dateRange) {
|
||||
this.exportInProgress = true;
|
||||
this.exportService.exportMeasurements(this.dateRange, this.userService.getLogin(), false,
|
||||
(status, fetched, total) => {
|
||||
if (status === ProgressStatus.FETCHING) {
|
||||
this.exportProgress = Math.floor((Math.min(fetched, total) / total) * 100);
|
||||
} else {
|
||||
this.exportInProgress = false;
|
||||
this.exportProgress = 0;
|
||||
// @ts-ignore
|
||||
if (status !== ProgressStatus.DONE) {
|
||||
const title = this.res.strings('export_measurements_export_aborted');
|
||||
let message;
|
||||
if (status === ProgressStatus.NO_DEVICES) {
|
||||
message = this.res.strings('export_measurements_no_devices');
|
||||
} else if (status === ProgressStatus.NO_MEASUREMENTS) {
|
||||
message = this.res.strings('export_measurements_no_measurements');
|
||||
}
|
||||
MessageDialogComponent.open(this.dialog, { title, message });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onCancelExportMeasurements(): void {
|
||||
this.exportService.stop();
|
||||
}
|
||||
|
||||
onDeleteEmail(id: number): void {
|
||||
if (this.user.getValue() == null) { return; }
|
||||
const u = this.user.getValue();
|
||||
@@ -157,4 +201,24 @@ export class UserAccountComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
canDeactivate(): boolean {
|
||||
return this.exportInProgress;
|
||||
}
|
||||
|
||||
processDeactivation(currentRoute: ActivatedRouteSnapshot,
|
||||
currentState: RouterStateSnapshot,
|
||||
nextState?: RouterStateSnapshot): void {
|
||||
ConfirmationDialogComponent.open(this.dialog, {
|
||||
title: this.res.strings('export_measurements_abort_process_confirmation_title'),
|
||||
message: this.res.strings('export_measurements_abort_process_confirmation_message'),
|
||||
positive: this.res.strings('export_measurements_abort_process_confirmation_positive'),
|
||||
negative: this.res.strings('export_measurements_abort_process_confirmation_negative')
|
||||
}).subscribe(value => {
|
||||
if (value.confirmed === true) {
|
||||
this.exportInProgress = false;
|
||||
if (nextState) { this.router.navigateByUrl(nextState.url).then(); }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<div matAutocompleteOrigin #origin="matAutocompleteOrigin"
|
||||
class="search-container search" tabindex="0"
|
||||
(click)="onSearchClick()" >
|
||||
(click)="onSearchClick()">
|
||||
<mat-icon class="search-icon">search</mat-icon>
|
||||
<input matInput #searchInput class="search-input" type="search"
|
||||
[formControl]="term"
|
||||
@@ -19,7 +19,7 @@
|
||||
</app-location-autocomplete>
|
||||
<app-map #appMap
|
||||
[bounds]="initialBounds"
|
||||
[maxZoo]="16"
|
||||
[maxZoom]="16"
|
||||
[mapEventHandlers]="mapEventHandlers"
|
||||
draggable="true">
|
||||
</app-map>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { LocalNamePipe, TemperaturePipe, WeatherIconPipe, WeatherPipe } from '..
|
||||
import { DefaultService } from '../../api/api/default.service';
|
||||
import { City, Coordinate, WeatherForecast, LocationHierarchy } from '../api';
|
||||
import * as L from 'leaflet';
|
||||
import * as MapUtils from '../utils/map-utilities';
|
||||
|
||||
|
||||
/**
|
||||
@@ -93,27 +94,6 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
* forecast for an already existing city should be reloaded.
|
||||
*/
|
||||
static readonly TIME_THRESHOLD = 900000;
|
||||
/**
|
||||
* The initial bounds of the map when the users language setting is german showing Central Europe.
|
||||
*/
|
||||
private static readonly DACH_BOUNDS: Array<Coordinate> = [
|
||||
{ latitude: 52.5170365, longitude: 13.3888599 }, // Berlin
|
||||
{ latitude: 53.550341, longitude: 10.000654 }, // Hamburg
|
||||
{ latitude: 46.9482713, longitude: 7.4514512 }, // Bern
|
||||
{ latitude: 46.2017559, longitude: 6.1466014 }, // Genf
|
||||
{ latitude: 48.2083537, longitude: 16.3725042 }, // Wien
|
||||
{ latitude: 46.6228162, longitude: 14.3079604 } // Klagenfurt
|
||||
];
|
||||
/**
|
||||
* The initial bounds of the map when the users language setting is english showing a world map.
|
||||
*/
|
||||
private static readonly WORLD_BOUNDS: Array<Coordinate> = [
|
||||
{ latitude: 35.6828387, longitude: 139.7594549 }, // Tokyo
|
||||
{ latitude: -12.0621065, longitude: -77.0365256 }, // Lima
|
||||
{ latitude: -6.1753942, longitude: 106.827183 }, // Jakarta
|
||||
{ latitude: -33.918861, longitude: 18.423300 }, // Kapstadt
|
||||
{ latitude: 68.9791718, longitude: 33.0925102 } // Murmansk
|
||||
];
|
||||
|
||||
@ViewChild('appMap') appMap: MapComponent;
|
||||
@ViewChild('searchInput') searchInput: ElementRef;
|
||||
@@ -196,9 +176,7 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
this.pendingMapTiles = new Map<string, MapTile>();
|
||||
this.cachedMapTiles = new Map<string, MapTile>();
|
||||
this.cachedCityData = new Map<number, CityData>();
|
||||
this.initialBounds = this.res.getLanguage() === 'de' ?
|
||||
ConditionMapComponent.DACH_BOUNDS
|
||||
: ConditionMapComponent.WORLD_BOUNDS;
|
||||
this.initialBounds = this.res.getLanguage() === 'de' ? MapUtils.DACH_BOUNDS : MapUtils.WORLD_BOUNDS;
|
||||
this.mapEventHandlers = {
|
||||
load: e => this.onZoomLevelChanged(e.target._zoom),
|
||||
zoomend: e => this.onZoomLevelChanged(e.target._zoom),
|
||||
|
||||
@@ -27,13 +27,13 @@ export class MapComponent implements OnInit, DoCheck {
|
||||
static readonly DEFAULT_ZOOM = 13;
|
||||
static readonly MAX_ZOOM = 18;
|
||||
private static readonly DEFAULT_LOCATION = new L.LatLng(51.461663, 7.016645);
|
||||
private static readonly DEFAULT_TILE_URL = 'https://cloud.locoslab.com/carta/restful-services/tile/{z}/{x}/{y}.png';
|
||||
private static readonly DEFAULT_TILE_URL = 'https://www.mowesta.com/carta/tile/{z}/{x}/{y}.png';
|
||||
|
||||
@ViewChild('map', { read: ElementRef, static: true }) mapElement: ElementRef;
|
||||
|
||||
@Input() coordinate: Coordinate;
|
||||
@Input() zoom: number;
|
||||
@Input() maxZoo: number;
|
||||
@Input() maxZoom: number;
|
||||
@Input() draggable: boolean;
|
||||
@Input() bounds: Coordinate[];
|
||||
@Input() boundary: Geometry;
|
||||
@@ -68,7 +68,7 @@ export class MapComponent implements OnInit, DoCheck {
|
||||
maxBounds: [[-90, -180],[90, 180]]
|
||||
});
|
||||
this.layer = new L.TileLayer(MapComponent.DEFAULT_TILE_URL, {
|
||||
maxZoom: this.maxZoo? this.maxZoo : MapComponent.MAX_ZOOM
|
||||
maxZoom: this.maxZoom? this.maxZoom : MapComponent.MAX_ZOOM
|
||||
}).addTo(this.map);
|
||||
if (this.mapEventHandlers) { this.map.on(this.mapEventHandlers); }
|
||||
if (this.layerEventHandlers) { this.layer.on(this.layerEventHandlers)}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@import '~@angular/material/theming';
|
||||
@import '~saturn-datepicker/theming';
|
||||
// Plus imports for other components in your app.
|
||||
|
||||
// Include the common styles for Angular Material. We include this here so that you only
|
||||
@@ -67,3 +68,4 @@ $custom-typography: mat-typography-config(
|
||||
// Alternatively, you can import and @include the theme mixins for each component
|
||||
// that you are using.
|
||||
@include angular-material-theme($app-theme);
|
||||
@include sat-datepicker-theme($app-theme);
|
||||
|
||||
Reference in New Issue
Block a user