Bug 5085: Initial extraction of sailing.shared.persistence

This commit is contained in:
Steffen Schaefer committed 2019-12-09 09:21:39 +01:00
1 parent cfd0456932
commit 69d76e03c5
45 files changed
+1022 -648

No files matched your search

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.sap.sailing.shared.persistence</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,7 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
@@ -0,0 +1,3 @@
eclipse.preferences.version=1
pluginProject.extensions=false
resolve.requirebundle=false
@@ -0,0 +1,25 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Persistence
Bundle-SymbolicName: com.sap.sailing.shared.persistence
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.sap.sailing.shared.persistence.Activator
Bundle-Vendor: SAP
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Automatic-Module-Name: com.sap.sailing.shared.persistence
Import-Package: org.apache.shiro.session;version="1.2.2",
org.apache.shiro.session.mgt;version="1.2.2",
org.apache.shiro.subject;version="1.2.2",
org.osgi.framework;version="1.3.0"
Bundle-ActivationPolicy: lazy
Require-Bundle: com.sap.sse.mongodb,
com.sap.sse.common,
com.sap.sailing.domain,
com.sap.sailing.domain.common,
org.mongodb.mongo-java-driver;bundle-version="3.6.4",
com.sap.sailing.domain.shared.android,
com.sap.sse.security.common
Export-Package: com.sap.sailing.shared.persistence,
com.sap.sailing.shared.persistence.device,
com.sap.sailing.shared.persistence.device.impl,
com.sap.sailing.shared.persistence.impl
@@ -0,0 +1,4 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>root</artifactId>
<groupId>com.sap.sailing</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>com.sap.sailing.shared.persistence</artifactId>
<packaging>eclipse-plugin</packaging>
</project>
@@ -0,0 +1,38 @@
package com.sap.sailing.shared.persistence;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import com.sap.sse.mongodb.MongoDBService;
import com.sap.sailing.shared.persistence.impl.CollectionNames;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
*
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
for (CollectionNames name : CollectionNames.values()) {
MongoDBService.INSTANCE.registerExclusively(CollectionNames.class, name.name());
}
}
/*
* (non-Javadoc)
*
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
@@ -0,0 +1,25 @@
package com.sap.sailing.shared.persistence;
import java.util.UUID;
import java.util.function.Function;
import com.mongodb.client.MongoDatabase;
import com.sap.sailing.domain.coursetemplate.CourseTemplate;
import com.sap.sailing.domain.coursetemplate.MarkProperties;
import com.sap.sailing.domain.coursetemplate.MarkRole;
import com.sap.sailing.domain.coursetemplate.MarkTemplate;
public interface DomainObjectFactory {
MongoDatabase getDatabase();
Iterable<MarkProperties> loadAllMarkProperties(Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver);
Iterable<MarkTemplate> loadAllMarkTemplates();
Iterable<MarkRole> loadAllMarkRoles();
Iterable<CourseTemplate> loadAllCourseTemplates(Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver);
}
@@ -0,0 +1,36 @@
package com.sap.sailing.shared.persistence;
import java.util.UUID;
import com.mongodb.client.MongoDatabase;
import com.sap.sailing.domain.coursetemplate.CourseTemplate;
import com.sap.sailing.domain.coursetemplate.MarkProperties;
import com.sap.sailing.domain.coursetemplate.MarkRole;
import com.sap.sailing.domain.coursetemplate.MarkTemplate;
import com.sap.sailing.shared.persistence.device.DeviceIdentifierMongoHandler;
import com.sap.sse.common.TypeBasedServiceFinder;
public interface MongoObjectFactory {
MongoDatabase getDatabase();
/** Stores {@link MarkProperties} from the database. */
void storeMarkProperties(TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder,
MarkProperties markProperties);
/** Removes a {@link MarkProperties} object from the database. */
void removeMarkProperties(UUID markPropertiesId);
void storeMarkTemplate(MarkTemplate markTemplate);
void removeMarkTemplate(UUID markTemplateId);
void storeCourseTemplate(CourseTemplate courseTemplate);
void removeCourseTemplate(UUID courseTemplateId);
void storeMarkRole(MarkRole markRole);
void removeMarkRole(UUID markRoleId);
}
@@ -0,0 +1,11 @@
package com.sap.sailing.shared.persistence;
import com.sap.sailing.shared.persistence.impl.PersistenceFactoryImpl;
import com.sap.sse.common.TypeBasedServiceFinderFactory;
public interface PersistenceFactory {
PersistenceFactory INSTANCE = new PersistenceFactoryImpl();
MongoObjectFactory getDefaultMongoObjectFactory(TypeBasedServiceFinderFactory typeBasedServiceFinderFactory);
DomainObjectFactory getDefaultDomainObjectFactory(TypeBasedServiceFinderFactory typeBasedServiceFinderFactory);
}
@@ -0,0 +1,6 @@
package com.sap.sailing.shared.persistence.device;
import com.sap.sailing.domain.racelogtracking.DeviceIdentifierSerializationHandler;
public interface DeviceIdentifierMongoHandler extends DeviceIdentifierSerializationHandler<Object> {
}
@@ -0,0 +1,17 @@
package com.sap.sailing.shared.persistence.device.impl;
import com.sap.sailing.domain.common.DeviceIdentifier;
import com.sap.sailing.domain.common.racelog.tracking.TransformationException;
import com.sap.sailing.domain.racelogtracking.impl.PlaceHolderDeviceIdentifierSerializationHandler;
import com.sap.sailing.shared.persistence.device.DeviceIdentifierMongoHandler;
public class PlaceHolderDeviceIdentifierMongoHandler extends PlaceHolderDeviceIdentifierSerializationHandler
implements DeviceIdentifierMongoHandler {
@Override
public DeviceIdentifier deserialize(Object serialized, String type, String stringRepresentation)
throws TransformationException {
return deserialize((String) serialized, type, stringRepresentation);
}
}
@@ -0,0 +1,20 @@
package com.sap.sailing.shared.persistence.impl;
import com.sap.sailing.domain.coursetemplate.CourseTemplate;
import com.sap.sailing.domain.coursetemplate.MarkProperties;
import com.sap.sailing.domain.coursetemplate.MarkRole;
import com.sap.sailing.domain.coursetemplate.MarkTemplate;
public enum CollectionNames {
/** Contains the {@link MarkProperties}. */
MARK_PROPERTIES,
/** Contains the {@link MarkTemplate} objects. */
MARK_TEMPLATES,
/** Contains the {@link MarkRole} objects. */
MARK_ROLES,
/** Contains the {@link CourseTemplate}s. */
COURSE_TEMPLATES;
}
@@ -0,0 +1,413 @@
package com.sap.sailing.shared.persistence.impl;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.sap.sailing.domain.common.DeviceIdentifier;
import com.sap.sailing.domain.common.MarkType;
import com.sap.sailing.domain.common.PassingInstruction;
import com.sap.sailing.domain.common.Position;
import com.sap.sailing.domain.common.impl.DegreePosition;
import com.sap.sailing.domain.common.racelog.tracking.TransformationException;
import com.sap.sailing.domain.coursetemplate.ControlPointTemplate;
import com.sap.sailing.domain.coursetemplate.CourseTemplate;
import com.sap.sailing.domain.coursetemplate.MarkPairTemplate;
import com.sap.sailing.domain.coursetemplate.MarkPairTemplate.MarkPairTemplateFactory;
import com.sap.sailing.domain.coursetemplate.MarkProperties;
import com.sap.sailing.domain.coursetemplate.MarkPropertiesBuilder;
import com.sap.sailing.domain.coursetemplate.MarkRole;
import com.sap.sailing.domain.coursetemplate.MarkTemplate;
import com.sap.sailing.domain.coursetemplate.RepeatablePart;
import com.sap.sailing.domain.coursetemplate.WaypointTemplate;
import com.sap.sailing.domain.coursetemplate.impl.CourseTemplateImpl;
import com.sap.sailing.domain.coursetemplate.impl.MarkRoleImpl;
import com.sap.sailing.domain.coursetemplate.impl.MarkTemplateImpl;
import com.sap.sailing.domain.coursetemplate.impl.RepeatablePartImpl;
import com.sap.sailing.domain.coursetemplate.impl.WaypointTemplateImpl;
import com.sap.sailing.domain.racelogtracking.impl.PlaceHolderDeviceIdentifierSerializationHandler;
import com.sap.sailing.shared.persistence.DomainObjectFactory;
import com.sap.sailing.shared.persistence.device.DeviceIdentifierMongoHandler;
import com.sap.sailing.shared.persistence.device.impl.PlaceHolderDeviceIdentifierMongoHandler;
import com.sap.sse.common.Color;
import com.sap.sse.common.NoCorrespondingServiceRegisteredException;
import com.sap.sse.common.TimePoint;
import com.sap.sse.common.TypeBasedServiceFinder;
import com.sap.sse.common.TypeBasedServiceFinderFactory;
import com.sap.sse.common.Util.Pair;
import com.sap.sse.common.impl.AbstractColor;
import com.sap.sse.common.impl.MillisecondsTimePoint;
public class DomainObjectFactoryImpl implements DomainObjectFactory {
private static final Logger logger = Logger.getLogger(DomainObjectFactoryImpl.class.getName());
private final MongoDatabase database;
private final TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder;
public DomainObjectFactoryImpl(MongoDatabase mongoDatabase) {
this(mongoDatabase, /* serviceFinderFactory */ null);
}
public DomainObjectFactoryImpl(MongoDatabase mongoDatabase,
TypeBasedServiceFinderFactory serviceFinderFactory) {
this.database = mongoDatabase;
if (serviceFinderFactory != null) {
this.deviceIdentifierServiceFinder = serviceFinderFactory
.createServiceFinder(DeviceIdentifierMongoHandler.class);
this.deviceIdentifierServiceFinder.setFallbackService(new PlaceHolderDeviceIdentifierMongoHandler());
} else {
this.deviceIdentifierServiceFinder = null;
}
}
@Override
public MongoDatabase getDatabase() {
return database;
}
@Override
public Iterable<MarkProperties> loadAllMarkProperties(Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver) {
final List<MarkProperties> result = new ArrayList<>();
final MongoCollection<Document> configurationCollection = database
.getCollection(CollectionNames.MARK_PROPERTIES.name());
try {
for (final Document dbObject : configurationCollection.find()) {
final MarkProperties entry = loadMarkPropertiesEntry(dbObject, markTemplateResolver, markRoleResolver);
result.add(entry);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error connecting to MongoDB, unable to load mark properties.");
logger.log(Level.SEVERE, "loadAllMarkProperties", e);
}
return result;
}
private MarkProperties loadMarkPropertiesEntry(final Document dbObject,
Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver) {
//load all mandatory data
final UUID id = UUID.fromString(dbObject.getString(FieldNames.MARK_PROPERTIES_ID.name()));
final String name = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_NAME.name());
final String shortName = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_SHORT_NAME.name());
final String pattern = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_PATTERN.name());
final String shape = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_SHAPE.name());
final String type = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_TYPE.name());
final MarkType markType = MarkType.valueOf(type);
final String storedColor = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_COLOR.name());
final Color color = AbstractColor.getCssColor(storedColor);
final Document positionDocument = dbObject.get(FieldNames.MARK_PROPERTIES_FIXED_POSITION.name(),
Document.class);
final Position fixedPosition = positionDocument == null ? null : loadPosition(positionDocument);
final ArrayList<?> tagsList = dbObject.get(FieldNames.MARK_PROPERTIES_TAGS.name(), ArrayList.class);
final Collection<String> tags = tagsList.stream().map(t -> t.toString()).collect(Collectors.toList());
//all mandatory data are loaded -> create builder
final MarkPropertiesBuilder builder = new MarkPropertiesBuilder(id, name, shortName, color, shape, pattern,
markType).withFixedPosition(fixedPosition).withTags(tags);
//load optional deviceId
try {
final Document deviceIdDocument = dbObject.get(FieldNames.MARK_PROPERTIES_TRACKING_DEVICE_IDENTIFIER.name(),
Document.class);
final DeviceIdentifier deviceIdentifier = deviceIdDocument == null ? null
: loadDeviceId(deviceIdentifierServiceFinder,
deviceIdDocument);
builder.withDeviceId(deviceIdentifier);
} catch (TransformationException | NoCorrespondingServiceRegisteredException e) {
logger.log(Level.WARNING, "Could not load deviceId for MarkProperties", e);
}
//load map of last used templates
final Document lastUsedTemplateObject = dbObject.get(FieldNames.MARK_PROPERTIES_USED_TEMPLATE.name(),
Document.class);
final Map<Object, Object> mapLastUsedTemplate = new HashMap<>();
lastUsedTemplateObject.forEach((k, v) -> mapLastUsedTemplate.put(k, v));
final Map<MarkTemplate, TimePoint> lastUsedTemplate = new HashMap<>();
for (Map.Entry<Object, Object> e : mapLastUsedTemplate.entrySet()) {
MarkTemplate markTemplate = markTemplateResolver.apply(UUID.fromString(e.getKey().toString()));
if (markTemplate != null) {
lastUsedTemplate.put(markTemplate, parseTimePoint(e.getValue()));
}
else {
logger.warning(String.format("Could not resolve MarkTemplate with id %s for MarkProperties %s.",
e.getKey().toString(), id));
}
}
builder.withLastUsedTemplate(lastUsedTemplate);
//load map of last used roles
final Document lastUsedRoleObject = dbObject.get(FieldNames.MARK_PROPERTIES_USED_ROLE.name(), Document.class);
final Map<Object, Object> mapUsedRole = new HashMap<>();
lastUsedRoleObject.forEach((k, v) -> mapUsedRole.put(k, v));
final Map<MarkRole, TimePoint> lastUsedRole = mapUsedRole.entrySet().stream()
.collect(Collectors.toMap(
(Object markRoleIdObject) -> markRoleResolver.apply(UUID.fromString((String) markRoleIdObject)),
v -> parseTimePoint(v)));
builder.withLastUsedRole(lastUsedRole);
return builder.build();
}
// TODO copy of com.sap.sailing.domain.persistence.impl.DomainObjectFactoryImpl
private DeviceIdentifier loadDeviceId(
TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder, Document deviceId)
throws TransformationException, NoCorrespondingServiceRegisteredException {
String deviceType = (String) deviceId.get(FieldNames.DEVICE_TYPE.name());
Object deviceTypeId = deviceId.get(FieldNames.DEVICE_TYPE_SPECIFIC_ID.name());
String stringRepresentation = (String) deviceId.get(FieldNames.DEVICE_STRING_REPRESENTATION.name());
try {
return deviceIdentifierServiceFinder.findService(deviceType).deserialize(deviceTypeId, deviceType,
stringRepresentation);
} catch (TransformationException e) {
return new PlaceHolderDeviceIdentifierSerializationHandler().deserialize(stringRepresentation, deviceType,
stringRepresentation);
}
}
// TODO copy of com.sap.sailing.domain.persistence.impl.DomainObjectFactoryImpl
public Position loadPosition(Document object) {
Number latNumber = (Number) object.get(FieldNames.LAT_DEG.name());
Double lat = latNumber == null ? null : latNumber.doubleValue();
Number lngNumber = (Number) object.get(FieldNames.LNG_DEG.name());
Double lng = lngNumber == null ? null : lngNumber.doubleValue();
if (lat != null && lng != null) {
return new DegreePosition(lat, lng);
} else {
return null;
}
}
private TimePoint parseTimePoint(Object timePointAsNumber) {
return timePointAsNumber != null ? new MillisecondsTimePoint(((Number) timePointAsNumber).longValue()) : null;
}
@Override
public Iterable<MarkTemplate> loadAllMarkTemplates() {
final List<MarkTemplate> result = new ArrayList<>();
final MongoCollection<Document> configurationCollection = database
.getCollection(CollectionNames.MARK_TEMPLATES.name());
try {
for (final Document dbObject : configurationCollection.find()) {
final MarkTemplate entry = loadMarkTemplateEntry(dbObject);
result.add(entry);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error connecting to MongoDB, unable to load mark templates.");
logger.log(Level.SEVERE, "loadAllMarkTemplates", e);
}
return result;
}
private MarkTemplate loadMarkTemplateEntry(Document dbObject) {
final UUID id = UUID.fromString(dbObject.getString(FieldNames.MARK_TEMPLATE_ID.name()));
final String name = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_NAME.name());
final String shortName = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_SHORT_NAME.name());
final String pattern = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_PATTERN.name());
final String shape = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_SHAPE.name());
final String type = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_TYPE.name());
final MarkType markType = type != null ? MarkType.valueOf(type) : null;
final String storedColor = dbObject.getString(FieldNames.COMMON_MARK_PROPERTIES_COLOR.name());
final Color color = AbstractColor.getCssColor(storedColor);
return new MarkTemplateImpl(id, name, shortName, color, shape, pattern, markType);
}
@Override
public Iterable<MarkRole> loadAllMarkRoles() {
final List<MarkRole> result = new ArrayList<>();
final MongoCollection<Document> configurationCollection = database
.getCollection(CollectionNames.MARK_ROLES.name());
try {
for (final Document dbObject : configurationCollection.find()) {
final MarkRole entry = loadMarkRoleEntry(dbObject);
result.add(entry);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error connecting to MongoDB, unable to load mark roles.");
logger.log(Level.SEVERE, "loadAllMarkRoles", e);
}
return result;
}
private MarkRole loadMarkRoleEntry(Document dbObject) {
final UUID id = UUID.fromString(dbObject.getString(FieldNames.MARK_ROLE_ID.name()));
final String name = dbObject.getString(FieldNames.MARK_ROLE_NAME.name());
return new MarkRoleImpl(id, name);
}
@Override
public Iterable<CourseTemplate> loadAllCourseTemplates(Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver) {
final List<CourseTemplate> result = new ArrayList<>();
final MongoCollection<Document> configurationCollection = database
.getCollection(CollectionNames.COURSE_TEMPLATES.name());
try {
for (final Document dbObject : configurationCollection.find()) {
final CourseTemplate entry = loadCourseTemplateEntry(dbObject, markTemplateResolver, markRoleResolver);
result.add(entry);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error connecting to MongoDB, unable to load course templates.");
logger.log(Level.SEVERE, "loadAllCourseTemplates", e);
}
return result;
}
private CourseTemplate loadCourseTemplateEntry(Document dbObject,
Function<UUID, MarkTemplate> markTemplateResolver,
Function<UUID, MarkRole> markRoleResolver) {
// load master data
final UUID id = UUID.fromString(dbObject.getString(FieldNames.COURSE_TEMPLATE_ID.name()));
final String name = dbObject.getString(FieldNames.COURSE_TEMPLATE_NAME.name());
final String imageURLString = dbObject.getString(FieldNames.COURSE_TEMPLATE_IMAGE_URL.name());
final Integer defaultNumberOfLaps = dbObject
.getInteger(FieldNames.COURSE_TEMPLATE_DEFAULT_NUMBER_OF_LAPS.name());
URL optionalImageURL = null;
if (imageURLString != null) {
try {
optionalImageURL = new URL(imageURLString);
} catch (MalformedURLException e) {
logger.warning(String.format("Error parsing image URL %s for course template %s", imageURLString, id));
}
}
// load mark templates and associated roles
final ArrayList<?> markTemplatesList = dbObject.get(FieldNames.COURSE_TEMPLATE_MARK_TEMPLATES.name(),
ArrayList.class);
final Set<MarkTemplate> markTemplates = new HashSet<>();
final Map<MarkTemplate, MarkRole> associatedRoles = new HashMap<>();
for (Object entry : markTemplatesList) {
if (entry instanceof Document) {
final Document entryObject = (Document) entry;
final UUID markTemplateUUID = UUID.fromString(entryObject.getString(FieldNames.COURSE_TEMPLATE_MARK_TEMPLATE_ID.name()));
final MarkTemplate markTemplate = markTemplateResolver.apply(
markTemplateUUID);
if (markTemplate != null) {
markTemplates.add(markTemplate);
final String roleIdAsStringOrNull = entryObject.getString(FieldNames.COURSE_TEMPLATE_MARK_TEMPLATE_ROLE_ID.name());
final MarkRole markRoleOrNull = roleIdAsStringOrNull == null ? null : markRoleResolver.apply(UUID.fromString(roleIdAsStringOrNull));
if (markRoleOrNull != null) {
associatedRoles.put(markTemplate, markRoleOrNull);
}
} else {
logger.warning(String.format("Could not resolve MarkTemplate with id %s for CourseTemplate %s.",
markTemplateUUID, id));
}
} else {
logger.warning(String.format("Unexpected entry for MarkTemplate found for CourseTemplate %s.", id));
}
}
// load waypoints
final ArrayList<?> waypointTemplatesList = dbObject.get(FieldNames.COURSE_TEMPLATE_WAYPOINTS.name(),
ArrayList.class);
final List<WaypointTemplate> waypointTemplates = new ArrayList<>();
final MarkPairTemplateFactory markPairTemplateFactory = new MarkPairTemplateFactory();
for (final Object o : waypointTemplatesList) {
if (o instanceof Document) {
final Document bdo = (Document) o;
waypointTemplates.add(loadWaypointTemplate(bdo, markTemplateResolver, markPairTemplateFactory::create));
} else {
logger.warning(String.format("Could not load document for CourseTemplate %s.", id));
}
}
// load repeatable parts
final BasicDBObject dbRepPart = (BasicDBObject) dbObject.get(FieldNames.COURSE_TEMPLATE_REPEATABLE_PART.name());
final RepeatablePart optionalRepeatablePart;
if (dbRepPart == null) {
optionalRepeatablePart = null;
} else {
final int zeroBasedIndexOfRepeatablePartStart = dbRepPart.getInt(FieldNames.REPEATABLE_PART_START.name());
final int zeroBasedIndexOfRepeatablePartEnd = dbRepPart.getInt(FieldNames.REPEATABLE_PART_END.name());
optionalRepeatablePart = new RepeatablePartImpl(zeroBasedIndexOfRepeatablePartStart, zeroBasedIndexOfRepeatablePartEnd);
}
// load tags
final ArrayList<?> tagsDbObject = dbObject.get(FieldNames.COURSE_TEMPLATE_TAGS.name(), ArrayList.class);
final List<String> tags = new ArrayList<>();
tagsDbObject.forEach(t -> tags.add(t.toString()));
final CourseTemplateImpl courseTemplateImpl = new CourseTemplateImpl(id, name, markTemplates, waypointTemplates,
associatedRoles, optionalImageURL, optionalRepeatablePart, defaultNumberOfLaps);
courseTemplateImpl.setTags(tags);
return courseTemplateImpl;
}
private WaypointTemplate loadWaypointTemplate(Document bdo,
Function<UUID, MarkTemplate> markTemplateResolver,
BiFunction<Pair<String, String>, List<MarkTemplate>, MarkPairTemplate> markPairResolver) {
// load passing instruction
final PassingInstruction passingInstruction = PassingInstruction
.valueOf(bdo.get(FieldNames.WAYPOINT_TEMPLATE_PASSINGINSTRUCTION.name()).toString());
// load master data
final String name = bdo.getString(FieldNames.WAYPOINT_TEMPLATE_CONTROL_POINT_NAME.name());
final String shortName = bdo.getString(FieldNames.WAYPOINT_TEMPLATE_CONTROL_POINT_SHORT_NAME.name());
// load mark templates for control point
final ArrayList<?> markTemplateUUIDsDbList = bdo.get(FieldNames.WAYPOINT_TEMPLATE_MARK_TEMPLATES.name(),
ArrayList.class);
boolean hasParsingError = false;
final List<MarkTemplate> markTemplates = new ArrayList<>();
for (Object obj : markTemplateUUIDsDbList) {
final MarkTemplate markTemplate = markTemplateResolver.apply(UUID.fromString(obj.toString()));
if (markTemplate == null) {
logger.warning(String.format("Could not resolve MarkTemplate with id %s for WaypointTemplate.",
obj.toString()));
hasParsingError = true;
break;
} else {
markTemplates.add(markTemplate);
}
}
if (hasParsingError) {
return null;
}
// create MarkTemplate or MarkTemplatePairImpl
final ControlPointTemplate controlPointTemplate;
if (markTemplates.size() == 2) {
controlPointTemplate = markPairResolver.apply(new Pair<>(name, shortName), markTemplates);
} else {
controlPointTemplate = markTemplates.get(0);
}
return new WaypointTemplateImpl(controlPointTemplate, passingInstruction);
}
}
@@ -0,0 +1,29 @@
package com.sap.sailing.shared.persistence.impl;
public enum FieldNames {
// general:
TIME_AS_MILLIS, KNOT_SPEED, DEGREE_BEARING, LAT_DEG, LNG_DEG,
// DeviceIdentifer
DEVICE_TYPE_SPECIFIC_ID, DEVICE_ID, DEVICE_TYPE, DEVICE_STRING_REPRESENTATION,
// mark properties fields
MARK_PROPERTIES_ID, MARK_PROPERTIES_FIXED_POSITION, MARK_PROPERTIES_TAGS, MARK_PROPERTIES_TRACKING_DEVICE_IDENTIFIER, MARK_PROPERTIES_USED_ROLE, MARK_PROPERTIES_USED_TEMPLATE,
// common mark properties
COMMON_MARK_PROPERTIES_COLOR, COMMON_MARK_PROPERTIES_NAME, COMMON_MARK_PROPERTIES_PATTERN, COMMON_MARK_PROPERTIES_SHAPE, COMMON_MARK_PROPERTIES_SHORT_NAME, COMMON_MARK_PROPERTIES_TYPE,
// mark template fields
MARK_TEMPLATE_ID,
// mark role fields
MARK_ROLE_ID, MARK_ROLE_NAME,
// repeatable part
REPEATABLE_PART_START, REPEATABLE_PART_END,
// course template fields
COURSE_TEMPLATE_ID, COURSE_TEMPLATE_NAME, COURSE_TEMPLATE_IMAGE_URL, COURSE_TEMPLATE_MARK_TEMPLATES, COURSE_TEMPLATE_MARK_TEMPLATE_ID, COURSE_TEMPLATE_MARK_TEMPLATE_ROLE_ID, COURSE_TEMPLATE_TAGS, COURSE_TEMPLATE_REPEATABLE_PART, COURSE_TEMPLATE_WAYPOINTS, COURSE_TEMPLATE_DEFAULT_NUMBER_OF_LAPS,
// waypoint template fields
WAYPOINT_TEMPLATE_PASSINGINSTRUCTION, WAYPOINT_TEMPLATE_MARK_TEMPLATES, WAYPOINT_TEMPLATE_CONTROL_POINT_NAME, WAYPOINT_TEMPLATE_CONTROL_POINT_SHORT_NAME
}
@@ -0,0 +1,297 @@
package com.sap.sailing.shared.persistence.impl;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.bson.Document;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.sap.sailing.domain.common.DeviceIdentifier;
import com.sap.sailing.domain.common.PassingInstruction;
import com.sap.sailing.domain.common.Position;
import com.sap.sailing.domain.common.racelog.tracking.TransformationException;
import com.sap.sailing.domain.coursetemplate.CommonMarkProperties;
import com.sap.sailing.domain.coursetemplate.CourseTemplate;
import com.sap.sailing.domain.coursetemplate.MarkProperties;
import com.sap.sailing.domain.coursetemplate.MarkRole;
import com.sap.sailing.domain.coursetemplate.MarkTemplate;
import com.sap.sailing.domain.coursetemplate.WaypointTemplate;
import com.sap.sailing.shared.persistence.MongoObjectFactory;
import com.sap.sailing.shared.persistence.device.DeviceIdentifierMongoHandler;
import com.sap.sailing.shared.persistence.device.impl.PlaceHolderDeviceIdentifierMongoHandler;
import com.sap.sse.common.NoCorrespondingServiceRegisteredException;
import com.sap.sse.common.TypeBasedServiceFinder;
import com.sap.sse.common.TypeBasedServiceFinderFactory;
public class MongoObjectFactoryImpl implements MongoObjectFactory {
private static final Logger logger = Logger.getLogger(MongoObjectFactoryImpl.class.getName());
private final MongoDatabase database;
private final TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder;
public MongoObjectFactoryImpl(MongoDatabase mongoDatabase) {
this(mongoDatabase, /* serviceFinderFactory */ null);
}
public MongoObjectFactoryImpl(MongoDatabase mongoDatabase, TypeBasedServiceFinderFactory serviceFinderFactory) {
this.database = mongoDatabase;
if (serviceFinderFactory != null) {
this.deviceIdentifierServiceFinder = serviceFinderFactory.createServiceFinder(DeviceIdentifierMongoHandler.class);
this.deviceIdentifierServiceFinder.setFallbackService(new PlaceHolderDeviceIdentifierMongoHandler());
} else {
this.deviceIdentifierServiceFinder = null;
}
}
@Override
public MongoDatabase getDatabase() {
return database;
}
@Override
public void storeMarkProperties(TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder,
MarkProperties markProperties) {
MongoCollection<Document> collection = database.getCollection(CollectionNames.MARK_PROPERTIES.name());
Document query = new Document(FieldNames.MARK_PROPERTIES_ID.name(), markProperties.getId().toString());
try {
Document entry = storeMarkPropertiesToDocument(deviceIdentifierServiceFinder, markProperties);
collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).replaceOne(query, entry,
new UpdateOptions().upsert(true));
} catch (TransformationException | NoCorrespondingServiceRegisteredException e) {
logger.log(Level.WARNING, "Could not load mark properties because device identifier could not be stored.",
e);
}
}
private Document storeMarkPropertiesToDocument(
TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder,
MarkProperties markProperties) throws TransformationException, NoCorrespondingServiceRegisteredException {
final Document result = new Document();
result.put(FieldNames.MARK_PROPERTIES_ID.name(), markProperties.getId().toString());
storeCommonMarkProperties(markProperties, result);
final Position fixedPositionOrNull = markProperties.getFixedPosition();
if (fixedPositionOrNull != null) {
result.put(FieldNames.MARK_PROPERTIES_FIXED_POSITION.name(),
storePosition(markProperties.getFixedPosition()));
}
BasicDBList tags = new BasicDBList();
markProperties.getTags().forEach(tags::add);
result.put(FieldNames.MARK_PROPERTIES_TAGS.name(), tags);
final DeviceIdentifier trackingDeviceIdentifierOrNull = markProperties.getTrackingDeviceIdentifier();
if (trackingDeviceIdentifierOrNull != null) {
result.put(FieldNames.MARK_PROPERTIES_TRACKING_DEVICE_IDENTIFIER.name(),
storeDeviceId(deviceIdentifierServiceFinder, trackingDeviceIdentifierOrNull));
}
Map<String, Long> lastUsedTemplateMap = markProperties.getLastUsedTemplate().entrySet().stream()
.collect(Collectors.toMap(k -> k.getKey().getId().toString(), v -> v.getValue().asMillis()));
result.put(FieldNames.MARK_PROPERTIES_USED_TEMPLATE.name(), new BasicDBObject(lastUsedTemplateMap));
Map<String, Long> lastUsedRoleMap = markProperties.getLastUsedRole().entrySet().stream()
.collect(Collectors.toMap(k -> k.getKey().getId().toString(), v -> v.getValue().asMillis()));
result.put(FieldNames.MARK_PROPERTIES_USED_ROLE.name(), new BasicDBObject(lastUsedRoleMap));
return result;
}
public static Document storeDeviceId(
TypeBasedServiceFinder<DeviceIdentifierMongoHandler> deviceIdentifierServiceFinder, DeviceIdentifier device)
throws TransformationException, NoCorrespondingServiceRegisteredException {
String type = device.getIdentifierType();
DeviceIdentifierMongoHandler handler = deviceIdentifierServiceFinder.findService(type);
com.sap.sse.common.Util.Pair<String, ? extends Object> pair = handler.serialize(device);
type = pair.getA();
Object deviceTypeSpecificId = pair.getB();
return new Document()
.append(FieldNames.DEVICE_TYPE.name(), type)
.append(FieldNames.DEVICE_TYPE_SPECIFIC_ID.name(), deviceTypeSpecificId)
.append(FieldNames.DEVICE_STRING_REPRESENTATION.name(), device.getStringRepresentation());
}
private Document storePosition(Position position) {
Document result = new Document();
result.put(FieldNames.LAT_DEG.name(), position.getLatDeg());
result.put(FieldNames.LNG_DEG.name(), position.getLngDeg());
return result;
}
private void storeCommonMarkProperties(CommonMarkProperties markProperties, final Document result) {
if (markProperties.getColor() != null) {
result.put(FieldNames.COMMON_MARK_PROPERTIES_COLOR.name(), markProperties.getColor().getAsHtml());
}
result.put(FieldNames.COMMON_MARK_PROPERTIES_NAME.name(), markProperties.getName());
result.put(FieldNames.COMMON_MARK_PROPERTIES_PATTERN.name(), markProperties.getPattern());
result.put(FieldNames.COMMON_MARK_PROPERTIES_SHAPE.name(), markProperties.getShape());
result.put(FieldNames.COMMON_MARK_PROPERTIES_SHORT_NAME.name(), markProperties.getShortName());
result.put(FieldNames.COMMON_MARK_PROPERTIES_TYPE.name(),
markProperties.getType() == null ? null : markProperties.getType().name());
}
@Override
public void removeMarkProperties(UUID markPropertiesId) {
MongoCollection<Document> configurationsCollections = database
.getCollection(CollectionNames.MARK_PROPERTIES.name());
Document query = new Document(FieldNames.MARK_PROPERTIES_ID.name(), markPropertiesId.toString());
configurationsCollections.deleteOne(query);
}
@Override
public void storeMarkTemplate(MarkTemplate markTemplate) {
final MongoCollection<Document> collection = database.getCollection(CollectionNames.MARK_TEMPLATES.name());
final Document query = new Document(FieldNames.MARK_TEMPLATE_ID.name(), markTemplate.getId().toString());
final Document entry = storeMarkTemplateToDocument(markTemplate);
collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).replaceOne(query, entry,
new UpdateOptions().upsert(true));
}
private Document storeMarkTemplateToDocument(MarkTemplate markTemplate) {
final Document result = new Document(FieldNames.MARK_TEMPLATE_ID.name(), markTemplate.getId().toString());
storeCommonMarkProperties(markTemplate, result);
return result;
}
@Override
public void removeMarkTemplate(UUID markTemplateId) {
final MongoCollection<Document> configurationsCollections = database
.getCollection(CollectionNames.MARK_TEMPLATES.name());
final Document query = new Document(FieldNames.MARK_TEMPLATE_ID.name(), markTemplateId.toString());
configurationsCollections.deleteOne(query);
}
@Override
public void storeMarkRole(MarkRole markRole) {
final MongoCollection<Document> collection = database.getCollection(CollectionNames.MARK_ROLES.name());
final Document query = new Document(FieldNames.MARK_ROLE_ID.name(), markRole.getId().toString());
final Document entry = storeMarkRoleToDocument(markRole);
collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).replaceOne(query, entry,
new UpdateOptions().upsert(true));
}
private Document storeMarkRoleToDocument(MarkRole markRole) {
final Document result = new Document(FieldNames.MARK_ROLE_ID.name(), markRole.getId().toString());
result.put(FieldNames.MARK_ROLE_NAME.name(), markRole.getName());
return result;
}
@Override
public void removeMarkRole(UUID markRoleId) {
final MongoCollection<Document> configurationsCollections = database
.getCollection(CollectionNames.MARK_ROLES.name());
final Document query = new Document(FieldNames.MARK_ROLE_ID.name(), markRoleId.toString());
configurationsCollections.deleteOne(query);
}
@Override
public void storeCourseTemplate(CourseTemplate courseTemplate) {
final MongoCollection<Document> collection = database.getCollection(CollectionNames.COURSE_TEMPLATES.name());
final Document query = new Document(FieldNames.COURSE_TEMPLATE_ID.name(), courseTemplate.getId().toString());
final Document entry = storeCourseTemplateToDocument(courseTemplate);
collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).replaceOne(query, entry,
new UpdateOptions().upsert(true));
}
private Document storeCourseTemplateToDocument(CourseTemplate courseTemplate) {
final Document result = new Document();
// store master data
result.put(FieldNames.COURSE_TEMPLATE_ID.name(), courseTemplate.getId().toString());
result.put(FieldNames.COURSE_TEMPLATE_NAME.name(), courseTemplate.getName());
result.put(FieldNames.COURSE_TEMPLATE_DEFAULT_NUMBER_OF_LAPS.name(), courseTemplate.getDefaultNumberOfLaps());
final URL optionalImageURL = courseTemplate.getOptionalImageURL();
if (optionalImageURL != null) {
result.put(FieldNames.COURSE_TEMPLATE_IMAGE_URL.name(), optionalImageURL.toExternalForm());
}
// store mark template list including role names for those who have one defined
final BasicDBList markTemplates = new BasicDBList();
courseTemplate.getMarkTemplatesWithOptionalRoles().forEach((m, role) -> {
final BasicDBObject markTemplateObject = new BasicDBObject(
FieldNames.COURSE_TEMPLATE_MARK_TEMPLATE_ID.name(), m.getId().toString());
if (role != null) {
markTemplateObject.append(FieldNames.COURSE_TEMPLATE_MARK_TEMPLATE_ROLE_ID.name(), role.getId().toString());
}
markTemplates.add(markTemplateObject);
});
result.put(FieldNames.COURSE_TEMPLATE_MARK_TEMPLATES.name(), markTemplates);
// store waypoint templates
final BasicDBList waypointTemplates = new BasicDBList();
for (WaypointTemplate waypointTemplate : courseTemplate.getWaypointTemplates()) {
BasicDBObject waypointTemplateObject = storeWaypointTemplate(waypointTemplate);
waypointTemplates.add(waypointTemplateObject);
}
result.put(FieldNames.COURSE_TEMPLATE_WAYPOINTS.name(), waypointTemplates);
// tags
final BasicDBList tags = new BasicDBList();
courseTemplate.getTags().forEach(tags::add);
result.put(FieldNames.COURSE_TEMPLATE_TAGS.name(), tags);
// repeatable part
if (courseTemplate.hasRepeatablePart()) {
final BasicDBObject repeatablePart = storeRepeatablePart(courseTemplate);
result.put(FieldNames.COURSE_TEMPLATE_REPEATABLE_PART.name(), repeatablePart);
}
return result;
}
private BasicDBObject storeWaypointTemplate(WaypointTemplate waypointTemplate) {
BasicDBObject waypointTemplateObject = new BasicDBObject();
waypointTemplateObject.put(FieldNames.WAYPOINT_TEMPLATE_PASSINGINSTRUCTION.name(),
getPassingInstructions(waypointTemplate.getPassingInstruction()));
waypointTemplateObject.put(FieldNames.WAYPOINT_TEMPLATE_CONTROL_POINT_NAME.name(),
waypointTemplate.getControlPointTemplate().getName());
waypointTemplateObject.put(FieldNames.WAYPOINT_TEMPLATE_CONTROL_POINT_SHORT_NAME.name(),
waypointTemplate.getControlPointTemplate().getShortName());
final BasicDBList markTemplates = new BasicDBList();
waypointTemplate.getControlPointTemplate().getMarks().forEach(m -> markTemplates.add(m.getId().toString()));
waypointTemplateObject.put(FieldNames.WAYPOINT_TEMPLATE_MARK_TEMPLATES.name(), markTemplates);
return waypointTemplateObject;
}
// TODO copy of com.sap.sailing.domain.persistence.impl.MongoObjectFactoryImpl
private String getPassingInstructions(PassingInstruction passingInstructions) {
final String passing;
if (passingInstructions != null) {
passing = passingInstructions.name();
} else {
passing = null;
}
return passing;
}
private BasicDBObject storeRepeatablePart(CourseTemplate courseTemplate) {
final BasicDBObject repeatablePart = new BasicDBObject();
repeatablePart.put(FieldNames.REPEATABLE_PART_START.name(),
courseTemplate.getRepeatablePart().getZeroBasedIndexOfRepeatablePartStart());
repeatablePart.put(FieldNames.REPEATABLE_PART_END.name(),
courseTemplate.getRepeatablePart().getZeroBasedIndexOfRepeatablePartEnd());
return repeatablePart;
}
@Override
public void removeCourseTemplate(UUID courseTemplateId) {
final MongoCollection<Document> configurationsCollections = database
.getCollection(CollectionNames.COURSE_TEMPLATES.name());
final Document query = new Document(FieldNames.COURSE_TEMPLATE_ID.name(), courseTemplateId.toString());
configurationsCollections.deleteOne(query);
}
}
@@ -0,0 +1,28 @@
package com.sap.sailing.shared.persistence.impl;
import com.sap.sse.common.TypeBasedServiceFinderFactory;
import com.sap.sse.mongodb.MongoDBService;
import com.sap.sailing.shared.persistence.DomainObjectFactory;
import com.sap.sailing.shared.persistence.MongoObjectFactory;
import com.sap.sailing.shared.persistence.PersistenceFactory;
public class PersistenceFactoryImpl implements PersistenceFactory {
private final DomainObjectFactory defaultDomainObjectFactory;
private final MongoObjectFactory defaultMongoObjectFactory;
public PersistenceFactoryImpl() {
this.defaultDomainObjectFactory = new DomainObjectFactoryImpl(MongoDBService.INSTANCE.getDB());
this.defaultMongoObjectFactory = new MongoObjectFactoryImpl(MongoDBService.INSTANCE.getDB());
}
@Override
public MongoObjectFactory getDefaultMongoObjectFactory(TypeBasedServiceFinderFactory typeBasedServiceFinderFactory) {
return new MongoObjectFactoryImpl(defaultMongoObjectFactory.getDatabase(), typeBasedServiceFinderFactory);
}
@Override
public DomainObjectFactory getDefaultDomainObjectFactory(TypeBasedServiceFinderFactory typeBasedServiceFinderFactory) {
return new DomainObjectFactoryImpl(defaultDomainObjectFactory.getDatabase(), typeBasedServiceFinderFactory);
}
}