28 Commits
Author SHA1 Message Date
handte 524802d209 Release 1.0.4
LocationBasedServices/maptology/master This commit looks good
2019-11-26 15:39:31 +01:00
Marcus Handte 95116a30fd Bugfix in app, disallow devices to use position service.
LocationBasedServices/maptology/master This commit looks good
2019-11-19 22:24:31 +01:00
Marcus Handte 077cecb670 Change device update api, add tests, fix version, add migration.
LocationBasedServices/maptology/master This commit looks good
2019-11-19 19:06:02 +01:00
Marcus Handte 6e5c90acd9 Finished data logger, fix position bean bug.
LocationBasedServices/maptology/master This commit looks good
2019-11-18 21:39:50 +01:00
Marcus Handte c2b52164d9 Downgrade broken gradle plugin.
LocationBasedServices/maptology/master This commit looks good
2019-11-18 15:26:46 +01:00
Marcus Handte efd893de8a Continued logger implementation.
LocationBasedServices/maptology/master This commit looks good
2019-11-11 18:18:16 +01:00
Marcus Handte 5ab1224dcf Change code generators, fix regression.
LocationBasedServices/maptology/master This commit looks good
2019-11-09 23:39:48 +01:00
Marcus Handte 7da98783c4 Update oss plugin, reduce dex memory consumption.
LocationBasedServices/maptology/master This commit looks good
Switch oss gradle plugin to custom build to get rid of warnings.
Reduce dex memory from 1g to 512m to avoid out of memory issues.
2019-11-09 22:27:33 +01:00
Marcus Handte 3447709f01 Upgrade android gradle plugin.
LocationBasedServices/maptology/master This commit looks good
2019-11-09 20:58:36 +01:00
handte 509baeaf00 Removed buildSrc, continued implementation of logger.
LocationBasedServices/maptology/master This commit looks good
Removed buildSrc to speed up Android plugin.
Refactored position service and added more logger code.
2019-11-01 18:23:01 +01:00
handte 72767c4a87 Added scientist integration, fixes for daylight savings time.
LocationBasedServices/maptology/master This commit looks good
Extended role management to support scientist role.
Added user interface to let scientists and admins view individual position updates.
Modified date computation to fix issues with daylight savings time.
2019-10-30 12:33:13 +01:00
handte f1d01741f6 Extended position service for data logging.
LocationBasedServices/maptology/master This commit looks good
Added endpoints and database extensions for data logging.
Renamed history service api to match position api.
Changed web app to use new api.
Switched android minifier from proguard to r8.
Added delta codec for sensor data compression.
Started implementing data logger service (unfinished).
2019-10-29 17:49:05 +01:00
Marcus Handte 7b5d96f6b9 Fixed test instabilities, added android eclipse plugin.
LocationBasedServices/maptology/master This commit looks good
2019-10-25 10:08:42 +02:00
handte 7085f910f7 Fix deployment path name.
LocationBasedServices/maptology/master This commit looks good
2019-09-18 16:11:32 +02:00
Marcus Handte c2e25c0945 Change deployment directories.
LocationBasedServices/maptology/master This commit looks good
2019-09-18 14:30:49 +02:00
Marcus Handte 2f2de2eba7 Update to 1.0.4-SNAPSHOT
LocationBasedServices/maptology/master This commit looks good
2019-09-13 21:54:31 +02:00
Marcus Handte 70c9a07469 Release 1.0.3
LocationBasedServices/maptology/master This commit looks good
2019-09-13 21:51:59 +02:00
Marcus Handte 32d97e9c78 Fix geocoder, bump android version code.
LocationBasedServices/maptology/master This commit looks good
2019-09-13 21:31:22 +02:00
Marcus Handte 9ac137b9f7 Add package lock.
LocationBasedServices/maptology/master This commit looks good
2019-09-13 21:11:33 +02:00
Marcus Handte 204c1b3e7a Fix android lint errors.
LocationBasedServices/maptology/master There was a failure building this commit
2019-09-13 21:07:31 +02:00
Marcus Handte 4a13f36971 Fix android timings and revert geocoder changes.
LocationBasedServices/maptology/master There was a failure building this commit
Use time tick to work around samsung scheduling differences.
Revert deprecation warning fix in geocoder to support current wildfly version.
2019-09-13 21:00:39 +02:00
Marcus Handte e1022fb785 Replace set window with set exact.
LocationBasedServices/maptology/master This commit looks good
2019-08-08 18:38:27 +02:00
Marcus Handte 35785b719c Update to 1.0.3-SNAPSHOT
LocationBasedServices/maptology/master This commit looks good
2019-08-08 09:35:49 +02:00
Marcus Handte 4f85f70d3e Release 1.0.2
LocationBasedServices/maptology/master This commit looks good
2019-08-08 09:29:25 +02:00
Marcus Handte 5bb2e6fee6 Fix android scheduling and layouts.
LocationBasedServices/maptology/master This commit looks good
Closes #64 Hide password on login.
Closes #63 Fix scheduling on Android 9.
Remove unused import in statistics bean.
2019-08-08 09:20:12 +02:00
handte d577cadf39 Improve logging and statistics.
LocationBasedServices/maptology/master This commit looks good
Avoid logging of credentials, except for failing device tokens.
Increase severity of invalid logins to simplfy intrusion detection.
Generate statistics about released positions as part of admin view.
2019-08-07 20:15:43 +02:00
handte cb4b3331f4 Improve layout of place order select.
LocationBasedServices/maptology/master This commit looks good
2019-08-07 16:31:42 +02:00
handte 12c5d79686 Update to 1.0.2-SNAPSHOT
LocationBasedServices/maptology/master This commit looks good
2019-08-07 16:21:11 +02:00
102 changed files with 3891 additions and 629 deletions
Vendored
+2 -2
View File
@@ -59,8 +59,8 @@ node {
stage ('Deploy') {
if (env.BRANCH_NAME == "master") {
withCredentials([sshUserPrivateKey(credentialsId: "maptology-server-key", keyFileVariable: "keyfile")]) {
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@srv.nes.uni-due.de:~/standalone/deployments/maptology.ear"
sh "scp -i ${keyfile} android-app/build/outputs/apk/release/*.apk wildfly@srv.nes.uni-due.de:/opt/android/"
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@srv.nes.uni-due.de:/opt/wildfly-17-maptology/standalone/deployments/maptology.ear"
sh "scp -i ${keyfile} android-app/build/outputs/apk/release/*.apk wildfly@srv.nes.uni-due.de:/opt/android/maptology/"
}
} else {
echo "Skipping deployment for non-master branch."
+16 -3
View File
@@ -27,10 +27,13 @@ android {
applicationId "com.maptology.android.app"
minSdkVersion 14
targetSdkVersion 28
versionCode 5
versionName "1.0.1"
versionCode 9
versionName "${version}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resValue "string", "application_long", "Maptology"
resValue "string", "application_short", "Maptology"
}
signingConfigs {
@@ -44,14 +47,21 @@ android {
buildTypes {
release {
useProguard false
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// add signing config if key is provided via system property
if (System.properties['android.keystore.password'] != null) signingConfig signingConfigs.release
}
debug {
applicationIdSuffix ".debug"
versionNameSuffix "-dbg"
resValue "string", "application_long", "Maptology (Debug)"
resValue "string", "application_short", "M (Debug)"
}
}
testOptions {
unitTests {
includeAndroidResources = true
@@ -62,6 +72,9 @@ android {
disable 'RtlSymmetry', 'RelativeOverlap'
// abortOnError false
}
dexOptions {
javaMaxHeapSize "512m"
}
}
+7 -1
View File
@@ -64,11 +64,17 @@
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<receiver android:name=".UpdateReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
<receiver android:name=".NoticeReceiver" android:exported="false">
<intent-filter>
<action android:name="com.maptology.android.app.NOTICE_SYNC"/>
</intent-filter>
</receiver>
<service android:name=".LocationService"/>
<service android:name=".LocationService"/>
<service android:name=".LoggerService"/>
</application>
</manifest>
@@ -0,0 +1,301 @@
package com.maptology.android.app;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.pm.PackageInfoCompat;
import com.maptology.android.app.task.UploadLocationTask;
import com.maptology.android.feign.model.Coordinate;
import com.maptology.android.feign.model.DeviceHandle;
/**
* An abstract base class for the location and logger
* service to share common functions without duplicating
* code.
*
* @author Marcus
*/
public abstract class AbstractService extends Service {
/**
* The channel id of the localization channel.
*/
private static final String CHANNEL_ID = "localization";
/**
* The application.
*/
protected MaptologyApp app;
/**
* The location manager to capture locations.
*/
protected LocationManager locationManager;
/**
* The handler to process timeouts in the ui thread.
*/
protected Handler handler;
@Nullable
@Override
public IBinder onBind(Intent intent) {
// nothing to bind to
return null;
}
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
app = (MaptologyApp)getApplicationContext();
createNotificationChannel(app);
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
/**
* Determines whether the location is sharable.
*
* @return True if sharable, false otherwise.
*/
protected boolean isSharable() {
return app.getRepository().isSharable();
}
/**
* Determines whether the location is analyzable.
*
* @return True if analyzable.
*/
protected boolean isAnalyzable() {
DeviceHandle handle = app.getRepository().deviceHandle.getValue();
boolean hasUser = handle != null && handle.getUser() != null;
return hasUser && app.getRepository().isAnalyzeable();
}
/**
* Returns the app version or -1 if an error occurs.
*
* @return The app version.
*/
protected long getVersion() {
try {
PackageInfo info = this.getPackageManager().getPackageInfo(getPackageName(), 0);
return PackageInfoCompat.getLongVersionCode(info);
} catch (PackageManager.NameNotFoundException e) {
return -1;
}
}
/**
* Determines whether the gps provider can be used.
*
* @return True if gps is available, enabled and we have all permissions.
*/
protected boolean canUseGps() {
boolean gps = app.getRepository().canUseGps();
return gps && canUseProvider(LocationManager.GPS_PROVIDER);
}
/**
* Determines whether a particular location provider can be used.
*
* @param provider The provider.
* @return True if we have all permissions and the provider is available and enabled.
*/
protected boolean canUseProvider(String provider) {
return hasLocationPermissions() && locationManager.getAllProviders().contains(provider);
}
/**
* Determines whether the app has the permissions to capture location.
*
* @return True if the app has permission to capture locations.
*/
protected boolean hasLocationPermissions() {
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
/**
* Updates the coordinate displayed in the user interface.
*
* @param longitude The longitude.
* @param latitude The latitude.
*/
protected void setCoordinate(double longitude, double latitude) {
Coordinate c = new Coordinate();
c.setLatitude(latitude);
c.setLongitude(longitude);
app.getRepository().gpsPosition.setValue(c);
}
/**
* Updates the locations, if an upload task is not running already.
*/
protected void onUploadUpdates() {
// upload the location, if the upload is not yet running
boolean uploading = app.getRepository().uploadingLocations.getValue();
DeviceHandle handle = app.getRepository().deviceHandle.getValue();
updateNotification(R.string.localization_notification_upload);
if (!uploading && handle != null ) {
UploadLocationTask task = new UploadLocationTask(app);
task.execute();
}
}
/**
* Returns the id for the foreground service notification.
*
* @return The notification id.
*/
protected abstract int getNotificationId();
/**
* Updates the foreground service notification with new text.
*
* @param content The content.
*/
protected void updateNotification(int content) {
Notification notification = getNotification(content);
NotificationManager manager = (NotificationManager)app.getSystemService(NOTIFICATION_SERVICE);
manager.notify(getNotificationId(), notification);
}
/**
* Returns the notification that is displayed during upload.
*
* @param content The notification content (res id).
* @return The notification.
*/
protected Notification getNotification(int content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(app, CHANNEL_ID)
.setContentTitle(getText(R.string.localization_notification_title))
.setContentText(getText(content))
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(app, 445, new Intent(app, StartActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
.setSmallIcon(R.drawable.icon_notification_small);
return builder.build();
}
/**
* Creates a notification channel for the app.
*
* @param app The app to retrieve the notification manager.
*/
public static void createNotificationChannel(MaptologyApp app) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = app.getString(R.string.localization_channel_name);
String description = app.getString(R.string.localization_channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = app.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
/**
* Starts the service, if it is not running already.
*
* @param context The context.
*/
public static void runService(Context context) {
if (!isLocalizable(context) || !hasDevice(context)) return;
Intent intent = new Intent();
if (isLoggable(context) && isPowerCordPlugged(context)) {
intent.setClass(context, LoggerService.class);
} else {
intent.setClass(context, LocationService.class);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
context.startService(intent);
} else {
context.startForegroundService(intent);
}
}
/**
* Stops all services unconditionally.
*
* @param context The context.
*/
public static void stopServices(Context context) {
for (Class<?> service : new Class[] { LocationService.class, LoggerService.class }) {
Intent intent = new Intent();
intent.setClass(context, service);
context.stopService(intent);
}
}
/**
* Determines whether the data logging is enabled.
*
* @param context The context.
* @return True if data logging is enabled, false otherwise.
*/
protected static boolean isLoggable(Context context) {
MaptologyApp app = (MaptologyApp)context.getApplicationContext();
return app.getRepository().isLoggable();
}
/**
* Determines whether the device localization is enabled.
*
* @param context The context.
* @return True if localization is enabled, false otherwise.
*/
protected static boolean isLocalizable(Context context) {
MaptologyApp app = (MaptologyApp)context.getApplicationContext();
return app.getRepository().isLocalizable();
}
/**
* Determines whether there is a device handle.
*
* @return True if there is a device handle, false otherwise.
*/
protected static boolean hasDevice(Context context) {
MaptologyApp app = (MaptologyApp)context.getApplicationContext();
return (app.getRepository().deviceHandle.getValue() != null);
}
/**
* Determines whether the power cord is plugged based on the
* information contained in the battery intent.
*
* @param context The context to fetch the intent.
* @return True if the power cord is plugged, false otherwise.
*/
protected static boolean isPowerCordPlugged(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int p = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return p == BatteryManager.BATTERY_PLUGGED_AC ||
p == BatteryManager.BATTERY_PLUGGED_USB ||
p == BatteryManager.BATTERY_PLUGGED_WIRELESS;
}
}
@@ -28,7 +28,7 @@ public class BootReceiver extends BroadcastReceiver {
MaptologyApp app = (MaptologyApp)context.getApplicationContext();
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
NoticeReceiver.schedulePeriodicSync(app);
LocationService.runService(app);
AbstractService.runService(app);
}
}
}
@@ -5,8 +5,8 @@ import java.util.ArrayList;
import java.util.List;
import com.maptology.android.app.location.LocationState;
import com.maptology.android.app.model.Network;
import com.maptology.android.app.model.Position;
import com.maptology.android.app.location.LocationNetwork;
import com.maptology.android.app.location.LocationPosition;
import com.maptology.android.app.repository.IValueListener;
import com.maptology.android.app.repository.Value;
import com.maptology.android.app.task.UploadLocationTask;
@@ -15,13 +15,8 @@ import com.maptology.android.feign.model.DeviceHandle;
import com.maptology.android.feign.model.ReleasedLocation;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -35,12 +30,10 @@ import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.pm.PackageInfoCompat;
import android.util.Log;
@@ -50,7 +43,7 @@ import android.util.Log;
*
* @author Marcus
*/
public class LocationService extends Service {
public class LocationService extends AbstractService {
/**
* The code for the alarm.
@@ -66,7 +59,7 @@ public class LocationService extends Service {
/**
* The minimum time between two localization attempts.
*/
private static final long LOCALIZATION_TIMEOUT = 60000;
private static final long LOCALIZATION_TIMEOUT = 55000;
/**
* The time to wait for wifi scans.
@@ -124,25 +117,11 @@ public class LocationService extends Service {
*/
private static final String TAG = "LocationService";
/**
* The channel id of the localization channel.
*/
private static final String CHANNEL_ID = "localization";
/**
* The notification id of the foreground service indicator.
*/
private static final int NOTIFICATION_ID = 5544;
/**
* The application.
*/
private MaptologyApp app;
/**
* The location manager to capture locations.
*/
private LocationManager locationManager;
/**
* The wifi manager to perform wifi scans and request wifi locks.
*/
@@ -152,11 +131,6 @@ public class LocationService extends Service {
*/
private PowerManager powerManager;
/**
* The handler to process timeouts in the ui thread.
*/
private Handler handler;
/**
* The current state of the service.
*/
@@ -165,7 +139,7 @@ public class LocationService extends Service {
/**
* The current list of networks.
*/
private List<Network> currentNetworks = null;
private List<LocationNetwork> currentNetworks = null;
/**
* The time of the last localization attempt of the service.
@@ -196,6 +170,17 @@ public class LocationService extends Service {
}
};
/**
* A broadcast receiver to receive timer ticks in the background.
*/
private BroadcastReceiver timeTickReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Tick received.");
onStartCommand(null, 0, 0);
}
};
/**
* A location listener that simply forwards its locations to
* the service.
@@ -234,7 +219,7 @@ public class LocationService extends Service {
};
/**
* A listern that deactivates the service when the upload completes.
* A listener that deactivates the service when the upload completes.
*/
private IValueListener<Boolean> uploadListener = new IValueListener<Boolean>() {
@Override
@@ -259,30 +244,19 @@ public class LocationService extends Service {
*/
private Runnable timeoutListener = null;
@Override
public IBinder onBind(Intent intent) {
// do not support binding
return null;
}
@Override
@SuppressLint("InlinedApi")
public void onCreate() {
Log.d(TAG, "Creating location service.");
super.onCreate();
handler = new Handler();
app = (MaptologyApp) getApplicationContext();
createNotificationChannel(app);
startForeground(NOTIFICATION_ID, getNotification(R.string.localization_notification_idle));
app.getRepository().uploadingLocations.addValueListener(uploadListener);
locationManager = (LocationManager) app.getSystemService(LOCATION_SERVICE);
wifiManager = (WifiManager) app.getSystemService(WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, TAG);
powerManager = (PowerManager) app.getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1)
registerReceiver(idleModeReceiver, new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
@Override
@@ -304,6 +278,7 @@ public class LocationService extends Service {
app.getRepository().uploadingLocations.removeValueListener(uploadListener);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1)
unregisterReceiver(idleModeReceiver);
unregisterReceiver(timeTickReceiver);
Log.d(TAG, "Releasing wake lock.");
if (wakeLock.isHeld()) wakeLock.release();
stopForeground(true);
@@ -312,32 +287,36 @@ public class LocationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!app.getRepository().isLocalizable()) {
if (!isLocalizable(this)) {
Log.d(TAG, "Stopping since localization is disabled.");
cancelExecution(this);
stopSelf();
return START_NOT_STICKY;
} else if (!hasDeviceHandle()) {
} else if (!hasDevice(this)) {
Log.d(TAG, "Stopping since device is not available.");
cancelExecution(this);
stopSelf();
return START_NOT_STICKY;
} else if (isLoggable(this) && isPowerCordPlugged(this)) {
Log.d(TAG, "Switching to logger service.");
cancelExecution(this);
stopSelf();
runService(app);
return START_NOT_STICKY;
}
if (!isPeriodicExecution(intent)) {
Log.d(TAG, "Scheduling periodic execution.");
scheduleExecution(this, localizationTime);
}
// ensure that localization is only running, if it is not
// running already or has been run only seconds ago
// start localization, if we are not running one already
long now = SystemClock.elapsedRealtime();
if (currentState == LocationState.IDLE) {
if (isDeviceIdle()) {
onDeviceIdle();
} else if (now - localizationTime > LOCALIZATION_TIMEOUT - 1000) {
if (now - localizationTime > LOCALIZATION_TIMEOUT / 2) {
Log.d(TAG, "Starting localization state machine.");
changeState();
} else {
Log.d(TAG, "Ignoring start request while timeout has not expired.");
if (isDeviceIdle()) {
onDeviceIdle();
}
Log.d(TAG, "Scheduling periodic execution.");
scheduleExecution(this, localizationTime);
}
} else {
Log.d(TAG, "Ignoring start request while service is " + currentState + ".");
@@ -345,16 +324,6 @@ public class LocationService extends Service {
return START_STICKY;
}
/**
* Determines whether there is a device handle.
*
* @return True if there is a device handle, false otherwise.
*/
private boolean hasDeviceHandle() {
return (app.getRepository().deviceHandle.getValue() != null);
}
/**
* Triggers a state change to the next logical state of the state machine.
*/
@@ -437,7 +406,7 @@ public class LocationService extends Service {
* already.
*
* @param success True to indicate success, false to indicate
* an unrecovable failure.
* an unrecoverable failure.
*/
private void resetState(boolean success) {
currentState = LocationState.IDLE;
@@ -552,18 +521,14 @@ public class LocationService extends Service {
changeState();
} else {
Log.d(TAG, "Starting cache lookup.");
Position p = app.getLocationStore().findPosition(currentNetworks, NETWORK_MINIMUM, MAXIMUM_WIFI_DEVIATION);
LocationPosition p = app.getLocationStore().findPosition(currentNetworks, NETWORK_MINIMUM, MAXIMUM_WIFI_DEVIATION);
if (p != null) {
long now = System.currentTimeMillis();
p.setUsageTime(now);
if (isFresh(p)) {
Log.d(TAG, "Using cached location.");
// update the user interface
// update the user interface
Coordinate c = new Coordinate();
c.setLatitude(p.getLatitude());
c.setLongitude(p.getLongitude());
app.getRepository().gpsPosition.setValue(c);
setCoordinate(p.getLongitude(), p.getLatitude());
// create a release
ReleasedLocation update = createLocation();
update.setAvailability(ReleasedLocation.AvailabilityEnum.CACHED);
@@ -592,19 +557,6 @@ public class LocationService extends Service {
}
}
/**
* Updates the locations, if an upload task is not running already.
*/
private void onUploadUpdates() {
// upload the location, if the upload is not yet running
boolean uploading = app.getRepository().uploadingLocations.getValue();
DeviceHandle handle = app.getRepository().deviceHandle.getValue();
updateNotification(R.string.localization_notification_upload);
if (!uploading && handle != null ) {
UploadLocationTask task = new UploadLocationTask(app);
task.execute();
}
}
/**
* Creates an idle position update, unless we already created it.
@@ -646,7 +598,7 @@ public class LocationService extends Service {
* @param p The position to check.
* @return True if the position is young enough, false if it is too old.
*/
private boolean isFresh(Position p) {
private boolean isFresh(LocationPosition p) {
return p.getUsageTime() - p.getCreationTime() <= MAXIMUM_CACHE_DURATION;
}
@@ -692,10 +644,10 @@ public class LocationService extends Service {
* @param results The results.
*/
private void setScan(List<ScanResult> results) {
List<Network> networks = new ArrayList<>();
List<LocationNetwork> networks = new ArrayList<>();
for (ScanResult r: results) {
if (r.level >= MINIMUM_WIFI_RSSI) {
Network n = new Network();
LocationNetwork n = new LocationNetwork();
n.setBssid(r.BSSID);
n.setRssi(r.level);
networks.add(n);
@@ -716,10 +668,7 @@ public class LocationService extends Service {
if (currentState == LocationState.GPS) cleanupGps();
if (currentState == LocationState.NET) cleanupNet();
// update the user interface
Coordinate c = new Coordinate();
c.setLatitude(location.getLatitude());
c.setLongitude(location.getLongitude());
app.getRepository().gpsPosition.setValue(c);
setCoordinate(location.getLongitude(), location.getLatitude());
// create final location
ReleasedLocation update = createLocation();
update.setCoordinate(new Coordinate());
@@ -735,7 +684,7 @@ public class LocationService extends Service {
onStoreUpdate(update);
// store location in cache
if (hasMinimumNetworks()) {
Position p = new Position();
LocationPosition p = new LocationPosition();
p.setLatitude(location.getLatitude());
p.setLongitude(location.getLongitude());
p.setCreationTime(System.currentTimeMillis());
@@ -776,40 +725,6 @@ public class LocationService extends Service {
return location;
}
/**
* Determines whether the location is sharable.
*
* @return True if sharable, false otherwise.
*/
private boolean isSharable() {
return app.getRepository().isSharable();
}
/**
* Determines whether the location is analyzable.
*
* @return True if analyzable.
*/
private boolean isAnalyzable() {
DeviceHandle handle = app.getRepository().deviceHandle.getValue();
boolean hasUser = handle != null && handle.getUser() != null;
return hasUser && app.getRepository().isAnalyzeable();
}
/**
* Returns the app version or -1 if an error occurs.
*
* @return The app version.
*/
private long getVersion() {
try {
PackageInfo info = this.getPackageManager().getPackageInfo(getPackageName(), 0);
return PackageInfoCompat.getLongVersionCode(info);
} catch (PackageManager.NameNotFoundException e) {
return -1;
}
}
/**
* Determines whether the current networks exceed the minimum network threshold.
*
@@ -844,17 +759,6 @@ public class LocationService extends Service {
}
}
/**
* Determines whether the gps provider can be used.
*
* @return True if gps is available, enabled and we have all permissions.
*/
private boolean canUseGps() {
boolean gps = app.getRepository().canUseGps();
if (!gps) Log.d(TAG, "Gps is manually disabled.");
return gps && canUseProvider(LocationManager.GPS_PROVIDER);
}
/**
* Determines whether the network provider can be used.
*
@@ -872,19 +776,8 @@ public class LocationService extends Service {
* @param provider The provider.
* @return True if we have all permissions and the provider is available and enabled.
*/
private boolean canUseProvider(String provider) {
return hasLocationPermissions() && locationManager.getAllProviders().contains(provider) &&
locationManager.isProviderEnabled(provider);
}
/**
* Determines whether the app has the permissions to capture location.
*
* @return True if the app has permission to capture locations.
*/
private boolean hasLocationPermissions() {
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
protected boolean canUseProvider(String provider) {
return super.canUseProvider(provider) && locationManager.isProviderEnabled(provider);
}
/**
@@ -914,43 +807,23 @@ public class LocationService extends Service {
}
/**
* Starts the service, if it is not running already.
*
* @param context The context.
*/
public static void runService(Context context) {
Intent intent = new Intent();
intent.setClass(context, LocationService.class);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
context.startService(intent);
} else {
context.startForegroundService(intent);
}
}
/**
* Stops the service unconditionally.
*
* @param context The context.
*/
public static void stopService(Context context) {
Intent intent = new Intent();
intent.setClass(context, LocationService.class);
context.stopService(intent);
}
/**
* Schedules the service for periodic execution.
* Schedules the service for the next execution.
*
* @param context The context used to schedule this.
*/
private static void scheduleExecution(Context context, long lastTime) {
PendingIntent pending = createIntent(context);
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long now = SystemClock.elapsedRealtime();
long next = Math.max(0, (lastTime + LOCALIZATION_TIMEOUT) - now);
long next = Math.max(5000, (lastTime + LOCALIZATION_TIMEOUT) - now);
Log.d(TAG, "Updating alarm to execute in " + next + " ms.");
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + next, LOCALIZATION_TIMEOUT, pending);
// this is too imprecise on Android 9
//manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + next, LOCALIZATION_TIMEOUT, pending);
PendingIntent pending = createIntent(context);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + next, pending);
} else {
manager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + next, LOCALIZATION_TIMEOUT / 2, pending);
}
}
/**
@@ -980,66 +853,8 @@ public class LocationService extends Service {
}
}
/**
* Determines whether the intent is a periodic execution.
*
* @param intent The intent.
* @return True if the intent is a periodic execution by the alarm manager.
*/
private static boolean isPeriodicExecution(Intent intent) {
try {
if (intent == null) return false;
return intent.getBooleanExtra(EXTRA_ALARM, false);
} catch (Exception e) {
Log.d(TAG, "Invalid intent, cannot extract alarm although it is defined.");
return false;
}
@Override
protected int getNotificationId() {
return NOTIFICATION_ID;
}
/**
* Updates the foreground service notification with new text.
*
* @param content The content.
*/
private void updateNotification(int content) {
Notification notification = getNotification(content);
NotificationManager manager = (NotificationManager)app.getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, notification);
}
/**
* Returns the notification that is displayed during upload.
*
* @param content The notification content (res id).
* @return The notification.
*/
private Notification getNotification(int content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(app, CHANNEL_ID)
.setContentTitle(getText(R.string.localization_notification_title))
.setContentText(getText(content))
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(app, 445, new Intent(app, StartActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
.setSmallIcon(R.drawable.icon_notification_small);
return builder.build();
}
/**
* Creates a notification channel for the app.
*
* @param app The app to retrieve the notification manager.
*/
public static void createNotificationChannel(MaptologyApp app) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = app.getString(R.string.localization_channel_name);
String description = app.getString(R.string.localization_channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = app.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
@@ -0,0 +1,685 @@
package com.maptology.android.app;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import com.maptology.android.app.repository.IValueListener;
import com.maptology.android.app.repository.Value;
import com.maptology.android.app.util.DeltaCodec;
import com.maptology.android.feign.model.Coordinate;
import com.maptology.android.feign.model.ReleasedLocation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A service for data logger configurations.
*
* @author Marcus
*/
public class LoggerService extends AbstractService {
/**
* The key for the detailed gps data.
*/
private String METADATA_GPS = "gps";
/**
* The key for the acceleration sensor.
*/
private String METADATA_ACCELEROMETER = "accel";
/**
* The key for the gyroscope.
*/
private String METADATA_GYROSCOPE = "gyro";
/**
* The key for the magnetometer.
*/
private String METADATA_MAGNETOMETER = "magnet";
/**
* The notification id of the foreground service indicator.
*/
private static final int NOTIFICATION_ID = 5545;
/**
* The log tag for the service.
*/
private static final String TAG = "LoggerService";
/**
* The tag for the cpu wakelock.
*/
private static final String WAKELOCK_TAG = "maptology:logger";
/**
* The approximate delay between two sensor values
* in milliseconds (10/sec).
*/
private static int SAMPLING_DELAY_SENSOR = 100;
/**
* The approximate delay between two gps values
* in milliseconds (1/sec).
*/
private static int SAMPLING_DELAY_GPS = 1000;
/**
* The number of digits kept for sensors.
*/
private static int PRECISION_SENSOR = 7;
/**
* The amount of time between the creation of a
* position update in milliseconds.
*/
private static int UPDATE_DELAY = 60000;
/**
* A scale factor to ensure that there are enough data bins,
* even if the update generation process is not executed at
* exactly the right frequency. 2 means that we provide twice
* as many data bins as we would require if the timing is perfect.
*/
private int UPDATE_FACTOR = 2;
/**
* A gps listener that memorizes a number of locations.
*/
private GpsListener gpsListener;
/**
* A listener that is attached to the acceleration sensor.
*/
private SensorListener accelerometerListener = new SensorListener(3, PRECISION_SENSOR, UPDATE_DELAY * UPDATE_FACTOR / SAMPLING_DELAY_SENSOR);
/**
* A listener that is attached to the gyroscope sensor.
*/
private SensorListener gyroscopeListener = new SensorListener(3, PRECISION_SENSOR, UPDATE_DELAY * UPDATE_FACTOR / SAMPLING_DELAY_SENSOR);
/**
* A listener that is attached to the magnetometer sensor.
*/
private SensorListener magnetometerListener = new SensorListener(3, PRECISION_SENSOR, UPDATE_DELAY * UPDATE_FACTOR / SAMPLING_DELAY_SENSOR);
/**
* The cpu wake lock.
*/
private PowerManager.WakeLock wakeLock;
/**
* The sensor manager.
*/
private SensorManager sensorManager;
/**
* A listener that deactivates the service when the upload completes.
*/
private IValueListener<Boolean> uploadListener = new IValueListener<Boolean>() {
@Override
public void onValueChanged(Value<Boolean> source, Boolean oldValue, Boolean newValue) {
if (!newValue) updateNotification(R.string.localization_notification_logger);
else updateNotification(R.string.localization_notification_upload);
}
};
/**
* The listener that will capture the data.
*/
private Runnable captureListener = new Runnable() {
@Override
public void run() {
onCapture();
}
};
@Override
public void onCreate() {
super.onCreate();
gpsListener = new GpsListener(LocationManager.GPS_PROVIDER, UPDATE_DELAY * UPDATE_FACTOR / SAMPLING_DELAY_GPS);
startForeground(NOTIFICATION_ID, getNotification(R.string.localization_notification_logger));
app.getRepository().uploadingLocations.addValueListener(uploadListener, true);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
wakeLock.acquire();
prepareCapture();
}
/**
* Flushes all listeners and registers the listeners that are not registered
* already and can be registered due to sensor availability and schedules the
* next capturing iteration.
*/
public void prepareCapture() {
flushListeners();
registerSensorListeners();
registerGpsListener();
Log.d(TAG, "Scheduling capture operation.");
handler.postDelayed(captureListener, UPDATE_DELAY);
}
/**
* Called when the timeout expires and an update must be created,
* stored and possibly uploaded.
*/
public void onCapture() {
Log.d(TAG, "Performing capture operation.");
try {
long start = System.currentTimeMillis();
ReleasedLocation location = gpsListener.getLocation();
Map<String, String> metadata = new HashMap<>();
if (magnetometerListener.isRegistered()) metadata.put(METADATA_MAGNETOMETER, magnetometerListener.encode());
if (accelerometerListener.isRegistered()) metadata.put(METADATA_ACCELEROMETER, accelerometerListener.encode());
if (gyroscopeListener.isRegistered()) metadata.put(METADATA_GYROSCOPE, gyroscopeListener.encode());
if (gpsListener.isRegistered()) metadata.put(METADATA_GPS, gpsListener.encode());
int length = 0;
for (String s: metadata.keySet()) {
Log.d(TAG, "Metadata " + s + " size is " + metadata.get(s).length() + " bytes.");
length += metadata.get(s).length();
}
Log.d(TAG, "Total sensor data size is " + length + " bytes.");
location.setMetadata(metadata);
app.getLocationStore().addUpdate(location);
app.getRepository().lastUpdate.setValue(location);
Log.d(TAG, "Total duration for packaging is " + (System.currentTimeMillis() - start) + " ms.");
onUploadUpdates();
} finally {
if (isLocalizable(this) && isLoggable(this) && isPowerCordPlugged(this)) {
Log.d(TAG, "Preparing next capture operation.");
prepareCapture();
} else {
Log.d(TAG, "Switching to localization service.");
stopSelf();
runService(app);
}
}
}
@Override
public void onDestroy() {
app.getRepository().uploadingLocations.removeValueListener(uploadListener);
handler.removeCallbacks(captureListener);
unregisterGpsListener();
unregisterSensorListeners();
if (wakeLock.isHeld()) wakeLock.release();
stopForeground(true);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (! isLocalizable(this)) {
Log.d(TAG, "Stopping since localization is disabled.");
stopSelf();
return START_NOT_STICKY;
} else if (!hasDevice(this)) {
Log.d(TAG, "Stopping since device is not available.");
stopSelf();
return START_NOT_STICKY;
}
return START_STICKY;
}
/**
* Executes a flush operation on all listeners.
*/
private void flushListeners() {
gpsListener.flush();
accelerometerListener.flush();
magnetometerListener.flush();
gyroscopeListener.flush();
}
/**
* Registers the gps listener, if that is possible and did not happen already.
*/
private void registerGpsListener() {
if (!gpsListener.isRegistered() && canUseGps()) {
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, SAMPLING_DELAY_GPS, 0, gpsListener);
gpsListener.setRegistered(true);
} catch (SecurityException e) {
Log.e(TAG, "Failed to register gps listener.", e);
}
}
}
/**
* Unregisters the gps listener, if it was registered successfully already.
*/
private void unregisterGpsListener() {
if (gpsListener.isRegistered()) {
locationManager.removeUpdates(gpsListener);
gpsListener.setRegistered(false);
}
}
/**
* Registers all sensor listeners for the sensors that are available.
*/
private void registerSensorListeners() {
registerSensorListener(Sensor.TYPE_ACCELEROMETER, accelerometerListener);
registerSensorListener(Sensor.TYPE_GYROSCOPE, gyroscopeListener);
registerSensorListener(Sensor.TYPE_MAGNETIC_FIELD, magnetometerListener);
}
/**
* Registers the sensor listener for the specified sensor type, if the sensor
* is available.
*
* @param sensorType The sensor type.
* @param listener The listener.
*/
private void registerSensorListener(int sensorType, SensorListener listener) {
if (listener.isRegistered()) return;
Sensor sensor = sensorManager.getDefaultSensor(sensorType);
if (sensor != null) {
int period = SAMPLING_DELAY_SENSOR * 1000;
if (Build.VERSION.SDK_INT > 21) {
period = Math.max(sensor.getMinDelay(), Math.min(sensor.getMaxDelay(), period));
}
boolean registered = sensorManager.registerListener(listener, sensor, period);
listener.setRegistered(registered);
}
}
/**
* Unregisters all sensor listeners that are registered.
*/
private void unregisterSensorListeners() {
unregisterSensorListener(accelerometerListener);
unregisterSensorListener(gyroscopeListener);
unregisterSensorListener(magnetometerListener);
}
/**
* Unregisters a particular sensor listener, if it was registered already.
*
* @param listener The listener to unregister.
*/
private void unregisterSensorListener(SensorListener listener) {
if (listener.isRegistered()) {
sensorManager.unregisterListener(listener);
listener.setRegistered(false);
}
}
/**
* Returns the id of the service's foreground notification.
*
* @return The notification id.
*/
@Override
protected int getNotificationId() {
return NOTIFICATION_ID;
}
/**
* A location listener that memorizes it's first location and
* enables the retrieval of a string-encoded trace.
*
* @author Marcus
*/
private class GpsListener implements LocationListener {
/**
* The flag for a valid accuracy.
*/
private static final int FLAG_ACCURACY = 1;
/**
* The flag for a valid altitude.
*/
private static final int FLAG_ALTITUDE = 2;
/**
* The flag for a valid bearing.
*/
private static final int FLAG_BEARING = 8;
/**
* The flag for a valid speed.
*/
private static final int FLAG_SPEED = 16;
/**
* The flag for a valid speed accuracy.
*/
private static final int FLAG_SPEED_ACCURACY = 32;
/**
* The flag for a valid vertical accuracy.
*/
private static final int FLAG_VERTICAL_ACCURACY = 64;
/**
* The flag for a valid bearing accuracy.
*/
private static final int FLAG_BEARING_ACCURACY = 128;
/**
* The delta codec.
*/
private DeltaCodec codec;
/**
* The unused data items.
*/
private List<long[]> cache;
/**
* The used data items.
*/
private List<long[]> data;
/**
* The first location since the flush.
*/
private ReleasedLocation location;
/**
* The location provider name.
*/
private String provider;
/**
* A flag to indicate whether the listener is
* registered.
*/
private boolean registered;
/**
* Creates a position listener with
* the specified limit on positions.
*
* @param limit The limit.
* @param provider The location provider name.
*/
GpsListener(String provider, int limit) {
int values = Math.max(1, limit);
this.provider = provider;
cache = new ArrayList<>(values);
data = new ArrayList<>(values);
codec = new DeltaCodec(11);
for (int i = 0; i < values; i++) {
// time, flags, 9 values
cache.add(new long[11]);
}
flush();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
@Override
public void onLocationChanged(Location location) {
if (this.location.getAvailability() != ReleasedLocation.AvailabilityEnum.FRESH) {
this.location.setAvailability(ReleasedLocation.AvailabilityEnum.FRESH);
this.location.setTimestamp(location.getTime());
this.location.setCoordinate(new Coordinate());
this.location.getCoordinate().setLatitude(location.getLatitude());
this.location.getCoordinate().setLongitude(location.getLongitude());
setCoordinate(location.getLongitude(), location.getLatitude());
if (location.hasAccuracy()) this.location.setAccuracy((double)location.getAccuracy());
if (location.hasAltitude()) this.location.setAltitude(location.getAltitude());
if (location.hasBearing()) this.location.setBearing((double)location.getBearing());
if (location.hasSpeed()) this.location.setSpeed((double)location.getSpeed());
}
long[] next = remove();
next[0] = location.getTime();
next[1] = getFlags(location);
next[2] = Math.round(location.getLongitude() * 10e6);
next[3] = Math.round(location.getLatitude() * 10e6);
next[4] = Math.round(location.getAccuracy() * 10e3);
next[5] = Math.round(location.getAltitude() * 10e3);
next[6] = Math.round(location.getBearing() * 10e3);
next[7] = Math.round(location.getSpeed() * 10e3);
if (Build.VERSION.SDK_INT >= 26) {
next[8] = Math.round(location.getSpeedAccuracyMetersPerSecond() * 10e3);
next[9] = Math.round(location.getVerticalAccuracyMeters() * 10e3);
next[10] = Math.round(location.getBearingAccuracyDegrees() * 10e3);
}
data.add(next);
}
/**
* Encodes the hasXXX values into a flag vector.
*
* @param location The location.
* @return The long representing the flags.
*/
private long getFlags(Location location) {
long flags = 0;
if (location.hasAccuracy()) flags += FLAG_ACCURACY;
if (location.hasAltitude()) flags += FLAG_ALTITUDE;
if (location.hasBearing()) flags += FLAG_BEARING;
if (location.hasSpeed()) flags += FLAG_SPEED;
if (Build.VERSION.SDK_INT >= 26) {
if (location.hasSpeedAccuracy()) flags += FLAG_SPEED_ACCURACY;
if (location.hasVerticalAccuracy()) flags += FLAG_VERTICAL_ACCURACY;
if (location.hasBearingAccuracy()) flags += FLAG_BEARING_ACCURACY;
}
return flags;
}
/**
* Returns the next entry to encode sensor data.
*
* @return The next entry removed either from cache
* or from the data segment.
*/
private long[] remove() {
if (cache.size() > 0) {
return cache.remove(cache.size() - 1);
} else {
return data.remove(0);
}
}
/**
* Returns the last location since the
* flush.
*
* @return The location.
*/
public ReleasedLocation getLocation() {
return location;
}
/**
* Encodes the current sensor data as a string.
*
* @return The sensor data.
*/
public String encode() {
return codec.encode(data);
}
/**
* Flushes the sensor data buffer.
*/
public void flush() {
cache.addAll(data);
data.clear();
location = new ReleasedLocation();
location.setTimestamp(System.currentTimeMillis());
location.setAvailability(ReleasedLocation.AvailabilityEnum.UNABLE);
location.setSharable(isSharable());
location.setAnalyzable(isAnalyzable());
location.setVersion((int)getVersion());
location.setProvider(provider);
}
/**
* Determines whether the listener is registered.
*
* @return True if registered, false otherwise.
*/
public boolean isRegistered() {
return registered;
}
/**
* Sets the flag to indicate whether the listener is registered.
*
* @param registered True if registered, false otherwise.
*/
public void setRegistered(boolean registered) {
this.registered = registered;
}
};
/**
* A listener for sensor data that performs delta encoding.
*
* @author Marcus
*/
private static class SensorListener implements SensorEventListener {
/**
* The delta codec.
*/
private DeltaCodec codec;
/**
* The precision.
*/
private double multiplier;
/**
* The unused data items.
*/
private List<long[]> cache;
/**
* The used data items.
*/
private List<long[]> data;
/**
* A flag to indicate whether the listener is registered.
*/
private boolean registered;
/**
* Creates a new sensor listener that will buffer
* at most limit values
*
* @param length The length of the senor data generated
* by the sensor. For a 3D sensor, this would be 3.
* @param precision The precision of the sensor data in
* decimal digits. For encoding, the data will be multiplied
* with 10^precision. Thus, for decoding, the data must
* be divided by the same precision.
* @param limit The maximum number of elements to keep in
* the buffer.
*/
public SensorListener(int length, int precision, int limit) {
multiplier = Math.pow(10, precision);
// timestamp, accuracy, values
int values = Math.max(1, limit);
cache = new ArrayList<>(values);
data = new ArrayList<>(values);
codec = new DeltaCodec(2 + length);
for (int i = 0; i < values; i++) {
cache.add(new long[2 + length]);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// nothing to be done
}
@Override
public void onSensorChanged(SensorEvent event) {
long prev = 0;
if (data.size() > 0) {
prev = data.get(data.size() - 1)[0];
long diff = event.timestamp / 1000 - prev;
if (diff / 1000 < SAMPLING_DELAY_SENSOR) return;
}
long[] next = remove();
next[0] = event.timestamp / 1000;
next[1] = event.accuracy;
for (int i = 0, s = event.values.length; i < s; i++) {
next[2 + i] = Math.round(event.values[i] * multiplier);
}
data.add(next);
}
/**
* Returns the next entry to encode sensor data.
*
* @return The next entry removed either from cache
* or from the data segment.
*/
private long[] remove() {
if (cache.size() > 0) {
return cache.remove(cache.size() - 1);
} else {
return data.remove(0);
}
}
/**
* Encodes the current sensor data.
*
* @return The sensor data.
*/
public String encode() {
Log.d(TAG, "Data size is: " + data.size());
return codec.encode(data);
}
/**
* Flushes the sensor data buffer.
*/
public void flush() {
cache.addAll(data);
data.clear();
}
/**
* Determines whether the listener is registered.
*
* @return True if registered, false otherwise.
*/
public boolean isRegistered() {
return registered;
}
/**
* Sets the flag to indicate whether the listener is registered.
*
* @param registered True if registered, false otherwise.
*/
public void setRegistered(boolean registered) {
this.registered = registered;
}
}
}
@@ -126,7 +126,7 @@ public class MainActivity extends AppCompatActivity implements
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MaptologyApp) getApplicationContext();
LocationService.runService(this);
AbstractService.runService(this);
setTitle(R.string.application_short);
if (TabletUtil.isLandscapeTablet(this)) {
setContentView(R.layout.activity_main_tablet);
@@ -262,8 +262,8 @@ public class MainActivity extends AppCompatActivity implements
* Method to request location permission for the app.
*/
private void checkPermissions() {
boolean permissionGranted = PermissionChecker.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean permissionGranted = PermissionChecker.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED &&
PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PermissionChecker.PERMISSION_GRANTED;
if (!permissionGranted) {
Log.d(TAG, "Requesting permissions.");
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, CODE_REQUEST_PERMISSIONS);
@@ -79,10 +79,13 @@ public class MaptologyApp extends Application {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (Repository.KEY_PRIVACY_LOCALIZE.equals(key)) {
if (sharedPreferences.getBoolean(key, false)) {
LocationService.runService(MaptologyApp.this);
AbstractService.runService(MaptologyApp.this);
} else {
LocationService.stopService(MaptologyApp.this);
AbstractService.stopServices(MaptologyApp.this);
}
} else if (Repository.KEY_PRIVACY_LOGGABLE.equals(key)) {
AbstractService.stopServices(MaptologyApp.this);
AbstractService.runService(MaptologyApp.this);
}
}
};
@@ -0,0 +1,35 @@
package com.maptology.android.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* A broadcast receiver that receives messages on package replacements.
*
* @author Marcus
*/
public class UpdateReceiver extends BroadcastReceiver {
/**
* The log tag for this class.
*/
private static final String TAG = "UpdateReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// should not happen but nobody likes crashing apps in background
if (intent == null || context == null) return;
Log.d(TAG, "Received an intent with action " + intent.getAction() + ".");
if (context.getApplicationContext() instanceof MaptologyApp) {
if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) {
Log.d(TAG, "Restarting services due to my package replacement.");
NoticeReceiver.schedulePeriodicSync((MaptologyApp)context.getApplicationContext());
AbstractService.runService(context);
}
}
}
}
@@ -184,7 +184,7 @@ public class DetailViewHolder extends RecyclerView.ViewHolder {
setText(positionText, null, positionLine);
if (share.getExpirationTime() < System.currentTimeMillis()) {
statusImage.setImageResource(R.drawable.ic_alarm_off_black_48dp);
} else if (share.getPaused()) {
} else if (share.isPaused()) {
statusImage.setImageResource(R.drawable.ic_pause_black_48dp);
} else {
statusImage.setImageResource(R.drawable.ic_share_black_48dp);
@@ -41,6 +41,7 @@ public abstract class AbstractLoginFragment extends AbstractFragment {
private int title;
private int explanation;
private int login;
private boolean passwordVisible = false;
/**
* The listener that listens to changes announced by the async task.
@@ -86,7 +87,6 @@ public abstract class AbstractLoginFragment extends AbstractFragment {
public void onClick(View v) {
String username = usernameText.getText().toString();
String password = passwordText.getText().toString();
username = analyzeInput(username);
password = analyzeInput(password);
if (username == null || password == null) {
@@ -101,17 +101,9 @@ public abstract class AbstractLoginFragment extends AbstractFragment {
});
passwordButton = (ImageButton) view.findViewById(R.id.button_password);
passwordButton.setOnClickListener(new View.OnClickListener() {
private boolean visible = false;
@Override
public void onClick(View v) {
visible = !visible;
if (visible) {
passwordButton.setImageResource(R.drawable.ic_visibility_off_black_24dp);
passwordText.setTransformationMethod(null);
} else {
passwordButton.setImageResource(R.drawable.ic_visibility_black_24dp);
passwordText.setTransformationMethod(new PasswordTransformationMethod());
}
setPasswordVisible(!passwordVisible);
}
});
noLoginButton.setOnClickListener(new View.OnClickListener() {
@@ -175,6 +167,17 @@ public abstract class AbstractLoginFragment extends AbstractFragment {
}
}
private void setPasswordVisible(boolean visible) {
if (visible) {
passwordButton.setImageResource(R.drawable.ic_visibility_off_black_24dp);
passwordText.setTransformationMethod(null);
} else {
passwordButton.setImageResource(R.drawable.ic_visibility_black_24dp);
passwordText.setTransformationMethod(new PasswordTransformationMethod());
}
this.passwordVisible = visible;
}
private void setEnabled(boolean enabled) {
loginButton.setEnabled(enabled);
noLoginButton.setEnabled(enabled);
@@ -182,6 +185,7 @@ public abstract class AbstractLoginFragment extends AbstractFragment {
usernameText.setEnabled(enabled);
passwordText.setEnabled(enabled);
progressBar.setVisibility(enabled?View.GONE:View.VISIBLE);
if (!enabled) setPasswordVisible(false);
}
private String analyzeInput(String input) {
@@ -9,6 +9,7 @@ import com.maptology.android.app.MaptologyApp;
import com.maptology.android.app.R;
import com.maptology.android.app.repository.Repository;
import com.maptology.android.feign.model.DeviceHandle;
import com.maptology.android.feign.model.User;
import android.annotation.TargetApi;
import android.app.AlertDialog;
@@ -50,6 +51,16 @@ public class SettingsFragment extends PreferenceFragmentCompat {
void showTerms();
}
/**
* The name of the scientist role that enables the data logger.
*/
private static final String ROLE_SCIENTIST = "scientist";
/**
* The name of the admin role that enables the data logger.
*/
private static final String ROLE_ADMIN = "admin";
/**
* The number of times a user must click the version button to switch
* between developer mode and non-developer mode.
@@ -151,6 +162,9 @@ public class SettingsFragment extends PreferenceFragmentCompat {
bindClear();
bindTerms();
bindLicenses();
if (!isLoggerAvailable()) {
disableLogger();
}
return v;
}
@@ -165,6 +179,25 @@ public class SettingsFragment extends PreferenceFragmentCompat {
}
}
/**
* Determines whether the logger switch is available.
*
* @return True if available, false otherwise.
*/
private boolean isLoggerAvailable() {
User user = getRepository().user.getValue();
if (user == null || user.getRoles() == null) return false;
else return user.getRoles().contains(ROLE_ADMIN) || user.getRoles().contains(ROLE_SCIENTIST);
}
private void disableLogger() {
Preference logger = findPreference(Repository.KEY_PRIVACY_LOGGABLE);
if (logger != null) {
logger.getParent().removePreference(logger);
}
}
/**
* Updates the version information by reading out the package version and
* the build date of classes.dex.
@@ -344,7 +344,7 @@ public class ShareFragment extends AbstractFragment implements DatePickerDialog.
expirationDateView.setText(format.asDate(share.getExpirationTime()));
creationTimeView.setText(format.asTime(share.getCreationTime()));
creationDateView.setText(format.asDate(share.getCreationTime()));
pausedBox.setChecked(share.getPaused());
pausedBox.setChecked(share.isPaused());
messageText.setText(share.getMessage());
messageText.setSelection(messageText.getText().length());
messageText.clearFocus();
@@ -11,7 +11,7 @@ public class LocationContract {
/**
* The table to store the released locations when they
* are captured. This table is required to handle
* transient network failsures.
* transient network failures.
*/
public class Update {
/**
@@ -72,6 +72,33 @@ public class LocationContract {
public static final String VERSION = "version";
}
/**
* The table to store the metadata for updates.
*/
public class Metadata {
/**
* The name of the table.
*/
public static final String TABLE = "location_metadata";
/**
* The id of the row.
*/
public static final String ID = "_id";
/**
* The id of the update to which this metadata refers to.
*/
public static final String UPDATE_ID = "update_id";
/**
* The tag describing the metadata type.
*/
public static final String TAG = "tag";
/**
* The value containing the actual data.
*/
public static final String VALUE = "value";
}
/**
* The table to store locations with their associated
* networks so that we do not have to compute them
@@ -150,7 +177,7 @@ public class LocationContract {
/**
* The db schema version.
*/
public static int VERSION = 6;
public static int VERSION = 7;
/**
* The name of the database.
@@ -5,6 +5,8 @@ import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.maptology.android.app.notice.NoticeContract;
/**
* Implements an sqlite open helper for the the location db.
*
@@ -99,6 +101,33 @@ public class LocationHelper extends SQLiteOpenHelper {
*/
private static String SQL_DROP_UPDATE = "DROP TABLE IF EXISTS " + LocationContract.Update.TABLE;
/**
* Creates the metadata table.
*/
private static String SQL_CREATE_METADATA = "CREATE TABLE " + LocationContract.Metadata.TABLE + " ( "
+ LocationContract.Metadata.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ LocationContract.Metadata.TAG + " TEXT, "
+ LocationContract.Metadata.VALUE + " TEXT, "
+ LocationContract.Metadata.UPDATE_ID + " INTEGER NOT NULL "
+ "REFERENCES " + LocationContract.Update.TABLE + " ( " + LocationContract.Update.ID + " ) ON DELETE CASCADE"
+ " )";
/**
* Drops the metadata table.
*/
private static String SQL_DROP_METADATA = "DROP TABLE IF EXISTS " + LocationContract.Metadata.TABLE;
/**
* Creates an index over the metadata update id to resolve the foreign key.
*/
private static String SQL_INDEX_METADATA_UI = "CREATE INDEX " + LocationContract.Metadata.TABLE + "_UI "
+ "ON " + LocationContract.Metadata.TABLE + " ( " +LocationContract.Metadata.UPDATE_ID +" )";
/**
* Drops the index on the metadata's update id.
*/
private static String SQL_DROP_METADATA_UI = "DROP INDEX IF EXISTS " + LocationContract.Metadata.TABLE + "_UI";
/**
* Creates a new helper from the context.
*
@@ -130,11 +159,13 @@ public class LocationHelper extends SQLiteOpenHelper {
try {
// create tables
db.execSQL(SQL_CREATE_UPDATE);
db.execSQL(SQL_CREATE_METADATA);
db.execSQL(SQL_CREATE_POSITION);
db.execSQL(SQL_CREATE_NETWORK);
// create indexes
db.execSQL(SQL_INDEX_POSITION_UT);
db.execSQL(SQL_INDEX_NETWORK_BS);
db.execSQL(SQL_INDEX_METADATA_UI);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
@@ -153,20 +184,36 @@ public class LocationHelper extends SQLiteOpenHelper {
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Migrating database from " + oldVersion + " to " + newVersion + ".");
// a quite crude "upgrade" script
db.beginTransaction();
try {
// drop indexes
db.execSQL(SQL_DROP_NETWORK_BS);
db.execSQL(SQL_DROP_POSITION_UT);
// drop tables
db.execSQL(SQL_DROP_NETWORK);
db.execSQL(SQL_DROP_POSITION);
db.execSQL(SQL_DROP_UPDATE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (oldVersion == 6 && newVersion == 7) {
// only add new table from 6 to 7
db.beginTransaction();
try {
db.execSQL(SQL_CREATE_METADATA);
db.execSQL(SQL_INDEX_METADATA_UI);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} else {
// otherwise recreate database
db.beginTransaction();
try {
// drop indexes
db.execSQL(SQL_DROP_METADATA_UI);
db.execSQL(SQL_DROP_NETWORK_BS);
db.execSQL(SQL_DROP_POSITION_UT);
// drop tables
db.execSQL(SQL_DROP_NETWORK);
db.execSQL(SQL_DROP_POSITION);
db.execSQL(SQL_DROP_METADATA);
db.execSQL(SQL_DROP_UPDATE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// recreate everything
onCreate(db);
}
// recreate everything
onCreate(db);
}
}
@@ -1,11 +1,11 @@
package com.maptology.android.app.model;
package com.maptology.android.app.location;
/**
* A stored network.
*
* @author Marcus
*/
public class Network {
public class LocationNetwork {
/**
* The id in the database.
@@ -1,4 +1,4 @@
package com.maptology.android.app.model;
package com.maptology.android.app.location;
import java.util.ArrayList;
import java.util.HashMap;
@@ -10,7 +10,7 @@ import java.util.Map;
*
* @author Marcus
*/
public class Position {
public class LocationPosition {
/**
* The id of the position.
@@ -19,7 +19,7 @@ public class Position {
/**
* The networks of the position.
*/
private List<Network> networks = new ArrayList<>();
private List<LocationNetwork> networks = new ArrayList<>();
/**
* The longitude of the position.
*/
@@ -72,7 +72,7 @@ public class Position {
*
* @return The list of networks.
*/
public List<Network> getNetworks() {
public List<LocationNetwork> getNetworks() {
return networks;
}
@@ -209,13 +209,13 @@ public class Position {
* @param maximumDeviation The maximum deviation to consider a network as matching.
* @return The number of matching networks.
*/
public int getMatches(List<Network> networks, int maximumDeviation) {
public int getMatches(List<LocationNetwork> networks, int maximumDeviation) {
Map<String, Integer> bssids = new HashMap<>();
for (Network n: this.networks) {
for (LocationNetwork n: this.networks) {
bssids.put(n.getBssid(), n.getRssi());
}
int count = 0;
for (Network n: networks) {
for (LocationNetwork n: networks) {
if (bssids.containsKey(n.getBssid()) && Math.abs(n.getRssi() - bssids.get(n.getBssid())) <= maximumDeviation) {
count += 1;
}
@@ -229,15 +229,15 @@ public class Position {
* @param networks The networks.
* @return The squared distance sum in vector space.
*/
public long getDistance(List<Network> networks) {
Map<String, Network> nets = new HashMap<>();
for (Network n: this.networks) {
public long getDistance(List<LocationNetwork> networks) {
Map<String, LocationNetwork> nets = new HashMap<>();
for (LocationNetwork n: this.networks) {
nets.put(n.getBssid(), n);
}
long distance = 0;
for (Network n: networks) {
for (LocationNetwork n: networks) {
int rssiOut = -100;
Network o = nets.get(n.getBssid());
LocationNetwork o = nets.get(n.getBssid());
if (o != null) {
rssiOut = o.getRssi();
}
@@ -261,7 +261,7 @@ public class Position {
b.append("ALTITUDE(" + altitude + ") ");
b.append("ACCURACY(" + accuracy + ") ");
b.append("NETWORKS( ");
for (Network n: networks) {
for (LocationNetwork n: networks) {
b.append(n.toString());
b.append(" ");
}
@@ -1,10 +1,10 @@
package com.maptology.android.app.location;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.maptology.android.app.model.Network;
import com.maptology.android.app.model.Position;
import com.maptology.android.feign.model.Coordinate;
import com.maptology.android.feign.model.ReleasedLocation;
@@ -56,7 +56,7 @@ public class LocationStore {
*
* @param p The position to add.
*/
public void addPosition(Position p) {
public void addPosition(LocationPosition p) {
if (db == null) return;
db.beginTransaction();
try {
@@ -73,7 +73,7 @@ public class LocationStore {
// get the position id
p.setId(getPositionId());
// add the networks
for (Network n: p.getNetworks()) {
for (LocationNetwork n: p.getNetworks()) {
addNetwork(p.getId(), n);
}
db.setTransactionSuccessful();
@@ -100,6 +100,13 @@ public class LocationStore {
return getCreatedId(LocationContract.Network.TABLE);
}
/**
* Returns the last created update id.
*
* @return The last created update id.
*/
private long getUpdateId() { return getCreatedId(LocationContract.Update.TABLE); }
/**
* Returns the last created id of the specified table.
*
@@ -123,7 +130,7 @@ public class LocationStore {
* @param position The position.
* @param n The network.
*/
private void addNetwork(long position, Network n) {
private void addNetwork(long position, LocationNetwork n) {
ContentValues values = new ContentValues();
values.put(LocationContract.Network.POSITION, position);
values.put(LocationContract.Network.BSSID, n.getBssid());
@@ -138,8 +145,8 @@ public class LocationStore {
* @param position The position.
* @return The list of networks.
*/
private List<Network> getNetworks(long position) {
List<Network> result = new ArrayList<>();
private List<LocationNetwork> getNetworks(long position) {
List<LocationNetwork> result = new ArrayList<>();
if (db == null) return result;
Cursor c = db.query(LocationContract.Network.TABLE, new String[] {
LocationContract.Network.ID,
@@ -148,7 +155,7 @@ public class LocationStore {
}, LocationContract.Network.POSITION + " = " + position, null, null, null, null);
while (c.moveToNext()) {
Network n = new Network();
LocationNetwork n = new LocationNetwork();
n.setId(c.getLong(0));
n.setBssid(c.getString(1));
n.setRssi(c.getInt(2));
@@ -174,7 +181,7 @@ public class LocationStore {
* @param updateNetworks True to update the networks, false
* to update only the position.
*/
public void setPosition(Position p, boolean updateNetworks) {
public void setPosition(LocationPosition p, boolean updateNetworks) {
if (db == null) return;
db.beginTransaction();
try {
@@ -189,7 +196,7 @@ public class LocationStore {
db.update(LocationContract.Position.TABLE, values, LocationContract.Position.ID + " = " + p.getId(), null);
if (updateNetworks) {
removeNetworks(p.getId());
for (Network n: p.getNetworks()) {
for (LocationNetwork n: p.getNetworks()) {
addNetwork(p.getId(), n);
}
}
@@ -205,8 +212,8 @@ public class LocationStore {
* @param id The id to load.
* @return The position with its networks.
*/
public Position getPosition(long id) {
Position result = null;
public LocationPosition getPosition(long id) {
LocationPosition result = null;
if (db == null) return result;
db.beginTransaction();
try {
@@ -221,7 +228,7 @@ public class LocationStore {
LocationContract.Position.ID + " = " + id,
null, null, null, null);
if (c.moveToNext()) {
result = new Position();
result = new LocationPosition();
result.setId(id);
result.setLatitude(c.getDouble(0));
result.setLongitude(c.getDouble(1));
@@ -267,7 +274,7 @@ public class LocationStore {
* @param maximumDeviation The maximum deviation of rssi values to consider a network matching.
* @return The position or null, if no match is good enough.
*/
public Position findPosition(List<Network> networks, int minimumMatching, int maximumDeviation) {
public LocationPosition findPosition(List<LocationNetwork> networks, int minimumMatching, int maximumDeviation) {
if (networks.size() == 0 || networks.size() < minimumMatching) return null;
if (db == null) return null;
StringBuilder b = new StringBuilder();
@@ -279,7 +286,7 @@ public class LocationStore {
b.append(", ");
}
}
Position best = null;
LocationPosition best = null;
int matches = 0;
double distance = 0;
db.beginTransaction();
@@ -289,7 +296,7 @@ public class LocationStore {
LocationContract.Network.BSSID + " IN (" + b.toString() + ")",
null, null, null, null, null);
while (c.moveToNext()) {
Position p = getPosition(c.getLong(0));
LocationPosition p = getPosition(c.getLong(0));
if (p != null) {
long d = p.getDistance(networks);
int m = p.getMatches(networks, maximumDeviation);
@@ -356,10 +363,29 @@ public class LocationStore {
values.put(LocationContract.Update.ACCURACY, location.getAccuracy());
values.put(LocationContract.Update.BEARING, location.getBearing());
values.put(LocationContract.Update.SPEED, location.getSpeed());
values.put(LocationContract.Update.ANALYZABLE, location.getAnalyzable()==null?0:(location.getAnalyzable()?1:0));
values.put(LocationContract.Update.SHARABLE, location.getSharable()==null?0:(location.getSharable()?1:0));
values.put(LocationContract.Update.ANALYZABLE, location.isAnalyzable()==null?0:(location.isAnalyzable()?1:0));
values.put(LocationContract.Update.SHARABLE, location.isSharable()==null?0:(location.isSharable()?1:0));
values.put(LocationContract.Update.VERSION, location.getVersion()==null?0:location.getVersion());
db.insert(LocationContract.Update.TABLE, null, values);
addMetadata(getUpdateId(), location.getMetadata());
}
/**
* Stores the meta for the update id.
*
* @param updateId The update id.
* @param metadata The metadata to store.
*/
private void addMetadata(long updateId, Map<String, String> metadata) {
if (metadata != null) {
for (Map.Entry<String, String> entry: metadata.entrySet()) {
ContentValues values = new ContentValues();
values.put(LocationContract.Metadata.UPDATE_ID, updateId);
values.put(LocationContract.Metadata.TAG, entry.getKey());
values.put(LocationContract.Metadata.VALUE, entry.getValue());
db.insert(LocationContract.Metadata.TABLE, null, values);
}
}
}
/**
@@ -405,11 +431,35 @@ public class LocationStore {
cor.setLongitude(c.getDouble(11));
r.setCoordinate(cor);
}
r.setMetadata(getMetadata(id));
}
c.close();;
return r;
}
/**
* Returns the metadata stored for the update.
*
* @param updateId The update id.
* @return The metadata (never null).
*/
private Map<String, String> getMetadata(long updateId) {
Map<String, String> result = new HashMap<>();
if (db == null) return result;
Cursor c = db.query(LocationContract.Metadata.TABLE, new String[]{
LocationContract.Metadata.TAG,
LocationContract.Metadata.VALUE
}, LocationContract.Metadata.UPDATE_ID + " = " + updateId, null, null, null, null);
while (c.moveToNext()) {
String tag = c.isNull(0)?null:c.getString(0);
String value = c.isNull(1)?null:c.getString(1);
result.put(tag, value);
}
c.close();
return result;
}
/**
* Removes the update with the specified id.
*
@@ -418,6 +468,17 @@ public class LocationStore {
public void removeUpdate(long id) {
if (db == null) return;
db.execSQL("DELETE FROM " + LocationContract.Update.TABLE + " WHERE " + LocationContract.Update.ID + " = " + id);
removeMetadata(id);
}
/**
* Removes the metadata fr the update with the specified id.
*
* @param updateId The id of the update.
*/
private void removeMetadata(long updateId) {
if (db == null) return;
db.execSQL("DELETE FROM " + LocationContract.Metadata.TABLE + " WHERE " + LocationContract.Metadata.UPDATE_ID + " = " + updateId);
}
/**
@@ -447,6 +508,13 @@ public class LocationStore {
return getCount(LocationContract.Network.TABLE);
}
/**
* Returns the number of entries in the metadata table.
*
* @return The number of metadata entries.
*/
public long getMetadataCount() { return getCount(LocationContract.Metadata.TABLE); }
/**
* Returns the element count in the table.
*
@@ -104,7 +104,7 @@ public class NoticeStore {
}
ContentValues values = new ContentValues();
values.put(NoticeContract.Notice.ID, notice.getId());
values.put(NoticeContract.Notice.ANNOUNCED, notice.getAnnounced());
values.put(NoticeContract.Notice.ANNOUNCED, notice.isAnnounced());
values.put(NoticeContract.Notice.CREATION_TIME, notice.getCreationTime());
values.put(NoticeContract.Notice.MODIFICATION_TIME, notice.getModificationTime());
values.put(NoticeContract.Notice.EXPIRATION_TIME, notice.getExpirationTime());
@@ -38,6 +38,11 @@ public class Repository {
*/
public static final String KEY_PRIVACY_LOCALIZE = "privacy_localize";
/**
* The key to globally enable or disable the high precision logger service.
*/
public static final String KEY_PRIVACY_LOGGABLE = "privacy_loggable";
/**
* The key to memorize whether we are in development mode.
*/
@@ -167,6 +172,12 @@ public class Repository {
return getPreference(KEY_PRIVACY_LOCALIZE, R.bool.privacy_localize_default);
}
public boolean isLoggable() {
return getPreference(KEY_PRIVACY_LOGGABLE, R.bool.privacy_loggable_default);
}
/**
* Sets whether the user has allowed that his positions can be used for research.
*
@@ -164,9 +164,9 @@ public class ShareStore {
values.put(ShareContract.Share.MESSAGE, share.getMessage());
values.put(ShareContract.Share.DESTINATION, share.getDestination());
values.put(ShareContract.Share.TOKEN, share.getToken());
values.put(ShareContract.Share.PAUSED, share.getPaused() ? 1 : 0);
values.put(ShareContract.Share.PAUSED, share.isPaused() ? 1 : 0);
values.put(ShareContract.Share.DEVICE, share.getDevice());
values.put(ShareContract.Share.DELETED, share.getDeleted() ? 1 : 0);
values.put(ShareContract.Share.DELETED, share.isDeleted() ? 1 : 0);
if (!exists) {
values.put(ShareContract.Share.ID, share.getId());
database.insert(ShareContract.Share.TABLE, null, values);
@@ -83,11 +83,11 @@ public class CreateShareTask extends AbstractApiTask<Void, Void, AsyncError> {
super.onPostExecute(asyncError);
if (app.getRepository().updatingShare.getValue() != interaction) return;
if (asyncError == null) {
share.setDeleted(createdShare.getDeleted());
share.setDeleted(createdShare.isDeleted());
share.setId(createdShare.getId());
share.setToken(createdShare.getToken());
share.setDestination(createdShare.getDestination());
share.setPaused(createdShare.getPaused());
share.setPaused(createdShare.isPaused());
share.setModificationTime(createdShare.getModificationTime());
share.setCreationTime(createdShare.getCreationTime());
share.setDevice(createdShare.getDevice());
@@ -150,7 +150,7 @@ public class SyncNoticeTask extends AbstractApiTask<Void, Void, List<Notice>> {
Log.d(TAG, "Received a notice without id (this is a problem, fix it).");
continue;
}
if (n.getDeleted() != null && n.getDeleted()) {
if (n.isDeleted() != null && n.isDeleted()) {
// delete outdated data
store.removeNotice(n.getId());
} else {
@@ -101,7 +101,7 @@ public class UpdateDeviceTask extends AbstractApiTask<Void, Void, AsyncError> {
return getError(e);
}
try {
device = apiClient.setCurrentDeviceUser();
device = apiClient.setCurrentUserDevice(device);
Log.d(TAG, "Device associated for user id " + device.getUser() + ".");
} catch (FeignException e) {
Log.d(TAG, "Device creation failure: " + e.status() + " " + e.getMessage());
@@ -41,7 +41,7 @@ public class UploadLocationTask extends AbstractApiTask<Void, Void, Void> {
/**
* The maximum number of locations to be uploaded in one batch.
*/
private static final int MAXIMUM_BATCH_SIZE = 100;
private static final int MAXIMUM_BATCH_SIZE = 5;
/**
* The respository of the app.
@@ -0,0 +1,131 @@
package com.maptology.android.app.util;
import java.util.ArrayList;
import java.util.List;
/**
* A delta compression codec based on Google's WGS84 encoder that
* supports multiple data streams to encode other data than latitude
* and longitude values. Callers must supply the number of streams
* encoded in the data and the streams must exhibit the same number
* of data items.
*
* @author Marcus
*/
public class DeltaCodec {
/**
* The number of streams to encode or decode.
*/
private int streams;
/**
* Creates a delta compressor for the specified number of streams.
*
* @param streams The number of streams to encode in the string.
*/
public DeltaCodec(int streams) {
this.streams = streams;
}
/**
* Returns the number of streams expected by this codec.
*
* @return The number of streams.
*/
public int getStreams() {
return streams;
}
/**
* Encodes a list of values into a string.
*
* @param values The values consisting of arrays that represent
* the individual streams.
* @return The string.
*/
public String encode(List<long[]> values) {
StringBuilder builder = new StringBuilder();
long[] previous = new long[streams];
for (int i = 0, s = values.size(); i < s; i++) {
long[] current = values.get(i);
for (int j = 0; j < streams; j++) {
long delta = current[j] - previous[j];
builder.append(encodeSignedNumber(delta));
previous[j] = current[j];
}
}
return builder.toString();
}
/**
* Extracts the list of data from an encoded string.
*
* @param encoded The encoded string.
* @param data An optional list of data items to be reused
* to avoid object allocations. Can be null.
* @return The list of data items representing the streams.
*/
public List<long[]> decode(String encoded, List<long[]> data) {
List<long[]> list = new ArrayList<>();
int index = 0;
int length = encoded.length();
long[] current = new long[streams];
while (index < length) {
long[] next;
if (data != null && data.size() > 0) {
next = data.remove(0);
} else {
next = new long[streams];
}
long c;
for (int i = 0; i < streams; i++) {
long shift = 0;
long result = 0;
do {
c = encoded.charAt(index++) - 63;
result |= (c & 0x1f) << shift;
shift += 5;
} while (c >= 0x20);
long delta = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
current[i] += delta;
next[i] = current[i];
}
list.add(next);
}
return list;
}
/**
* Encodes a signed number as string.
*
* @param num The number.
* @return The string.
*/
private static String encodeSignedNumber(long num) {
long sgn_num = num << 1;
if (num < 0) {
sgn_num = ~(sgn_num);
}
return (encodeNumber(sgn_num));
}
/**
* Encodes an unsigned number as string.
*
* @param num The number.
* @return The string.
*/
private static String encodeNumber(long num) {
StringBuilder encodeString = new StringBuilder();
while (num >= 0x20) {
int nextValue = (int)(0x20 | (num & 0x1f)) + 63;
encodeString.append((char) (nextValue));
num >>= 5;
}
num += 63;
encodeString.append((char) (num));
return encodeString.toString();
}
}
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M15.9,5c-0.17,0 -0.32,0.09 -0.41,0.23l-0.07,0.15 -5.18,11.65c-0.16,0.29 -0.26,0.61 -0.26,0.96 0,1.11 0.9,2.01 2.01,2.01 0.96,0 1.77,-0.68 1.96,-1.59l0.01,-0.03L16.4,5.5c0,-0.28 -0.22,-0.5 -0.5,-0.5zM1,9l2,2c2.88,-2.88 6.79,-4.08 10.53,-3.62l1.19,-2.68C9.89,3.84 4.74,5.27 1,9zM21,11l2,-2c-1.64,-1.64 -3.55,-2.82 -5.59,-3.57l-0.53,2.82c1.5,0.62 2.9,1.53 4.12,2.75zM17,15l2,-2c-0.8,-0.8 -1.7,-1.42 -2.66,-1.89l-0.55,2.92c0.42,0.27 0.83,0.59 1.21,0.97zM5,13l2,2c1.13,-1.13 2.56,-1.79 4.03,-2l1.28,-2.88c-2.63,-0.08 -5.3,0.87 -7.31,2.88z"/>
</vector>
@@ -4,13 +4,9 @@
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:orientation="vertical"
android:layout_centerHorizontal="true"
android:gravity="center"
android:layout_width="@dimen/max_view_width"
android:layout_height="match_parent">
<ScrollView android:layout_width="match_parent"
<ScrollView android:layout_width="@dimen/max_view_width"
android:fillViewport="true"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
@@ -50,6 +46,7 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/space_large"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/input_password"
@@ -69,7 +66,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/space_medium"
android:background="@color/white"
android:background="@android:color/transparent"
android:src="@drawable/ic_visibility_black_24dp" />
</LinearLayout>
@@ -106,7 +103,6 @@
</ScrollView>
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
@@ -23,6 +23,7 @@
<string name="localization_notification_wifi">Suche Wi-Fi Netze</string>
<string name="localization_notification_net">Bestimme Netzstandort</string>
<string name="localization_notification_upload">Teile Standort</string>
<string name="localization_notification_logger">Erfasse Sensordaten</string>
<string name="localization_channel_name">Standortbestimmung</string>
<string name="localization_channel_description">Benachrichtigungen über die Standortbestimmung im Hintergrund.</string>
@@ -120,6 +121,8 @@
<string name="setting_category_privacy">Datenschutz</string>
<string name="setting_privacy_localize_title">Standortbestimmung</string>
<string name="setting_privacy_localize_summary">Aktiviert die Standortbestimmung und -freigabe im Hintergrund. Deaktivierung beendet die Standortbestimmung vollständig.</string>
<string name="setting_privacy_loggable_title">Sensorerfassung</string>
<string name="setting_privacy_loggable_summary">Aktiviert die automatische Erfassung von Sensordaten im Hintergrund, sobald das Gerät mit Strom versorgt wird.</string>
<string name="setting_privacy_share_title">Standortveröffentlichung</string>
<string name="setting_privacy_share_summary">Erlaubt die anonyme Nutzung aller Standortdaten zu Forschungszwecken. Bei Deaktivierung erfolgt keine Nutzung durch uns und die Zugriffskontrolle erfolgt nur auf Basis Deiner Freigaben.</string>
<string name="setting_privacy_analyze_title">Standortanalyse</string>
@@ -1,13 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
<string name="application_long" translatable="false">Maptology</string>
<string name="application_short" translatable="false">Maptology</string>
-->
<string name="maptology_url_default" translatable="false">https://www.maptology.com/api</string>
<string name="maptology_url_share" translatable="false">https://www.maptology.com/app/shares/</string>
<string name="maptology_url_register" translatable="false">https://www.maptology.com/app/register</string>
<string name="maptology_url_places" translatable="false">https://www.maptology.com/app/places</string>
<bool name="privacy_localize_default">true</bool>
<bool name="privacy_loggable_default">false</bool>
<bool name="privacy_analyze_default">false</bool>
<bool name="privacy_share_default">false</bool>
<bool name="terms_accepted_default">false</bool>
@@ -24,6 +24,7 @@
<string name="localization_notification_gps">Acquiring GPS position</string>
<string name="localization_notification_wifi">Scanning Wi-Fi networks</string>
<string name="localization_notification_net">Acquiring net-based position</string>
<string name="localization_notification_logger">Receiving sensor data</string>
<string name="localization_notification_upload">Uploading location</string>
<string name="localization_channel_name">Localization</string>
@@ -123,6 +124,8 @@
<string name="setting_category_privacy">Privacy</string>
<string name="setting_privacy_localize_title">Localization</string>
<string name="setting_privacy_localize_summary">Enables background localization and location-sharing. If disabled, the application will no longer try to determine your location.</string>
<string name="setting_privacy_loggable_title">Sensing</string>
<string name="setting_privacy_loggable_summary">Enables automatic sensor data capturing, whenever the device is connected to an external power source.</string>
<string name="setting_privacy_share_title">Research</string>
<string name="setting_privacy_share_summary">Allows us to analyze your locations for research purposes. If disabled, we will not analyze your location data and access is controlled only through your shares.</string>
<string name="setting_privacy_analyze_title">Analysis</string>
@@ -8,6 +8,12 @@
android:defaultValue="@bool/privacy_localize_default"
android:summary="@string/setting_privacy_localize_summary"
android:title="@string/setting_privacy_localize_title" />
<CheckBoxPreference
android:icon="@drawable/ic_network_check_black_24dp"
android:key="privacy_loggable"
android:defaultValue="@bool/privacy_loggable_default"
android:summary="@string/setting_privacy_loggable_summary"
android:title="@string/setting_privacy_loggable_title" />
<CheckBoxPreference
android:icon="@drawable/ic_share_black_24dp"
android:key="privacy_share"
@@ -0,0 +1,74 @@
package com.maptology.android.app.test.codec;
import com.maptology.android.app.util.DeltaCodec;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Test cases for the delta codec.
*
* @author Marcus
*/
public class DeltaCodecTest {
/**
* Tests that the delta codec can encode and decode data.
*/
@Test
public void testReadWriteDeltaCodec() {
for (int i = 1; i < 5; i++) {
DeltaCodec codec = new DeltaCodec(i);
List<long[]> expected = generateTestData(i, 100);
String encoded = codec.encode(expected);
List<long[]> actual = codec.decode(encoded, new ArrayList<long[]>());
assertEquals(expected, actual);
}
}
/**
* Generates some random data for the tests.
*
* @param length The length of the arrays.
* @param size The size of the list.
* @return The list with arrays of the specified length.
*/
public List<long[]> generateTestData(int length, int size) {
List<long[]> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
long[] data = new long[length];
result.add(data);
for (int j = 0; j < data.length; j++) {
data[j] = i * j;
if (i % 2 == 0) data[j] = -data[j];
}
}
return result;
}
/**
* Ensures that the two lists of arrays are identical in terms of contents.
*
* @param expected The expected list.
* @param actual The actual list.
*/
public void assertEquals(List<long[]> expected, List<long[]> actual) {
Assert.assertEquals("Size must match.", expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
long[] e = expected.get(i);
long[] a = actual.get(i);
Assert.assertEquals("Length must match.", e.length, a.length);
for (int j = 0; j < e.length; j++)
Assert.assertEquals("Value must match.", e[j], a[j]);
}
}
}
@@ -5,8 +5,8 @@ import android.location.LocationManager;
import androidx.test.core.app.ApplicationProvider;
import com.maptology.android.app.location.LocationStore;
import com.maptology.android.app.model.Network;
import com.maptology.android.app.model.Position;
import com.maptology.android.app.location.LocationNetwork;
import com.maptology.android.app.location.LocationPosition;
import com.maptology.android.feign.model.Coordinate;
import com.maptology.android.feign.model.ReleasedLocation;
import org.junit.Assert;
@@ -18,6 +18,7 @@ import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
@@ -43,22 +44,27 @@ public class LocationStoreTest {
ReleasedLocation r1 = createLocation(1);
store.addUpdate(r1);
Assert.assertEquals("Should contain one entry.", 1, store.getUpdateCount());
Assert.assertEquals("Should contain two entries", 2, store.getMetadataCount());
List<Long> ids = store.getUpdates(100);
Assert.assertEquals("Should contain one entry.", 1, ids.size());
ReleasedLocation loaded = store.getUpdate(ids.get(0));
Assert.assertNotNull("Loaded should exist.", loaded);
System.out.println(loaded.getMetadata());
assertEquals(r1, loaded);
ReleasedLocation r2 = createLocation(2);
store.addUpdate(r2);
ids = store.getUpdates(100);
Assert.assertEquals("Should contain two entries.", 2, ids.size());
Assert.assertEquals("Should contain two entries", 4, store.getMetadataCount());
loaded = store.getUpdate(ids.get(1));
Assert.assertNotNull("Loaded should exist.", loaded);
assertEquals(r2, loaded);
store.removeUpdate(ids.get(0));
Assert.assertEquals("Should contain one entry.", 1, store.getUpdateCount());
Assert.assertEquals("Should contain two entries", 2, store.getMetadataCount());
store.removeUpdate(ids.get(1));
Assert.assertEquals("Should contain no entries", 0, store.getUpdateCount());
Assert.assertEquals("Should contain two entries", 0, store.getMetadataCount());
}
/**
@@ -82,6 +88,9 @@ public class LocationStoreTest {
r.setAnalyzable(true);
r.setVersion(12);
r.setAccuracy(1d);
r.setMetadata(new HashMap<String, String>());
r.getMetadata().put("key_a", "value_a");
r.getMetadata().put("key_b", "value_b");
return r;
}
@@ -103,22 +112,26 @@ public class LocationStoreTest {
Assert.assertEquals("Speeed should match.", e.getSpeed(), a.getSpeed());
Assert.assertEquals("Alt should match.", e.getAltitude(), a.getAltitude());
Assert.assertEquals("Bearing should match.", e.getBearing(), a.getBearing());
Assert.assertEquals("Share should match.", e.getSharable(), a.getSharable());
Assert.assertEquals("Analyze should match.", e.getAnalyzable(), a.getAnalyzable());
Assert.assertEquals("Share should match.", e.isSharable(), a.isSharable());
Assert.assertEquals("Analyze should match.", e.isAnalyzable(), a.isAnalyzable());
Assert.assertEquals("Version should match.", e.getVersion(), a.getVersion());
Assert.assertEquals("Accuracy should match.", e.getAccuracy(), a.getAccuracy());
Assert.assertEquals("Metadata should have same size.", e.getMetadata().size(), a.getMetadata().size());
for (String key: e.getMetadata().keySet()) {
Assert.assertEquals("Metadata value should match.", e.getMetadata().get(key), a.getMetadata().get(key));
}
}
@Test
public void testAddGetDeletePositions() {
LocationStore store = new LocationStore(ApplicationProvider.getApplicationContext());
Position p = createPosition(1);
LocationPosition p = createPosition(1);
p.getNetworks().addAll(createNetworks(5, "xyz"));
store.addPosition(p);
Assert.assertEquals("Should have one position.", 1, store.getPositionCount());
Assert.assertEquals("Should have 5 networks.", 5, store.getNetworkCount());
Position same = store.getPosition(p.getId());
LocationPosition same = store.getPosition(p.getId());
Assert.assertNotNull("Should be able to load stored position.", same);
}
@@ -128,7 +141,7 @@ public class LocationStoreTest {
* @param e The expected position.
* @param a The actual position.
*/
private void assertEquals(Position e, Position a) {
private void assertEquals(LocationPosition e, LocationPosition a) {
Assert.assertEquals("Should have same id.", e.getId(), a.getId());
Assert.assertEquals("Should have same usage.", e.getUsageTime(), a.getUsageTime());
Assert.assertEquals("Should have same time.", e.getCreationTime(), a.getCreationTime());
@@ -138,8 +151,8 @@ public class LocationStoreTest {
Assert.assertEquals("Should have same prec.", e.getAccuracy(), a.getAccuracy());
Assert.assertEquals("Should have same provider.", e.getProvider(), a.getProvider());
Assert.assertEquals("Should have same networks.", e.getNetworks().size(), a.getNetworks().size());
n: for (Network n: e.getNetworks()) {
for (Network x: a.getNetworks()) {
n: for (LocationNetwork n: e.getNetworks()) {
for (LocationNetwork x: a.getNetworks()) {
if (n.getBssid().equals(x.getBssid())) {
Assert.assertEquals("Should have same rssi", n.getRssi(), x.getRssi());
continue n;
@@ -155,8 +168,8 @@ public class LocationStoreTest {
* @param time The time to set.
* @return The position.
*/
private Position createPosition(long time) {
Position p = new Position();
private LocationPosition createPosition(long time) {
LocationPosition p = new LocationPosition();
p.setUsageTime(time);
p.setAltitude(2d);
p.setCreationTime(time);
@@ -174,10 +187,10 @@ public class LocationStoreTest {
* @param prefix The prefix.
* @return The list of networks.
*/
private List<Network> createNetworks(int count, String prefix) {
List<Network> result = new ArrayList<>();
private List<LocationNetwork> createNetworks(int count, String prefix) {
List<LocationNetwork> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
Network n = new Network();
LocationNetwork n = new LocationNetwork();
n.setBssid(prefix + Integer.toString(i));
n.setRssi(i);
result.add(n);
@@ -52,7 +52,7 @@ public class NoticeStoreTest {
Assert.assertEquals("Creation time should be same.", notice.getCreationTime(), fetched.getCreationTime());
Assert.assertEquals("Modification time should be same.", notice.getModificationTime(), fetched.getModificationTime());
Assert.assertEquals("Expiration time should be same.", notice.getExpirationTime(), fetched.getExpirationTime());
Assert.assertEquals("Announced should be same.", notice.getAnnounced(), fetched.getAnnounced());
Assert.assertEquals("Announced should be same.", notice.isAnnounced(), fetched.isAnnounced());
Assert.assertEquals("Messages should be same.", notice.getMessages().size(), fetched.getMessages().size());
store.removeNotice(notice.getId());
Notice deleted = store.getNotice(notice.getId());
+15 -23
View File
@@ -1,5 +1,5 @@
plugins {
id 'org.detoeuf.swagger-codegen' version '1.7.4'
id 'org.hidetake.swagger.generator' version '2.18.1'
}
description = "Maptology Android Feign"
@@ -14,36 +14,28 @@ dependencies {
compile "io.github.openfeign:feign-core:9.4.0"
compile "io.github.openfeign:feign-jackson:9.4.0"
compileOnly "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.1"
swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.9'
}
sourceSets.main.java.srcDirs = ['src/main/java', 'build/swagger/src/main/java']
swagger {
inputSpec = file(project(':common-api:').buildDir.path + '/swagger/maptology.json')
outputDir = file("${project.buildDir}/swagger")
lang = 'java'
library = 'feign'
additionalProperties = [
'invokerPackage' : 'com.maptology.android.feign',
'modelPackage' : 'com.maptology.android.feign.model',
'apiPackage' : 'com.maptology.android.feign.api',
'dateLibrary' : 'java8'
]
systemProperties = [
'apis' : '',
'models' : '',
'supportingFiles' : 'false',
'modelDocs' : 'false',
'apiTests' : 'false',
'modelTests' : 'false'
]
swaggerSources {
mowesta {
inputFile = file(project(':common-api:').buildDir.path + '/swagger/maptology.json')
code {
outputDir = file("${project.buildDir}/swagger")
language = 'java'
configFile = file('config.json')
components = ['models', 'apis']
}
}
}
// require api build to access swagger definition
tasks['swagger'].dependsOn(project(':common-api').tasks['build'])
tasks['resolveSwaggerTemplate'].dependsOn(project(':common-api').tasks['build'])
// require swagger code gen before compilation
compileJava.dependsOn('swagger')
compileJava.dependsOn('generateSwaggerCode')
+7
View File
@@ -0,0 +1,7 @@
{
"library": "feign",
"modelPackage": "com.maptology.android.feign.model",
"apiPackage": "com.maptology.android.feign.api",
"invokerPackage": "com.maptology.android.feign",
"dateLibrary": "java8"
}
+23 -33
View File
@@ -1,31 +1,34 @@
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.8.1'
classpath 'com.google.android.gms:oss-licenses-plugin:0.9.5'
classpath files('gradle/gradle-android-eclipse-1.1.jar')
classpath 'com.android.tools.build:gradle:3.5.2'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.10.0'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.0.Fixed'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
}
repositories {
maven {
url = 'https://project.nes.uni-due.de/artifactory/releases';
credentials { username = 'public'; password = 'public' }
authentication { basic(BasicAuthentication) }
}
maven {
url = 'https://project.nes.uni-due.de/artifactory/snaphsots';
url = 'https://project.nes.uni-due.de/artifactory/snapshots';
credentials { username = 'public'; password = 'public' }
authentication { basic(BasicAuthentication) }
}
maven { url "http://repository.jboss.org/nexus/content/groups/public/" }
google()
mavenCentral()
jcenter()
}
}
allprojects {
apply plugin: 'maven-publish'
apply plugin: 'com.jfrog.artifactory'
// set version for our project
group = 'com.maptology'
version = '1.0.1'
version = '1.0.4'
// set versions for our libraries
ext {
@@ -42,26 +45,24 @@ allprojects {
// testing dependencies
versionJunit = '4.12'
versionArquillianContainer = '2.2.0.Final'
versionArquillianJunit = '1.4.1.Final'
versionArquillianJunit = '1.5.0.Final'
// thorntail dependencies
versionH2database = '1.4.196'
versionThorntail = '2.5.0.Final'
// android stuff
versionAndroidx = '1.0.0'
versionRobolectric = '4.3'
versionRobolectric = '4.3.1'
versionPlay = '17.0.0'
versionAndroidxTest = '1.2.0'
}
}
subprojects {
apply plugin: 'maven-publish'
apply plugin: 'com.jfrog.artifactory'
apply plugin: 'eclipse'
if (name.equals('android-app')) {
apply plugin: 'com.greensopinion.gradle-android-eclipse'
apply plugin: 'org.handte.gradle-android-eclipse'
apply plugin: 'com.android.application'
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
@@ -85,17 +86,6 @@ subprojects {
configurations.eclipseTestConfig,
]
downloadSources = true
file {
beforeMerged { classpath ->
classpath.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/", "bin"))
}
whenMerged { classpath ->
classpath.entries.removeAll {
return ('con'.equals(it.getKind()) && it.getPath().startsWith('org.eclipse.jdt.launching.JRE_CONTAINER'))
}
}
}
}
}
@@ -128,15 +118,13 @@ subprojects {
maven {
url = 'https://project.nes.uni-due.de/artifactory/releases';
credentials { username = 'public'; password = 'public' }
authentication { basic(BasicAuthentication) }
}
maven {
url = 'https://project.nes.uni-due.de/artifactory/snaphsots';
url = 'https://project.nes.uni-due.de/artifactory/snapshots';
credentials { username = 'public'; password = 'public' }
authentication { basic(BasicAuthentication) }
}
maven { url "http://repository.jboss.org/nexus/content/groups/public/" }
google()
mavenCentral()
jcenter()
}
@@ -145,6 +133,8 @@ subprojects {
artifactoryPublish {
publications(publishing.publications.maven);
}
}
tasks.register("generatePomFileForMavenPublication") { }
tasks.register("build") { }
+8 -1
View File
@@ -17,7 +17,7 @@ sourceSets {
test.compileClasspath += configurations.compileOnly
}
// generate swagger documenation from api using a plugin
// generate swagger documentation from api using a plugin
swagger {
apiSource {
attachSwaggerArtifact = true
@@ -29,10 +29,12 @@ swagger {
'com.maptology.api.device.IDeviceService',
'com.maptology.api.share.IShareService',
'com.maptology.api.location.ILocationService',
'com.maptology.api.position.IPositionService',
'com.maptology.api.privilege.IPrivilegeService',
'com.maptology.api.history.IHistoryService'
]
schemes = [ 'http', 'https']
host = 'localhost'
basePath = '/api'
info {
title = 'Maptology Service'
@@ -68,6 +70,11 @@ swagger {
description = 'Operations requiring admin privileges.'
type = 'basic'
}
securityDefinition {
name = 'scientist'
description = 'Operations requiring scientist privileges.'
type = 'basic'
}
}
}
@@ -46,7 +46,7 @@ public class PageConfig {
/**
* The maximum number of elements on the page.
*/
@ApiParam(name="pageSize", value="The maximum number of elements on the page.", defaultValue="20", allowableValues="range[1,100]")
@ApiParam(name="pageSize", value="The maximum number of elements on the page.", defaultValue="20", allowableValues="range[1,1000]")
@Min(1)
@Max(1000)
@QueryParam("pageSize")
@@ -38,6 +38,10 @@ public class Tags {
*/
public static final String VISIT = "Visit";
/**
* The tag for position endpoints.
*/
public static final String POSITION = "Position";
/**
* Tag for notice, log and version endpoints.
@@ -17,6 +17,11 @@ public class Authorizations {
* Basic auth for regular users.
*/
public static final String USER = "user";
/**
* Basic auth for scientists.
*/
public static final String SCIENTIST = "scientist";
/**
* Bearer auth for devices.
@@ -18,13 +18,17 @@ public class Roles {
public static final String USER = "user";
/**
* The string value of the logger role.
*/
public static final String SCIENTIST = "scientist";
/**
* The string value of the device role.
*/
public static final String DEVICE = "device";
/**
* Prevents accidential instantiation.
* Prevents accidental instantiation.
*/
private Roles() { }
@@ -36,7 +40,7 @@ public class Roles {
* @return The roles used for humans.
*/
public static String[] getHumanRoles() {
return new String[] { ADMIN, USER };
return new String[] { ADMIN, USER, SCIENTIST };
}
/**
@@ -54,7 +58,7 @@ public class Roles {
* @return The names of all roles.
*/
public static String[] getAllRoles() {
return new String[] { ADMIN, USER, DEVICE };
return new String[] { ADMIN, USER, DEVICE, SCIENTIST };
}
@@ -66,10 +66,11 @@ public interface IDeviceService {
/**
* Sets the user account for a previously registered device.
*
* @param device The device to set.
* @return A response.
*/
@PUT
@Path("devices/current/user")
@POST
@Path("users/current/devices")
@ApiOperation(value = "Connects a device created without user account with a user account.",
notes = "Executing this is operation requires a valid device and a valid user authentication to be transmitted simultaneously. ",
tags = {Tags.DEFAULT, Tags.DEVICE})
@@ -80,7 +81,7 @@ public interface IDeviceService {
})
@PermitAll
@RolesAllowed({Roles.DEVICE, Roles.USER})
Response setCurrentDeviceUser();
Response setCurrentUserDevice(@ApiParam("The device values.") @Valid @NotNull Device device);
/**
* Returns the current device.
@@ -197,7 +197,7 @@ public interface IHistoryService {
* @return The list of visits made by the specified device during the time span.
*/
@GET
@Path("devices/{id: [0-9]+}/visits")
@Path("devices/{id: [0-9]+}/visits/range")
@ApiOperation(value = " Returns the visits of a device for a particular time span.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.USER)}, tags = { Tags.DEFAULT, Tags.DEVICE })
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The list of visits from the begin time for the duration.", response=Visit.class, responseContainer="List"),
@@ -206,7 +206,7 @@ public interface IHistoryService {
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient rights for executing this method.")
})
@RolesAllowed({Roles.USER, Roles.ADMIN})
Response getDeviceVisits(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id,
Response getDeviceVisitsRange(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id,
@ApiParam(value="The start time in Epoch milliseconds.", required=true) @QueryParam("start") @Valid long start,
@ApiParam(value="The duration in milliseconds.", required=true) @QueryParam("duration") @Valid @Min(0) @Max(48*60*60*1000) @DefaultValue("86400000") long duration);
@@ -1,22 +1,31 @@
package com.maptology.api.location;
import com.maptology.api.PageConfig;
import com.maptology.api.Tags;
import com.maptology.api.access.Authorizations;
import com.maptology.api.access.Roles;
import io.swagger.annotations.*;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.maptology.api.Tags;
import com.maptology.api.access.Authorizations;
import com.maptology.api.access.Roles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
/**
* Provides inforamtion about the location.
*
@@ -110,23 +119,5 @@ public interface ILocationService {
@RolesAllowed({Roles.USER, Roles.ADMIN})
Response getDeviceLocation(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* Returns all publicly available positions.
*
* @param pageConfig The page configuration.
* @return A page with positions.
*/
@GET
@Path("positions")
@ApiOperation(value = "Returns all positions.", authorizations = @Authorization(Authorizations.ADMIN), tags = {Tags.DEFAULT, Tags.SERVICE})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = PositionPage.class),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for retrieval."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN})
Response getPositions(@BeanParam @Valid PageConfig pageConfig);
}
@@ -18,7 +18,7 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Represents a location update conisting of a batch of locations.
* Represents a location update consisting of a batch of locations.
*
* @author Marcus
*/
@@ -1,5 +1,8 @@
package com.maptology.api.location;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@@ -7,7 +10,8 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* A detailled location
* A detailed location with usage approved or prohibited
* by the user.
*
* @author Marcus
*/
@@ -28,41 +32,65 @@ public class ReleasedLocation extends DetailedLocation {
@XmlAttribute(required=true)
@ApiModelProperty(value="A boolean value to mark the update as analyzable to compute places and visits.", required=true)
private boolean analyzable;
/**
* Additional metadata about the position.
*/
@XmlAttribute(required=false)
@ApiModelProperty(value="Additional data about the position such as readings from other sensors.", required=false)
private Map<String, String> metadata = new HashMap<>();
/**
* Returns the sharable.
* Returns the sharable flag.
*
* @return The sharable.
* @return The sharable flag.
*/
public boolean isSharable() {
return sharable;
}
/**
* Sets the sharable.
* Sets the sharable flag.
*
* @param sharable The sharable to set.
* @param sharable The sharable flag to set.
*/
public void setSharable(boolean sharable) {
this.sharable = sharable;
}
/**
* Returns the analyzable.
* Returns the analyzable flag.
*
* @return The analyzable.
* @return The analyzable flag.
*/
public boolean isAnalyzable() {
return analyzable;
}
/**
* Sets the analyzable.
* Sets the analyzable flag.
*
* @param analyzable The analyzable to set.
* @param analyzable The analyzable flag to set.
*/
public void setAnalyzable(boolean analyzable) {
this.analyzable = analyzable;
}
/**
* Returns the meta data collected for the location.
*
* @return The meta data collected for the location.
*/
public Map<String, String> getMetadata() {
return metadata;
}
/**
* Sets the meta data collected for the location.
*
* @param metadata The meta data for the location.
*/
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
}
@@ -0,0 +1,129 @@
package com.maptology.api.position;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.maptology.api.PageConfig;
import com.maptology.api.Tags;
import com.maptology.api.access.Authorizations;
import com.maptology.api.access.Roles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
/**
* A service to access and upload positions.
*
* @author Marcus
*/
@Api
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/")
public interface IPositionService {
/**
* Returns all publicly available positions.
*
* @param pageConfig The page configuration.
* @param metadata A flag to control whether metadata is included.
* @return A page with positions.
*/
@GET
@Path("positions")
@ApiOperation(value = "Returns all positions.", authorizations = @Authorization(Authorizations.ADMIN), tags = {Tags.DEFAULT, Tags.POSITION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = PositionPage.class),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for retrieval."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN})
Response getPositions(@BeanParam @Valid PageConfig pageConfig, @ApiParam(value="Controls whether metadata is included, if available.") @QueryParam("metadata") @DefaultValue("false") boolean metadata);
/**
* Adds the positions for the specified device.
*
* @param id The device id.
* @param update The position update to add.
* @return Ok, if successful.
*/
@POST
@Path("devices/{id: [0-9]+}/positions")
@ApiOperation(value = "Adds all positions for the device.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.SCIENTIST), @Authorization(Authorizations.DEVICE)}, tags = {Tags.DEFAULT, Tags.POSITION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful."),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for upload."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST})
Response addDevicePositions(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id, @ApiParam("The batch position update to add.") @NotNull @Valid PositionUpdate update);
/**
* Returns a page with positions for a particular device.
*
* @param id The id of the device.
* @param pageConfig The page configuration.
* @param metadata A flag to include or exclude metadata.
* @return A page of positions for a particular device.
*/
@GET
@Path("devices/{id: [0-9]+}/positions")
@ApiOperation(value = "Returns all positions for a particular device.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.SCIENTIST)}, tags = {Tags.DEFAULT, Tags.POSITION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = PositionPage.class),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for retrieval."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST})
Response getDevicePositions(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id,
@BeanParam @Valid PageConfig pageConfig, @ApiParam(value="Controls whether metadata is included, if available.") @QueryParam("metadata") @DefaultValue("false") boolean metadata);
/**
* Returns the positions of a particular device in a certain time range.
*
* @param id The id of the user.
* @param start The start time.
* @param duration The duration.
* @param metadata A flag to control whether to include the metadata.
* @return The positions of the device in the time range.
*/
@GET
@Path("device/{id: [0-9]+}/positions/range")
@ApiOperation(value = "Returns the position for the device in a certain time range.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.SCIENTIST)}, tags = {Tags.DEFAULT, Tags.POSITION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = Position.class, responseContainer = "List"),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for retrieval."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST})
Response getDevicePositionsRange(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id,
@ApiParam(value="The start time in Epoch milliseconds.", required=true) @QueryParam("start") @Valid long start,
@ApiParam(value="The duration in milliseconds.", required=true) @QueryParam("duration") @Valid @Min(0) @Max(48*60*60*1000) @DefaultValue("86400000") long duration,
@ApiParam(value="Controls whether metadata is included, if available.") @QueryParam("metadata") @DefaultValue("false") boolean metadata);
}
@@ -1,9 +1,13 @@
package com.maptology.api.location;
package com.maptology.api.position;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.maptology.api.device.OperatingSystem;
import com.maptology.api.location.DetailedLocation;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -44,6 +48,14 @@ public class Position extends DetailedLocation {
@XmlAttribute(required=true)
@ApiModelProperty(value="A unique position id.", required=true)
private long id;
/**
* Additional metadata about the position.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="Additional data about the position such as readings from other sensors.", required=true)
private Map<String, String> metadata = new HashMap<>();
/**
* Returns the device.
@@ -117,4 +129,22 @@ public class Position extends DetailedLocation {
this.id = id;
}
/**
* Returns the meta data collected for the position.
*
* @return The meta data collected for the position.
*/
public Map<String, String> getMetadata() {
return metadata;
}
/**
* Sets the meta data collected for the position.
*
* @param metadata The meta data for the position.
*/
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
}
@@ -1,4 +1,4 @@
package com.maptology.api.location;
package com.maptology.api.position;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
@@ -0,0 +1,106 @@
package com.maptology.api.position;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* A position update provided by a data logger.
*
* @author Marcus
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@ApiModel(description="Represents a position update conisting of a batch of positions.")
public class PositionUpdate {
@NotNull
@Valid
@XmlElementWrapper
@XmlElement(name="position")
@JsonProperty(value="positions") // force jackson to keep the name
@ApiModelProperty(value="The positions released with this update.", required=true)
private List<Position> positions = new ArrayList<>();
/**
* A boolean value to mark the position update as analyzable.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="A boolean value to mark the update as analyzable to compute places and visits.", required=true)
private boolean analyzable;
/**
* Creates a position update.
*/
public PositionUpdate() {
super();
}
/**
* Creates a position update with the specified positions.
*
* @param positions The positions to add.
* @param analyzable True to compute visits and places.
*/
public PositionUpdate(Collection<Position> positions, boolean analyzable) {
this.positions = new ArrayList<>(positions);
this.analyzable = analyzable;
}
/**
* Returns the positions.
*
* @return The positions.
*/
public List<Position> getPositions() {
return positions;
}
/**
* Sets the positions.
*
* @param positions The positions to set.
*/
public void setPositions(List<Position> positions) {
this.positions = positions;
}
/**
* Returns the analyzable.
*
* @return The analyzable.
*/
public boolean isAnalyzable() {
return analyzable;
}
/**
* Sets the analyzable.
*
* @param analyzable The analyzable to set.
*/
public void setAnalyzable(boolean analyzable) {
this.analyzable = analyzable;
}
}
@@ -0,0 +1,7 @@
/**
* This package defines services and data types for data
* logging and analysis.
*
* @author Marcus
*/
package com.maptology.api.position;
+2 -1
View File
@@ -1,2 +1,3 @@
android.enableJetifier=true
android.useAndroidX=true
android.useAndroidX=true
android.enableR8=true
Binary file not shown.
@@ -1,7 +1,11 @@
package com.maptology.service.conversion;
import java.util.HashMap;
import java.util.Map;
import com.maptology.api.location.Coordinate;
import com.maptology.api.location.Position;
import com.maptology.api.position.Position;
import com.maptology.service.entity.MetadataEntity;
import com.maptology.service.entity.PositionEntity;
/**
@@ -10,6 +14,20 @@ import com.maptology.service.entity.PositionEntity;
* @author Marcus
*/
public class PositionConverter extends AbstractConverter<PositionEntity, Position> {
/**
* A flag to include or exclude meta data. True to include.
*/
private boolean metadata;
/**
* Creates a position converter that includes or excludes the meta datta.
*
* @param metadata True to include, false to exclude meta data.
*/
public PositionConverter(boolean metadata) {
this.metadata = metadata;
}
@Override
public Position create() {
@@ -27,6 +45,13 @@ public class PositionConverter extends AbstractConverter<PositionEntity, Positio
if (source.getCoordinate() != null) {
p.setCoordinate(new Coordinate(source.getCoordinate().getLongitude(), source.getCoordinate().getLatitude()));
}
Map<String, String> metadata = new HashMap<>();
if (this.metadata) {
for (MetadataEntity e: source.getMetadata()) {
metadata.put(e.getTag(), e.getValue());
}
}
p.setMetadata(metadata);
p.setCreationTime(source.getCreationTime());
p.setDevice(source.getDevice());
p.setId(source.getId());
@@ -0,0 +1,113 @@
package com.maptology.service.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Index;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
* Represents metadata attached to a position. The metadata consist of
* a tag-value pair. The value is stored as a clob to allow large metadata
* items.
*
* @author Marcus
*/
@Entity
@Table(name = "metadata",
indexes = {
@Index(columnList = "tag", unique = false)
})
@NamedQueries({
})
@IdClass(MetadataId.class)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class MetadataEntity {
/**
* The reference to the position.
*/
@Id
@NotNull
@JoinColumn(name = "position_id")
@ManyToOne(optional = false)
private PositionEntity position;
/**
* The tag to determine the metadata type.
*/
@Id
@NotNull
@Column(name="tag", length = 64)
private String tag;
/**
* The value with the actual metadata.
*/
@Lob
@Column(name="value")
private String value;
/**
* Returns the position.
*
* @return The position.
*/
public PositionEntity getPosition() {
return position;
}
/**
* Sets the position.
*
* @param position The position to set.
*/
public void setPosition(PositionEntity position) {
this.position = position;
}
/**
* Returns the tag.
*
* @return The tag.
*/
public String getTag() {
return tag;
}
/**
* Sets the tag.
*
* @param tag The tag to set.
*/
public void setTag(String tag) {
this.tag = tag;
}
/**
* Returns the value.
*
* @return The value.
*/
public String getValue() {
return value;
}
/**
* Sets the value.
*
* @param value The value to set.
*/
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,84 @@
package com.maptology.service.entity;
import java.io.Serializable;
/**
* The composite id class for the metadata entity.
*
* @author Marcus
*/
public class MetadataId implements Serializable {
/**
* The serialization version.
*/
private static final long serialVersionUID = 369357479470919114L;
/**
* The position entity that the metadata is attached to.
*/
private PositionEntity position;
/**
* The tag that identifies the type of metadata.
*/
private String tag;
/**
* Creates a new id with null values.
*/
public MetadataId() {
super();
}
/**
* Creates a new id with the specified position and tag.
*
* @param position The position.
* @param tag The tag.
*/
public MetadataId(PositionEntity position, String tag) {
this.position = position;
this.tag = tag;
}
/**
* Returns the position.
*
* @return The position.
*/
public PositionEntity getPosition() {
return position;
}
/**
* Returns the tag.
*
* @return The tag.
*/
public String getTag() {
return tag;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) return false;
MetadataId e = (MetadataId)obj;
if (e.position == null && position != null || position == null && e.position != null) return false;
if (e.position != null && position.getId() != e.position.getId()) return false;
if (e.tag == null && tag != null || tag == null && e.tag == null) return false;
return e.tag == null || e.tag.equals(tag);
}
@Override
public int hashCode() {
int code = 0;
if (position != null) {
code = ((int)(position.getId()) ^ (int)(position.getId() >> 32));
}
if (tag != null) {
code = 31 * code + tag.hashCode();
}
return code;
}
}
@@ -1,6 +1,8 @@
package com.maptology.service.entity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
@@ -10,6 +12,7 @@ import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@@ -20,6 +23,7 @@ import javax.persistence.LockModeType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.NoResultException;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@@ -29,6 +33,7 @@ import com.maptology.api.PageConfig;
import com.maptology.api.device.OperatingSystem;
import com.maptology.api.location.Availability;
/**
* Represents a stored location that has been made available
* for research purposes.
@@ -38,12 +43,17 @@ import com.maptology.api.location.Availability;
@Entity
@Table(name = "position",
indexes = {
@Index(columnList = "creationTime,timestamp", unique = false)
@Index(columnList = "creationTime,timestamp", unique = false),
@Index(columnList = "device,timestamp", unique = false)
})
@NamedQueries({
@NamedQuery(name="findAllPositions", lockMode=LockModeType.NONE, query="select p from PositionEntity p order by p.id asc"),
@NamedQuery(name="getLastPosition", lockMode=LockModeType.NONE, query="select max(p.creationTime) from PositionEntity p"),
@NamedQuery(name="countPositions", lockMode=LockModeType.NONE, query="select count(p) from PositionEntity p")
@NamedQuery(name="countPositions", lockMode=LockModeType.NONE, query="select count(p) from PositionEntity p"),
@NamedQuery(name="findDeviceRangePositions", lockMode=LockModeType.NONE, query="select p from PositionEntity p where p.timestamp>=:minTime and p.timestamp<=:maxTime and p.device in :devices order by p.device, p.timestamp asc"),
@NamedQuery(name="findDevicePositions", lockMode=LockModeType.NONE, query="select p from PositionEntity p where p.device=:device order by p.id asc"),
@NamedQuery(name="countDevicePositions", lockMode=LockModeType.NONE, query="select count(p) from PositionEntity p where p.device=:device"),
@NamedQuery(name="getLastDevicePosition", lockMode=LockModeType.NONE, query="select max(p.creationTime) from PositionEntity p where p.device=:device")
})
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@SequenceGenerator(name = "pid_generator", sequenceName = "PID_GENERATOR", initialValue = 1, allocationSize = 50)
@@ -128,6 +138,12 @@ public class PositionEntity {
*/
private int version;
/**
* Additional meta data collected for the position.
*/
@OneToMany(mappedBy = "position", fetch = FetchType.LAZY)
private Set<MetadataEntity> metadata = new HashSet<>();
/**
* Automatically sets the creation date.
*/
@@ -352,6 +368,24 @@ public class PositionEntity {
this.version = version;
}
/**
* Returns the metadata.
*
* @return The metadata.
*/
public Set<MetadataEntity> getMetadata() {
return metadata;
}
/**
* Sets the metadata.
*
* @param metadata The metadata to set.
*/
public void setMetadata(Set<MetadataEntity> metadata) {
this.metadata = metadata;
}
/**
* Returns the last creation time of the position.
*
@@ -401,4 +435,77 @@ public class PositionEntity {
return q.getResultList();
}
/**
* Returns the last creation date of a position for the device.
*
* @param em The entity manager.
* @param device The device to search.
* @return The creation time stamp of the last position for the device.
*/
public static long getLastDevice(EntityManager em, long device) {
TypedQuery<Long> q = em.createNamedQuery("getLastDevicePosition", Long.class);
q.setParameter("device", device);
try {
Long result = q.getSingleResult();
if (result == null) return 0;
else return result;
} catch (NoResultException e) {
return 0;
}
}
/**
* Returns the number of positions for a device.
*
* @param em The entity manager.
* @param device The device to search.
* @return The number of positions.
*/
public static long getCountDevice(EntityManager em, long device) {
TypedQuery<Long> q = em.createNamedQuery("countDevicePositions", Long.class);
q.setParameter("device", device);
try {
Long result = q.getSingleResult();
if (result == null) return 0;
else return result;
} catch (NoResultException e) {
return 0;
}
}
/**
* Returns a page of positions for the device.
*
* @param em The entity manager.
* @param device The device.
* @param page The page.
* @return The page contents.
*/
public static List<PositionEntity> findByDevice(EntityManager em, long device, PageConfig page) {
TypedQuery<PositionEntity> q = em.createNamedQuery("findDevicePositions", PositionEntity.class);
q.setParameter("device", device);
q.setFirstResult(page.getOffset());
q.setMaxResults(page.getSize());
return q.getResultList();
}
/**
* Find the positions for a certain set of devices in the specified time range.
*
* @param em The entity manager.
* @param devices The devices to search.
* @param start The minimum time to return (inclusive) in epoch milliseconds.
* @param duration The duration to return in milliseconds.
* @return The positions for the devices in the time range.
*/
public static List<PositionEntity> findByDeviceAndRange(EntityManager em, Set<Long> devices, long start, long duration) {
TypedQuery<PositionEntity> q = em.createNamedQuery("findDeviceRangePositions", PositionEntity.class);
q.setParameter("devices", devices);
q.setParameter("minTime", start);
q.setParameter("maxTime", start + duration);
return q.getResultList();
}
}
@@ -51,13 +51,13 @@ public class LoginManager {
public User login(String login, String password) {
UserEntity entity = UserEntity.findByLogin(em, login);
if (entity == null) {
log.log(Level.INFO, "User '" + login + "' does not exist.");
log.log(Level.SEVERE, "User '" + login + "' does not exist.");
} else if (entity.isDeleted()) {
log.log(Level.INFO, "User '" + login + "' is deleted.");
log.log(Level.SEVERE, "User '" + login + "' is deleted.");
} else if (entity.isSuspended()) {
log.log(Level.INFO, "User '" + login + "' is suspended.");
log.log(Level.SEVERE, "User '" + login + "' is suspended.");
} else if(!isEmailVerified(entity)){
log.log(Level.INFO, "User '" + login + "' has no verified email.");
log.log(Level.SEVERE, "User '" + login + "' has no verified email.");
}
else {
SecureHash hash = new SecureHash(entity.getIterations(), entity.getSalt(), entity.getHash());
@@ -66,7 +66,7 @@ public class LoginManager {
UserConverter c = new UserConverter(true);
return c.convert(entity);
} else {
log.log(Level.INFO, "User '" + login + "' provided wrong password.");
log.log(Level.SEVERE, "User '" + login + "' provided wrong password.");
}
}
return null;
@@ -96,15 +96,15 @@ public class LoginManager {
log.log(Level.INFO, "Validating device token");
DeviceEntity entity = DeviceEntity.findByToken(em, token);
if (entity == null) {
log.log(Level.INFO, "Device '" + token + "' does not exist.");
log.log(Level.SEVERE, "Device '" + token + "' does not exist.");
} else if (entity.isDeleted()) {
log.log(Level.INFO, "Device '" + token + "' is deleted.");
log.log(Level.SEVERE, "Device '" + entity.getId() + "' is deleted.");
} else if (entity.getUser() != null && entity.getUser().isDeleted()) {
log.log(Level.INFO, "User '" + entity.getUser().getLogin() + "' is deleted.");
log.log(Level.SEVERE, "User '" + entity.getUser().getLogin() + "' is deleted.");
} else if (entity.getUser() != null && entity.getUser().isSuspended()) {
log.log(Level.INFO, "User '" + entity.getUser().getLogin() + "' is suspended.");
log.log(Level.SEVERE, "User '" + entity.getUser().getLogin() + "' is suspended.");
} else {
log.log(Level.INFO, "Device '" + token + "' authenticated.");
log.log(Level.INFO, "Device '" + entity.getId() + "' authenticated.");
DeviceConverter c = new DeviceConverter(true);
return c.convert(entity);
}
@@ -5,8 +5,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.ejb.Stateless;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.EntityManager;
@@ -22,11 +22,10 @@ import com.maptology.service.entity.UserEntity;
*
* @author Marcus
*/
@Stateful
@RequestScoped
@Stateless
@Dependent
public class DataSessionBean implements IDataSessionBean {
@Inject
protected Logger log;
@@ -50,6 +49,7 @@ public class DataSessionBean implements IDataSessionBean {
addRole(Roles.ADMIN, "Grants admin privileges.");
addRole(Roles.USER, "Grants user privileges.");
addRole(Roles.DEVICE, "Grants device privileges.");
addRole(Roles.SCIENTIST, "Grants scientist privileges.");
}
/**
@@ -82,7 +82,6 @@ public class DataSessionBean implements IDataSessionBean {
protected void initUsers() {
log.log(Level.INFO, "Initializing users.");
initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new String[] { Roles.ADMIN, Roles.USER});
initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER });
}
/**
@@ -106,6 +105,16 @@ public class DataSessionBean implements IDataSessionBean {
}
}
/**
* Creates a user with the specified settings.
*
* @param login The login name.
* @param name The user name.
* @param password The password.
* @param email The email address.
* @param roles The user roles.
* @return The user entity.
*/
protected UserEntity createUser(String login, String name, String password, String email, String[] roles) {
UserEntity u = new UserEntity();
u.setLogin(login);
@@ -125,6 +134,14 @@ public class DataSessionBean implements IDataSessionBean {
return u;
}
/**
* Creates an email for a user.
*
* @param u The user.
* @param email The email address.
* @param verified True to set verified.
* @param correspondence True to make correspondence.
*/
protected void createEmail(UserEntity u, String email, boolean verified, boolean correspondence) {
EmailEntity e = new EmailEntity();
e.setUser(u);
@@ -3,8 +3,8 @@ package com.maptology.service.session;
import java.util.logging.Level;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.ejb.Stateless;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
import com.maptology.api.access.Roles;
@@ -18,16 +18,17 @@ import com.maptology.service.entity.UserEntity;
* @author Marcus
*/
@Alternative
@Stateful
@RequestScoped
@Stateless
@Dependent
public class DebugDataSessionBean extends DataSessionBean implements IDataSessionBean {
@PermitAll
@Override
public void init() {
super.init();
initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER, Roles.SCIENTIST });
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 });
createUser("intruder", "The intruder", "secure", "no-reply@handte.org", new String[] { Roles.USER, Roles.SCIENTIST });
}
@Override
@@ -1,5 +1,7 @@
package com.maptology.service.session;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -13,9 +15,12 @@ import javax.inject.Inject;
import com.maptology.api.PageConfig;
import com.maptology.api.access.Roles;
import com.maptology.api.location.PositionPage;
import com.maptology.api.location.ReleasedLocation;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionPage;
import com.maptology.api.position.PositionUpdate;
import com.maptology.service.entity.DeviceEntity;
import com.maptology.service.entity.EntityForbiddenException;
/**
* A position session bean for debugging that does not connect
@@ -26,7 +31,7 @@ import com.maptology.service.entity.DeviceEntity;
@Stateful
@RequestScoped
@Alternative
@DeclareRoles(Roles.ADMIN)
@DeclareRoles({Roles.DEVICE, Roles.ADMIN, Roles.SCIENTIST })
public class DebugPositionSessionBean implements IPositionSessionBean {
@Inject
@@ -34,23 +39,61 @@ public class DebugPositionSessionBean implements IPositionSessionBean {
@Override
@PermitAll
public void addPosition(DeviceEntity device, ReleasedLocation location) {
public void addDevicePosition(DeviceEntity device, ReleasedLocation location) {
log.log(Level.INFO, "Received location from " + device.getId() + " from time " + location.getTimestamp());
}
@Override
@RolesAllowed({Roles.ADMIN, Roles.DEVICE })
public void addDevicePositions(long device, PositionUpdate update) throws EntityForbiddenException {
log.log(Level.INFO, "Received " + update.getPositions().size() + " positions from " + device + ".");
}
@Override
@RolesAllowed(Roles.ADMIN)
public PositionPage getPositions(PageConfig pageConfig) {
public PositionPage getPositions(PageConfig pageConfig, boolean metadata) {
PositionPage empty = new PositionPage();
empty.setOffset(pageConfig.getOffset());
empty.setSize(pageConfig.getSize());
return empty;
}
@Override
public long getPositionCount() {
return 0;
}
@Override
@RolesAllowed(Roles.ADMIN)
public long getLastModifiedPosition() {
return 0;
}
@Override
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST })
public PositionPage getDevicePositions(long device, PageConfig pageConfig, boolean meta) throws EntityForbiddenException {
PositionPage empty = new PositionPage();
empty.setOffset(pageConfig.getOffset());
empty.setSize(pageConfig.getSize());
return empty;
}
@Override
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST })
public long getDevicePositionCount(long device) {
return 0;
}
@Override
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST })
public long getLastModifiedDevicePosition(long device) {
return 0;
}
@Override
@RolesAllowed({Roles.ADMIN, Roles.SCIENTIST })
public List<Position> getDevicePositionsRange(long userId, long start, long duration, boolean metadata) throws EntityForbiddenException {
return new ArrayList<Position>();
}
}
@@ -59,22 +59,24 @@ public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
/**
* Connects a device that has been created without user account with
* an existing user account.
*
*
* @param device The device.
* @return The device, if successful.
* @throws EntityForbiddenException Thrown if the user or device is not valid.
* @throws EntityConflictException Thrown if the device is already connected with
* a user account.
*/
@RolesAllowed({Roles.DEVICE, Roles.USER})
public Device setCurrentDeviceUser() throws EntityForbiddenException, EntityConflictException {
DeviceEntity device = getPrincipalDevice();
public Device setCurrentUserDevice(Device device) throws EntityForbiddenException, EntityConflictException {
DeviceEntity principalDevice = getPrincipalDevice();
UserEntity user = getPrincipalUser();
if (device == null) throw new EntityForbiddenException(DeviceEntity.class, null);
if (user == null) throw new EntityForbiddenException(UserEntity.class, null);
if (device.getUser() != null) throw new EntityConflictException(DeviceEntity.class, device.getId());
device.setUser(user);
if (principalDevice == null) throw new EntityForbiddenException(DeviceEntity.class, null, "Cannot find principal device.");
if (user == null) throw new EntityForbiddenException(UserEntity.class, null, "Cannot find principal user.");
if (device.getId() != principalDevice.getId()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Invalid device specification.");
if (principalDevice.getUser() != null) throw new EntityConflictException(DeviceEntity.class, principalDevice.getId());
principalDevice.setUser(user);
em.flush();
return new DeviceConverter(true).convert(device);
return new DeviceConverter(true).convert(principalDevice);
}
@@ -129,11 +131,36 @@ public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
*/
@RolesAllowed({Roles.USER})
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered) throws EntityNotFoundException {
UserEntity user = getPrincipalUser();
if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
return getAllForUser(DeviceEntity.class, user, pageConfig, new OrderCriterion("id"), filtered, new DevicePage(), new DeviceConverter(filtered));
UserEntity user = getPrincipalUser();
if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
return getAllForUser(DeviceEntity.class, user, pageConfig, new OrderCriterion("id"), filtered, new DevicePage(), new DeviceConverter(filtered));
}
/**
* Returns all devices for the user with the specified id.
*
* @param userId The user id.
* @param pageConfig The page config.
* @param filtered True to filter deleted, false to return all devices.
* @return The page of devices.
* @throws EntityNotFoundException Thrown if the user cannot be found.
* @throws EntityForbiddenException Thrown if a non-admin user tries to access some other user.
*/
@RolesAllowed({Roles.ADMIN, Roles.USER})
public DevicePage getAllDevicesForUser(long userId, PageConfig pageConfig, boolean filtered) throws EntityNotFoundException, EntityForbiddenException {
UserEntity user = em.find(UserEntity.class, userId);
if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find user " + userId + ".");
if (!sessionContext.isCallerInRole(Roles.ADMIN)) {
UserEntity e = getPrincipalUser();
if (e == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user.");
if (e.getId() != user.getId()) throw new EntityForbiddenException(UserEntity.class, userId, "User is not allowed to access other user.");
}
return getAllForUser(DeviceEntity.class, user, pageConfig, new OrderCriterion("id"), filtered, new DevicePage(), new DeviceConverter(filtered));
}
/**
* Returns the last modification time for the devices of the current user.
*
@@ -1,9 +1,15 @@
package com.maptology.service.session;
import java.util.List;
import com.maptology.api.PageConfig;
import com.maptology.api.location.PositionPage;
import com.maptology.api.location.ReleasedLocation;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionPage;
import com.maptology.api.position.PositionUpdate;
import com.maptology.service.entity.DeviceEntity;
import com.maptology.service.entity.EntityForbiddenException;
import com.maptology.service.entity.EntityNotFoundException;
/**
* The interface for the session bean that stores
@@ -19,23 +25,84 @@ public interface IPositionSessionBean {
* @param device The device that created the location.
* @param location The location.
*/
void addPosition(DeviceEntity device, ReleasedLocation location);
void addDevicePosition(DeviceEntity device, ReleasedLocation location);
/**
* Adds the positions for the device.
*
* @param device The device.
* @param update The position update.
* @throws EntityForbiddenException Thrown if the operation is not allowed.
* @throws EntityNotFoundException Thrown if the device does not exist.
*/
void addDevicePositions(long device, PositionUpdate update) throws EntityForbiddenException, EntityNotFoundException;
/**
* Returns a position page for the configuration.
*
* @param pageConfig The page configuration.
* @param metadata A flag to include or exclude metadata.
* @return The page with the positions.
*/
PositionPage getPositions(PageConfig pageConfig);
PositionPage getPositions(PageConfig pageConfig, boolean metadata);
/**
* Returns the total number of positions.
*
* @return The total number of positions.
*/
long getPositionCount();
/**
* Returns the highest creation time stamp of the positions.
*
* @return The highest creaton time stamp.
* @return The highest creation time stamp.
*/
long getLastModifiedPosition();
/**
* Returns a position page for a particular device in a particular time range.
*
* @param device The device to search for.
* @param start The start range.
* @param duration The duration.
* @param pageConfig The page configuration.
* @param metadata A flag to control the retrieval of metadata.
* @return The position page.
* @throws EntityForbiddenException Thrown if the user is not allowed to access the positions.
* @throws EntityNotFoundException Thrown if the device does not exist.
*/
PositionPage getDevicePositions(long device, PageConfig pageConfig, boolean metadata) throws EntityForbiddenException, EntityNotFoundException;
/**
* Returns the number of positions for the device within the specified time range.
*
* @param device The device.
* @param start The start time in epoch millis.
* @param duration The duration in millis.
* @return The number of results.
*/
long getDevicePositionCount(long device);
/**
* Returns the last modification time stamp of positions for the device.
*
* @param device The device.
* @return The last modification time stamp.
*/
long getLastModifiedDevicePosition(long device);
/**
* Returns the positions of the specified user device in a certain time range.
*
* @param device The deviceId id to retrieve.
* @param start The start time in epoch milliseconds.
* @param duration The duration in milliseconds.
* @param metadata A flag to control the retrieval of metadata.
* @return The list of positions.
* @throws EntityForbiddenException Thrown if the user is not allowed to access the device.
* @throws EntityNotFoundException Thrown if the device cannot be found.
*/
List<Position> getDevicePositionsRange(long device, long start, long duration, boolean metadata) throws EntityForbiddenException, EntityNotFoundException;
}
@@ -14,13 +14,11 @@ import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import com.maptology.api.PageConfig;
import com.maptology.api.access.Roles;
import com.maptology.api.location.Availability;
import com.maptology.api.location.Coordinate;
import com.maptology.api.location.Location;
import com.maptology.api.location.LocationUpdate;
import com.maptology.api.location.PositionPage;
import com.maptology.api.location.ReleasedLocation;
import com.maptology.service.conversion.LocationConverter;
import com.maptology.service.entity.DeviceEntity;
@@ -97,7 +95,7 @@ public class LocationSessionBean extends AbstractPrincipalSessionBean {
}
// store the position in the secondary database, if allowed by user
if (location.isSharable()) {
positionSession.addPosition(device, location);
positionSession.addDevicePosition(device, location);
}
// check for too new updates (should only happen if clocks are out of sync)
if (location.getTimestamp() > offsetTime) {
@@ -294,30 +292,6 @@ public class LocationSessionBean extends AbstractPrincipalSessionBean {
return getShareLocation(privilege.getShare().getToken(), currentTime);
}
/**
* Returns a position page for the configuration.
*
* @param pageConfig The page configuration.
* @return The page.
*/
@RolesAllowed(Roles.ADMIN)
public PositionPage getPositions(PageConfig pageConfig) {
return positionSession.getPositions(pageConfig);
}
/**
* Returns the highest creation time stamp of the positions.
*
* @return The highest creaton time stamp.
*/
@RolesAllowed(Roles.ADMIN)
public long getLastModifiedPosition() {
return positionSession.getLastModifiedPosition();
}
/**
* Finds the closest place that is less than max distance away.
*
@@ -1,5 +1,11 @@
package com.maptology.service.session;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -7,6 +13,8 @@ import javax.annotation.Resource;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
@@ -16,11 +24,17 @@ import javax.transaction.UserTransaction;
import com.maptology.api.PageConfig;
import com.maptology.api.access.Roles;
import com.maptology.api.location.PositionPage;
import com.maptology.api.device.Device;
import com.maptology.api.location.ReleasedLocation;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionPage;
import com.maptology.api.position.PositionUpdate;
import com.maptology.service.conversion.PositionConverter;
import com.maptology.service.entity.DeviceEntity;
import com.maptology.service.entity.EmbeddedCoordinate;
import com.maptology.service.entity.EntityForbiddenException;
import com.maptology.service.entity.EntityNotFoundException;
import com.maptology.service.entity.MetadataEntity;
import com.maptology.service.entity.PositionEntity;
import com.maptology.service.injection.Public;
@@ -31,31 +45,53 @@ import com.maptology.service.injection.Public;
* @author Marcus
*/
@Stateless
@DeclareRoles(Roles.ADMIN)
@DeclareRoles({ Roles.DEVICE, Roles.ADMIN, Roles.SCIENTIST })
@TransactionManagement(TransactionManagementType.BEAN)
public class PositionSessionBean implements IPositionSessionBean {
/**
* The logger.
*/
@Inject
Logger log;
/**
* A user transaction to store and fetch data.
*/
@Resource
protected UserTransaction t;
/**
* The entity manager.
*/
@Public
@Inject
protected EntityManager em;
/**
* The session context to access the principal.
*/
@Resource
protected SessionContext sessionContext;
/**
* The device session bean to retrieve devices.
*/
@EJB
protected DeviceSessionBean deviceSession;
@Override
@PermitAll
public void addPosition(DeviceEntity device, ReleasedLocation location) {
public void addDevicePosition(DeviceEntity device, ReleasedLocation location) {
PositionEntity p = new PositionEntity();
p.setAccuracy(location.getAccuracy());
p.setAltitude(location.getAltitude());
p.setAvailability(location.getAvailability());
p.setBearing(location.getBearing());
if (location.getCoordinate() != null) {
p.setCoordinate(new EmbeddedCoordinate
(location.getCoordinate().getLongitude(), location.getCoordinate().getLatitude()));
p.setCoordinate(new EmbeddedCoordinate(location.getCoordinate().getLongitude(),
location.getCoordinate().getLatitude()));
}
p.setDevice(device.getId());
p.setOs(device.getOs());
@@ -63,40 +99,23 @@ public class PositionSessionBean implements IPositionSessionBean {
p.setSpeed(location.getSpeed());
p.setTimestamp(location.getTimestamp());
p.setVersion(location.getVersion());
try {
t.begin();
try {
em.persist(p);
} finally {
try {
t.commit();
} catch (Exception e) {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
HashSet<MetadataEntity> metadata = new HashSet<>();
if (location.getMetadata() != null) {
for (Entry<String, String> entry: location.getMetadata().entrySet()) {
MetadataEntity entity = new MetadataEntity();
entity.setPosition(p);
entity.setTag(entry.getKey());
entity.setValue(entry.getValue());
metadata.add(entity);
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
}
@Override
@RolesAllowed(Roles.ADMIN)
public long getLastModifiedPosition() {
return PositionEntity.getLast(em);
}
@Override
@RolesAllowed(Roles.ADMIN)
public PositionPage getPositions(PageConfig pageConfig) {
PositionPage page = new PositionPage();
page.setOffset(pageConfig.getOffset());
page.setSize(pageConfig.getSize());
}
p.setMetadata(metadata);
try {
t.begin();
try {
page.setTotal((int)PositionEntity.getCount(em));
if (page.getOffset() < page.getTotal()) {
page.setElements(new PositionConverter().convert(PositionEntity.findAll(em, pageConfig)));
em.persist(p);
for (MetadataEntity e: p.getMetadata()) {
em.persist(e);
}
} finally {
try {
@@ -105,11 +124,165 @@ public class PositionSessionBean implements IPositionSessionBean {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
}
@Override
@RolesAllowed(Roles.ADMIN)
public long getLastModifiedPosition() {
return PositionEntity.getLast(em);
}
@Override
@RolesAllowed(Roles.ADMIN)
public long getPositionCount() {
return PositionEntity.getCount(em);
}
@Override
@RolesAllowed(Roles.ADMIN)
public PositionPage getPositions(PageConfig pageConfig, boolean metadata) {
PositionPage page = new PositionPage();
page.setOffset(pageConfig.getOffset());
page.setSize(pageConfig.getSize());
try {
t.begin();
try {
page.setTotal((int) PositionEntity.getCount(em));
if (page.getOffset() < page.getTotal()) {
page.setElements(new PositionConverter(metadata).convert(PositionEntity.findAll(em, pageConfig)));
}
} finally {
try {
t.commit();
} catch (Exception e) {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
return page;
}
@Override
@RolesAllowed({ Roles.ADMIN, Roles.SCIENTIST })
public PositionPage getDevicePositions(long deviceId, PageConfig pageConfig, boolean metadata) throws EntityForbiddenException, EntityNotFoundException {
Device device = deviceSession.getDevice(deviceId);
PositionPage page = new PositionPage();
page.setOffset(pageConfig.getOffset());
page.setSize(pageConfig.getSize());
try {
t.begin();
try {
page.setTotal((int) PositionEntity.getCountDevice(em, device.getId()));
if (page.getOffset() < page.getTotal()) {
page.setElements(new PositionConverter(metadata)
.convert(PositionEntity.findByDevice(em, device.getId(), pageConfig)));
}
} finally {
try {
t.commit();
} catch (Exception e) {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
return page;
}
@Override
@RolesAllowed({ Roles.ADMIN, Roles.SCIENTIST })
public long getDevicePositionCount(long device) {
return PositionEntity.getCountDevice(em, device);
}
@Override
@RolesAllowed({ Roles.ADMIN, Roles.SCIENTIST })
public long getLastModifiedDevicePosition(long device) {
return PositionEntity.getLastDevice(em, device);
}
@Override
@RolesAllowed({ Roles.ADMIN, Roles.SCIENTIST })
public List<Position> getDevicePositionsRange(long deviceId, long start, long duration, boolean metadata) throws EntityForbiddenException, EntityNotFoundException {
Device device = deviceSession.getDevice(deviceId);
List<Position> results = new ArrayList<>();
PositionConverter converter = new PositionConverter(metadata);
try {
t.begin();
try {
List<PositionEntity> positions = PositionEntity.findByDeviceAndRange(em, Collections.singleton(device.getId()), start, duration);
results.addAll(converter.convert(positions));
} finally {
try {
t.commit();
} catch (Exception e) {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
return results;
}
@Override
@RolesAllowed({ Roles.ADMIN, Roles.SCIENTIST })
public void addDevicePositions(long deviceId, PositionUpdate update) throws EntityForbiddenException, EntityNotFoundException {
// check that user is admin or is accessing own device
// by loading the device from the device session bean
Device device = deviceSession.getDevice(deviceId);
log.log(Level.INFO, "Adding " + update.getPositions().size() + " positions for device " + deviceId + ".");
try {
t.begin();
try {
for (Position location : update.getPositions()) {
PositionEntity p = new PositionEntity();
p.setAccuracy(location.getAccuracy());
p.setAltitude(location.getAltitude());
p.setAvailability(location.getAvailability());
p.setBearing(location.getBearing());
if (location.getCoordinate() != null) {
p.setCoordinate(new EmbeddedCoordinate(location.getCoordinate().getLongitude(),
location.getCoordinate().getLatitude()));
}
p.setDevice(device.getId());
p.setOs(location.getOs());
p.setProvider(location.getProvider());
p.setSpeed(location.getSpeed());
p.setTimestamp(location.getTimestamp());
p.setVersion(location.getVersion());
em.persist(p);
if (p.getMetadata() != null) {
Set<MetadataEntity> data = new HashSet<>();
p.setMetadata(data);
for (Entry<String, String> meta : location.getMetadata().entrySet()) {
MetadataEntity m = new MetadataEntity();
m.setTag(meta.getKey());
m.setValue(meta.getValue());
m.setPosition(p);
data.add(m);
em.persist(m);
}
}
}
} finally {
try {
t.commit();
} catch (Exception e) {
log.log(Level.WARNING, "Failed to commit transaction.", e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to begin transaction.", e);
}
}
}
@@ -12,6 +12,7 @@ import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import com.maptology.api.access.Roles;
import com.maptology.api.log.EntityStatistic;
@@ -24,6 +25,7 @@ import com.maptology.service.entity.EmailEntity;
import com.maptology.service.entity.LocationEntity;
import com.maptology.service.entity.NoticeEntity;
import com.maptology.service.entity.PlaceEntity;
import com.maptology.service.entity.PositionEntity;
import com.maptology.service.entity.PrivilegeEntity;
import com.maptology.service.entity.RoleEntity;
import com.maptology.service.entity.ShareEntity;
@@ -50,6 +52,12 @@ public class StatisticsSessionBean extends AbstractSessionBean {
*/
private static final int NUMBER_NOT_AVAILABLE = -1;
/**
* The position session to retrieve position related statistics.
*/
@Inject
protected IPositionSessionBean positionSession;
/**
* The list of entities.
*/
@@ -77,6 +85,12 @@ public class StatisticsSessionBean extends AbstractSessionBean {
s.setTotal(total);
result.add(s);
}
// add position statistics
EntityStatistic positionStatistic = new EntityStatistic();
positionStatistic.setName(PositionEntity.class.getSimpleName());
positionStatistic.setDeleted(0);
positionStatistic.setTotal(positionSession.getPositionCount());
result.add(positionStatistic);
return result;
}
@@ -93,7 +93,7 @@ public class VisitSessionBean extends AbstractPrincipalSessionBean {
* @throws EntityForbiddenException Thrown if the user may not access the device.
*/
@RolesAllowed({Roles.ADMIN, Roles.USER})
public List<Visit> getDeviceVisits(long id, long beginTime, long endTime, boolean filtered) throws EntityNotFoundException, EntityForbiddenException {
public List<Visit> getDeviceVisitsRange(long id, long beginTime, long endTime, boolean filtered) throws EntityNotFoundException, EntityForbiddenException {
DeviceEntity device = em.find(DeviceEntity.class, id);
if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found.");
if (filtered && device.isDeleted()) throw new EntityNotFoundException(DeviceEntity.class, id, "Device is deleted.");
@@ -33,6 +33,7 @@
<jta-data-source>java:jboss/datasources/maptology-public</jta-data-source>
<class>com.maptology.service.entity.EmbeddedCoordinate</class>
<class>com.maptology.service.entity.PositionEntity</class>
<class>com.maptology.service.entity.MetadataEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
@@ -116,7 +116,7 @@ public class DeviceSessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
deviceSession.setCurrentDeviceUser();
deviceSession.setCurrentUserDevice(handle);
Assert.fail("Setting a device without user or device should fail.");
} catch (Exception e) {
Assert.assertEquals("Setting device without user or device should be forbidden.", EntityForbiddenException.class, e.getClass());
@@ -129,7 +129,7 @@ public class DeviceSessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
Device device = deviceSession.setCurrentDeviceUser();
Device device = deviceSession.setCurrentUserDevice(handle);
Assert.assertNotNull("Device user should be set after association.", device.getUser());
} catch (Exception e) {
Assert.fail("Setting a device user should succeed.");
@@ -140,7 +140,7 @@ public class DeviceSessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
deviceSession.setCurrentDeviceUser();
deviceSession.setCurrentUserDevice(handle);
Assert.fail("Setting a device user for a connected device should fail.");
} catch (Exception e) {
Assert.assertEquals("Setting a user for a connected device should raise conflict.", EntityConflictException.class, e.getClass());
@@ -88,7 +88,7 @@ public class HistorySessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
List<Visit> visits = visitSession.getDeviceVisits(handle.getId(), start, stop, false);
List<Visit> visits = visitSession.getDeviceVisitsRange(handle.getId(), start, stop, false);
Assert.assertEquals("Should have two visits.", 2, visits.size());
Assert.assertNotEquals("Should have different places.", visits.get(0).getPlace(), visits.get(1).getPlace());
List<Place> places = new ArrayList<>();
@@ -181,7 +181,7 @@ public class HistorySessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
List<Visit> visits = visitSession.getDeviceVisits(handle.getId(), start, stop, false);
List<Visit> visits = visitSession.getDeviceVisitsRange(handle.getId(), start, stop, false);
Assert.assertEquals("Should have no visits.", 0, visits.size());
} catch (Exception e) {
Assert.assertNull("Should not receive an exception.", e);
@@ -236,7 +236,7 @@ public class HistorySessionTest extends AbstractSessionTest {
@Override
public void run() {
try {
List<Visit> visits = visitSession.getDeviceVisits(handle.getId(), start, stop, false);
List<Visit> visits = visitSession.getDeviceVisitsRange(handle.getId(), start, stop, false);
Assert.assertEquals("Should have two visits.", 2, visits.size());
Assert.assertNotEquals("Should have different places.", visits.get(0).getPlace(), visits.get(1).getPlace());
List<Place> places = new ArrayList<>();
@@ -0,0 +1,221 @@
package com.maptology.service.test.session;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Inject;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.maptology.api.PageConfig;
import com.maptology.api.device.DeviceHandle;
import com.maptology.api.device.DeviceInfo;
import com.maptology.api.device.OperatingSystem;
import com.maptology.api.location.Availability;
import com.maptology.api.location.Coordinate;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionPage;
import com.maptology.api.position.PositionUpdate;
import com.maptology.service.entity.EntityForbiddenException;
import com.maptology.service.entity.EntityNotFoundException;
import com.maptology.service.session.DeviceSessionBean;
import com.maptology.service.session.IPositionSessionBean;
import com.maptology.service.session.UserSessionBean;
/**
* Runs test cases against the position session bean.
*
* @author Marcus
*/
@RunWith(Arquillian.class)
public class PositionSessionTest extends AbstractSessionTest {
@Inject
IPositionSessionBean positionSession;
@EJB
DeviceSessionBean deviceSession;
@EJB
UserSessionBean userSession;
/**
* Ensures that a user can add positions and retrieve the properly later on.
*/
@Test
public void testAddRetrievePositionsAsScientist() {
DeviceHandle handle = addDevice("handte");
executeAs("handte", new Runnable() {
@Override
public void run() {
Assert.assertEquals("New device should have no positions.", 0l, positionSession.getDevicePositionCount(handle.getId()));
// add one position
long now = System.currentTimeMillis();
Position p = newPosition(handle.getId(), now);
p.getMetadata().put("key", "value");
try {
positionSession.addDevicePositions(handle.getId(), new PositionUpdate(Collections.singletonList(p), false));
} catch (Exception e) {
Assert.fail("Add device positions should succeed.");
}
Assert.assertEquals("Device should have added position.", 1l, positionSession.getDevicePositionCount(handle.getId()));
try {
PositionPage page = positionSession.getDevicePositions(handle.getId(), new PageConfig(0, 20), true);
Assert.assertEquals("Page should have one position.", 1, page.getElements().size());
Position x = page.getElements().get(0);
assertEquals(p, x);
} catch (Exception e) {
Assert.fail("Retrieve device positions should succeed.");
}
// add 19 positions as batch
List<Position> positions = new ArrayList<Position>();
for (int i = 0; i < 19; i++) {
positions.add(p);
}
try {
positionSession.addDevicePositions(handle.getId(), new PositionUpdate(positions, true));
} catch (Exception e) {
Assert.fail("Add device positions should succeed.");
}
Assert.assertEquals("Device should have added positions.", 20l, positionSession.getDevicePositionCount(handle.getId()));
try {
PositionPage page = positionSession.getDevicePositions(handle.getId(), new PageConfig(0, 20), true);
Assert.assertEquals("Page should have 20 positions.", 20, page.getElements().size());
for (Position x: page.getElements()) {
assertEquals(p, x);
}
} catch (Exception e) {
Assert.fail("Retrieve device positions should succeed.");
}
}
});
}
/**
* Ensures that accesses to devices of other users are not allowed.
*/
@Test
public void testCanOnlyRetrieveOwnPositions() {
DeviceHandle handle = addDevice("admin");
executeAs("handte", new Runnable() {
@Override
public void run() {
try {
positionSession.getDevicePositions(handle.getId(), new PageConfig(0, 20), true);
Assert.fail("Should raise forbidden.");
} catch (EntityNotFoundException e) {
Assert.fail("Should raise forbidden.");
} catch (EntityForbiddenException e) {
Assert.assertNotNull("Should have forbidden exception.", e);
}
}
});
}
/**
* Ensures that accesses to non-existing devices fail with the proper exception.
*/
@Test
public void testCannotRetrieveInvalidDevice() {
executeAs("handte", new Runnable() {
@Override
public void run() {
try {
positionSession.getDevicePositions(-10, new PageConfig(0, 20), true);
Assert.fail("Should raise not found.");
} catch (EntityNotFoundException e) {
Assert.assertNotNull("Should have not found exception.", e);
} catch (EntityForbiddenException e) {
Assert.fail("Should raise not found.");
}
}
});
}
/**
* Ensures that the expected and the actual position are the same. The only
* field that is not checked is the creation time.
*
* @param expected The expected position.
* @param actual The actual position.
*/
protected void assertEquals(Position expected, Position actual) {
Assert.assertEquals("Accuracy should be set.", expected.getAccuracy(), actual.getAccuracy());
Assert.assertEquals("Altitude should be set.", expected.getAltitude(), actual.getAltitude());
Assert.assertEquals("Availability should be set.", expected.getAvailability(), actual.getAvailability());
Assert.assertEquals("Bearing should be set.", expected.getBearing(), actual.getBearing());
Assert.assertEquals("Longiutde should be set.", expected.getCoordinate().getLongitude(), actual.getCoordinate().getLongitude(), 0.001);
Assert.assertEquals("Latitude should be set.", expected.getCoordinate().getLatitude(), actual.getCoordinate().getLatitude(), 0.001);
Assert.assertEquals("Device should be set.", expected.getDevice(), actual.getDevice());
Assert.assertEquals("OS should be set.", expected.getOs(), actual.getOs());
Assert.assertEquals("Provider should be set.", expected.getProvider(), actual.getProvider());
Assert.assertEquals("Speed should be set.", expected.getSpeed(), actual.getSpeed());
Assert.assertEquals("Timestamp should be set.", expected.getTimestamp(), actual.getTimestamp());
Assert.assertEquals("Version should be set.", expected.getVersion(), actual.getVersion());
Assert.assertEquals("Metadata size should be same.", expected.getMetadata().size(), actual.getMetadata().size());
for (String key: expected.getMetadata().keySet()) {
String v1 = expected.getMetadata().get(key);
String v2 = actual.getMetadata().get(key);
Assert.assertEquals("Value for key: " + key + " should match.", v1, v2);
}
}
/**
* Creates a test position for the device with the specified time.
*
* @param device The device.
* @param time The creation time.
* @return The position.
*/
protected Position newPosition(long device, long time) {
Position p = new Position();
p.setAccuracy(1d);
p.setAltitude(2d);
p.setAvailability(Availability.FRESH);
p.setBearing(3d);
p.setCoordinate(new Coordinate(-1, -2));
p.setDevice(device);
p.setOs(OperatingSystem.ANDROID);
p.setProvider("gps");
p.setSpeed(4d);
p.setTimestamp(time);
p.setVersion(5);
return p;
}
/**
* Adds a device for the user.
*
* @param user The user login.
* @return The newly created device.
*/
protected DeviceHandle addDevice(String user) {
DeviceHandle[] device = new DeviceHandle[1];
executeAs(user, new Runnable() {
@Override
public void run() {
final DeviceInfo info = new DeviceInfo();
info.setDevice("device");
info.setManufacturer("manufacturer");
info.setModel("model");
info.setOs(OperatingSystem.ANDROID);
device[0] = deviceSession.addDevice(info);
}
});
Assert.assertNotNull("Handle should not be null.", device[0]);
return device[0];
}
}
@@ -9,8 +9,6 @@
<class>com.maptology.service.session.DebugDataSessionBean</class>
<!-- do not send email messages during testing -->
<class>com.maptology.service.session.DebugEmailSessionBean</class>
<!-- do not store any positions in the secondary database -->
<class>com.maptology.service.session.DebugPositionSessionBean</class>
</alternatives>
<weld:scan>
<weld:include name="com.maptology.service.**"/>
@@ -4,6 +4,22 @@
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="maptology-datastore" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>com.maptology.service.entity.AbstractEntity</class>
<class>com.maptology.service.entity.AbstractUserSpecificEntity</class>
<class>com.maptology.service.entity.CodeEntity</class>
<class>com.maptology.service.entity.DeviceEntity</class>
<class>com.maptology.service.entity.EmailEntity</class>
<class>com.maptology.service.entity.EmbeddedCoordinate</class>
<class>com.maptology.service.entity.EmbeddedMessage</class>
<class>com.maptology.service.entity.LocationEntity</class>
<class>com.maptology.service.entity.NoticeEntity</class>
<class>com.maptology.service.entity.PlaceEntity</class>
<class>com.maptology.service.entity.PrivilegeEntity</class>
<class>com.maptology.service.entity.RoleEntity</class>
<class>com.maptology.service.entity.ShareEntity</class>
<class>com.maptology.service.entity.UserEntity</class>
<class>com.maptology.service.entity.VisitEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="jboss.entity.manager.jndi.name" value="java:app/maptology/datastore"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
@@ -12,5 +28,13 @@
</persistence-unit>
<persistence-unit name="maptology-public" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>com.maptology.service.entity.EmbeddedCoordinate</class>
<class>com.maptology.service.entity.PositionEntity</class>
<class>com.maptology.service.entity.MetadataEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
@@ -71,11 +71,12 @@ public class GeocoderBuilder {
*
* @return The geo coder service.
*/
@SuppressWarnings("deprecation")
public IGeocoderService build() {
ResteasyClientBuilder builder = new ResteasyClientBuilder();
builder.httpEngine(new URLConnectionEngine());
if (socketTimeout != null) builder.readTimeout(socketTimeout, TimeUnit.SECONDS);
if (connectionTimeout != null) builder.connectTimeout(connectionTimeout, TimeUnit.SECONDS);
if (socketTimeout != null) builder.socketTimeout(socketTimeout,TimeUnit.SECONDS);
if (connectionTimeout != null) builder.establishConnectionTimeout(connectionTimeout, TimeUnit.SECONDS);
ResteasyClient client = builder.build();
return client.target(GEOCODER_URL).proxy(IGeocoderService.class);
}
@@ -43,8 +43,11 @@ public class MaptologyThorntailApplication extends MaptologyApplication {
user.setDescription("Operations requiring a valid user.");
BasicAuthDefinition admin = new BasicAuthDefinition();
admin.setDescription("Operations requiring admin privileges.");
BasicAuthDefinition scientist = new BasicAuthDefinition();
scientist.setDescription("Operations requiring scientist privileges.");
swagger.securityDefinition("user", user);
swagger.securityDefinition("admin", admin);
swagger.securityDefinition("scientist", scientist);
ApiKeyAuthDefinition device = new ApiKeyAuthDefinition("Authorization", In.HEADER);
swagger.securityDefinition("device", device);
beanConfig.configure(swagger);
@@ -28,6 +28,7 @@ public class MaptologyApplication extends Application {
classes.add(DeviceResource.class);
classes.add(ShareResource.class);
classes.add(LocationResource.class);
classes.add(PositionResource.class);
classes.add(PrivilegeResource.class);
classes.add(HistoryResource.class);
classes.add(ProcessingTimeFilter.class);
@@ -65,7 +65,6 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule {
if (headers != null) {
while (headers.hasMoreElements()) {
String header = headers.nextElement();
log.log(Level.SEVERE, "Found auth header: " + header);
String[] subHeaders = header.split(",");
for (String subHeader: subHeaders) {
subHeader = subHeader.trim();
@@ -101,7 +100,7 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule {
LoginManager manager = new LoginManager(em);
ta.begin();
if (deviceCredential != null) device = manager.login(deviceCredential.getToken());
if (userCredential != null) user = manager.login(userCredential.getUsername(), userCredential.getPassword());
if (userCredential != null) user = manager.login(userCredential.getUsername(), userCredential.getPassword());
} finally {
ta.commit();
}
@@ -129,7 +128,7 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule {
}
try {
MaptologyPrincipal principal = new MaptologyPrincipal(username + ":" + devicename, userId, deviceId);
log.log(Level.INFO, "Creating principal: " + principal);
log.log(Level.INFO, "Successful login for device(" + principal.getDevice() + ") and user(" + principal.getUser() + ").");
callbackHandler.handle(new Callback[]{
new CallerPrincipalCallback(clientSubject, principal),
new GroupPrincipalCallback(clientSubject, roles.toArray(new String[roles.size()]))
@@ -66,10 +66,10 @@ public class DeviceResource implements IDeviceService {
}
@Override
public Response setCurrentDeviceUser() {
public Response setCurrentUserDevice(Device device) {
try {
Device result = deviceSession.setCurrentDeviceUser();
return Response.ok(result).build();
Device result = deviceSession.setCurrentUserDevice(device);
return Response.ok(result).build();
} catch (EntityForbiddenException e) {
return Response.status(Status.FORBIDDEN).build();
} catch (EntityConflictException e) {
@@ -81,7 +81,7 @@ public class DeviceResource implements IDeviceService {
}
}
}
@Override
public Response getCurrentDevice() {
try {
@@ -141,9 +141,9 @@ public class HistoryResource implements IHistoryService {
}
@Override
public Response getDeviceVisits(long id, long start, long duration) {
public Response getDeviceVisitsRange(long id, long start, long duration) {
try {
List<Visit> visits = visitSession.getDeviceVisits(id, start, start + duration, !servletRequest.isUserInRole(Roles.ADMIN));
List<Visit> visits = visitSession.getDeviceVisitsRange(id, start, start + duration, !servletRequest.isUserInRole(Roles.ADMIN));
return Response.ok(visits).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
@@ -12,10 +12,8 @@ import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import com.maptology.api.PageConfig;
import com.maptology.api.location.ILocationService;
import com.maptology.api.location.Location;
import com.maptology.api.location.LocationUpdate;
@@ -109,17 +107,6 @@ public class LocationResource implements ILocationService {
}
}
@Override
public Response getPositions(PageConfig pageConfig) {
long time = locationSession.getLastModifiedPosition();
EntityTag tag = new EntityTag(Long.toString(time));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
b = Response.ok(locationSession.getPositions(pageConfig));
}
return b.tag(tag).build();
}
/**
* Computes an entity tag and a cache control header for a location and
* performs the associated precondition checks.
@@ -0,0 +1,124 @@
package com.maptology.service.rest;
import java.util.List;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import com.maptology.api.PageConfig;
import com.maptology.api.position.IPositionService;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionUpdate;
import com.maptology.service.entity.EntityForbiddenException;
import com.maptology.service.entity.EntityNotFoundException;
import com.maptology.service.session.IPositionSessionBean;
/**
* The resource for the position service.
*
* @author Marcus
*/
@RequestScoped
public class PositionResource implements IPositionService {
/**
* The session bean to access positions.
*/
@Inject
IPositionSessionBean positionSession;
/**
* The request that will be injected by the jax-rs runtime.
*/
@Context
Request request;
/**
* The uri info to build location urls.
*/
@Context
UriInfo uriInfo;
/**
* A logger injected by CDI.
*/
@Inject
Logger log;
@Override
public Response getPositions(PageConfig pageConfig, boolean metadata) {
long time = positionSession.getLastModifiedPosition();
EntityTag tag = new EntityTag(Long.toString(time));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
b = Response.ok(positionSession.getPositions(pageConfig, metadata));
}
return b.tag(tag).build();
}
@Override
public Response addDevicePositions(long id, PositionUpdate update) {
try {
positionSession.addDevicePositions(id, update);
return Response.ok().build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
} catch (EntityForbiddenException e) {
return Response.status(Status.FORBIDDEN).build();
}
}
@Override
public Response getDevicePositions(long id, PageConfig pageConfig, boolean metadata) {
try {
long time = positionSession.getLastModifiedDevicePosition(id);
EntityTag tag = new EntityTag(Long.toString(time));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
b = Response.ok(positionSession.getDevicePositions(id, pageConfig, metadata));
}
return b.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
} catch (EntityForbiddenException e) {
return Response.status(Status.FORBIDDEN).build();
}
}
@Override
public Response getDevicePositionsRange(long id, long start, long duration, boolean metadata) {
try {
List<Position> positions = positionSession.getDevicePositionsRange(id, start, duration, metadata);
long maxId = 0;
for (Position p: positions) {
maxId = Math.max(p.getId(), maxId);
}
EntityTag tag = new EntityTag(Long.toString(maxId));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
b = Response.ok(positions);
}
return b.tag(tag).build();
} catch (EntityNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
} catch (EntityForbiddenException e) {
return Response.status(Status.FORBIDDEN).build();
}
}
}
@@ -3,6 +3,7 @@ package com.maptology.service.test.rest;
import org.junit.Assert;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
/**
@@ -24,7 +25,7 @@ public final class AssertResponse {
*/
public static void isStatus(Response response, Response.Status expected) {
try {
Assert.assertEquals("Should return status: " + expected, response.getStatus(), expected.getStatusCode());
Assert.assertEquals("Should return status: " + expected, expected.getStatusCode(), response.getStatus());
} catch (AssertionError e) {
logResponse(response);
throw e;
@@ -86,6 +87,24 @@ public final class AssertResponse {
}
}
/**
* Ensures that the body exhibits the expected generic type and reads its content.
*
* @param <T> The generic type to read.
* @param response The response.
* @param expectedClass The epxected type.
* @return The type.
*/
public static <T> T hasBody(Response response, GenericType<T> expectedClass) {
try {
response.bufferEntity();
return response.readEntity(expectedClass);
} catch (ProcessingException e) {
logResponse(response);
throw e;
}
}
/**
* Logs the response using standard out.
*
@@ -81,19 +81,23 @@ public class DeviceResourceTest extends AbstractResourceTest {
Response r = anonProxy.createDevice(createValidDeviceInfo());
AssertResponse.isStatus(r, Status.CREATED);
DeviceHandle d = AssertResponse.hasBody(r, DeviceHandle.class);
Response noDevice = userProxy.setCurrentDeviceUser();
Device bad = new Device();
bad.setOs(OperatingSystem.ANDROID);
Response noDevice = userProxy.setCurrentUserDevice(bad);
AssertResponse.isStatus(noDevice, Status.FORBIDDEN);
Response noUser = deviceProxy.setCurrentDeviceUser();
Response noUser = deviceProxy.setCurrentUserDevice(bad);
AssertResponse.isStatus(noUser, Status.FORBIDDEN);
IDeviceService deviceService = getTarget("handte", "secure", d.getToken()).proxy(IDeviceService.class);
Response ok = deviceService.setCurrentDeviceUser();
Response deviceResponse = deviceService.getCurrentDevice();
Device currentDevice = AssertResponse.hasBody(deviceResponse, Device.class);
Response ok = deviceService.setCurrentUserDevice(currentDevice);
AssertResponse.isStatus(ok, Status.OK);
Device device = AssertResponse.hasBody(ok, Device.class);
Assert.assertNotNull("User must be set.", device.getUser());
IUserService userService = getTarget("handte", "secure").proxy(IUserService.class);
User user = AssertResponse.hasBody(userService.getCurrentUser(), User.class);
Assert.assertEquals("User must be correct after update.", (long)user.getId(), (long)device.getUser());
Response conflict = deviceService.setCurrentDeviceUser();
Response conflict = deviceService.setCurrentUserDevice(device);
AssertResponse.isStatus(conflict, Status.CONFLICT);
Device result = AssertResponse.hasBody(conflict, Device.class);
Assert.assertNotNull("User must be set.", result.getUser());
@@ -0,0 +1,158 @@
package com.maptology.service.test.rest;
import java.util.Collections;
import java.util.List;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.maptology.api.PageConfig;
import com.maptology.api.device.DeviceHandle;
import com.maptology.api.device.DeviceInfo;
import com.maptology.api.device.IDeviceService;
import com.maptology.api.device.OperatingSystem;
import com.maptology.api.location.Availability;
import com.maptology.api.location.Coordinate;
import com.maptology.api.position.IPositionService;
import com.maptology.api.position.Position;
import com.maptology.api.position.PositionPage;
import com.maptology.api.position.PositionUpdate;
/**
* Tests the api of the position resource.
*
* @author Marcus
*/
@RunWith(Arquillian.class)
public class PositionResourceTest extends AbstractResourceTest {
/**
* A device handle for the user.
*/
private DeviceHandle deviceHandle;
/**
* Retrieves the user handte and creates a device.
*/
@Before
public void createTestDeviceAndUser() {
IDeviceService device = getTarget("handte", "secure").proxy(IDeviceService.class);
DeviceInfo info = new DeviceInfo();
info.setDevice("device");
info.setManufacturer("manufacturer");
info.setModel("model");
info.setOs(OperatingSystem.IOS);
Response handleResponse = device.createDevice(info);
AssertResponse.isStatus(handleResponse, Status.CREATED);
deviceHandle = AssertResponse.hasBody(handleResponse, DeviceHandle.class);
}
/**
* Ensures that positions can be uploaded by a device and fetched by a user.
*/
@Test
public void testUploadAndFetchPositions() {
IPositionService position = getTarget("handte", "secure").proxy(IPositionService.class);
long now = System.currentTimeMillis();
Position p = newPosition(deviceHandle.getId(), now);
Response addresponse = position.addDevicePositions(deviceHandle.getId(), new PositionUpdate(Collections.singletonList(p), true));
AssertResponse.isStatus(addresponse, Status.OK);
IPositionService userPosition = getTarget("handte", "secure").proxy(IPositionService.class);
Response pageresponse = userPosition.getDevicePositions(deviceHandle.getId(), new PageConfig(0, 20), true);
AssertResponse.isStatus(pageresponse, Status.OK);
PositionPage page = AssertResponse.hasBody(pageresponse, PositionPage.class);
Assert.assertEquals("Has one position.", 1, page.getElements().size());
assertEquals(p, page.getElements().get(0));
Response listresponse = userPosition.getDevicePositionsRange(deviceHandle.getId(), now - 1, 2, true);
AssertResponse.isStatus(listresponse, Status.OK);
List<Position> positions = AssertResponse.hasBody(listresponse, new GenericType<List<Position>>() { });
Assert.assertEquals("Has one position in time range.", 1, positions.size());
assertEquals(p, positions.get(0));
}
/**
* Ensures that a device cannot fetch its positions.
*/
@Test
public void testDeviceCannotFetchItsPositions() {
IPositionService position = getTarget(deviceHandle.getToken()).proxy(IPositionService.class);
Response failResponse = position.getDevicePositions(deviceHandle.getId(), new PageConfig(0, 20), true);
AssertResponse.isForbidden(failResponse);
Response fail2Response = position.getDevicePositionsRange(deviceHandle.getId(), System.currentTimeMillis() - 10000, 20000, true);
AssertResponse.isForbidden(fail2Response);
}
/**
* Ensures that another user cannot fetch positions.
*/
@Test
public void testOtherUserCannotFetchPositions() {
IPositionService position = getTarget("intruder", "secure").proxy(IPositionService.class);
Response failResponse = position.getDevicePositions(deviceHandle.getId(), new PageConfig(0, 20), true);
AssertResponse.isForbidden(failResponse);
Response fail2Response = position.getDevicePositionsRange(deviceHandle.getId(), System.currentTimeMillis() - 10000, 20000, true);
AssertResponse.isForbidden(fail2Response);
}
/**
* Ensures that the expected and the actual position are the same. The only
* field that is not checked is the creation time.
*
* @param expected The expected position.
* @param actual The actual position.
*/
protected void assertEquals(Position expected, Position actual) {
Assert.assertEquals("Accuracy should be set.", expected.getAccuracy(), actual.getAccuracy());
Assert.assertEquals("Altitude should be set.", expected.getAltitude(), actual.getAltitude());
Assert.assertEquals("Availability should be set.", expected.getAvailability(), actual.getAvailability());
Assert.assertEquals("Bearing should be set.", expected.getBearing(), actual.getBearing());
Assert.assertEquals("Longiutde should be set.", expected.getCoordinate().getLongitude(), actual.getCoordinate().getLongitude(), 0.001);
Assert.assertEquals("Latitude should be set.", expected.getCoordinate().getLatitude(), actual.getCoordinate().getLatitude(), 0.001);
Assert.assertEquals("Device should be set.", expected.getDevice(), actual.getDevice());
Assert.assertEquals("OS should be set.", expected.getOs(), actual.getOs());
Assert.assertEquals("Provider should be set.", expected.getProvider(), actual.getProvider());
Assert.assertEquals("Speed should be set.", expected.getSpeed(), actual.getSpeed());
Assert.assertEquals("Timestamp should be set.", expected.getTimestamp(), actual.getTimestamp());
Assert.assertEquals("Version should be set.", expected.getVersion(), actual.getVersion());
Assert.assertEquals("Metadata size should be same.", expected.getMetadata().size(), actual.getMetadata().size());
for (String key: expected.getMetadata().keySet()) {
String v1 = expected.getMetadata().get(key);
String v2 = actual.getMetadata().get(key);
Assert.assertEquals("Value for key: " + key + " should match.", v1, v2);
}
}
/**
* Creates a test position for the device with the specified time.
*
* @param device The device.
* @param time The creation time.
* @return The position.
*/
protected Position newPosition(long device, long time) {
Position p = new Position();
p.setAccuracy(1d);
p.setAltitude(2d);
p.setAvailability(Availability.FRESH);
p.setBearing(3d);
p.setCoordinate(new Coordinate(-1, -2));
p.setDevice(device);
p.setOs(OperatingSystem.ANDROID);
p.setProvider("gps");
p.setSpeed(4d);
p.setTimestamp(time);
p.setVersion(5);
return p;
}
}
View File
+6 -2
View File
@@ -14,7 +14,7 @@ import { MatButtonModule, MatIconModule,
MatListModule, MatPaginatorModule, MatTableModule,
MatPaginatorIntl, MatExpansionModule, MatSelectModule,
MatDatepickerModule, MatNativeDateModule,
MatTabsModule, MatGridListModule } from '@angular/material';
MatTabsModule, MatGridListModule, MatSliderModule } from '@angular/material';
import { LocationStrategy, PathLocationStrategy, registerLocaleData, DatePipe } from '@angular/common';
import LocaleDE from '@angular/common/locales/de';
@@ -87,6 +87,8 @@ import { VersionService } from './services/version.service';
import { ResourceService } from './services/resource.service';
import { ExportComponent } from './views/export.component';
import { ExportService } from './services/export.service';
import { DevicePositionService } from './services/device-position.service';
import { DevicePositionsComponent } from './views/device-positions.component';
/**
* Computes the api domain from the browser location.
@@ -147,6 +149,7 @@ registerLocaleData(LocaleDE);
NoticesComponent,
PlaceVisitsComponent,
DeviceVisitsComponent,
DevicePositionsComponent,
ManageLogComponent,
LogDialogComponent,
ManageSystemComponent,
@@ -173,6 +176,7 @@ registerLocaleData(LocaleDE);
MatListModule,
MatIconModule,
MatCardModule,
MatSliderModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
@@ -203,7 +207,7 @@ registerLocaleData(LocaleDE);
// add our application services (api access, logging, authentication)
ApiClientService, ConsoleService, AuthGuard,
ResourceService, CredentialService, UserService, VersionService, ExportService,
DeviceService, PrivilegeService, PlaceService, NoticeService, PlaceVisitService, DeviceVisitService,
DeviceService, PrivilegeService, PlaceService, NoticeService, PlaceVisitService, DeviceVisitService, DevicePositionService,
ManageLogService, ManageUserService, ManageNoticeService
],
entryComponents: [MessageDialogComponent, ConfirmationDialogComponent, ShareDialogComponent, NicknameDialogComponent, LogDialogComponent],
+3 -1
View File
@@ -25,6 +25,7 @@ import { ManageUsersComponent } from './views/manage-users.component';
import { ManageNoticesComponent } from './views/manage-notices.component';
import { EditNoticeComponent } from './views/edit-notice.component';
import { ExportComponent } from './views/export.component';
import { DevicePositionsComponent } from './views/device-positions.component';
export const routes: Routes = [
{ path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
@@ -33,7 +34,8 @@ export const routes: Routes = [
{ path: '', component: DevicesComponent },
{ path: ':id', children: [
{ path: 'location', component: DeviceLocationComponent },
{ path: 'visits', component: DeviceVisitsComponent }
{ path: 'visits', component: DeviceVisitsComponent },
{ path: 'positions', component: DevicePositionsComponent }
] },
]},
{ path: 'notices', component: InsideComponent, children: [
@@ -0,0 +1,74 @@
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { DataSource } from '@angular/cdk/table';
import { Device, Position } from '../../api/models';
import { ApiClientService } from '../../api';
import { CollectionViewer } from '@angular/cdk/collections';
/**
* A service that handles visits for a particular device and time.
*/
@Injectable()
export class DevicePositionService implements DataSource<Position> {
readonly device = new BehaviorSubject<Device>(null);
readonly loading = new BehaviorSubject<boolean>(false);
readonly date = new BehaviorSubject<Date>(new Date());
private elements = new BehaviorSubject<Position[]>([]);
private id: number;
private subscriptions = 0;
constructor(private apiClientService: ApiClientService) {
}
getPositions(): Position[] {
return this.elements.getValue();
}
setDevice(id: number) {
if (this.loading.getValue()) { return; }
this.loading.next(true);
this.device.next(null);
this.elements.next([]);
this.id = id;
if (id != null) {
this.apiClientService.getDevice(id).subscribe((result) => {
this.device.next(result.body);
this.loading.next(false);
this.setDate(this.date.getValue());
}, (error) => {
this.id = null;
this.loading.next(false);
});
}
}
setDate(date: Date) {
if (this.loading.getValue()) { return; }
this.loading.next(true);
const d = (date == null) ? new Date() : new Date(date);
d.setHours(0, 0, 0, 0);
const millis = d.getTime();
this.date.next(d);
this.elements.next([]);
this.apiClientService.getDevicePositionsRange(this.id, millis, 24 * 60 * 60 * 1000, false).subscribe((result) => {
this.elements.next(result.body.sort((a, b) => a.timestamp - b.timestamp));
this.loading.next(false);
}, (error) => {
this.elements.next([]);
this.loading.next(false);
});
}
connect(collectionViewer: CollectionViewer): Observable<Position[]> {
this.subscriptions += 1;
return this.elements;
}
disconnect(collectionViewer: CollectionViewer): void {
this.subscriptions -= 1;
}
}
@@ -57,7 +57,7 @@ export class DeviceVisitService implements DataSource<Visit> {
const millis = d.getTime();
this.date.next(d);
this.elements.next([]);
this.apiClientService.getDeviceVisits(this.id, millis, 24 * 60 * 60 * 1000).subscribe((result) => {
this.apiClientService.getDeviceVisitsRange(this.id, millis, 24 * 60 * 60 * 1000).subscribe((result) => {
this.elements.next(result.body);
this.loadPlaces();
}, (error) => {
@@ -251,6 +251,17 @@ export class ResourceService {
'visits_previous_tooltip': 'Vorheriger Tag',
'visits_next_tooltip': 'Nächster Tag',
'visits_day_placeholder': 'Tag auswählen',
'positions_title': 'Aktualisierungen',
'positions_manufacturer': 'Hersteller',
'positions_model': 'Modell',
'positions_os': 'Betriebssystem',
'positions_creation': 'Registrierung',
'positions_modification': 'Aktualisierung',
'positions_previous_day_tooltip': 'Vorheriger Tag',
'positions_next_day_tooltip': 'Nächster Tag',
'positions_previous_minute_tooltip': 'Vorherige Minute',
'positions_next_minute_tooltip': 'Nächste Minute',
'positions_day_placeholder': 'Tag auswählen',
'notices_title' : 'Neues',
'manage_users_success' : 'Die Kontoänderung wurde erfolgreich durchgeführt.',
'manage_users_error' : 'Die Kontoänderung konnte nicht durchgeführt werden.',
@@ -271,8 +282,10 @@ export class ResourceService {
'manage_users_delete_tooltip' : 'Konto löschen',
'manage_users_user_tooltip' : 'Zum Nutzer machen',
'manage_users_admin_tooltip' : 'Zum Administrator machen',
'manage_users_scientist_tooltip' : 'Zum Wissenschaftler machen',
'manage_users_user': 'Nutzer',
'manage_users_admin': 'Administrator',
'manage_users_scientist' : 'Wissenschaftler',
'manage_system_title': 'System',
'manage_system_gbs' : 'Gigabytes',
'manage_system_gb' : 'Gigabyte',
@@ -390,6 +403,7 @@ export class ResourceService {
'devices_actions': 'Aktionen',
'devices_location_tooltip': 'Standort anzeigen',
'devices_history_tooltip': 'Verlauf anzeigen',
'devices_position_tooltip': 'Aktualisierungen anzeigen',
'devices_delete_tooltip': 'Gerät löschen',
'device_location_device_error': 'Die Geräteinformationen konnten nicht geladen werden.',
'device_location_location_error': 'Der Standort konte nicht abgerufen werden.',
@@ -678,6 +692,17 @@ export class ResourceService {
'visits_previous_tooltip': 'Previous day',
'visits_next_tooltip': 'Next day',
'visits_day_placeholder': 'Select day',
'positions_title': 'Updates',
'positions_manufacturer': 'Manufacturer',
'positions_model': 'Model',
'positions_os': 'OS',
'positions_creation': 'Registration',
'positions_modification': 'Modification',
'positions_previous_day_tooltip': 'Previous day',
'positions_next_day_tooltip': 'Next day',
'positions_previous_minute_tooltip': 'Previous minute',
'positions_next_minute_tooltip': 'Next minute',
'positions_day_placeholder': 'Select day',
'notices_title' : 'News',
'manage_users_success' : 'The account has been modified successfully.',
'manage_users_error' : 'The account modification failed.',
@@ -698,8 +723,10 @@ export class ResourceService {
'manage_users_delete_tooltip' : 'Delete account',
'manage_users_user_tooltip' : 'Convert to user account',
'manage_users_admin_tooltip' : 'Convert to adminstrator account',
'manage_users_scientist_tooltip' : 'Convert to scientist account',
'manage_users_user': 'User',
'manage_users_admin': 'Administrator',
'manage_users_scientist': 'Scientist',
'manage_system_title': 'System',
'manage_system_gbs' : 'gigabytes',
'manage_system_gb' : 'gigabyte',
@@ -817,6 +844,7 @@ export class ResourceService {
'devices_actions': 'Actions',
'devices_location_tooltip': 'Show current location',
'devices_history_tooltip': 'Show location history',
'devices_position_tooltip': 'Show individual updates',
'devices_delete_tooltip': 'Delete device',
'device_location_device_error': 'Failed to load the device information.',
'device_location_location_error': 'Failed to load the device location.',
+3 -1
View File
@@ -40,7 +40,9 @@ export enum UserRole {
/** The role of a regular user. */
User = 'user',
/** The role of an admin user. */
Admin = 'admin'
Admin = 'admin',
/** The role of a scientist user. */
Scientist = 'scientist'
}
/**
@@ -0,0 +1,68 @@
<app-marker-map>
<mat-card class="sidebar" [ngStyle]="getPanelWidth()" style="margin-right:10px;margin-top:10px">
<mat-card-title>
<mat-icon style="font-size: 18px;">linear_scale</mat-icon>{{ res.strings('positions_title') }}
</mat-card-title>
<mat-divider></mat-divider>
<mat-card-content style="padding-top: 20px;">
<ng-container *ngIf="device | async as d">
<div class="detail-row">
<span class="detail-label">{{ res.strings('positions_manufacturer') }}</span>
<span class="detail-value">{{ d.manufacturer }}</span>
</div>
<div class="detail-row">
<span class="detail-label">{{ res.strings('positions_model') }}</span>
<span class="detail-value">{{ d.model }}</span>
</div>
<div class="detail-row">
<span class="detail-label">{{ res.strings('positions_os') }}</span>
<span class="detail-value">{{ d.os }}</span>
</div>
<div class="detail-row">
<span class="detail-label">{{ res.strings('positions_creation') }}</span>
<span class="detail-value">{{ d.creationTime | date:'short' }}</span>
</div>
<div class="detail-row">
<span class="detail-label">{{ res.strings('positions_modification') }}</span>
<span class="detail-value">{{ d.modificationTime | date:'short' }}</span>
</div>
</ng-container>
</mat-card-content>
<mat-divider></mat-divider>
<mat-card-actions fxFlexLayout="row" fxLayoutAlign="space-around center">
<ng-container *ngIf="!loading.getValue();else progressBarDevice">
<button mat-icon-button [matTooltip]="res.strings('positions_previous_minute_tooltip')"
[disabled]="cannotSlidePrevious()" (click)="onIncrementSlider(-1)">
<mat-icon>chevron_left</mat-icon>
</button>
<mat-slider min="0" max="1440" [(ngModel)]="sliderValue" [displayWith]="getSliderFormat" thumbLabel tickInterval="1" (input)="onSliderChange($event)" [disabled]="isSliderDisabled()" style="width: 220px"></mat-slider>
<button mat-icon-button [matTooltip]="res.strings('positions_next_minute_tooltip')"
[disabled]="cannotSlideNext()" (click)="onIncrementSlider(1)">
<mat-icon>chevron_right</mat-icon>
</button>
</ng-container>
<ng-template #progressBarDevice>
<mat-spinner [diameter]="36"></mat-spinner>
</ng-template>
</mat-card-actions>
<mat-card-footer fxFlexLayout="row" fxLayoutAlign="space-around center">
<button mat-icon-button [matTooltip]="res.strings('positions_previous_day_tooltip')"
[disabled]="loading.getValue() || !hasPreviousDay()" (click)="onPreviousDay()">
<mat-icon>chevron_left</mat-icon>
</button>
<mat-form-field style="margin-bottom:0px;width:120px">
<input matInput [matDatepicker]="picker" [min]="minDate" [max]="maxDate" [(value)]="selectedDate"
(dateInput)="onDateChange($event)" [placeholder]="res.strings('button_update')" disabled>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker [disabled]="loading.getValue()" #picker touchUi="true"></mat-datepicker>
</mat-form-field>
<button mat-icon-button [matTooltip]="res.strings('positions_next_day_tooltip')"
[disabled]="loading.getValue() || !hasNextDay()" (click)="onNextDay()">
<mat-icon>chevron_right</mat-icon>
</button>
<button mat-raised-button color="primary" (click)="reload()" [matTooltip]="res.strings('button_update')">
<mat-icon class="icon-button">update</mat-icon>
</button>
</mat-card-footer>
</mat-card>
</app-marker-map>
@@ -0,0 +1,257 @@
import { Component, OnInit, OnDestroy, ViewChild, AfterViewInit, ElementRef, DoCheck } from '@angular/core';
import { ApiClientService } from '../../api';
import { MatDialog, MatSnackBar, MatDatepicker, MatDatepickerInputEvent, MatSliderChange, MatSlider } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription, BehaviorSubject } from 'rxjs';
import { Device, Position } from '../../api/models';
import { Snackbars } from '../utils/snackbars';
import * as L from 'leaflet';
import { MarkerMapComponent } from '../widgets/marker-map.component';
import { DeviceVisitService } from '../services/device-visit.service';
import { DataSource } from '@angular/cdk/table';
import { ConfirmationDialogComponent } from '../widgets/confirmation-dialog.component';
import { TableColumn, TableHandler } from '../utils/tables';
import { ResourceService } from '../services/resource.service';
import { DevicePositionService } from '../services/device-position.service';
import { ValueConverter } from '@angular/compiler/src/render3/view/template';
@Component({
selector: 'app-device-positions',
templateUrl: './device-positions.component.html'
})
export class DevicePositionsComponent implements OnInit, AfterViewInit, OnDestroy, DoCheck {
@ViewChild(MarkerMapComponent, { static: true }) map: MarkerMapComponent;
@ViewChild('table', { read: ElementRef, static: true }) table: ElementRef;
id: string;
maxDate = new Date();
minDate = new Date();
selectedDate = new Date();
device: BehaviorSubject<Device>;
dataSource: DataSource<Position>;
loading: BehaviorSubject<boolean>;
date: BehaviorSubject<Date>;
sliderValue = 6 * 60;
compact = false;
private positions: L.Polyline = null;
private selectedPosition: L.CircleMarker = null;
private dateSubscription: Subscription;
private deviceSubscription: Subscription;
private loadingSubscription: Subscription;
constructor(
public res: ResourceService,
private devicePositionService: DevicePositionService,
private route: ActivatedRoute
) {
this.dataSource = devicePositionService;
this.device = devicePositionService.device;
this.loading = devicePositionService.loading;
this.date = devicePositionService.date;
}
reload() {
this.devicePositionService.setDevice(+this.id);
}
setDate(date: Date) {
this.devicePositionService.setDate(date);
}
onNextDay() {
const d = new Date(this.selectedDate);
d.setDate(d.getDate() + 1);
this.setDate(d);
}
hasNextDay(): boolean {
const d = new Date(this.selectedDate);
d.setDate(d.getDate() + 1);
return this.maxDate.getTime() >= d.getTime();
}
onPreviousDay() {
const d = new Date(this.selectedDate);
d.setDate(d.getDate() - 1);
this.setDate(d);
}
hasPreviousDay(): boolean {
const d = new Date(this.selectedDate);
d.setDate(d.getDate() - 1);
return this.minDate.getTime() <= d.getTime();
}
onDateChange(event: MatDatepickerInputEvent<Date>) {
this.setDate(event.value);
}
isSliderDisabled(): boolean {
return this.loading.getValue() || this.devicePositionService.getPositions().length === 0;
}
onSliderChange(event: MatSliderChange) {
this.sliderValue = event.value;
this.updateSelectedPosition();
}
cannotSlideNext(): boolean {
return this.isSliderDisabled() || this.sliderValue >= 1440;
}
cannotSlidePrevious(): boolean {
return this.isSliderDisabled() || this.sliderValue <= 0;
}
onIncrementSlider(value: number) {
this.sliderValue += value;
this.updateSelectedPosition();
}
getSliderFormat(value: number): string {
let m = '' + (value % 60);
if (m.length === 1) { m += '0'; }
const h = '' + Math.floor(value / 60);
return h + ':' + m;
}
getPanelWidth(): any {
if (this.compact) {
return { width: '280px' };
} else {
return { width: '280px' };
}
}
ngDoCheck(): void {
this.compact = (this.map.getWidth() < 900);
}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.devicePositionService.setDevice(+this.id);
this.dateSubscription = this.date.subscribe((date) => {
this.selectedDate = new Date(date);
});
this.deviceSubscription = this.device.subscribe((device) => {
if (device == null) {
this.minDate = new Date();
this.maxDate = new Date();
} else {
this.minDate = new Date(device.creationTime);
this.maxDate = new Date();
}
this.minDate.setHours(0, 0, 0, 0);
this.maxDate.setHours(23, 59, 59, 999);
});
this.selectedPosition = L.circleMarker([ 0, 0], {
radius: 10,
fillColor: '#f9a825',
fill: true,
stroke: true,
weight: 4,
opacity: 0.8,
color: '#01579b'
});
}
ngAfterViewInit() {
this.loadingSubscription = this.loading.subscribe((load) => {
if (load) {
this.clearPositions();
this.updateSelectedPosition();
} else {
this.createPositions();
this.updateSelectedPosition();
}
});
}
ngOnDestroy() {
this.dateSubscription.unsubscribe();
this.deviceSubscription.unsubscribe();
this.loadingSubscription.unsubscribe();
}
private updateSelectedPosition(): void {
if (this.loading.getValue() || this.devicePositionService.getPositions().length === 0) {
this.selectedPosition.remove();
} else {
const date = new Date(this.selectedDate);
date.setHours(Math.floor(this.sliderValue / 60));
date.setMinutes(this.sliderValue % 60, 0, 0);
const time = date.getTime();
let before: Position = null;
let after: Position = null;
for (const p of this.devicePositionService.getPositions()) {
if (p.coordinate != null) {
if (p.timestamp <= time) {
before = p;
} else if (after == null) {
after = p;
break;
}
}
}
if (before == null && after == null) {
this.selectedPosition.remove();
} else {
if (before == null && after != null) {
this.selectedPosition.setLatLng([after.coordinate.latitude, after.coordinate.longitude]);
} else if (after == null && before != null) {
this.selectedPosition.setLatLng([before.coordinate.latitude, before.coordinate.longitude]);
} else {
const percent = (time - before.timestamp) / (after.timestamp - before.timestamp);
const b = before.coordinate;
const a = after.coordinate;
this.selectedPosition.setLatLng(
[this.interpolate(b.latitude, a.latitude, percent),
this.interpolate(b.longitude, a.longitude, percent)]);
}
this.selectedPosition.addTo(this.map.map.map);
}
}
}
private interpolate(from: number, to: number, percent: number): number {
return from + (to - from) * percent;
}
private createPositions(): void {
const latlngs: ([number, number])[] = new Array();
for (const p of this.devicePositionService.getPositions()) {
if (p.coordinate != null) {
latlngs.push([ p.coordinate.latitude, p.coordinate.longitude ]);
}
}
if (latlngs.length > 0) {
this.positions = L.polyline(latlngs, {
color: '#f9a825',
stroke: true,
weight: 4
});
this.positions.addTo(this.map.map.map);
const bounds = new L.LatLngBounds(latlngs);
this.map.centerBounds(bounds);
}
}
private clearPositions(): void {
this.map.setPinPosition(null);
if (this.positions != null) {
this.positions.remove();
this.positions = null;
}
}
}
@@ -35,8 +35,6 @@ export class DeviceVisitsComponent implements OnInit, AfterViewInit, OnDestroy,
{ name: 'actions', dropPriority: 0, width: 130, fixedWidth: true }
];
private static readonly DAY = 24 * 60 * 60 * 1000;
@ViewChild(MarkerMapComponent, { static: true }) map: MarkerMapComponent;
@ViewChild('table', { read: ElementRef, static: true }) table: ElementRef;
@@ -86,22 +84,28 @@ export class DeviceVisitsComponent implements OnInit, AfterViewInit, OnDestroy,
}
onNextDay() {
this.setDate(new Date(this.selectedDate.getTime() + DeviceVisitsComponent.DAY));
const d = new Date(this.selectedDate);
d.setDate(d.getDate() + 1);
this.setDate(d);
}
hasNextDay(): boolean {
const next = this.selectedDate.getTime() + DeviceVisitsComponent.DAY;
return this.maxDate.getTime() >= next;
const d = new Date(this.selectedDate);
d.setDate(d.getDate() + 1);
return this.maxDate.getTime() >= d.getTime();
}
onPreviousDay() {
this.setDate(new Date(this.selectedDate.getTime() - DeviceVisitsComponent.DAY));
const d = new Date(this.selectedDate);
d.setDate(d.getDate() - 1);
this.setDate(d);
}
hasPreviousDay(): boolean {
const next = this.selectedDate.getTime() - DeviceVisitsComponent.DAY;
return this.minDate.getTime() <= next;
const d = new Date(this.selectedDate);
d.setDate(d.getDate() - 1);
return this.minDate.getTime() <= d.getTime();
}
onDateChange(event: MatDatepickerInputEvent<Date>) {
@@ -47,6 +47,9 @@
<mat-icon>my_location</mat-icon>
</button>
<button mat-icon-button [matTooltip]="res.strings('devices_history_tooltip')" [routerLink]="element.id + '/visits'" [disabled]="loading.getValue()">
<mat-icon>bubble_chart</mat-icon>
</button>
<button *ngIf="canShowPositions()" mat-icon-button [matTooltip]="res.strings('devices_position_tooltip')" [routerLink]="element.id + '/positions'" [disabled]="loading.getValue()">
<mat-icon>linear_scale</mat-icon>
</button>
<button mat-icon-button [matTooltip]="res.strings('devices_delete_tooltip')" (click)="onDelete(element.id)" [disabled]="loading.getValue()">
+15 -1
View File
@@ -10,6 +10,7 @@ import { ApiClientService } from '../../api';
import { Snackbars } from '../utils/snackbars';
import { TableHandler, TableColumn } from '../utils/tables';
import { ResourceService } from '../services/resource.service';
import { UserService, UserState, UserRole } from '../services/user.service';
@Component({
selector: 'app-devices',
@@ -24,7 +25,7 @@ export class DevicesComponent implements OnInit, OnDestroy, DoCheck {
{ name: 'model', dropPriority: 0, width: 200 },
{ name: 'creationTime', dropPriority: 3, width: 130, fixedWidth: true },
{ name: 'modificationTime', dropPriority: 4, width: 130, fixedWidth: true },
{ name: 'actions', dropPriority: 0, width: 130, fixedWidth: true }
{ name: 'actions', dropPriority: 0, width: 150, fixedWidth: true }
];
@ViewChild('table', { read: ElementRef, static: true }) table: ElementRef;
@@ -39,6 +40,7 @@ export class DevicesComponent implements OnInit, OnDestroy, DoCheck {
constructor(
public res: ResourceService,
private userService: UserService,
private apiClientService: ApiClientService,
private deviceSerivce: DeviceService,
private snackbar: MatSnackBar,
@@ -85,6 +87,18 @@ export class DevicesComponent implements OnInit, OnDestroy, DoCheck {
}
}
canShowPositions(): boolean {
if (this.userService.state.getValue() === UserState.Available) {
const user = this.userService.user.getValue();
for (const role of user.roles) {
if (role === UserRole.Scientist || role === UserRole.Admin) {
return true;
}
}
}
return false;
}
onDelete(id: number): void {
ConfirmationDialogComponent.open(this.dialog, {
title: this.res.strings('devices_delete_confirm_title'),
@@ -36,11 +36,16 @@
<ng-container matColumnDef="type">
<mat-header-cell *matHeaderCellDef [ngStyle]='getStyle("type")'> {{ res.strings('manage_users_type') }} </mat-header-cell>
<mat-cell *matCellDef="let element" [ngStyle]='getStyle("type")'>
<ng-container *ngIf="isAdmin(element);else user">
<ng-container *ngIf="isAdmin(element);else scientist">
<mat-icon [matTooltip]="res.strings('manage_users_admin')">security</mat-icon>
</ng-container>
<ng-template #user>
<mat-icon [matTooltip]="res.strings('manage_users_user')">face</mat-icon>
<ng-template #scientist>
<ng-container *ngIf="isScientist(element);else user">
<mat-icon [matTooltip]="res.strings('manage_users_scientist')">insert_chart</mat-icon>
</ng-container>
<ng-template #user>
<mat-icon [matTooltip]="res.strings('manage_users_user')">face</mat-icon>
</ng-template>
</ng-template>
</mat-cell>
</ng-container>
@@ -82,16 +87,21 @@
<button mat-icon-button [matTooltip]="res.strings('manage_users_delete_tooltip')" (click)="onDelete(element)" [disabled]="loading.getValue()">
<mat-icon>delete</mat-icon>
</button>
<ng-container *ngIf="isAdmin(element);else userbutton">
<ng-container *ngIf="isAdmin(element) || isScientist(element)">
<button mat-icon-button [matTooltip]="res.strings('manage_users_user_tooltip')" (click)="makeUser(element)" [disabled]="loading.getValue()">
<mat-icon>face</mat-icon>
</button>
</ng-container>
<ng-template #userbutton>
<ng-container *ngIf="!isScientist(element)">
<button mat-icon-button [matTooltip]="res.strings('manage_users_scientist_tooltip')" (click)="makeScientist(element)" [disabled]="loading.getValue()">
<mat-icon>insert_chart</mat-icon>
</button>
</ng-container>
<ng-container *ngIf="!isAdmin(element)">
<button mat-icon-button [matTooltip]="res.strings('manage_users_admin_tooltip')" (click)="makeAdmin(element)" [disabled]="loading.getValue()">
<mat-icon>security</mat-icon>
</button>
</ng-template>
</ng-container>
</ng-template>
</ng-container>
</mat-cell>

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