Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5691ef3a3 | ||
|
|
8e3dc80fb8 | ||
|
|
20108b282d | ||
|
|
aac6c5f5f3 | ||
|
|
3b644cece3 | ||
|
|
6b5f01a573 | ||
|
|
98212476f4 | ||
|
|
eac84438f1 | ||
|
|
dfacfd4ff4 | ||
|
|
301578f241 | ||
|
|
41dc0030c3 | ||
|
|
73ea8185a4 | ||
|
|
ff89c9a7cc | ||
|
|
7451e492c6 | ||
|
|
cf1cdb653b | ||
|
|
850f8add53 | ||
|
|
0d577ee938 | ||
|
|
fc7f9f0ed4 | ||
|
|
6d140284fa | ||
|
|
4e31cdcad7 | ||
|
|
2d1bf8a3bc | ||
|
|
c49fe8fcb4 | ||
|
|
cf74b4fdc8 | ||
|
|
bf90db3620 | ||
|
|
6bd1076e75 | ||
|
|
0772ea42d8 | ||
|
|
751f3f17e6 | ||
|
|
7885c7bb3c | ||
|
|
899b651ab1 | ||
|
|
4d40e47492 | ||
|
|
281831dbc9 | ||
|
|
2e9107dbc0 | ||
|
|
fa4714169a | ||
|
|
3ff2bf8d21 | ||
|
|
b728be2f86 | ||
|
|
d10ceef29b | ||
|
|
92f7027ca4 | ||
|
|
afe4776f59 | ||
|
|
06fb703f31 | ||
|
|
a1fc342862 | ||
|
|
ac06575858 | ||
|
|
58485d2db2 | ||
|
|
0abb3e2663 | ||
|
|
9c2934926f | ||
|
|
9a9bc07051 | ||
|
|
bf635a00ed | ||
|
|
4c5ff0d9e1 | ||
|
|
80f3195e32 | ||
|
|
524802d209 | ||
|
|
95116a30fd | ||
|
|
077cecb670 | ||
|
|
6e5c90acd9 | ||
|
|
c2b52164d9 | ||
|
|
efd893de8a | ||
|
|
5ab1224dcf | ||
|
|
7da98783c4 | ||
|
|
3447709f01 | ||
|
|
509baeaf00 | ||
|
|
72767c4a87 | ||
|
|
f1d01741f6 | ||
|
|
7b5d96f6b9 | ||
|
|
7085f910f7 | ||
|
|
c2e25c0945 | ||
|
|
2f2de2eba7 |
@@ -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."
|
||||
|
||||
@@ -27,7 +27,7 @@ android {
|
||||
applicationId "com.maptology.android.app"
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 28
|
||||
versionCode 8
|
||||
versionCode 10
|
||||
versionName "${version}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
@@ -47,7 +47,6 @@ 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
|
||||
@@ -73,6 +72,9 @@ android {
|
||||
disable 'RtlSymmetry', 'RelativeOverlap'
|
||||
// abortOnError false
|
||||
}
|
||||
dexOptions {
|
||||
javaMaxHeapSize "512m"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -245,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
|
||||
@@ -270,23 +244,12 @@ public class LocationService extends Service {
|
||||
*/
|
||||
private Runnable timeoutListener = null;
|
||||
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
// do not support binding
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
@@ -324,16 +287,22 @@ 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;
|
||||
}
|
||||
// start localization, if we are not running one already
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
@@ -355,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.
|
||||
*/
|
||||
@@ -447,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;
|
||||
@@ -562,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);
|
||||
@@ -602,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.
|
||||
@@ -656,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;
|
||||
}
|
||||
|
||||
@@ -702,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);
|
||||
@@ -726,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());
|
||||
@@ -745,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());
|
||||
@@ -786,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.
|
||||
*
|
||||
@@ -854,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.
|
||||
*
|
||||
@@ -882,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -923,32 +806,6 @@ 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 the next execution.
|
||||
*
|
||||
@@ -996,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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<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());
|
||||
|
||||
@@ -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')
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -1,36 +1,39 @@
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:3.5.0'
|
||||
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.3'
|
||||
version = '1.0.5-SNAPSHOT'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
// api dependencies
|
||||
versionJavaee = '7.0'
|
||||
versionJavaee = '8.0.0'
|
||||
versionJaxb = '2.3.1'
|
||||
versionAnnotation = '1.3.2'
|
||||
versionSwagger = '1.5.22'
|
||||
@@ -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") { }
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ description = 'Maptology Common Api'
|
||||
|
||||
dependencies {
|
||||
testCompile "junit:junit:${versionJunit}"
|
||||
compileOnly "javax.xml.bind:jaxb-api:${versionJaxb}"
|
||||
compileOnly "javax:javaee-api:${versionJavaee}"
|
||||
compileOnly "javax.xml.bind:jaxb-api:${versionJaxb}"
|
||||
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
compileOnly "io.swagger:swagger-annotations:${versionSwagger}"
|
||||
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
|
||||
}
|
||||
@@ -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,24 +29,26 @@ 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 = 'www.maptology.com'
|
||||
basePath = '/api'
|
||||
info {
|
||||
title = 'Maptology Service'
|
||||
version = "${version}"
|
||||
description = 'Maptology Service'
|
||||
version = project.version
|
||||
description = 'The application programming interface of Maptology.'
|
||||
termsOfService = 'https://maptology.com/terms-of-service'
|
||||
contact {
|
||||
email = 'nes-admin@uni-due.de'
|
||||
name = 'NES Universität Duisburg-Essen'
|
||||
name = 'Networked Embedded Systems'
|
||||
url = 'https://www.nes.uni-due.de'
|
||||
}
|
||||
license {
|
||||
url = 'https://www.maptology.com/license'
|
||||
name = 'Proprietary'
|
||||
name = 'Maptology License'
|
||||
}
|
||||
}
|
||||
swaggerFileName = 'maptology'
|
||||
@@ -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;
|
||||
@@ -1,2 +1,3 @@
|
||||
android.enableJetifier=true
|
||||
android.useAndroidX=true
|
||||
android.useAndroidX=true
|
||||
android.enableR8=true
|
||||
@@ -1,12 +1,12 @@
|
||||
description = 'Maptology Service Ejb'
|
||||
|
||||
dependencies {
|
||||
compileOnly "javax:javaee-api:${versionJavaee}"
|
||||
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
|
||||
compile project(':common-api')
|
||||
compile project(':service-geocode')
|
||||
|
||||
testCompile "javax:javaee-api:${versionJavaee}"
|
||||
testCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
testCompile "javax.xml.bind:jaxb-api:${versionJaxb}"
|
||||
testCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
testCompile "junit:junit:${versionJunit}"
|
||||
@@ -26,7 +26,8 @@ jar {
|
||||
'Created-By' : "Gradle ${gradle.gradleVersion}",
|
||||
'Build-Jdk' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})",
|
||||
'Build-OS' : "${System.properties['os.name']} ${System.properties['os.arch']} ${System.properties['os.version']}",
|
||||
'Implementation-Build' : "${System.properties['jenkins.build.number']}"
|
||||
'Implementation-Build' : "${System.properties['jenkins.build.number']}",
|
||||
'Implementation-Version' : project.version
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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,13 +39,19 @@ 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());
|
||||
@@ -57,5 +68,32 @@ public class DebugPositionSessionBean implements IPositionSessionBean {
|
||||
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,16 +25,26 @@ 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.
|
||||
@@ -43,5 +59,50 @@ public interface IPositionSessionBean {
|
||||
* @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,46 +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 long getPositionCount() {
|
||||
return PositionEntity.getCount(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 {
|
||||
@@ -111,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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
|
||||
|
Before Width: | Height: | Size: 445 B After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -1,103 +1,61 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Swagger UI</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
|
||||
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Maptology Api</title>
|
||||
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
body {
|
||||
margin:0;
|
||||
background: #fafafa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
<body>
|
||||
body
|
||||
{
|
||||
margin:0;
|
||||
background: #fffcf7;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<script>
|
||||
if(window.navigator.userAgent.indexOf("Edge") > -1) {
|
||||
console.log("Removing native Edge fetch implementation")
|
||||
window.fetch = undefined
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
// Begin Swagger UI call region
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "swagger.json",
|
||||
dom_id: '#swagger-ui',
|
||||
validatorUrl: null,
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
// End Swagger UI call region
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="locked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="close">
|
||||
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow">
|
||||
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow-down">
|
||||
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
|
||||
</symbol>
|
||||
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="jump-to">
|
||||
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="expand">
|
||||
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
|
||||
</symbol>
|
||||
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
|
||||
// Build a system
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "swagger.json",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
validatorUrl: null,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<!doctype html>
|
||||
<html lang="en-US">
|
||||
<title>Swagger UI: OAuth2 Redirect</title>
|
||||
<body onload="run()">
|
||||
</body>
|
||||
</html>
|
||||
@@ -45,11 +46,18 @@
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
(qp.error_uri ? "More info: "+qp.error_uri : "");
|
||||
}
|
||||
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: "Authorization failed: no accessCode received from the server"
|
||||
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":[],"names":[],"mappings":"","file":"swagger-ui.css","sourceRoot":""}
|
||||
@@ -0,0 +1,8 @@
|
||||
description = 'Maptology Service Tool'
|
||||
|
||||
dependencies {
|
||||
compile project(':common-api')
|
||||
compile "org.jboss.resteasy:resteasy-client:${versionResteasy}"
|
||||
compile "org.jboss.resteasy:resteasy-jackson2-provider:${versionResteasy}"
|
||||
testCompile "junit:junit:${versionJunit}"
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.maptology.tool;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.Status;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.maptology.api.PageConfig;
|
||||
import com.maptology.api.position.IPositionService;
|
||||
import com.maptology.api.position.Position;
|
||||
import com.maptology.api.position.PositionPage;
|
||||
import com.maptology.api.user.IUserService;
|
||||
import com.maptology.api.user.User;
|
||||
|
||||
/**
|
||||
* Downloads all data available for a particular device.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DownloadDeviceData {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Runs the program.
|
||||
*
|
||||
* @param args Ignored.
|
||||
* @throws Exception Thrown if something fails.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
IPositionService positionService = null;
|
||||
User user = null;
|
||||
while (user == null) {
|
||||
String username = null;
|
||||
while (username == null || username.length() == 0) {
|
||||
System.out.println("Username: ");
|
||||
username = scanner.nextLine().trim();
|
||||
}
|
||||
String password = null;
|
||||
while (password == null || password.length() == 0) {
|
||||
System.out.println("Password: ");
|
||||
password = scanner.nextLine().trim();
|
||||
}
|
||||
IUserService userService = ToolUtilities.getProxy(IUserService.class, username, password);
|
||||
Response r = userService.getCurrentUser();
|
||||
if (r.getStatusInfo() == Status.OK) {
|
||||
user = r.readEntity(User.class);
|
||||
positionService = ToolUtilities.getProxy(IPositionService.class, username, password);
|
||||
} else {
|
||||
System.out.println("Login failed.");
|
||||
}
|
||||
}
|
||||
scanner.close();
|
||||
System.out.println("Using user: " + user.getName());
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
File folder = new File(ToolUtilities.OUTPUT_FOLDER);
|
||||
folder.mkdirs();
|
||||
System.out.println("Using output folder: " + folder.getAbsolutePath());
|
||||
for (long device: ToolUtilities.DEVICES) {
|
||||
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(folder, "device-" + device + ".json")), StandardCharsets.UTF_8));
|
||||
System.out.println("Downloading device positions for: " + device);
|
||||
int offset = 0;
|
||||
int remaining = 0;
|
||||
int count = 0;
|
||||
do {
|
||||
System.out.println("Downloading page for offset: " + offset);
|
||||
Response r = positionService.getDevicePositions(device, new PageConfig(offset, 100), true);
|
||||
if (r.getStatusInfo() == Status.OK) {
|
||||
PositionPage page = r.readEntity(PositionPage.class);
|
||||
List<Position> positions = page.getElements();
|
||||
for (Position p: positions) {
|
||||
writer.write(mapper.writeValueAsString(p));
|
||||
writer.newLine();
|
||||
}
|
||||
offset += page.getSize();
|
||||
remaining = page.getTotal() - offset;
|
||||
count += positions.size();
|
||||
} else {
|
||||
System.out.println("Fetch failed.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
} while (remaining > 0);
|
||||
writer.close();
|
||||
System.out.println("Downloaded " + count + " positions.");
|
||||
}
|
||||
System.out.println("Download complete.");
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.maptology.tool;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.maptology.api.position.Position;
|
||||
import com.maptology.tool.util.DeltaCodec;
|
||||
|
||||
/**
|
||||
* Generates the polyline of a particular device by decoding
|
||||
* the gps data and if available, the metadata.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class GenerateDevicePolyline {
|
||||
|
||||
/**
|
||||
* Runs the program.
|
||||
*
|
||||
* @param args Ignored.
|
||||
* @throws Exception Thrown if something fails.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
File folder = new File(ToolUtilities.OUTPUT_FOLDER);
|
||||
for (long device: ToolUtilities.DEVICES) {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(folder, "device-" + device + ".json")), StandardCharsets.UTF_8));
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
Position position = mapper.readValue(line, Position.class);
|
||||
if (position.getCoordinate() != null) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
if (position.getMetadata().containsKey("gps")) {
|
||||
DeltaCodec codec = new DeltaCodec(11);
|
||||
List<long[]> result = codec.decode(position.getMetadata().get("gps"), new ArrayList<long[]>());
|
||||
for (long[] value: result) {
|
||||
b.append("[" + value[3] * (double)10e-8 + ", " + value[2] * (double)10e-8 + "], ");
|
||||
}
|
||||
// compute some statistics
|
||||
double mdx = 0;
|
||||
long mtx = 0;
|
||||
double asx = 0;
|
||||
for (int i = 1; i < result.size(); i++) {
|
||||
long[] x = result.get(i - 1);
|
||||
long[] y = result.get(i);
|
||||
double d = ToolUtilities.getDistance(x[2] * (double)10e-8, x[3] * (double)10e-8, y[2] * (double)10e-8, y[3] * (double)10e-8);
|
||||
mdx = Math.max(mdx, d);
|
||||
mtx = Math.max(mtx, Math.abs(x[0] - y[0]));
|
||||
if (y[0] - x[0] > 0)
|
||||
asx += (d * 1000 / (y[0] - x[0])) / (result.size() - 1);
|
||||
}
|
||||
System.out.println(mdx + "\t" + mtx + "\t" + asx);
|
||||
} else {
|
||||
b.append("[" + position.getCoordinate().getLatitude() + ", " + position.getCoordinate().getLongitude() + "], ");
|
||||
}
|
||||
System.out.println(b.toString());
|
||||
}
|
||||
}
|
||||
reader.close();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.maptology.tool;
|
||||
|
||||
import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
|
||||
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
|
||||
|
||||
/**
|
||||
* The tool configuration and utilities.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ToolUtilities {
|
||||
|
||||
/**
|
||||
* The url of the maptology api.
|
||||
*/
|
||||
public static String API_URL = "https://www.maptology.com/api";
|
||||
|
||||
/**
|
||||
* The devices
|
||||
*/
|
||||
public static long[] DEVICES = new long[] { 361281 };
|
||||
|
||||
/**
|
||||
* The output folder to write data.
|
||||
*/
|
||||
public static String OUTPUT_FOLDER = "temp";
|
||||
|
||||
|
||||
/**
|
||||
* The earth's radius in meters.
|
||||
*/
|
||||
public static final int EARTH_RADIUS = 6371000;
|
||||
|
||||
/**
|
||||
* Returns a proxy for the service with the specified login data.
|
||||
*
|
||||
* @param <T> The type of the service.
|
||||
* @param service The class representing the service interface.
|
||||
* @param username The user name.
|
||||
* @param password The user password.
|
||||
* @return The proxy for the service.
|
||||
*/
|
||||
public static <T> T getProxy(Class<T> service, String username, String password) {
|
||||
ResteasyClientBuilder builder = new ResteasyClientBuilder();
|
||||
builder.httpEngine(new URLConnectionEngine());
|
||||
ResteasyClient client = builder.build();
|
||||
return client.register(new BasicAuthentication(username, password)).target(API_URL).proxy(service);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the distance in meters between the two wgs coordinates specified by
|
||||
* alon, alat and blon, blat.
|
||||
*
|
||||
* @param alon The longitude of the first point.
|
||||
* @param alat The latitude of the first point.
|
||||
* @param blon The longitude of the second point.
|
||||
* @param blat The latitude of the second point.
|
||||
* @return The distance in meters.
|
||||
*/
|
||||
public static double getDistance(double alon, double alat, double blon, double blat) {
|
||||
double dlong = Math.toRadians(blon - alon);
|
||||
double dlat = Math.toRadians(blat - alat);
|
||||
double ax = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(Math.toRadians(alat)) * Math.cos(Math.toRadians(blat))
|
||||
* Math.pow(Math.sin(dlong / 2.0), 2);
|
||||
double c = 2 * Math.atan2(Math.sqrt(ax), Math.sqrt(1 - ax));
|
||||
return EARTH_RADIUS * c;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.maptology.tool.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,57 @@
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Trace Visualization</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
|
||||
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
|
||||
</head>
|
||||
<body>
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0px;
|
||||
}
|
||||
#mapid {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<div id="mapid"></div>
|
||||
<script>
|
||||
|
||||
// add your points to draw into the array
|
||||
var polylinePoints = [
|
||||
[50.774138199999996, 7.0871493999999995], [50.774135199999996, 7.0871102], [50.7741407, 7.0871035]
|
||||
];
|
||||
|
||||
// create a map, add polyline set view
|
||||
var mymap = L.map('mapid').setView(polylinePoints[0], 13);
|
||||
|
||||
L.tileLayer('https://cloud.locoslab.com/carta/restful-services/tile/{z}/{x}/{y}.png', {
|
||||
maxZoom: 20,
|
||||
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
|
||||
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
|
||||
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
|
||||
id: 'mapbox/streets-v11'
|
||||
}).addTo(mymap);
|
||||
|
||||
var polylineOptions = {
|
||||
color: 'blue',
|
||||
weight: 6,
|
||||
opacity: 0.9
|
||||
};
|
||||
|
||||
var polyline = new L.Polyline(polylinePoints, polylineOptions);
|
||||
polyline.addTo(mymap);
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -9,7 +9,7 @@ dependencies {
|
||||
testCompile "junit:junit:${versionJunit}"
|
||||
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
|
||||
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
|
||||
providedCompile "javax:javaee-api:${versionJavaee}"
|
||||
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
|
||||
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
|
||||
providedCompile "org.jboss.resteasy:resteasy-client:${versionResteasy}"
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
Before Width: | Height: | Size: 445 B After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -1,103 +1,61 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Swagger UI</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
|
||||
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Maptology Api</title>
|
||||
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
body {
|
||||
margin:0;
|
||||
background: #fafafa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
<body>
|
||||
body
|
||||
{
|
||||
margin:0;
|
||||
background: #fffcf7;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<script>
|
||||
if(window.navigator.userAgent.indexOf("Edge") > -1) {
|
||||
console.log("Removing native Edge fetch implementation")
|
||||
window.fetch = undefined
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
// Begin Swagger UI call region
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "maptology.json",
|
||||
dom_id: '#swagger-ui',
|
||||
validatorUrl: null,
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
// End Swagger UI call region
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="locked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="close">
|
||||
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow">
|
||||
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow-down">
|
||||
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
|
||||
</symbol>
|
||||
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="jump-to">
|
||||
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="expand">
|
||||
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
|
||||
</symbol>
|
||||
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
|
||||
// Build a system
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "maptology.json",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
validatorUrl: null,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<!doctype html>
|
||||
<html lang="en-US">
|
||||
<title>Swagger UI: OAuth2 Redirect</title>
|
||||
<body onload="run()">
|
||||
</body>
|
||||
</html>
|
||||
@@ -45,11 +46,18 @@
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
(qp.error_uri ? "More info: "+qp.error_uri : "");
|
||||
}
|
||||
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: "Authorization failed: no accessCode received from the server"
|
||||
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
|
||||