Merge branch 'dev_0.7'
diff --git a/gradlew b/gradlew
old mode 100644
new mode 100755
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManager.java b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManager.java
index 06921ff..bb24acf 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManager.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -52,6 +52,7 @@
import org.eclipse.mdm.api.odsadapter.search.ODSSearchService;
import org.eclipse.mdm.api.odsadapter.transaction.ODSTransaction;
import org.eclipse.mdm.api.odsadapter.utils.ODSConverter;
+import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -86,7 +87,8 @@
/**
* Constructor.
*
- * @param modelManager The {@link ODSModelManager}.
+ * @param modelManager
+ * The {@link ODSModelManager}.
*/
public ODSEntityManager(ODSModelManager modelManager, String esHost) {
this.modelManager = modelManager;
@@ -133,7 +135,7 @@
*/
@Override
public Optional<FileService> getFileService() {
- if(modelManager.getFileServer() == null) {
+ if (modelManager.getFileServer() == null) {
return Optional.empty();
}
return Optional.of(new CORBAFileService(modelManager, transfer));
@@ -145,7 +147,7 @@
@Override
public Environment loadEnvironment() throws DataAccessException {
List<Environment> environments = loadAll(Environment.class);
- if(environments.size() != 1) {
+ if (environments.size() != 1) {
throw new DataAccessException("Unable to laod the environment entity.");
}
@@ -160,16 +162,17 @@
InstanceElement ieUser = null;
try {
ieUser = modelManager.getAoSession().getUser();
- return Optional.of(entityLoader.load(new Key<>(User.class), ODSConverter.fromODSLong(ieUser.getId())));
- } catch(AoException e) {
+ return Optional.of(
+ entityLoader.load(new Key<>(User.class), Long.toString(ODSConverter.fromODSLong(ieUser.getId()))));
+ } catch (AoException e) {
throw new DataAccessException("Unable to load the logged in user entity due to: " + e.reason, e);
} finally {
try {
- if(ieUser != null) {
+ if (ieUser != null) {
ieUser.destroy();
ieUser._release();
}
- } catch(AoException aoe) {
+ } catch (AoException aoe) {
LOGGER.warn("Unable to destroy the CORBA resource due to: " + aoe.reason, aoe);
ieUser._release();
}
@@ -180,7 +183,7 @@
* {@inheritDoc}
*/
@Override
- public <T extends Entity> T load(Class<T> entityClass, Long instanceID) throws DataAccessException {
+ public <T extends Entity> T load(Class<T> entityClass, String instanceID) throws DataAccessException {
return entityLoader.load(new Key<>(entityClass), instanceID);
}
@@ -188,7 +191,7 @@
* {@inheritDoc}
*/
@Override
- public <T extends Entity> T load(Class<T> entityClass, ContextType contextType, Long instanceID)
+ public <T extends Entity> T load(Class<T> entityClass, ContextType contextType, String instanceID)
throws DataAccessException {
return entityLoader.load(new Key<>(entityClass, contextType), instanceID);
}
@@ -202,17 +205,18 @@
EntityType childEntityType = modelManager.getEntityType(child);
Query query = modelManager.createQuery().selectID(parentEntityType);
- if(child instanceof Channel && ChannelGroup.class.equals(entityClass)) {
- // this covers the gap between channel and channel group via local column
+ if (child instanceof Channel && ChannelGroup.class.equals(entityClass)) {
+ // this covers the gap between channel and channel group via local
+ // column
EntityType localColumnEntityType = modelManager.getEntityType("LocalColumn");
query.join(childEntityType, localColumnEntityType).join(localColumnEntityType, parentEntityType);
} else {
query.join(childEntityType, parentEntityType);
}
- Optional<Long> instanceID = query.fetchSingleton(Filter.idOnly(childEntityType, child.getID()))
+ Optional<String> instanceID = query.fetchSingleton(Filter.idOnly(childEntityType, child.getID()))
.map(r -> r.getRecord(parentEntityType)).map(Record::getID);
- if(instanceID.isPresent()) {
+ if (instanceID.isPresent()) {
return Optional.of(entityLoader.load(new Key<>(entityClass), instanceID.get()));
}
@@ -227,30 +231,35 @@
return entityLoader.loadAll(new Key<>(entityClass), pattern);
}
- // /**
- // * {@inheritDoc}
- // */
- // @Override
- // public <T extends StatusAttachable> List<T> loadAll(Class<T> entityClass, Status status, String pattern)
- // throws DataAccessException {
- // EntityType entityType = modelManager.getEntityType(entityClass);
- // EntityType statusEntityType = modelManager.getEntityType(status.getTypeName());
+ // /**
+ // * {@inheritDoc}
+ // */
+ // @Override
+ // public <T extends StatusAttachable> List<T> loadAll(Class<T> entityClass,
+ // Status status, String pattern)
+ // throws DataAccessException {
+ // EntityType entityType = modelManager.getEntityType(entityClass);
+ // EntityType statusEntityType =
+ // modelManager.getEntityType(status.getTypeName());
//
- // List<Long> instanceIDs = modelManager.createQuery()
- // .join(entityType, statusEntityType).selectID(entityType)
- // .fetch(Filter.and()
- // .id(statusEntityType, status.getID())
- // .name(entityType, pattern))
- // .stream().map(r -> r.getRecord(entityType)).map(Record::getID).collect(Collectors.toList());
+ // List<String> instanceIDs = modelManager.createQuery()
+ // .join(entityType, statusEntityType).selectID(entityType)
+ // .fetch(Filter.and()
+ // .id(statusEntityType, status.getID())
+ // .name(entityType, pattern))
+ // .stream().map(r ->
+ // r.getRecord(entityType)).map(Record::getID).collect(Collectors.toList());
//
- // return entityLoader.loadAll(new Key<>(entityClass), instanceIDs);
- // }
+ // return entityLoader.loadAll(new Key<>(entityClass), instanceIDs);
+ // }
//
- // @Override
- // public List<Status> loadAllStatus(Class<? extends StatusAttachable> entityClass, String pattern)
- // throws DataAccessException {
- // return entityLoader.loadAll(new Key<>(Status.class, entityClass), pattern);
- // }
+ // @Override
+ // public List<Status> loadAllStatus(Class<? extends StatusAttachable>
+ // entityClass, String pattern)
+ // throws DataAccessException {
+ // return entityLoader.loadAll(new Key<>(Status.class, entityClass),
+ // pattern);
+ // }
/**
* {@inheritDoc}
@@ -271,43 +280,45 @@
EntityType childEntityType = modelManager.getEntityType(entityClass);
Query query = modelManager.createQuery();
- if(parent instanceof ChannelGroup && Channel.class.equals(entityClass)) {
- // this covers the gap between channel and channel group via local column
+ if (parent instanceof ChannelGroup && Channel.class.equals(entityClass)) {
+ // this covers the gap between channel and channel group via local
+ // column
EntityType localColumnEntityType = modelManager.getEntityType("LocalColumn");
query.join(childEntityType, localColumnEntityType).join(localColumnEntityType, parentEntityType);
} else {
query.join(childEntityType, parentEntityType);
}
- List<Long> instanceIDs = query.selectID(childEntityType)
- .fetch(Filter.and()
- .id(parentEntityType, parent.getID())
- .name(childEntityType, pattern))
- .stream().map(r -> r.getRecord(childEntityType)).map(Record::getID).collect(Collectors.toList());
+ List<String> instanceIDs = query.selectID(childEntityType)
+ .fetch(Filter.and().id(parentEntityType, parent.getID()).name(childEntityType, pattern)).stream()
+ .map(r -> r.getRecord(childEntityType)).map(Record::getID).collect(Collectors.toList());
return entityLoader.loadAll(new Key<>(entityClass), instanceIDs);
}
- // /**
- // * {@inheritDoc}
- // */
- // @Override
- // public <T extends StatusAttachable> List<T> loadChildren(Entity parent, Class<T> entityClass, Status status,
- // String pattern) throws DataAccessException {
- // EntityType parentEntityType = modelManager.getEntityType(parent);
- // EntityType childEntityType = modelManager.getEntityType(entityClass);
- // EntityType statusEntityType = modelManager.getEntityType(status.getTypeName());
+ // /**
+ // * {@inheritDoc}
+ // */
+ // @Override
+ // public <T extends StatusAttachable> List<T> loadChildren(Entity parent,
+ // Class<T> entityClass, Status status,
+ // String pattern) throws DataAccessException {
+ // EntityType parentEntityType = modelManager.getEntityType(parent);
+ // EntityType childEntityType = modelManager.getEntityType(entityClass);
+ // EntityType statusEntityType =
+ // modelManager.getEntityType(status.getTypeName());
//
- // List<Long> instanceIDs = modelManager.createQuery()
- // .join(childEntityType, parentEntityType, statusEntityType)
- // .selectID(childEntityType)
- // .fetch(Filter.and()
- // .id(parentEntityType, parent.getID())
- // .id(statusEntityType, status.getID())
- // .name(childEntityType, pattern))
- // .stream().map(r -> r.getRecord(childEntityType)).map(Record::getID).collect(Collectors.toList());
+ // List<String> instanceIDs = modelManager.createQuery()
+ // .join(childEntityType, parentEntityType, statusEntityType)
+ // .selectID(childEntityType)
+ // .fetch(Filter.and()
+ // .id(parentEntityType, parent.getID())
+ // .id(statusEntityType, status.getID())
+ // .name(childEntityType, pattern))
+ // .stream().map(r ->
+ // r.getRecord(childEntityType)).map(Record::getID).collect(Collectors.toList());
//
- // return entityLoader.loadAll(new Key<>(entityClass), instanceIDs);
- // }
+ // return entityLoader.loadAll(new Key<>(entityClass), instanceIDs);
+ // }
/**
* {@inheritDoc}
@@ -318,19 +329,19 @@
Query query = modelManager.createQuery();
Map<ContextType, EntityType> contextRootEntityTypes = new EnumMap<>(ContextType.class);
- for(ContextType contextType : ContextType.values()) {
+ for (ContextType contextType : ContextType.values()) {
EntityType entityType = modelManager.getEntityType(ContextRoot.class, contextType);
contextRootEntityTypes.put(contextType, entityType);
query.join(contextDescribableEntityType.getRelation(entityType), Join.OUTER).selectID(entityType);
}
- Optional<Result> result = query.fetchSingleton(Filter.idOnly(contextDescribableEntityType,
- contextDescribable.getID()));
- if(result.isPresent()) {
+ Optional<Result> result = query
+ .fetchSingleton(Filter.idOnly(contextDescribableEntityType, contextDescribable.getID()));
+ if (result.isPresent()) {
List<ContextType> contextTypes = new ArrayList<>();
- for(Entry<ContextType, EntityType> entry : contextRootEntityTypes.entrySet()) {
- Optional<Long> instanceID = result.map(r -> r.getRecord(entry.getValue())).map(Record::getID);
- if(instanceID.isPresent()) {
+ for (Entry<ContextType, EntityType> entry : contextRootEntityTypes.entrySet()) {
+ Optional<String> instanceID = result.map(r -> r.getRecord(entry.getValue())).map(Record::getID);
+ if (instanceID.isPresent()) {
contextTypes.add(entry.getKey());
}
}
@@ -351,19 +362,19 @@
Query query = modelManager.createQuery();
Map<ContextType, EntityType> contextRootEntityTypes = new EnumMap<>(ContextType.class);
- for(ContextType contextType : contextTypes.length == 0 ? ContextType.values() : contextTypes) {
+ for (ContextType contextType : contextTypes.length == 0 ? ContextType.values() : contextTypes) {
EntityType entityType = modelManager.getEntityType(ContextRoot.class, contextType);
contextRootEntityTypes.put(contextType, entityType);
query.join(contextDescribableEntityType.getRelation(entityType), Join.OUTER).selectID(entityType);
}
- Optional<Result> result = query.fetchSingleton(Filter.idOnly(contextDescribableEntityType,
- contextDescribable.getID()));
- if(result.isPresent()) {
+ Optional<Result> result = query
+ .fetchSingleton(Filter.idOnly(contextDescribableEntityType, contextDescribable.getID()));
+ if (result.isPresent()) {
Map<ContextType, ContextRoot> contextRoots = new EnumMap<>(ContextType.class);
- for(Entry<ContextType, EntityType> entry : contextRootEntityTypes.entrySet()) {
- Long instanceID = result.get().getRecord(entry.getValue()).getID();
- if(instanceID > 0) {
+ for (Entry<ContextType, EntityType> entry : contextRootEntityTypes.entrySet()) {
+ String instanceID = result.get().getRecord(entry.getValue()).getID();
+ if (ODSUtils.isValidID(instanceID)) {
contextRoots.put(entry.getKey(),
entityLoader.load(new Key<>(ContextRoot.class, entry.getKey()), instanceID));
}
@@ -390,7 +401,7 @@
public Transaction startTransaction() throws DataAccessException {
try {
return new ODSTransaction(modelManager, loadEnvironment(), transfer);
- } catch(AoException e) {
+ } catch (AoException e) {
throw new DataAccessException("Unable to start transaction due to: " + e.reason, e);
}
}
@@ -402,7 +413,7 @@
public void close() throws ConnectionException {
try {
modelManager.close();
- } catch(AoException e) {
+ } catch (AoException e) {
throw new ConnectionException("Unable to close the connection to the data source due to: " + e.reason, e);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManagerFactory.java b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManagerFactory.java
index bf73827..056655a 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManagerFactory.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSEntityManagerFactory.java
@@ -62,7 +62,7 @@
// Instance variables
// ======================================================================
- private final ORB orb = ORB.init(new String[]{}, System.getProperties());
+ private final ORB orb = ORB.init(new String[] {}, System.getProperties());
// ======================================================================
// Public methods
@@ -92,7 +92,7 @@
@Override
public EntityManager connect(Map<String, String> parameters) throws ConnectionException {
AoSession aoSession = null;
- try(ServiceLocator serviceLocator = new ServiceLocator(orb, getParameter(parameters, PARAM_NAMESERVICE))) {
+ try (ServiceLocator serviceLocator = new ServiceLocator(orb, getParameter(parameters, PARAM_NAMESERVICE))) {
String nameOfService = getParameter(parameters, PARAM_SERVICENAME).replace(".ASAM-ODS", "");
AoFactory aoFactory = serviceLocator.resolveFactory(nameOfService);
@@ -108,7 +108,8 @@
LOGGER.info("Connection to ODS server established.");
CORBAFileServerIF fileServer = serviceLocator.resolveFileServer(nameOfService);
- return new ODSEntityManager(new ODSModelManager(orb, aoSession, fileServer), parameters.get(PARAM_ELASTIC_SEARCH_URL));
+ return new ODSEntityManager(new ODSModelManager(orb, aoSession, fileServer),
+ parameters.get(PARAM_ELASTIC_SEARCH_URL));
} catch (AoException e) {
closeSession(aoSession);
throw new ConnectionException("Unablte to connect to ODS server due to: " + e.reason, e);
@@ -122,7 +123,8 @@
/**
* Closes given {@link AoSession} with catching and logging errors.
*
- * @param aoSession The {@code AoSession} that shall be closed.
+ * @param aoSession
+ * The {@code AoSession} that shall be closed.
*/
private static void closeSession(AoSession aoSession) {
if (aoSession == null) {
@@ -139,10 +141,13 @@
/**
* Reads the property identified by given property name.
*
- * @param parameters The properties {@code Map}.
- * @param name The property name.
+ * @param parameters
+ * The properties {@code Map}.
+ * @param name
+ * The property name.
* @return The property value is returned.
- * @throws ConnectionException Thrown if property does not exist or is empty.
+ * @throws ConnectionException
+ * Thrown if property does not exist or is empty.
*/
private static String getParameter(Map<String, String> parameters, String name) throws ConnectionException {
String value = parameters.get(name);
@@ -175,13 +180,16 @@
/**
* Constructor.
*
- * @param orb The {@link ORB} singleton instance.
- * @param path The naming context path.
- * @throws ConnectionException Thrown if unable to resolve the naming context.
+ * @param orb
+ * The {@link ORB} singleton instance.
+ * @param path
+ * The naming context path.
+ * @throws ConnectionException
+ * Thrown if unable to resolve the naming context.
*/
public ServiceLocator(ORB orb, String path) throws ConnectionException {
namingContext = NamingContextExtHelper.narrow(orb.string_to_object(path));
- if(namingContext == null) {
+ if (namingContext == null) {
throw new ConnectionException("Unable to resolve NameService '" + path + "'.");
}
}
@@ -193,9 +201,11 @@
/**
* Resolves and returns the {@link AoFactory} service for given ID.
*
- * @param id Used as identifier.
+ * @param id
+ * Used as identifier.
* @return The {@code AoFactory} is returned.
- * @throws ConnectionException Thrown if unable to resolve the {@code
+ * @throws ConnectionException
+ * Thrown if unable to resolve the {@code
* AoFactory}.
*/
public AoFactory resolveFactory(String id) throws ConnectionException {
@@ -203,16 +213,18 @@
}
/**
- * Resolves and returns the {@link CORBAFileServerIF} service for
- * given ID.
+ * Resolves and returns the {@link CORBAFileServerIF} service for given
+ * ID.
*
- * @param id Used as identifier.
- * @return The {@code CORBAFileServerIF} or null, if none found, is returned.
+ * @param id
+ * Used as identifier.
+ * @return The {@code CORBAFileServerIF} or null, if none found, is
+ * returned.
*/
public CORBAFileServerIF resolveFileServer(String id) {
try {
return CORBAFileServerIFHelper.narrow(resolve(id, "CORBA-FT"));
- } catch(ConnectionException e) {
+ } catch (ConnectionException e) {
LOGGER.warn(e.getMessage());
return null;
}
@@ -221,15 +233,18 @@
/**
* Resolves a CORBA service object for given id and kind.
*
- * @param id Used as identifier.
- * @param kind Used as qualifier.
+ * @param id
+ * Used as identifier.
+ * @param kind
+ * Used as qualifier.
* @return The resolved CORBA service object is returned.
- * @throws ConnectionException Thrown in case of errors.
+ * @throws ConnectionException
+ * Thrown in case of errors.
*/
- public Object resolve(String id, String kind) throws ConnectionException {
+ public Object resolve(String id, String kind) throws ConnectionException {
try {
return namingContext.resolve(new NameComponent[] { new NameComponent(id, kind) });
- } catch(NotFound | CannotProceed | InvalidName e) {
+ } catch (NotFound | CannotProceed | InvalidName e) {
throw new ConnectionException("Unable to resolve service '" + id + "." + kind + "'.", e);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSNotificationManagerFactory.java b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSNotificationManagerFactory.java
index a0d55b4..7053bd4 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/ODSNotificationManagerFactory.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/ODSNotificationManagerFactory.java
@@ -22,7 +22,8 @@
/**
* Factory for creating a notification manager.
*
- * Currently only supports creating a notification manager for server type 'peak'.
+ * Currently only supports creating a notification manager for server type
+ * 'peak'.
*
* @since 1.0.0
* @author Matthias Koller, Peak Solution GmbH
@@ -30,81 +31,73 @@
*/
@Stateful
@LocalBean
-public class ODSNotificationManagerFactory implements NotificationManagerFactory
-{
+public class ODSNotificationManagerFactory implements NotificationManagerFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ODSNotificationManagerFactory.class);
-
+
public static final String PARAM_SERVER_TYPE = "serverType";
public static final String PARAM_URL = "url";
public static final String PARAM_EVENT_MEDIATYPE = "eventMimetype";
public static final String PARAM_POLLING_INTERVAL = "pollingInterval";
-
+
public static final String SERVER_TYPE_PEAK = "peak";
public static final String SERVER_TYPE_AVALON = "avalon";
public static final String PARAM_NAMESERVICE_URL = "nameserviceURL";
- public NotificationManager create(BaseEntityManager<? extends BaseEntityFactory> entityManager, Map<String, String> parameters) throws ConnectionException {
+ public NotificationManager create(BaseEntityManager<? extends BaseEntityFactory> entityManager,
+ Map<String, String> parameters) throws ConnectionException {
String type = getParameter(parameters, PARAM_SERVER_TYPE);
-
+
Optional<ModelManager> mm = entityManager.getModelManager();
- if (!mm.isPresent())
- {
+ if (!mm.isPresent()) {
throw new ConnectionException("EntityManager has no ModelManager!");
}
- if (!ODSModelManager.class.isInstance(mm.get()))
- {
+ if (!ODSModelManager.class.isInstance(mm.get())) {
throw new ConnectionException("ModelManager is not a ODSModelManager!");
}
-
- if (SERVER_TYPE_PEAK.equalsIgnoreCase(type))
- {
+
+ if (SERVER_TYPE_PEAK.equalsIgnoreCase(type)) {
String url = getParameter(parameters, PARAM_URL);
String eventMediaType = getParameter(parameters, PARAM_EVENT_MEDIATYPE);
-
+
LOGGER.info("Connecting to Peak Notification Server ...");
LOGGER.info("URL: {}", url);
LOGGER.info("Event MediaType: {}", eventMediaType);
-
+
try {
return new PeakNotificationManager((ODSModelManager) mm.get(), url, eventMediaType, true);
} catch (NotificationException e) {
throw new ConnectionException("Could not connect to notification service!", e);
}
- }
- else if (SERVER_TYPE_AVALON.equalsIgnoreCase(type))
- {
-
+ } else if (SERVER_TYPE_AVALON.equalsIgnoreCase(type)) {
+
String serviceName = getParameter(parameters, ODSEntityManagerFactory.PARAM_SERVICENAME);
serviceName = serviceName.replace(".ASAM-ODS", "");
String nameServiceURL = getParameter(parameters, ODSEntityManagerFactory.PARAM_NAMESERVICE);
-
+
LOGGER.info("Connecting to Avalon Notification Server ...");
LOGGER.info("Name service URL: {}", nameServiceURL);
LOGGER.info("Service name: {}", serviceName);
-
+
long pollingInterval = 500L;
- try
- {
+ try {
pollingInterval = Long.parseLong(getParameter(parameters, PARAM_POLLING_INTERVAL));
+ } catch (NumberFormatException | ConnectionException e) {
+ LOGGER.warn("Could not parse parse parameter pollingInterval. Using default value: " + pollingInterval,
+ e);
}
- catch (NumberFormatException | ConnectionException e)
- {
- LOGGER.warn("Could not parse parse parameter pollingInterval. Using default value: " + pollingInterval, e);
- }
-
- return new AvalonNotificationManager((ODSModelManager) mm.get(), serviceName, nameServiceURL, true, pollingInterval);
- }
- else
- {
+
+ return new AvalonNotificationManager((ODSModelManager) mm.get(), serviceName, nameServiceURL, true,
+ pollingInterval);
+ } else {
throw new ConnectionException("Invalid server type. Expected on of: 'peak'");
}
}
-
+
private String getParameter(Map<String, String> parameters, String name) throws ConnectionException {
String value = parameters.get(name);
- if(value == null || value.isEmpty()) {
+ if (value == null || value.isEmpty()) {
throw new ConnectionException("Connection parameter with name '" + name + "' is either missing or empty.");
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/ReadRequestHandler.java b/src/main/java/org/eclipse/mdm/api/odsadapter/ReadRequestHandler.java
index c1a49ad..53611f0 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/ReadRequestHandler.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/ReadRequestHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -50,7 +50,8 @@
/**
* Constructor.
*
- * @param modelManager Used to gain access to value matrices.
+ * @param modelManager
+ * Used to gain access to value matrices.
*/
public ReadRequestHandler(ODSModelManager modelManager) {
this.modelManager = modelManager;
@@ -63,9 +64,11 @@
/**
* Loads {@link MeasuredValues} as defined in given {@link ReadRequest}.
*
- * @param readRequest The {@code MeasuredValues} request configuration.
+ * @param readRequest
+ * The {@code MeasuredValues} request configuration.
* @return The loaded {@code MeasuredValues} are returned.
- * @throws DataAccessException Thrown if unable to load {@code
+ * @throws DataAccessException
+ * Thrown if unable to load {@code
* MeasuredValues}.
*/
public List<MeasuredValues> execute(ReadRequest readRequest) throws DataAccessException {
@@ -78,7 +81,7 @@
NameValueSeqUnit[] nvsus = valueMatrix.getValue(columns, readRequest.getStartIndex(),
readRequest.getRequestSize());
return ODSConverter.fromODSMeasuredValuesSeq(nvsus);
- } catch(AoException aoe) {
+ } catch (AoException aoe) {
throw new DataAccessException(aoe.reason, aoe);
} finally {
releaseColumns(columns);
@@ -92,43 +95,49 @@
/**
* Loads all for each defined {@link Channel} in given {@link ReadRequest}
- * and loads the corresponding {@link Column} using given {@link
- * ValueMatrix}.
+ * and loads the corresponding {@link Column} using given
+ * {@link ValueMatrix}.
*
- * @param readRequest Defines required {@code Column}s.
- * @param valueMatrix Used to load required {@code Column}s.
+ * @param readRequest
+ * Defines required {@code Column}s.
+ * @param valueMatrix
+ * Used to load required {@code Column}s.
* @return {@code Column} configured in given {@code ReadRequest} are
- * returned with defined {@link Unit} setup.
- * @throws AoException Throw if unable to load all available {@code Column}s.
- * @throws DataAccessException Thrown on wrong {@code ReadRequest} setup.
+ * returned with defined {@link Unit} setup.
+ * @throws AoException
+ * Throw if unable to load all available {@code Column}s.
+ * @throws DataAccessException
+ * Thrown on wrong {@code ReadRequest} setup.
*/
private Column[] getODSColumns(ReadRequest readRequest, ValueMatrix valueMatrix)
throws AoException, DataAccessException {
- if(readRequest.isLoadAllChannels()) {
- // TODO should it be possible to overwrite the unit of some channels?!
- // -> this results in a performance issue since we need to call getName()
+ if (readRequest.isLoadAllChannels()) {
+ // TODO should it be possible to overwrite the unit of some
+ // channels?!
+ // -> this results in a performance issue since we need to call
+ // getName()
// on each column for mapping!
return valueMatrix.getColumns("*");
}
List<Column> columnList = new ArrayList<>();
try {
- for(Entry<Channel, Unit> entry : readRequest.getChannels().entrySet()) {
+ for (Entry<Channel, Unit> entry : readRequest.getChannels().entrySet()) {
Channel channel = entry.getKey();
Unit unit = entry.getValue();
Column[] columns = valueMatrix.getColumns(channel.getName());
- if(columns == null || columns.length != 1) {
+ if (columns == null || columns.length != 1) {
releaseColumns(columns);
throw new DataAccessException("Column with name '" + channel.getName() + "' not found.");
}
Column column = columns[0];
- if(!unit.nameMatches(channel.getUnit().getName())) {
+ if (!unit.nameMatches(channel.getUnit().getName())) {
column.setUnit(unit.getName());
}
columnList.add(column);
}
return columnList.toArray(new Column[columnList.size()]);
- } catch(AoException e) {
+ } catch (AoException e) {
releaseColumns(columnList.toArray(new Column[columnList.size()]));
throw new DataAccessException("Unable to load column due to: " + e.reason, e);
}
@@ -138,30 +147,33 @@
* Returns the {@link ValueMatrix} CORBA service object associated with
* given {@link ReadRequest}.
*
- * @param readRequest The {@code ReadRequest}.
+ * @param readRequest
+ * The {@code ReadRequest}.
* @return The {@code ValueMatrix} is returned.
- * @throws AoException Thrown if unable to load the {@code ValueMatrix}.
+ * @throws AoException
+ * Thrown if unable to load the {@code ValueMatrix}.
*/
private ValueMatrix getValueMatrix(ReadRequest readRequest) throws AoException {
Entity entity = readRequest.getChannelGroup();
- T_LONGLONG iid = ODSConverter.toODSLong(entity.getID());
- T_LONGLONG aid = ((ODSEntityType) modelManager.getEntityType(entity)).getODSID();
+ T_LONGLONG iid = ODSConverter.toODSID(entity.getID());
+ T_LONGLONG aid = ((ODSEntityType) modelManager.getEntityType(entity)).getODSID();
return modelManager.getApplElemAccess().getValueMatrixInMode(new ElemId(aid, iid), ValueMatrixMode.CALCULATED);
}
/**
* Releases given {@link ValueMatrix} CORBA object.
*
- * @param valueMatrix Will be released.
+ * @param valueMatrix
+ * Will be released.
*/
private void releaseValueMatrix(ValueMatrix valueMatrix) {
- if(valueMatrix == null) {
+ if (valueMatrix == null) {
return;
}
try {
valueMatrix.destroy();
- } catch(AoException aoe) {
+ } catch (AoException aoe) {
// ignore
} finally {
valueMatrix._release();
@@ -171,17 +183,18 @@
/**
* Releases each CORBA {@link Column} object.
*
- * @param columns Will be released.
+ * @param columns
+ * Will be released.
*/
- private void releaseColumns(Column[] columns) {
- if(columns == null) {
+ private void releaseColumns(Column[] columns) {
+ if (columns == null) {
return;
}
for (Column column : columns) {
try {
column.destroy();
- } catch(AoException e) {
+ } catch (AoException e) {
// ignore
} finally {
column._release();
@@ -190,4 +203,3 @@
}
}
-
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileServer.java b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileServer.java
index 282a27c..13c9d19 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileServer.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileServer.java
@@ -40,8 +40,8 @@
import com.highqsoft.corbafileserver.generated.SeverityFlag;
/**
- * Service provides access to the low level {@link CORBAFileServerIF}
- * file service API.
+ * Service provides access to the low level {@link CORBAFileServerIF} file
+ * service API.
*
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
@@ -75,8 +75,10 @@
/**
* Constructor.
*
- * @param modelManager Used for setup.
- * @param transfer The transfer type for up- and downloads.
+ * @param modelManager
+ * Used for setup.
+ * @param transfer
+ * The transfer type for up- and downloads.
*/
CORBAFileServer(ODSModelManager modelManager, Transfer transfer) {
fileServer = modelManager.getFileServer();
@@ -92,19 +94,22 @@
// ======================================================================
/**
- * Opens a consumable download {@link InputStream} for given {@link
- * FileLink}.
+ * Opens a consumable download {@link InputStream} for given
+ * {@link FileLink}.
*
- * @param fileLink Used to access the remote path.
- * @param elemId Used for security checks.
+ * @param fileLink
+ * Used to access the remote path.
+ * @param elemId
+ * Used for security checks.
* @return The consumable {@code InputStream} is returned.
- * @throws IOException Thrown if unable to open an the {@code InputStream}.
+ * @throws IOException
+ * Thrown if unable to open an the {@code InputStream}.
*/
public InputStream openStream(FileLink fileLink, ElemId elemId) throws IOException {
InputStream inputStream;
- if(transfer.isStream()) {
+ if (transfer.isStream()) {
inputStream = new InputStreamAdapter(openSimpleStream(fileLink, elemId));
- } else if(transfer.isSocket()) {
+ } else if (transfer.isSocket()) {
inputStream = openSocketStream(fileLink, elemId);
} else {
throw new IllegalStateException("Transfer state '" + transfer + "' is not supported.");
@@ -116,16 +121,20 @@
/**
* Uploads given {@link InputStream} for given {@link FileLink}.
*
- * @param inputStream The {@code InputStream} to be uploaded.
- * @param fileLink The associated {@code FileLink}.
- * @param elemId Used for security checks.
- * @throws IOException Thrown if unable to upload given {@code InputStream}.
+ * @param inputStream
+ * The {@code InputStream} to be uploaded.
+ * @param fileLink
+ * The associated {@code FileLink}.
+ * @param elemId
+ * Used for security checks.
+ * @throws IOException
+ * Thrown if unable to upload given {@code InputStream}.
*/
public void uploadStream(InputStream inputStream, FileLink fileLink, ElemId elemId) throws IOException {
String remotePath;
- if(transfer.isStream()) {
+ if (transfer.isStream()) {
remotePath = uploadVIAStream(inputStream, fileLink, elemId);
- } else if(transfer.isSocket()) {
+ } else if (transfer.isSocket()) {
remotePath = uploadVIASocket(inputStream, fileLink, elemId);
} else {
throw new IllegalStateException("Transfer state '" + transfer + "' is not supported.");
@@ -137,10 +146,13 @@
/**
* Loads the file size for given {@link FileLink}.
*
- * @param fileLink The {@code FileLink} whose file size will be loaded.
- * @param elemId Used for security checks.
+ * @param fileLink
+ * The {@code FileLink} whose file size will be loaded.
+ * @param elemId
+ * Used for security checks.
* @return The file size is returned.
- * @throws IOException Thrown if unable to load the file size.
+ * @throws IOException
+ * Thrown if unable to load the file size.
*/
public long loadSize(FileLink fileLink, ElemId elemId) throws IOException {
try {
@@ -153,9 +165,12 @@
/**
* Deletes the {@link FileLink} from the remote storage.
*
- * @param fileLink Will be deleted from the remote storage.
- * @param elemId Used for security checks.
- * @throws IOException Thrown if unable to delete given {@code FileLink}.
+ * @param fileLink
+ * Will be deleted from the remote storage.
+ * @param elemId
+ * Used for security checks.
+ * @throws IOException
+ * Thrown if unable to delete given {@code FileLink}.
*/
public void delete(FileLink fileLink, ElemId elemId) throws IOException {
try {
@@ -172,10 +187,13 @@
/**
* Opens a simple {@link InputStreamIF} using the {@link CORBAFileServerIF}.
*
- * @param fileLink Used to access the remote path.
- * @param elemId Used for security checks.
+ * @param fileLink
+ * Used to access the remote path.
+ * @param elemId
+ * Used for security checks.
* @return The {@code InputStreamIF} is returned.
- * @throws IOException Thrown if unable to open the {@code InputStreamIF}.
+ * @throws IOException
+ * Thrown if unable to open the {@code InputStreamIF}.
*/
private InputStreamIF openSimpleStream(FileLink fileLink, ElemId elemId) throws IOException {
try {
@@ -188,23 +206,26 @@
/**
* Opens a socket {@link InputStream} using the {@link CORBAFileServerIF}.
*
- * @param fileLink Used to access the remote path.
- * @param elemId Used for security checks.
+ * @param fileLink
+ * Used to access the remote path.
+ * @param elemId
+ * Used for security checks.
* @return The {@code InputStream} is returned.
- * @throws IOException Thrown if unable to open the socket {@code
+ * @throws IOException
+ * Thrown if unable to open the socket {@code
* InputStream}.
*/
private InputStream openSocketStream(FileLink fileLink, ElemId elemId) throws IOException {
// auto assigned port with awaiting exactly ONE incoming connection
- try(ServerSocket serverSocket = new ServerSocket(0, 1)) {
+ try (ServerSocket serverSocket = new ServerSocket(0, 1)) {
serverSocket.setSoTimeout(SOCKET_TIMEOUT * 6);
new Thread(() -> {
try {
/*
- * NOTE: Since a socket file transfer registration may block until
- * this server socket's accept method is called, the registration
- * is done asynchronously!
+ * NOTE: Since a socket file transfer registration may block
+ * until this server socket's accept method is called, the
+ * registration is done asynchronously!
*/
fileServer.getForInstanceBySocket(aoSession, fileLink.getRemotePath(), elemId.aid, elemId.iid,
InetAddress.getLocalHost().getHostName(), serverSocket.getLocalPort());
@@ -223,16 +244,20 @@
* Uploads given {@link InputStream} for given {@link FileLink} using the
* {@link CORBAFileServerIF}.
*
- * @param inputStream The {@code InputStream} to be uploaded.
- * @param fileLink The associated {@code FileLink}.
- * @param elemId Used for security checks.
+ * @param inputStream
+ * The {@code InputStream} to be uploaded.
+ * @param fileLink
+ * The associated {@code FileLink}.
+ * @param elemId
+ * Used for security checks.
* @return The remote path of the uploaded {@code InputStream} is returned.
- * @throws IOException Thrown if unable to upload given {@code InputStream}.
+ * @throws IOException
+ * Thrown if unable to upload given {@code InputStream}.
*/
private String uploadVIAStream(InputStream inputStream, FileLink fileLink, ElemId elemId) throws IOException {
- try(CORBAInputStreamAdapter stream = new CORBAInputStreamAdapter(orb, inputStream, fileLink.getSize())) {
- return fileServer.saveForInstance(aoSession, fileLink.getFileName(), "",
- elemId.aid, elemId.iid, stream._this());
+ try (CORBAInputStreamAdapter stream = new CORBAInputStreamAdapter(orb, inputStream, fileLink.getSize())) {
+ return fileServer.saveForInstance(aoSession, fileLink.getFileName(), "", elemId.aid, elemId.iid,
+ stream._this());
} catch (CORBAFileServerException e) {
throw new IOException("Unable to upload file via stream due to: " + e.reason, e);
}
@@ -242,11 +267,15 @@
* Uploads given {@link InputStream} for given {@link FileLink} via socket
* upload using the {@link CORBAFileServerIF}.
*
- * @param inputStream The {@code InputStream} to be uploaded.
- * @param fileLink The associated {@code FileLink}.
- * @param elemId Used for security checks.
+ * @param inputStream
+ * The {@code InputStream} to be uploaded.
+ * @param fileLink
+ * The associated {@code FileLink}.
+ * @param elemId
+ * Used for security checks.
* @return The remote path of the uploaded {@code InputStream} is returned.
- * @throws IOException Thrown if unable to upload given {@code InputStream}.
+ * @throws IOException
+ * Thrown if unable to upload given {@code InputStream}.
*/
private String uploadVIASocket(InputStream inputStream, FileLink fileLink, ElemId elemId) throws IOException {
// auto assigned port with awaiting exactly ONE incoming connection
@@ -254,14 +283,14 @@
serverSocket.setSoTimeout(SOCKET_TIMEOUT * 6);
new Thread(() -> {
- try(Socket client = serverSocket.accept(); OutputStream outputStream = client.getOutputStream()) {
+ try (Socket client = serverSocket.accept(); OutputStream outputStream = client.getOutputStream()) {
byte[] buffer = new byte[bufferSize];
int length;
- while((length = inputStream.read(buffer)) > -1) {
+ while ((length = inputStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, length);
}
- } catch(IOException e) {
+ } catch (IOException e) {
LOGGER.error("Unable to initialize socket stream, awaiting socket timeout.", e);
}
}).start();
@@ -276,15 +305,16 @@
}
/**
- * Tries to load the buffer size used by the {@link CORBAFileServerIF}
- * to reach best performance. In case of errors a default buffer size of
- * of {@value #DEFAULT_BUFFER_SIZE} is used.
+ * Tries to load the buffer size used by the {@link CORBAFileServerIF} to
+ * reach best performance. In case of errors a default buffer size of of
+ * {@value #DEFAULT_BUFFER_SIZE} is used.
*
* @return The buffer size is returned.
*/
private int getBufferSize() {
try {
- // try to use the same buffer size as the corba file server for best performance
+ // try to use the same buffer size as the corba file server for best
+ // performance
return Integer.parseInt(fileServer.getContext(aoSession, "CORBAFileServer.BufferSize"));
} catch (CORBAFileServerException e) {
return DEFAULT_BUFFER_SIZE;
@@ -296,8 +326,8 @@
// ======================================================================
/**
- * A simple {@link InputStream} adapter implementation for an {@link
- * InputStreamIF}.
+ * A simple {@link InputStream} adapter implementation for an
+ * {@link InputStreamIF}.
*/
private static final class InputStreamAdapter extends InputStream {
@@ -314,7 +344,8 @@
/**
* Constructor.
*
- * @param inputStream The wrapped {@link InputStreamIF}.
+ * @param inputStream
+ * The wrapped {@link InputStreamIF}.
*/
private InputStreamAdapter(InputStreamIF inputStream) {
this.inputStream = inputStream;
@@ -341,11 +372,11 @@
try {
DS_BYTEHolder byteHolder = new DS_BYTEHolder();
int receivedBytes = inputStream.read(byteHolder, offset, length);
- if(receivedBytes > 0) {
+ if (receivedBytes > 0) {
System.arraycopy(byteHolder.value, 0, buffer, 0, receivedBytes);
}
return receivedBytes;
- } catch(CORBAFileServerException e) {
+ } catch (CORBAFileServerException e) {
throw new IOException("Failed to retrieve bytes from CORBA input stream due to: " + e.reason, e);
}
}
@@ -368,8 +399,8 @@
// remotely consumable local input stream
/**
- * A simple {@link InputStreamIF} adapter implementation for an {@link
- * InputStream}.
+ * A simple {@link InputStreamIF} adapter implementation for an
+ * {@link InputStream}.
*/
private static final class CORBAInputStreamAdapter extends InputStreamIFPOA implements AutoCloseable {
@@ -390,11 +421,15 @@
/**
* Constructor.
*
- * @param orb Used to access the root {@link POA} to activate this
- * CORBA service object.
- * @param inputStream The wrapped {@link InputStream}.
- * @param length The length of the wrapped {@code InputStream}.
- * @throws IOException Thrown on errors.
+ * @param orb
+ * Used to access the root {@link POA} to activate this CORBA
+ * service object.
+ * @param inputStream
+ * The wrapped {@link InputStream}.
+ * @param length
+ * The length of the wrapped {@code InputStream}.
+ * @throws IOException
+ * Thrown on errors.
*/
private CORBAInputStreamAdapter(ORB orb, InputStream inputStream, long length) throws IOException {
this.inputStream = inputStream;
@@ -423,8 +458,8 @@
try {
return inputStream.read(b.value, off, len);
} catch (IOException e) {
- throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION,
- SeverityFlag.ERROR, e.getMessage());
+ throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION, SeverityFlag.ERROR,
+ e.getMessage());
}
}
@@ -436,8 +471,8 @@
try {
inputStream.close();
} catch (IOException e) {
- throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION,
- SeverityFlag.ERROR, e.getMessage());
+ throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION, SeverityFlag.ERROR,
+ e.getMessage());
} finally {
try {
poa.deactivate_object(objectID);
@@ -453,9 +488,9 @@
@Override
public int length() throws CORBAFileServerException {
/*
- * NOTE: A file length is of type long and therefore,
- * for very large files (> 2.14 GB), the exact length
- * is lost due to narrowing conversion!
+ * NOTE: A file length is of type long and therefore, for very large
+ * files (> 2.14 GB), the exact length is lost due to narrowing
+ * conversion!
*/
return (int) length;
}
@@ -468,8 +503,8 @@
try {
inputStream.reset();
} catch (IOException e) {
- throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION,
- SeverityFlag.ERROR, e.getMessage());
+ throw new CORBAFileServerException(ErrorCode.FILESERVER_IO_EXCEPTION, SeverityFlag.ERROR,
+ e.getMessage());
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileService.java b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileService.java
index 3bd9c8a..0ab1058 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileService.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/CORBAFileService.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -71,8 +71,10 @@
/**
* Constructor.
*
- * @param modelManager Used for {@link Entity} to {@link ElemId} conversion.
- * @param transfer The transfer type for up- and downloads.
+ * @param modelManager
+ * Used for {@link Entity} to {@link ElemId} conversion.
+ * @param transfer
+ * The transfer type for up- and downloads.
*/
public CORBAFileService(ODSModelManager modelManager, Transfer transfer) {
this.modelManager = modelManager;
@@ -97,17 +99,17 @@
LocalTime start = LocalTime.now();
UUID id = UUID.randomUUID();
LOGGER.debug("Sequential download of {} file(s) with id '{}' started.", groups.size(), id);
- for(List<FileLink> group : groups.values()) {
+ for (List<FileLink> group : groups.values()) {
FileLink fileLink = group.get(0);
download(entity, target, fileLink, (b, p) -> {
double tranferredBytes = transferred.addAndGet(b);
- if(progressListener != null) {
+ if (progressListener != null) {
progressListener.progress(b, (float) (tranferredBytes / totalSize));
}
});
- for(FileLink other : group.subList(1, group.size())) {
+ for (FileLink other : group.subList(1, group.size())) {
other.setLocalPath(fileLink.getLocalPath());
}
}
@@ -132,12 +134,12 @@
download(entity, target, fileLink, (b, p) -> {
double tranferredBytes = transferred.addAndGet(b);
- if(progressListener != null) {
+ if (progressListener != null) {
progressListener.progress(b, (float) (tranferredBytes / totalSize));
}
});
- for(FileLink other : group.subList(1, group.size())) {
+ for (FileLink other : group.subList(1, group.size())) {
other.setLocalPath(fileLink.getLocalPath());
}
@@ -154,13 +156,13 @@
try {
future.get();
return null;
- } catch(ExecutionException | InterruptedException e) {
+ } catch (ExecutionException | InterruptedException e) {
LOGGER.error("Download of failed due to: " + e.getMessage(), e);
return e;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
- if(!errors.isEmpty()) {
+ if (!errors.isEmpty()) {
throw new IOException("Download faild for '" + errors.size() + "' files.");
}
LOGGER.debug("Parallel download with id '{}' finished in {}.", id,
@@ -176,17 +178,17 @@
* {@inheritDoc}
*/
@Override
- public void download(Entity entity, Path target, FileLink fileLink,
- ProgressListener progressListener) throws IOException {
- if(Files.exists(target)) {
- if(!Files.isDirectory(target)) {
+ public void download(Entity entity, Path target, FileLink fileLink, ProgressListener progressListener)
+ throws IOException {
+ if (Files.exists(target)) {
+ if (!Files.isDirectory(target)) {
throw new IllegalArgumentException("Target path is not a directory.");
}
} else {
Files.createDirectory(target);
}
- try(InputStream inputStream = openStream(entity, fileLink, progressListener)) {
+ try (InputStream inputStream = openStream(entity, fileLink, progressListener)) {
fileLink.setLocalPath(target.resolve(fileLink.getFileName()));
Path absolutePath = fileLink.getLocalPath().toAbsolutePath();
String remotePath = fileLink.getRemotePath();
@@ -202,22 +204,23 @@
* {@inheritDoc}
*/
@Override
- public InputStream openStream(Entity entity, FileLink fileLink,
- ProgressListener progressListener) throws IOException {
+ public InputStream openStream(Entity entity, FileLink fileLink, ProgressListener progressListener)
+ throws IOException {
InputStream sourceStream;
- if(fileLink.isLocal()) {
+ if (fileLink.isLocal()) {
// file is locally available -> USE this shortcut!
sourceStream = Files.newInputStream(fileLink.getLocalPath());
- } else if(fileLink.isRemote()) {
+ } else if (fileLink.isRemote()) {
sourceStream = fileServer.openStream(fileLink, toElemID(entity));
} else {
throw new IllegalArgumentException("File link is neither in local nor remote state: " + fileLink);
}
// NOTE: Access to immediate input stream is buffered.
- if(progressListener != null) {
+ if (progressListener != null) {
loadSize(entity, fileLink);
- // NOTE: Progress updates immediately triggered by the stream consumer.
+ // NOTE: Progress updates immediately triggered by the stream
+ // consumer.
return new TracedInputStream(sourceStream, progressListener, fileLink.getSize());
}
@@ -229,12 +232,12 @@
*/
@Override
public void loadSize(Entity entity, FileLink fileLink) throws IOException {
- if(fileLink.getSize() > -1) {
+ if (fileLink.getSize() > -1) {
// file size is already known
return;
- } else if(fileLink.isLocal()) {
+ } else if (fileLink.isLocal()) {
fileLink.setFileSize(Files.size(fileLink.getLocalPath()));
- } else if(fileLink.isRemote()) {
+ } else if (fileLink.isRemote()) {
fileLink.setFileSize(fileServer.loadSize(fileLink, toElemID(entity)));
} else {
throw new IllegalArgumentException("File link is neither in local nor remote state: " + fileLink);
@@ -246,13 +249,17 @@
* multiple times are uploaded only once. The upload progress may be traced
* with a progress listener.
*
- * @param entity Used for security checks.
- * @param fileLinks Collection of {@code FileLink}s to upload.
- * @param progressListener The progress listener.
- * @throws IOException Thrown if unable to upload files.
+ * @param entity
+ * Used for security checks.
+ * @param fileLinks
+ * Collection of {@code FileLink}s to upload.
+ * @param progressListener
+ * The progress listener.
+ * @throws IOException
+ * Thrown if unable to upload files.
*/
- public void uploadSequential(Entity entity, Collection<FileLink> fileLinks,
- ProgressListener progressListener) throws IOException {
+ public void uploadSequential(Entity entity, Collection<FileLink> fileLinks, ProgressListener progressListener)
+ throws IOException {
Map<Path, List<FileLink>> groups = fileLinks.stream().filter(FileLink::isLocal)
.collect(Collectors.groupingBy(FileLink::getLocalPath));
@@ -261,17 +268,17 @@
LocalTime start = LocalTime.now();
UUID id = UUID.randomUUID();
LOGGER.debug("Sequential upload of {} file(s) with id '{}' started.", groups.size(), id);
- for(List<FileLink> group : groups.values()) {
+ for (List<FileLink> group : groups.values()) {
FileLink fileLink = group.get(0);
upload(entity, fileLink, (b, p) -> {
double tranferredBytes = transferred.addAndGet(b);
- if(progressListener != null) {
+ if (progressListener != null) {
progressListener.progress(b, (float) (tranferredBytes / totalSize));
}
});
- for(FileLink other : group.subList(1, group.size())) {
+ for (FileLink other : group.subList(1, group.size())) {
other.setRemotePath(fileLink.getRemotePath());
}
}
@@ -283,13 +290,17 @@
* multiple times are uploaded only once. The upload progress may be traced
* with a progress listener.
*
- * @param entity Used for security checks.
- * @param fileLinks Collection of {@code FileLink}s to upload.
- * @param progressListener The progress listener.
- * @throws IOException Thrown if unable to upload files.
+ * @param entity
+ * Used for security checks.
+ * @param fileLinks
+ * Collection of {@code FileLink}s to upload.
+ * @param progressListener
+ * The progress listener.
+ * @throws IOException
+ * Thrown if unable to upload files.
*/
- public void uploadParallel(Entity entity, Collection<FileLink> fileLinks,
- ProgressListener progressListener) throws IOException {
+ public void uploadParallel(Entity entity, Collection<FileLink> fileLinks, ProgressListener progressListener)
+ throws IOException {
Map<Path, List<FileLink>> groups = fileLinks.stream().filter(FileLink::isLocal)
.collect(Collectors.groupingBy(FileLink::getLocalPath));
@@ -302,12 +313,12 @@
upload(entity, fileLink, (b, p) -> {
double tranferredBytes = transferred.addAndGet(b);
- if(progressListener != null) {
+ if (progressListener != null) {
progressListener.progress(b, (float) (tranferredBytes / totalSize));
}
});
- for(FileLink other : group.subList(1, group.size())) {
+ for (FileLink other : group.subList(1, group.size())) {
other.setRemotePath(fileLink.getRemotePath());
}
@@ -324,13 +335,13 @@
try {
future.get();
return null;
- } catch(ExecutionException | InterruptedException e) {
+ } catch (ExecutionException | InterruptedException e) {
LOGGER.error("Upload of failed due to: " + e.getMessage(), e);
return e;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
- if(!errors.isEmpty()) {
+ if (!errors.isEmpty()) {
throw new IOException("Upload faild for '" + errors.size() + "' files.");
}
LOGGER.debug("Parallel upload with id '{}' finished in {}.", id, Duration.between(start, LocalTime.now()));
@@ -344,24 +355,27 @@
/**
* Deletes given {@link FileLink}s form the remote storage.
*
- * @param entity Used for security checks.
- * @param fileLinks Collection of {@code FileLink}s to delete.
+ * @param entity
+ * Used for security checks.
+ * @param fileLinks
+ * Collection of {@code FileLink}s to delete.
*/
public void delete(Entity entity, Collection<FileLink> fileLinks) {
fileLinks.stream().filter(FileLink::isRemote)
- .collect(groupingBy(FileLink::getRemotePath, reducing((fl1, fl2) -> fl1)))
- .values().stream().filter(Optional::isPresent).map(Optional::get)
- .forEach(fl -> delete(entity, fl));
+ .collect(groupingBy(FileLink::getRemotePath, reducing((fl1, fl2) -> fl1))).values().stream()
+ .filter(Optional::isPresent).map(Optional::get).forEach(fl -> delete(entity, fl));
}
/**
* Deletes given {@link FileLink} form the remote storage.
*
- * @param entity Used for security checks.
- * @param fileLink The {@code FileLink}s to delete.
+ * @param entity
+ * Used for security checks.
+ * @param fileLink
+ * The {@code FileLink}s to delete.
*/
public void delete(Entity entity, FileLink fileLink) {
- if(!fileLink.isRemote()) {
+ if (!fileLink.isRemote()) {
// nothing to do
return;
}
@@ -379,24 +393,28 @@
// ======================================================================
/**
- * Uploads given {@link FileLink}. The upload progress may be traced with
- * a progress listener.
+ * Uploads given {@link FileLink}. The upload progress may be traced with a
+ * progress listener.
*
- * @param entity Used for security checks.
- * @param fileLink The {@code FileLink} to upload.
- * @param progressListener The progress listener.
- * @throws IOException Thrown if unable to upload file.
+ * @param entity
+ * Used for security checks.
+ * @param fileLink
+ * The {@code FileLink} to upload.
+ * @param progressListener
+ * The progress listener.
+ * @throws IOException
+ * Thrown if unable to upload file.
*/
private void upload(Entity entity, FileLink fileLink, ProgressListener progressListener) throws IOException {
- if(fileLink.isRemote()) {
+ if (fileLink.isRemote()) {
// nothing to do
return;
- } else if(!fileLink.isLocal()) {
+ } else if (!fileLink.isLocal()) {
throw new IllegalArgumentException("File link does not have a local path.");
}
InputStream sourceStream = Files.newInputStream(fileLink.getLocalPath());
- if(progressListener != null) {
+ if (progressListener != null) {
sourceStream = new TracedInputStream(sourceStream, progressListener, fileLink.getSize());
}
@@ -409,29 +427,33 @@
}
/**
- * Creates an ODS entity identity {@link ElemId} object for given {@link
- * Entity}.
+ * Creates an ODS entity identity {@link ElemId} object for given
+ * {@link Entity}.
*
- * @param entity The {@code Entity}.
+ * @param entity
+ * The {@code Entity}.
* @return The created {@code ElemId} is returned.
*/
private ElemId toElemID(Entity entity) {
return new ElemId(((ODSEntityType) modelManager.getEntityType(entity)).getODSID(),
- ODSConverter.toODSLong(entity.getID()));
+ ODSConverter.toODSID(entity.getID()));
}
/**
* Calculates the total download size for given {@link FileLink} groups.
*
- * @param entity Used for security checks.
- * @param groups The {@code FileLink} groups.
+ * @param entity
+ * Used for security checks.
+ * @param groups
+ * The {@code FileLink} groups.
* @return The total download size is returned.
- * @throws IOException Thrown if unable to load the file size.
+ * @throws IOException
+ * Thrown if unable to load the file size.
*/
private long calculateDownloadSize(Entity entity, Map<String, List<FileLink>> groups) throws IOException {
List<FileLink> links = groups.values().stream().map(l -> l.get(0)).collect(Collectors.toList());
long totalSize = 0;
- for(FileLink fileLink : links) {
+ for (FileLink fileLink : links) {
loadSize(entity, fileLink);
// overflow may occur in case of total size exceeds 9223 PB!
totalSize = Math.addExact(totalSize, fileLink.getSize());
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/TracedInputStream.java b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/TracedInputStream.java
index a0bb3a6..7f1901f 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/TracedInputStream.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/filetransfer/TracedInputStream.java
@@ -39,10 +39,12 @@
/**
* Constructor.
*
- * @param inputStream The traced {@link InputStream}.
- * @param progressListener The listener will be used to fire update
- * notifications.
- * @param length The length of the consumed {@code InputStream}.
+ * @param inputStream
+ * The traced {@link InputStream}.
+ * @param progressListener
+ * The listener will be used to fire update notifications.
+ * @param length
+ * The length of the consumed {@code InputStream}.
*/
TracedInputStream(InputStream inputStream, ProgressListener progressListener, long length) {
this.progressListener = progressListener;
@@ -68,7 +70,7 @@
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int read = inputStream.read(buffer, offset, length);
- if(read > -1) {
+ if (read > -1) {
transferred += read;
progressListener.progress(read, (float) (transferred / size));
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/Cache.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/Cache.java
index 1a53eb8..2238bff 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/Cache.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/Cache.java
@@ -27,24 +27,27 @@
/**
* Caches given {@link EntityResult}.
*
- * @param entityResult The {@link EntityResult}.
+ * @param entityResult
+ * The {@link EntityResult}.
*/
public void add(EntityResult<?> entityResult) {
cache.put(entityResult.request.entityConfig, entityResult);
}
/**
- * Returns the cached {@link EntityResult} associated with given {@link
- * EntityConfig}.
+ * Returns the cached {@link EntityResult} associated with given
+ * {@link EntityConfig}.
*
- * @param entityConfig Used as identifier.
+ * @param entityConfig
+ * Used as identifier.
* @return The {@code EntityResult} is returned.
- * @throws IllegalArgumentException Thrown if requested {@code
+ * @throws IllegalArgumentException
+ * Thrown if requested {@code
* EntityResult} not found.
*/
public EntityResult<?> get(EntityConfig<?> entityConfig) {
EntityResult<?> entityResult = cache.get(entityConfig);
- if(entityResult == null) {
+ if (entityResult == null) {
throw new IllegalArgumentException("Entity result not found");
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/ChildRequest.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/ChildRequest.java
index 81566c8..ebdd4f2 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/ChildRequest.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/ChildRequest.java
@@ -17,12 +17,12 @@
import org.eclipse.mdm.api.base.query.Relation;
import org.eclipse.mdm.api.odsadapter.lookup.config.EntityConfig;
-
/**
- * Extends {@link EntityRequest} to load children for a given {@link
- * EntityRequest}.
+ * Extends {@link EntityRequest} to load children for a given
+ * {@link EntityRequest}.
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -41,8 +41,10 @@
/**
* Constructor.
*
- * @param parentRequest The parent {@link EntityRequest}.
- * @param entityConfig The {@link EntityConfig}.
+ * @param parentRequest
+ * The parent {@link EntityRequest}.
+ * @param entityConfig
+ * The {@link EntityConfig}.
*/
ChildRequest(EntityRequest<?> parentRequest, EntityConfig<T> entityConfig) {
super(parentRequest, entityConfig);
@@ -57,7 +59,8 @@
* Loads all related child entities.
*
* @return Returns the queried {@code EntityResult}.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
public EntityResult<T> load() throws DataAccessException {
filtered = parent.filtered;
@@ -72,9 +75,10 @@
// select parent entity ID
.select(parentRelation.getAttribute());
- if(entityConfig.isReflexive()) {
+ if (entityConfig.isReflexive()) {
query.select(reflexiveRelation.getAttribute());
- // entities with children have to be processed before their children!
+ // entities with children have to be processed before their
+ // children!
query.order(entityType.getIDAttribute());
}
@@ -85,10 +89,10 @@
// configure filter
Filter adjustedFilter = Filter.or();
- if(filtered) {
+ if (filtered) {
// preserve current conditions
adjustedFilter.ids(parentRelation, parent.entityResult.getIDs());
- if(entityConfig.isReflexive()) {
+ if (entityConfig.isReflexive()) {
// extend to retrieve all reflexive child candidates
adjustedFilter.add(Operation.IS_NOT_NULL.create(reflexiveRelation.getAttribute(), 0L));
}
@@ -96,27 +100,27 @@
// load entities and prepare mappings for required related entities
List<EntityRecord<?>> parentRecords = new ArrayList<>();
- for(Record record : collectRecords(query.fetch(adjustedFilter))) {
- Optional<Long> parentID = record.getID(parentRelation);
- Optional<Long> reflexiveParentID = Optional.empty();
- if(entityConfig.isReflexive()) {
+ for (Record record : collectRecords(query.fetch(adjustedFilter))) {
+ Optional<String> parentID = record.getID(parentRelation);
+ Optional<String> reflexiveParentID = Optional.empty();
+ if (entityConfig.isReflexive()) {
reflexiveParentID = record.getID(reflexiveRelation);
}
EntityRecord<T> entityRecord;
- if(parentID.isPresent()) {
+ if (parentID.isPresent()) {
EntityResult<?> parentResult = parent.entityResult;
@SuppressWarnings({ "unchecked", "rawtypes" })
Optional<EntityRecord<?>> parentRecord = (Optional) parentResult.get(parentID.get());
- if(!parentRecord.isPresent()) {
+ if (!parentRecord.isPresent()) {
continue;
}
entityRecord = entityResult.add(parentRecord.get(), record);
parentRecords.add(parentRecord.get());
- } else if(entityConfig.isReflexive() && reflexiveParentID.isPresent()) {
+ } else if (entityConfig.isReflexive() && reflexiveParentID.isPresent()) {
Optional<EntityRecord<T>> parentRecord = entityResult.get(reflexiveParentID.get());
- if(!parentRecord.isPresent()) {
+ if (!parentRecord.isPresent()) {
// this entity's parent was not loaded -> skip
continue;
}
@@ -129,10 +133,10 @@
// collect related instance IDs
concat(concat(optionalRelations.stream(), mandatoryRelations.stream()), inheritedRelations.stream())
- .forEach(rc -> rc.add(entityRecord, record));
+ .forEach(rc -> rc.add(entityRecord, record));
}
- if(entityResult.isEmpty()) {
+ if (entityResult.isEmpty()) {
// no entities found -> neither related nor child entities required
return entityResult;
}
@@ -143,12 +147,12 @@
assignRelatedEntities(inheritedRelations);
// sort children of parent
- for(EntityRecord<?> entityRecord : parentRecords) {
+ for (EntityRecord<?> entityRecord : parentRecords) {
entityRecord.core.getChildrenStore().sort(entityConfig.getEntityClass(), entityConfig.getComparator());
}
// load children
- for(EntityConfig<? extends Deletable> childConfig : entityConfig.getChildConfigs()) {
+ for (EntityConfig<? extends Deletable> childConfig : entityConfig.getChildConfigs()) {
cache.add(new ChildRequest<>(this, childConfig).load());
}
@@ -163,25 +167,27 @@
* Maps related entities for each given {@link RelationConfig} using the
* entities loaded in previous {@link EntityRequest}.
*
- * @param relationConfigs The {@code RelationConfig}s.
- * @throws DataAccessException Thrown if unable to load related entities.
+ * @param relationConfigs
+ * The {@code RelationConfig}s.
+ * @throws DataAccessException
+ * Thrown if unable to load related entities.
*/
private void assignRelatedEntities(List<RelationConfig> relationConfigs) throws DataAccessException {
- for(RelationConfig relationConfig : relationConfigs) {
+ for (RelationConfig relationConfig : relationConfigs) {
EntityConfig<?> relatedConfig = relationConfig.entityConfig;
boolean isContextTypeDefined = entityConfig.getContextType().isPresent();
- for(Entity relatedEntity : cache.get(relatedConfig).getEntities()) {
+ for (Entity relatedEntity : cache.get(relatedConfig).getEntities()) {
boolean setByContextType = !isContextTypeDefined && relatedConfig.getContextType().isPresent();
List<EntityRecord<?>> entityRecords = relationConfig.dependants.remove(relatedEntity.getID());
entityRecords = entityRecords == null ? new ArrayList<EntityRecord<?>>() : entityRecords;
- for(EntityRecord<?> entityRecord : entityRecords) {
+ for (EntityRecord<?> entityRecord : entityRecords) {
setRelatedEntity(entityRecord, relatedEntity,
setByContextType ? relatedConfig.getContextType().get() : null);
}
}
- if(!relationConfig.dependants.isEmpty()) {
+ if (!relationConfig.dependants.isEmpty()) {
// this may occur if the instance id of the related entity
// is defined, but the entity itself does not exist
throw new IllegalStateException("Unable to load related entities.");
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityLoader.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityLoader.java
index d91f87f..1707353 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityLoader.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityLoader.java
@@ -31,7 +31,8 @@
/**
* Constructor.
*
- * @param modelManager The {@link ODSModelManager}.
+ * @param modelManager
+ * The {@link ODSModelManager}.
*/
public EntityLoader(ODSModelManager modelManager) {
this.modelManager = modelManager;
@@ -44,15 +45,19 @@
/**
* Loads the entity with given instance ID.
*
- * @param <T> The entity type.
- * @param key Used to resolve the entity configuration.
- * @param instanceID The instance ID.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used to resolve the entity configuration.
+ * @param instanceID
+ * The instance ID.
* @return The queried {@code Entity} is returned.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
- public <T extends Entity> T load(Key<T> key, Long instanceID) throws DataAccessException {
+ public <T extends Entity> T load(Key<T> key, String instanceID) throws DataAccessException {
List<T> entities = loadAll(key, Collections.singletonList(instanceID));
- if(entities.size() != 1) {
+ if (entities.size() != 1) {
throw new DataAccessException("Faild to load entity by instance ID.");
}
return entities.get(0);
@@ -61,13 +66,17 @@
/**
* Loads all entities matching given name pattern.
*
- * @param <T> The entity type.
- * @param key Used to resolve the entity configuration.
- * @param pattern Is always case sensitive and may contain wildcard
- * characters as follows: "?" for one matching character and "*"
- * for a sequence of matching characters.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used to resolve the entity configuration.
+ * @param pattern
+ * Is always case sensitive and may contain wildcard characters
+ * as follows: "?" for one matching character and "*" for a
+ * sequence of matching characters.
* @return A {@link List} with queried entities is returned.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
public <T extends Entity> List<T> loadAll(Key<T> key, String pattern) throws DataAccessException {
return createRequest(key).loadAll(pattern);
@@ -76,13 +85,17 @@
/**
* Loads all entities matching given instance IDs.
*
- * @param <T> The entity type.
- * @param key Used to resolve the entity configuration.
- * @param instanceIDs The instance IDs.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used to resolve the entity configuration.
+ * @param instanceIDs
+ * The instance IDs.
* @return A {@link List} with queried entities is returned.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
- public <T extends Entity> List<T> loadAll(Key<T> key, Collection<Long> instanceIDs) throws DataAccessException {
+ public <T extends Entity> List<T> loadAll(Key<T> key, Collection<String> instanceIDs) throws DataAccessException {
return createRequest(key).loadAll(instanceIDs);
}
@@ -93,8 +106,10 @@
/**
* Creates a new {@link EntityRequest} for given {@link Key}.
*
- * @param <T> The entity type.
- * @param key Used to resolve the entity configuration.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used to resolve the entity configuration.
* @return The created {@code EntityRequest} is returned.
*/
private <T extends Entity> EntityRequest<T> createRequest(Key<T> key) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRecord.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRecord.java
index 08fc581..f1ede3f 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRecord.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRecord.java
@@ -6,7 +6,8 @@
/**
* Utility class to group {@link Entity} and its {@link Core}.
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -26,8 +27,10 @@
/**
* Constructor.
*
- * @param entity The {@link Entity}.
- * @param core The {@link Core} of the {@code Entity}.
+ * @param entity
+ * The {@link Entity}.
+ * @param core
+ * The {@link Core} of the {@code Entity}.
*/
EntityRecord(T entity, Core core) {
this.entity = entity;
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRequest.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRequest.java
index e5e4553..9c81920 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRequest.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityRequest.java
@@ -32,10 +32,11 @@
import org.eclipse.mdm.api.odsadapter.query.ODSModelManager;
/**
- * Recursively loads entities for a given {@link EntityConfig} with all
- * resolved dependencies (optional, mandatory children).
+ * Recursively loads entities for a given {@link EntityConfig} with all resolved
+ * dependencies (optional, mandatory children).
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -61,8 +62,10 @@
/**
* Constructor.
*
- * @param modelManager The {@link ODSModelManager}.
- * @param config The {@link EntityConfig}.
+ * @param modelManager
+ * The {@link ODSModelManager}.
+ * @param config
+ * The {@link EntityConfig}.
*/
public EntityRequest(ModelManager modelManager, EntityConfig<T> config) {
this.modelManager = modelManager;
@@ -73,8 +76,10 @@
/**
* Constructor.
*
- * @param parentRequest The parent {@link EntityRequest}.
- * @param entityConfig The {@link EntityConfig}.
+ * @param parentRequest
+ * The parent {@link EntityRequest}.
+ * @param entityConfig
+ * The {@link EntityConfig}.
*/
protected EntityRequest(EntityRequest<?> parentRequest, EntityConfig<T> entityConfig) {
modelManager = parentRequest.modelManager;
@@ -89,11 +94,13 @@
/**
* Loads all entities matching given name pattern.
*
- * @param pattern Is always case sensitive and may contain wildcard
- * characters as follows: "?" for one matching character and "*"
- * for a sequence of matching characters.
+ * @param pattern
+ * Is always case sensitive and may contain wildcard characters
+ * as follows: "?" for one matching character and "*" for a
+ * sequence of matching characters.
* @return A sorted {@link List} with queried entities is returned.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
public List<T> loadAll(String pattern) throws DataAccessException {
return load(Filter.nameOnly(entityConfig.getEntityType(), pattern)).getSortedEntities();
@@ -102,12 +109,14 @@
/**
* Loads all entities matching given instance IDs.
*
- * @param instanceIDs The instance IDs.
+ * @param instanceIDs
+ * The instance IDs.
* @return A sorted {@link List} with queried entities is returned.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
- public List<T> loadAll(Collection<Long> instanceIDs) throws DataAccessException {
- if(instanceIDs.isEmpty()) {
+ public List<T> loadAll(Collection<String> instanceIDs) throws DataAccessException {
+ if (instanceIDs.isEmpty()) {
// just to be sure...
return Collections.emptyList();
}
@@ -123,10 +132,13 @@
* Adds foreign key select statements to given {@link Query} for each given
* {@link EntityConfig}.
*
- * @param query The {@link Query}.
- * @param relatedConfigs The {@code EntityConfig}s.
- * @param mandatory Flag indicates whether given {@code EntityConfig}s are
- * mandatory or not.
+ * @param query
+ * The {@link Query}.
+ * @param relatedConfigs
+ * The {@code EntityConfig}s.
+ * @param mandatory
+ * Flag indicates whether given {@code EntityConfig}s are
+ * mandatory or not.
* @return For each {@code EntityConfig} a corresponding {@code
* RelationConfig} is returned in a {@code List}.
*/
@@ -134,7 +146,7 @@
boolean mandatory) {
List<RelationConfig> relationConfigs = new ArrayList<>();
EntityType entityType = entityConfig.getEntityType();
- for(EntityConfig<?> relatedEntityConfig : relatedConfigs) {
+ for (EntityConfig<?> relatedEntityConfig : relatedConfigs) {
RelationConfig relationConfig = new RelationConfig(entityType, relatedEntityConfig, mandatory);
query.select(relationConfig.relation.getAttribute());
relationConfigs.add(relationConfig);
@@ -147,7 +159,8 @@
* Convenience method collects the queried {@link Record} from each
* {@link Result}.
*
- * @param results The {@code Result}s.
+ * @param results
+ * The {@code Result}s.
* @return The queried {@link Record}s are returned.
*/
protected List<Record> collectRecords(List<Result> results) {
@@ -157,24 +170,26 @@
/**
* Loads and maps related entities for each given {@link RelationConfig}.
*
- * @param relationConfigs The {@code RelationConfig}s.
- * @throws DataAccessException Thrown if unable to load related entities.
+ * @param relationConfigs
+ * The {@code RelationConfig}s.
+ * @throws DataAccessException
+ * Thrown if unable to load related entities.
*/
protected void loadRelatedEntities(List<RelationConfig> relationConfigs) throws DataAccessException {
- for(RelationConfig relationConfig : relationConfigs) {
+ for (RelationConfig relationConfig : relationConfigs) {
EntityConfig<?> relatedConfig = relationConfig.entityConfig;
boolean isContextTypeDefined = entityConfig.getContextType().isPresent();
- for(Entity relatedEntity : new EntityRequest<>(this, relatedConfig)
+ for (Entity relatedEntity : new EntityRequest<>(this, relatedConfig)
.loadAll(relationConfig.dependants.keySet())) {
boolean setByContextType = !isContextTypeDefined && relatedConfig.getContextType().isPresent();
- for(EntityRecord<?> entityRecord : relationConfig.dependants.remove(relatedEntity.getID())) {
+ for (EntityRecord<?> entityRecord : relationConfig.dependants.remove(relatedEntity.getID())) {
setRelatedEntity(entityRecord, relatedEntity,
setByContextType ? relatedConfig.getContextType().get() : null);
}
}
- if(!relationConfig.dependants.isEmpty()) {
+ if (!relationConfig.dependants.isEmpty()) {
// this may occur if the instance id of the related entity
// is defined, but the entity itself does not exist
throw new IllegalStateException("Unable to load related entities.");
@@ -185,25 +200,29 @@
/**
* Assigns given related {@link Entity} to given {@link EntityRecord}.
*
- * @param entityRecord The {@code EntityRecord} which references given {@code Entity}.
- * @param relatedEntity The related {@code Entity}.
- * @param contextType Used as qualifier for relation assignment.
+ * @param entityRecord
+ * The {@code EntityRecord} which references given
+ * {@code Entity}.
+ * @param relatedEntity
+ * The related {@code Entity}.
+ * @param contextType
+ * Used as qualifier for relation assignment.
*/
protected void setRelatedEntity(EntityRecord<?> entityRecord, Entity relatedEntity, ContextType contextType) {
- if(contextType == null) {
+ if (contextType == null) {
entityRecord.core.getMutableStore().set(relatedEntity);
} else {
entityRecord.core.getMutableStore().set(relatedEntity, contextType);
}
List<TemplateAttribute> templateAttributes = new ArrayList<>();
- if(entityRecord.entity instanceof ContextComponent && relatedEntity instanceof TemplateComponent) {
+ if (entityRecord.entity instanceof ContextComponent && relatedEntity instanceof TemplateComponent) {
templateAttributes.addAll(((TemplateComponent) relatedEntity).getTemplateAttributes());
- } else if(entityRecord.entity instanceof ContextSensor && relatedEntity instanceof TemplateSensor) {
+ } else if (entityRecord.entity instanceof ContextSensor && relatedEntity instanceof TemplateSensor) {
templateAttributes.addAll(((TemplateSensor) relatedEntity).getTemplateAttributes());
}
- if(!templateAttributes.isEmpty()) {
+ if (!templateAttributes.isEmpty()) {
// hide Value containers that are missing in the template
Set<String> names = new HashSet<>(entityRecord.core.getValues().keySet());
names.remove(Entity.ATTR_NAME);
@@ -221,9 +240,11 @@
* Loads all entities matching given {@link Filter} including all of related
* entities (optional, mandatory and children).
*
- * @param filter The {@link Filter}.
+ * @param filter
+ * The {@link Filter}.
* @return Returns the queried {@code EntityResult}.
- * @throws DataAccessException Thrown if unable to load entities.
+ * @throws DataAccessException
+ * Thrown if unable to load entities.
*/
private EntityResult<T> load(Filter filter) throws DataAccessException {
filtered = !filter.isEmtpty() || entityConfig.isReflexive();
@@ -233,9 +254,10 @@
Query query = modelManager.createQuery().selectAll(entityConfig.getEntityType());
- if(entityConfig.isReflexive()) {
+ if (entityConfig.isReflexive()) {
query.select(reflexiveRelation.getAttribute());
- // entities with children have to be processed before their children!
+ // entities with children have to be processed before their
+ // children!
query.order(entityType.getIDAttribute());
}
@@ -245,10 +267,10 @@
// configure filter
Filter adjustedFilter = Filter.or();
- if(filtered) {
+ if (filtered) {
// preserve current conditions
adjustedFilter.merge(filter);
- if(entityConfig.isReflexive()) {
+ if (entityConfig.isReflexive()) {
// extend to retrieve all reflexive child candidates
adjustedFilter.add(Operation.IS_NOT_NULL.create(reflexiveRelation.getAttribute(), 0L));
}
@@ -256,16 +278,16 @@
// load entities and prepare mappings for required related entities
List<EntityRecord<?>> parentRecords = new ArrayList<>();
- for(Record record : collectRecords(query.fetch(adjustedFilter))) {
- Optional<Long> reflexiveParentID = Optional.empty();
- if(entityConfig.isReflexive()) {
+ for (Record record : collectRecords(query.fetch(adjustedFilter))) {
+ Optional<String> reflexiveParentID = Optional.empty();
+ if (entityConfig.isReflexive()) {
reflexiveParentID = record.getID(reflexiveRelation);
}
EntityRecord<T> entityRecord;
- if(entityConfig.isReflexive() && reflexiveParentID.isPresent()) {
+ if (entityConfig.isReflexive() && reflexiveParentID.isPresent()) {
Optional<EntityRecord<T>> parentRecord = entityResult.get(reflexiveParentID.get());
- if(!parentRecord.isPresent()) {
+ if (!parentRecord.isPresent()) {
// this entity's parent was not loaded -> skip
continue;
}
@@ -278,10 +300,10 @@
// collect related instance IDs
Stream.concat(optionalRelations.stream(), mandatoryRelations.stream())
- .forEach(rc -> rc.add(entityRecord, record));
+ .forEach(rc -> rc.add(entityRecord, record));
}
- if(entityResult.isEmpty()) {
+ if (entityResult.isEmpty()) {
// no entities found -> neither related nor child entities required
return entityResult;
}
@@ -291,15 +313,16 @@
loadRelatedEntities(mandatoryRelations);
// sort children of parent
- if(entityConfig.isReflexive()) {
- @SuppressWarnings("unchecked") EntityConfig<Deletable> childConfig = (EntityConfig<Deletable>) entityConfig;
- for(EntityRecord<?> entityRecord : parentRecords) {
+ if (entityConfig.isReflexive()) {
+ @SuppressWarnings("unchecked")
+ EntityConfig<Deletable> childConfig = (EntityConfig<Deletable>) entityConfig;
+ for (EntityRecord<?> entityRecord : parentRecords) {
entityRecord.core.getChildrenStore().sort(childConfig.getEntityClass(), childConfig.getComparator());
}
}
// load children
- for(EntityConfig<? extends Deletable> childConfig : entityConfig.getChildConfigs()) {
+ for (EntityConfig<? extends Deletable> childConfig : entityConfig.getChildConfigs()) {
cache.add(new ChildRequest<>(this, childConfig).load());
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityResult.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityResult.java
index 48d7198..a54912c 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityResult.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/EntityResult.java
@@ -31,7 +31,8 @@
/**
* Container for entities by executing an {@link EntityRequest}.
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -41,7 +42,7 @@
// Instance variables
// ======================================================================
- private final Map<Long, EntityRecord<T>> entityRecords = new HashMap<>();
+ private final Map<String, EntityRecord<T>> entityRecords = new HashMap<>();
private final List<T> entities = new ArrayList<>();
final EntityRequest<T> request;
@@ -53,7 +54,8 @@
/**
* Constructor.
*
- * @param request The associated {@link EntityRequest}.
+ * @param request
+ * The associated {@link EntityRequest}.
*/
EntityResult(EntityRequest<T> request) {
this.request = request;
@@ -66,10 +68,11 @@
/**
* Returns the {@link EntityRecord} identified by given instance ID.
*
- * @param id The instance ID.
+ * @param id
+ * The instance ID.
* @return {@code Optional} is empty if {@code EntityRecord} not found.
*/
- public Optional<EntityRecord<T>> get(Long id) {
+ public Optional<EntityRecord<T>> get(String id) {
return Optional.ofNullable(entityRecords.get(id));
}
@@ -77,7 +80,8 @@
* Creates an {@link EntityRecord} for given {@link Record} and mapps it
* internally by its instance ID.
*
- * @param record The {@code Record}.
+ * @param record
+ * The {@code Record}.
* @return The created {@code EntityRecord} is returned.
*/
public EntityRecord<T> add(Record record) {
@@ -88,15 +92,17 @@
* Creates an {@link EntityRecord} for given {@link Record} using given
* parent {@code EntityRecord} and mapps it internally by its instance ID.
*
- * @param parentRecord The created {@code EntityRecord} will be related as
- * a child with this one.
- * @param record The {@code Record}.
+ * @param parentRecord
+ * The created {@code EntityRecord} will be related as a child
+ * with this one.
+ * @param record
+ * The {@code Record}.
* @return The created {@code EntityRecord} is returned.
*/
public EntityRecord<T> add(EntityRecord<?> parentRecord, Record record) {
Core core = new DefaultCore(record);
- if(CatalogAttribute.class.equals(request.entityConfig.getEntityClass())) {
+ if (CatalogAttribute.class.equals(request.entityConfig.getEntityClass())) {
// add read only properties from application model
adjustCatalogAttributeCore(parentRecord.entity, core);
}
@@ -122,8 +128,8 @@
* @return Returned {@code Collection} is unmodifiable.
*/
public List<T> getSortedEntities() {
- return Collections.unmodifiableList(entities.stream()
- .sorted(request.entityConfig.getComparator()).collect(Collectors.toList()));
+ return Collections.unmodifiableList(
+ entities.stream().sorted(request.entityConfig.getComparator()).collect(Collectors.toList()));
}
/**
@@ -131,7 +137,7 @@
*
* @return Returned {@code Collection} is unmodifiable.
*/
- public Collection<Long> getIDs() {
+ public Collection<String> getIDs() {
return Collections.unmodifiableCollection(entityRecords.keySet());
}
@@ -149,11 +155,13 @@
// ======================================================================
/**
- * Adds further meta data to the given {@link CatalogAttribute} {@link
- * Core}.
+ * Adds further meta data to the given {@link CatalogAttribute}
+ * {@link Core}.
*
- * @param catalogComponent The parent {@link CatalogComponent}.
- * @param catalogAttributeCore The {@code CatalogAttribute} {@code Core}.
+ * @param catalogComponent
+ * The parent {@link CatalogComponent}.
+ * @param catalogAttributeCore
+ * The {@code CatalogAttribute} {@code Core}.
*/
private void adjustCatalogAttributeCore(Entity catalogComponent, Core catalogAttributeCore) {
EntityType entityType = request.modelManager.getEntityType(catalogComponent.getName());
@@ -162,7 +170,7 @@
Map<String, Value> values = catalogAttributeCore.getValues();
Value enumerationClass = ValueType.STRING.create(VATTR_ENUMERATION_CLASS);
values.put(VATTR_ENUMERATION_CLASS, enumerationClass);
- if(attribute.getValueType().isEnumerationType()) {
+ if (attribute.getValueType().isEnumerationType()) {
enumerationClass.set(attribute.getEnumClass().getName());
}
@@ -174,10 +182,11 @@
}
/**
- * Creates a new {@link EntityRecord} instance for given {@link Core}.
- * The {@link EntityRecord} is internally mapped the its instance ID.
+ * Creates a new {@link EntityRecord} instance for given {@link Core}. The
+ * {@link EntityRecord} is internally mapped the its instance ID.
*
- * @param core The {@code Core}.
+ * @param core
+ * The {@code Core}.
* @return The created {@link EntityRecord} is returned.
*/
private EntityRecord<T> create(Core core) {
@@ -191,11 +200,11 @@
entityRecords.put(core.getID(), entityRecord);
entities.add(entityRecord.entity);
return entityRecord;
- } catch (InstantiationException | IllegalAccessException |
- NoSuchMethodException | InvocationTargetException e) {
+ } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
+ | InvocationTargetException e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
- if(constructor != null) {
+ if (constructor != null) {
constructor.setAccessible(isAccessible);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/RelationConfig.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/RelationConfig.java
index 3acd926..8df3de6 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/RelationConfig.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/RelationConfig.java
@@ -25,7 +25,7 @@
// Instance variables
// ======================================================================
- final Map<Long, List<EntityRecord<?>>> dependants = new HashMap<>();
+ final Map<String, List<EntityRecord<?>>> dependants = new HashMap<>();
final EntityConfig<?> entityConfig;
final Relation relation;
final boolean mandatory;
@@ -37,9 +37,12 @@
/**
* Constructor.
*
- * @param source The source {@link EntityType}.
- * @param entityConfig The target {@link EntityConfig}.
- * @param mandatory Flag indicates whether a related must exist or not.
+ * @param source
+ * The source {@link EntityType}.
+ * @param entityConfig
+ * The target {@link EntityConfig}.
+ * @param mandatory
+ * Flag indicates whether a related must exist or not.
*/
public RelationConfig(EntityType source, EntityConfig<?> entityConfig, boolean mandatory) {
this.entityConfig = entityConfig;
@@ -52,18 +55,20 @@
// ======================================================================
/**
- * Given {@link EntityRecord} depends on {@link Entity}s which are loaded
- * by processing this relation config. Therefore given {@code EntityRecord}
+ * Given {@link EntityRecord} depends on {@link Entity}s which are loaded by
+ * processing this relation config. Therefore given {@code EntityRecord}
* cached and satisfied as soon as the corresponding entities are loaded.
*
- * @param entityRecord The dependant {@code EntityRecord}.
- * @param record The {@link Record} associated with given {@link EntityRecord}.
+ * @param entityRecord
+ * The dependant {@code EntityRecord}.
+ * @param record
+ * The {@link Record} associated with given {@link EntityRecord}.
*/
public void add(EntityRecord<?> entityRecord, Record record) {
- Optional<Long> relatedEntityID = record.getID(relation);
- if(relatedEntityID.isPresent()) {
+ Optional<String> relatedEntityID = record.getID(relation);
+ if (relatedEntityID.isPresent()) {
dependants.computeIfAbsent(relatedEntityID.get(), k -> new ArrayList<>()).add(entityRecord);
- } else if(mandatory) {
+ } else if (mandatory) {
throw new IllegalStateException("Mandatory relation unsatisfied.");
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfig.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfig.java
index 856b143..fdb39a9 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfig.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfig.java
@@ -17,7 +17,8 @@
* Describes the composition of an {@link Entity} with its mandatory, optional
* and child relations.
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -49,7 +50,8 @@
/**
* Constructor.
*
- * @param key The {@link Key} this entity config is bound to.
+ * @param key
+ * The {@link Key} this entity config is bound to.
*/
public EntityConfig(Key<T> key) {
this.key = key;
@@ -173,7 +175,8 @@
/**
* Sets a new {@link Comparator} for this entity config.
*
- * @param comparator The new {@code Comparator}.
+ * @param comparator
+ * The new {@code Comparator}.
*/
public void setComparator(Comparator<? super T> comparator) {
this.comparator = comparator;
@@ -182,12 +185,13 @@
/**
* Sets the {@link EntityType} for this entity config.
*
- * @param entityType The {@code EntityType}.
- * @throws IllegalStateException Thrown if {@link EntityType} is already
- * defined.
+ * @param entityType
+ * The {@code EntityType}.
+ * @throws IllegalStateException
+ * Thrown if {@link EntityType} is already defined.
*/
public void setEntityType(EntityType entityType) {
- if(this.entityType != null) {
+ if (this.entityType != null) {
throw new IllegalStateException("It is not allowed to override the entity type.");
}
@@ -198,11 +202,13 @@
* Sets the default MIME type for newly created {@link Entity}s associated
* with this entity config.
*
- * @param mimeType The default MIME type.
- * @throws IllegalStateException Thrown if default MIME type is already defined.
+ * @param mimeType
+ * The default MIME type.
+ * @throws IllegalStateException
+ * Thrown if default MIME type is already defined.
*/
public void setMimeType(String mimeType) {
- if(this.mimeType != null && !this.mimeType.isEmpty()) {
+ if (this.mimeType != null && !this.mimeType.isEmpty()) {
throw new IllegalStateException("It is not allowed to override the default MIME type.");
}
@@ -212,7 +218,8 @@
/**
* Adds a related inherited {@link EntityConfig}.
*
- * @param entityConfig The {@code EntityConfig}.
+ * @param entityConfig
+ * The {@code EntityConfig}.
*/
public void addInherited(EntityConfig<?> entityConfig) {
inheritedConfigs.add(entityConfig);
@@ -221,7 +228,8 @@
/**
* Adds a related mandatory {@link EntityConfig}.
*
- * @param entityConfig The {@code EntityConfig}.
+ * @param entityConfig
+ * The {@code EntityConfig}.
*/
public void addMandatory(EntityConfig<?> entityConfig) {
mandatoryConfigs.add(entityConfig);
@@ -230,7 +238,8 @@
/**
* Adds a related optional {@link EntityConfig}.
*
- * @param entityConfig The {@code EntityConfig}.
+ * @param entityConfig
+ * The {@code EntityConfig}.
*/
public void addOptional(EntityConfig<?> entityConfig) {
optionalConfigs.add(entityConfig);
@@ -239,10 +248,11 @@
/**
* Adds a related child {@link EntityConfig}.
*
- * @param childConfig The {@code EntityConfig}.
+ * @param childConfig
+ * The {@code EntityConfig}.
*/
public void addChild(EntityConfig<? extends Deletable> childConfig) {
- if(this == childConfig) {
+ if (this == childConfig) {
reflexive = true;
} else {
childConfigs.add(childConfig);
@@ -256,7 +266,8 @@
/**
* Used as an identifier for {@link EntityConfig}s.
*
- * @param <T> The entity type.
+ * @param <T>
+ * The entity type.
*/
public static final class Key<T extends Entity> {
@@ -275,7 +286,8 @@
/**
* Constructor.
*
- * @param entityClass The {@link Entity} class.
+ * @param entityClass
+ * The {@link Entity} class.
*/
public Key(Class<T> entityClass) {
this.entityClass = entityClass;
@@ -286,8 +298,10 @@
/**
* Constructor.
*
- * @param entityClass The {@link Entity} class.
- * @param statusAttachableClass The {@link StatusAttachable} class.
+ * @param entityClass
+ * The {@link Entity} class.
+ * @param statusAttachableClass
+ * The {@link StatusAttachable} class.
*/
public Key(Class<T> entityClass, Class<? extends StatusAttachable> statusAttachableClass) {
this.statusAttachableClass = statusAttachableClass;
@@ -298,8 +312,10 @@
/**
* Constructor.
*
- * @param entityClass The {@link Entity} class.
- * @param contextType The {@link ContextType}.
+ * @param entityClass
+ * The {@link Entity} class.
+ * @param contextType
+ * The {@link ContextType}.
*/
public Key(Class<T> entityClass, ContextType contextType) {
this.entityClass = entityClass;
@@ -325,11 +341,11 @@
@Override
public boolean equals(Object object) {
// reference check (this == object) omitted
- if(object instanceof Key) {
+ if (object instanceof Key) {
Key<?> other = (Key<?>) object;
- return Objects.equals(entityClass, other.entityClass) &&
- Objects.equals(statusAttachableClass, other.statusAttachableClass) &&
- Objects.equals(contextType, other.contextType);
+ return Objects.equals(entityClass, other.entityClass)
+ && Objects.equals(statusAttachableClass, other.statusAttachableClass)
+ && Objects.equals(contextType, other.contextType);
}
return false;
@@ -342,11 +358,11 @@
public String toString() {
StringBuilder sb = new StringBuilder(entityClass.getSimpleName());
- if(statusAttachableClass != null) {
+ if (statusAttachableClass != null) {
sb.append('_').append(statusAttachableClass.getSimpleName());
}
- if(contextType != null) {
+ if (contextType != null) {
sb.append('_').append(contextType);
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfigRepository.java b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfigRepository.java
index cf8b3fc..4bec31a 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfigRepository.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/lookup/config/EntityConfigRepository.java
@@ -34,82 +34,91 @@
// ======================================================================
/**
- * Returns the {@link EntityConfig} associated with given {@link Key}.
- * This method tries to find the associated {@code EntityConfig} in the
- * root configurations. If it is not found there, then it tries to find
- * it in the child {@code EntityConfig}s.
+ * Returns the {@link EntityConfig} associated with given {@link Key}. This
+ * method tries to find the associated {@code EntityConfig} in the root
+ * configurations. If it is not found there, then it tries to find it in the
+ * child {@code EntityConfig}s.
*
- * @param <T> The entity type.
- * @param key Used as identifier.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used as identifier.
* @return The {@code EntityConfig} is returned.
- * @throws IllegalArgumentException Thrown if unable to find associated
- * {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if unable to find associated {@code EntityConfig}.
*/
public <T extends Entity> EntityConfig<T> find(Key<T> key) {
Optional<EntityConfig<T>> entityConfig = get(entityConfigs, key);
- if(entityConfig.isPresent()) {
+ if (entityConfig.isPresent()) {
return entityConfig.get();
}
- return get(childConfigs, key).orElseThrow(() ->new IllegalArgumentException("Entity configuration not found."));
+ return get(childConfigs, key)
+ .orElseThrow(() -> new IllegalArgumentException("Entity configuration not found."));
}
/**
- * Returns the {@link EntityConfig} associated with given {@link Key}.
- * This method tries to find the associated {@code EntityConfig} in the
- * root configurations.
+ * Returns the {@link EntityConfig} associated with given {@link Key}. This
+ * method tries to find the associated {@code EntityConfig} in the root
+ * configurations.
*
- * @param <T> The entity type.
- * @param key Used as identifier.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used as identifier.
* @return The {@code EntityConfig} is returned.
- * @throws IllegalArgumentException Thrown if unable to find associated
- * {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if unable to find associated {@code EntityConfig}.
*/
public <T extends Entity> EntityConfig<T> findRoot(Key<T> key) {
return get(entityConfigs, key)
- .orElseThrow(() ->new IllegalArgumentException("Entity configuration not found."));
+ .orElseThrow(() -> new IllegalArgumentException("Entity configuration not found."));
}
/**
- * Returns the {@link EntityConfig} associated with given {@link Key}.
- * This method tries to find the associated {@code EntityConfig} in the
- * child configurations.
+ * Returns the {@link EntityConfig} associated with given {@link Key}. This
+ * method tries to find the associated {@code EntityConfig} in the child
+ * configurations.
*
- * @param <T> The entity type.
- * @param key Used as identifier.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used as identifier.
* @return The {@code EntityConfig} is returned.
- * @throws IllegalArgumentException Thrown if unable to find associated
- * {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if unable to find associated {@code EntityConfig}.
*/
public <T extends Entity> EntityConfig<T> findImplicit(Key<T> key) {
- return get(childConfigs, key).orElseThrow(() ->new IllegalArgumentException("Entity configuration not found."));
+ return get(childConfigs, key)
+ .orElseThrow(() -> new IllegalArgumentException("Entity configuration not found."));
}
/**
- * Returns the {@link EntityConfig} associated with given {@link
- * EntityType}.
+ * Returns the {@link EntityConfig} associated with given
+ * {@link EntityType}.
*
- * @param entityType Its name is used as identifier.
+ * @param entityType
+ * Its name is used as identifier.
* @return The {@code EntityConfig} is returned.
- * @throws IllegalArgumentException Thrown if unable to find associated
- * {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if unable to find associated {@code EntityConfig}.
*/
public EntityConfig<?> find(EntityType entityType) {
Optional<EntityConfig<?>> entityConfig = entityConfigs.values().stream()
.filter(ec -> ec.getEntityType().equals(entityType)).findFirst();
- if(entityConfig.isPresent()) {
+ if (entityConfig.isPresent()) {
// entity config is a root type
return entityConfig.get();
}
entityConfig = childConfigs.values().stream().filter(ec -> ec.getEntityType().equals(entityType)).findFirst();
- if(entityConfig.isPresent()) {
+ if (entityConfig.isPresent()) {
// entity config is an implicitly loaded child type
return entityConfig.get();
}
EntityConfig<?> config = contextConfigs.get(entityType.getName());
- if(config == null) {
+ if (config == null) {
new IllegalArgumentException("Entity configuration for type '" + entityType + "' not found.");
}
@@ -120,15 +129,17 @@
/**
* Stores given {@link EntityConfig} in this repository.
*
- * @param entityConfig The {@code EntityConfig}.
- * @throws IllegalArgumentException Thrown if an attempt to overwrite an
- * existing {@code EntityConfig} is recorded.
+ * @param entityConfig
+ * The {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if an attempt to overwrite an existing
+ * {@code EntityConfig} is recorded.
*/
public void register(EntityConfig<?> entityConfig) {
registerChildConfigs(entityConfig);
EntityConfig<?> currentByClass = entityConfigs.put(entityConfig.getKey(), entityConfig);
- if(currentByClass != null) {
+ if (currentByClass != null) {
throw new IllegalArgumentException("It is not allowed to overwrite existing configurations.");
}
}
@@ -138,18 +149,20 @@
// ======================================================================
/**
- * Recursively registers all child configurations of given {@link
- * EntityConfig}.
+ * Recursively registers all child configurations of given
+ * {@link EntityConfig}.
*
- * @param entityConfig The {@code EntityConfig}.
- * @throws IllegalArgumentException Thrown if an attempt to overwrite an
- * existing {@code EntityConfig} is recorded.
+ * @param entityConfig
+ * The {@code EntityConfig}.
+ * @throws IllegalArgumentException
+ * Thrown if an attempt to overwrite an existing
+ * {@code EntityConfig} is recorded.
*/
private void registerChildConfigs(EntityConfig<?> entityConfig) {
Class<? extends Entity> entityClass = entityConfig.getEntityClass();
- if(ContextRoot.class.equals(entityClass) || ContextComponent.class.equals(entityClass)) {
- for(EntityConfig<?> childConfig : entityConfig.getChildConfigs()) {
- if(contextConfigs.put(childConfig.getEntityType().getName(), childConfig) != null) {
+ if (ContextRoot.class.equals(entityClass) || ContextComponent.class.equals(entityClass)) {
+ for (EntityConfig<?> childConfig : entityConfig.getChildConfigs()) {
+ if (contextConfigs.put(childConfig.getEntityType().getName(), childConfig) != null) {
throw new IllegalArgumentException("It is not allowed to overwrite existing configurations.");
}
@@ -158,8 +171,8 @@
return;
}
- for(EntityConfig<?> childConfig : entityConfig.getChildConfigs()) {
- if(childConfigs.put(childConfig.getKey(), childConfig) != null) {
+ for (EntityConfig<?> childConfig : entityConfig.getChildConfigs()) {
+ if (childConfigs.put(childConfig.getKey(), childConfig) != null) {
throw new IllegalArgumentException("It is not allowed to overwrite existing configurations.");
}
@@ -168,12 +181,15 @@
}
/**
- * Retrieves the {@link EntityConfig} associated with given {@link Key}
- * from given {@code Map}.
+ * Retrieves the {@link EntityConfig} associated with given {@link Key} from
+ * given {@code Map}.
*
- * @param <T> The entity type.
- * @param entityConfigs Used to retrieve requested {@code EntityConfig}.
- * @param key Used as identifier.
+ * @param <T>
+ * The entity type.
+ * @param entityConfigs
+ * Used to retrieve requested {@code EntityConfig}.
+ * @param key
+ * Used as identifier.
* @return {@code Optional} is empty if {@code EntityConfig} not found.
*/
@SuppressWarnings("unchecked")
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/NotificationEntityLoader.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/NotificationEntityLoader.java
index a09cab8..3dcb43d 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/NotificationEntityLoader.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/NotificationEntityLoader.java
@@ -24,131 +24,132 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.primitives.Longs;
-
public class NotificationEntityLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(NotificationEntityLoader.class);
private final ODSModelManager modelManager;
private final EntityLoader loader;
-
+
private boolean loadContextDescribable;
-
+
public NotificationEntityLoader(ODSModelManager modelManager, boolean loadContextDescribable) {
this.modelManager = modelManager;
this.loader = new EntityLoader(modelManager);
this.loadContextDescribable = loadContextDescribable;
}
- public <T extends Entity> T load(Key<T> key, long userId) throws DataAccessException {
+ public <T extends Entity> T load(Key<T> key, String userId) throws DataAccessException {
return loader.load(key, userId);
}
- public List<? extends Entity> loadEntities(long aid, List<Long> ids) throws DataAccessException {
+ public List<? extends Entity> loadEntities(String aid, List<String> ids) throws DataAccessException {
return loadEntities(modelManager.getEntityType(aid), ids);
}
-
+
/**
- * @param entityType entity type of the entities to load.
- * @param ids IDs of the entities to load.
+ * @param entityType
+ * entity type of the entities to load.
+ * @param ids
+ * IDs of the entities to load.
* @return loaded entities.
- * @throws DataAccessException Throw if the entities cannot be loaded.
+ * @throws DataAccessException
+ * Throw if the entities cannot be loaded.
*/
- public List<? extends Entity> loadEntities(EntityType entityType, List<Long> ids) throws DataAccessException {
-
- if (ids.isEmpty())
- {
+ public List<? extends Entity> loadEntities(EntityType entityType, List<String> ids) throws DataAccessException {
+
+ if (ids.isEmpty()) {
return Collections.emptyList();
}
-
+
EntityConfig<?> config = getEntityConfig(entityType);
-
- if (config == null || isLoadContextDescribable(config))
- {
- // entityType not modelled in MDM, try to load its ContextDescribable if it is a ContextRoot/ContextComponent
+
+ if (config == null || isLoadContextDescribable(config)) {
+ // entityType not modelled in MDM, try to load its
+ // ContextDescribable if it is a ContextRoot/ContextComponent
final EntityType testStep = modelManager.getEntityType(TestStep.class);
final EntityType measurement = modelManager.getEntityType(Measurement.class);
-
- if (hasRelationTo(entityType, testStep, measurement))
- {
+
+ if (hasRelationTo(entityType, testStep, measurement)) {
return loadEntityForContextRoot(entityType, ids);
- }
- else if (hasRelationTo(entityType,
- modelManager.getEntityType("UnitUnderTest"),
- modelManager.getEntityType("TestSequence"),
- modelManager.getEntityType("TestEquipment")))
- {
+ } else if (hasRelationTo(entityType, modelManager.getEntityType("UnitUnderTest"),
+ modelManager.getEntityType("TestSequence"), modelManager.getEntityType("TestEquipment"))) {
return loadEntityForContextComponent(entityType, ids);
- }
- else
- {
+ } else {
LOGGER.debug("Cannot load entitis for entityType " + entityType + " and ids " + ids);
return Collections.emptyList();
}
- }
- else
- {
+ } else {
return loader.loadAll(config.getKey(), ids);
}
}
/**
* Loads the ContextDescribables to the given context root instances
- * @param contextRoot entityType of the context root
- * @param ids IDs of the context roots.
+ *
+ * @param contextRoot
+ * entityType of the context root
+ * @param ids
+ * IDs of the context roots.
* @return the loaded ContextDescribables
- * @throws DataAccessException Throw if the ContextDescribables cannot be loaded.
+ * @throws DataAccessException
+ * Throw if the ContextDescribables cannot be loaded.
*/
- private List<ContextDescribable> loadEntityForContextRoot(EntityType contextRoot, List<Long> ids) throws DataAccessException {
-
+ private List<ContextDescribable> loadEntityForContextRoot(EntityType contextRoot, List<String> ids)
+ throws DataAccessException {
+
final EntityType testStep = modelManager.getEntityType(TestStep.class);
final EntityType measurement = modelManager.getEntityType(Measurement.class);
-
- List<Long> testStepIDs = modelManager.createQuery().selectID(testStep)
+
+ List<String> testStepIDs = modelManager.createQuery().selectID(testStep)
.join(testStep.getRelation(contextRoot), Join.OUTER)
- .fetch(Filter.and().add(Operation.IN_SET.create(contextRoot.getIDAttribute(), Longs.toArray(ids))))
+ .fetch(Filter.and().add(Operation.IN_SET.create(contextRoot.getIDAttribute(), ids)))
.stream().map(r -> r.getRecord(testStep)).map(Record::getID).collect(Collectors.toList());
-
- List<Long> measurementIDs = modelManager.createQuery().selectID(measurement)
+
+ List<String> measurementIDs = modelManager.createQuery().selectID(measurement)
.join(measurement.getRelation(contextRoot), Join.OUTER)
- .fetch(Filter.and().add(Operation.IN_SET.create(contextRoot.getIDAttribute(), Longs.toArray(ids))))
+ .fetch(Filter.and().add(Operation.IN_SET.create(contextRoot.getIDAttribute(), ids)))
.stream().map(r -> r.getRecord(measurement)).map(Record::getID).collect(Collectors.toList());
-
+
List<ContextDescribable> list = new ArrayList<>();
list.addAll(loader.loadAll(new Key<>(TestStep.class), testStepIDs));
list.addAll(loader.loadAll(new Key<>(Measurement.class), measurementIDs));
-
+
return list;
}
/**
* Loads the ContextDescribables to the given context component instances
- * @param contextComponent entityType of the context component
- * @param ids IDs of the contextComponents to load.
+ *
+ * @param contextComponent
+ * entityType of the context component
+ * @param ids
+ * IDs of the contextComponents to load.
* @return the loaded ContextDescribables
- * @throws DataAccessException Throw if the ContextDescribables cannot be loaded.
+ * @throws DataAccessException
+ * Throw if the ContextDescribables cannot be loaded.
*/
- private List<ContextDescribable> loadEntityForContextComponent(EntityType contextComponent, List<Long> ids) throws DataAccessException {
-
+ private List<ContextDescribable> loadEntityForContextComponent(EntityType contextComponent, List<String> ids)
+ throws DataAccessException {
+
// ContextComponent can only have one parent
final EntityType contextRoot = contextComponent.getParentRelations().get(0).getTarget();
final EntityType testStep = modelManager.getEntityType(TestStep.class);
final EntityType measurement = modelManager.getEntityType(Measurement.class);
-
- List<Long> testStepIDs = modelManager.createQuery().selectID(testStep)
+
+ List<String> testStepIDs = modelManager.createQuery().selectID(testStep)
.join(testStep.getRelation(contextRoot), Join.OUTER)
.join(contextRoot.getRelation(contextComponent), Join.OUTER)
- .fetch(Filter.and().add(Operation.IN_SET.create(contextComponent.getIDAttribute(), Longs.toArray(ids))))
+ .fetch(Filter.and().add(Operation.IN_SET.create(contextComponent.getIDAttribute(), ids)))
.stream().map(r -> r.getRecord(testStep)).map(Record::getID).collect(Collectors.toList());
-
- List<Long> measurementIDs = modelManager.createQuery().selectID(measurement)
+
+ List<String> measurementIDs = modelManager.createQuery().selectID(measurement)
.join(measurement.getRelation(contextRoot), Join.OUTER)
.join(contextRoot.getRelation(contextComponent), Join.OUTER)
- .fetch(Filter.and().add(Operation.IN_SET.create(contextComponent.getIDAttribute(), Longs.toArray(ids))))
+ .fetch(Filter.and().add(Operation.IN_SET.create(contextComponent.getIDAttribute(), ids)))
.stream().map(r -> r.getRecord(measurement)).map(Record::getID).collect(Collectors.toList());
-
+
List<ContextDescribable> list = new ArrayList<>();
list.addAll(loader.loadAll(new Key<>(TestStep.class), testStepIDs));
list.addAll(loader.loadAll(new Key<>(Measurement.class), measurementIDs));
@@ -157,28 +158,31 @@
/**
* @param entityConfig
- * @return true, if the entityConfig belongs to a context root or context component and the option loadContextDescribable
+ * @return true, if the entityConfig belongs to a context root or context
+ * component and the option loadContextDescribable
*/
private boolean isLoadContextDescribable(EntityConfig<?> entityConfig) {
- return loadContextDescribable && (entityConfig.getEntityClass().isAssignableFrom(ContextRoot.class) || entityConfig.getEntityClass().isAssignableFrom(ContextComponent.class));
+ return loadContextDescribable && (entityConfig.getEntityClass().isAssignableFrom(ContextRoot.class)
+ || entityConfig.getEntityClass().isAssignableFrom(ContextComponent.class));
}
/**
- * Checks if a relation between sourceEntityType and at least one entity type in targetEntityType exists.
- * @param sourceEntityType source entity type.
- * @param targetEntityTypes list of target enitity types.
- * @return true, if relation between source entity type and at least one target entity type exists.
+ * Checks if a relation between sourceEntityType and at least one entity
+ * type in targetEntityType exists.
+ *
+ * @param sourceEntityType
+ * source entity type.
+ * @param targetEntityTypes
+ * list of target enitity types.
+ * @return true, if relation between source entity type and at least one
+ * target entity type exists.
*/
private boolean hasRelationTo(EntityType sourceEntityType, EntityType... targetEntityTypes) {
- for (EntityType e : targetEntityTypes)
- {
- try
- {
+ for (EntityType e : targetEntityTypes) {
+ try {
sourceEntityType.getRelation(e);
return true;
- }
- catch (IllegalArgumentException ex)
- {
+ } catch (IllegalArgumentException ex) {
return false;
}
}
@@ -187,16 +191,15 @@
}
/**
- * @param entityType entity type the {@link EntityConfig} is requested for
- * @return {@link EntityConfig} or null if not config was found for the specified entity type
+ * @param entityType
+ * entity type the {@link EntityConfig} is requested for
+ * @return {@link EntityConfig} or null if not config was found for the
+ * specified entity type
*/
private EntityConfig<?> getEntityConfig(EntityType entityType) {
- try
- {
- return modelManager.getEntityConfig(entityType);
- }
- catch (IllegalArgumentException e)
- {
+ try {
+ return modelManager.getEntityConfig(entityType);
+ } catch (IllegalArgumentException e) {
return null;
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/AvalonNotificationManager.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/AvalonNotificationManager.java
index 04d199d..ba66a74 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/AvalonNotificationManager.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/AvalonNotificationManager.java
@@ -37,7 +37,8 @@
import com.highqsoft.avalonCorbaNotification.notification.MODE_REPLACE;
/**
- * Notification manager for handling notifications from the Avalon Notification Service
+ * Notification manager for handling notifications from the Avalon Notification
+ * Service
*
* ModificationType.MODEL_MODIFIED is not supported!
*
@@ -49,122 +50,115 @@
private static final Logger LOGGER = LoggerFactory.getLogger(AvalonNotificationManager.class);
-
private final Map<String, EventProcessor> eventProcessors = new HashMap<>();
-
+
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
-
+
private final ODSModelManager modelManager;
private final String serviceName;
private final String nameServiceURL;
private long pollingInterval = 500L;
private final NotificationEntityLoader loader;
-
- private final ORB orb = ORB.init(new String[]{}, System.getProperties());
-
+
+ private final ORB orb = ORB.init(new String[] {}, System.getProperties());
+
/**
* Creates a new AvalonNotificationManager.
- * @param modelManager ODSModelManager used to laod entities.
- * @param serviceName name of the notification service.
- * @param nameServiceURL URL of the name service.
- * @param loadContextDescribable if true, notifications for {@link ContextRoot}
- * and {@link ContextComponent} will load their parent {@link ContextDescribable}.
- * @param pollingInterval polling interval in milleseconds
+ *
+ * @param modelManager
+ * ODSModelManager used to laod entities.
+ * @param serviceName
+ * name of the notification service.
+ * @param nameServiceURL
+ * URL of the name service.
+ * @param loadContextDescribable
+ * if true, notifications for {@link ContextRoot} and
+ * {@link ContextComponent} will load their parent
+ * {@link ContextDescribable}.
+ * @param pollingInterval
+ * polling interval in milleseconds
*/
- public AvalonNotificationManager(ODSModelManager modelManager, String serviceName,
- String nameServiceURL, boolean loadContextDescribable, long pollingInterval)
- {
+ public AvalonNotificationManager(ODSModelManager modelManager, String serviceName, String nameServiceURL,
+ boolean loadContextDescribable, long pollingInterval) {
this.modelManager = modelManager;
this.serviceName = serviceName;
this.nameServiceURL = nameServiceURL;
this.pollingInterval = pollingInterval;
loader = new NotificationEntityLoader(modelManager, loadContextDescribable);
}
-
+
@Override
- public void register(String registration, NotificationFilter filter, final NotificationListener listener) throws NotificationException
- {
- try
- {
+ public void register(String registration, NotificationFilter filter, final NotificationListener listener)
+ throws NotificationException {
+ try {
EventProcessor consumer = new EventProcessor(orb, listener, this, nameServiceURL, serviceName);
-
- List<Long> aids = filter.getEntityTypes().stream()
- .map(e -> e.getId())
- .collect(Collectors.toList());
-
+
+ List<String> aids = filter.getEntityTypes().stream().map(e -> e.getId()).collect(Collectors.toList());
+
Set<ModificationType> modes = filter.getTypes().stream()
- .filter(m -> !ModificationType.MODEL_MODIFIED.equals(m))
- .collect(Collectors.toSet());
-
+ .filter(m -> !ModificationType.MODEL_MODIFIED.equals(m)).collect(Collectors.toSet());
+
consumer.connect();
consumer.setFilter(aids, modes);
-
- ScheduledFuture<?> future = executor.scheduleAtFixedRate(consumer, 0, pollingInterval, TimeUnit.MILLISECONDS);
- consumer.setFuture(future);
-
- eventProcessors.put(registration, consumer);
- }
- catch (Exception e)
- {
+
+ ScheduledFuture<?> future = executor.scheduleAtFixedRate(consumer, 0, pollingInterval,
+ TimeUnit.MILLISECONDS);
+ consumer.setFuture(future);
+
+ eventProcessors.put(registration, consumer);
+ } catch (Exception e) {
throw new NotificationException("Exception creating notification listener registration!", e);
}
}
@Override
- public void deregister(String registration)
- {
+ public void deregister(String registration) {
EventProcessor processor = eventProcessors.get(registration);
- if (processor != null)
- {
+ if (processor != null) {
processor.disconnect();
eventProcessors.remove(registration);
}
}
-
+
@Override
public void close(boolean isDeregisterAll) throws NotificationException {
LOGGER.info("Closing NotificationManager...");
-
- for (String registration : eventProcessors.keySet())
- {
+
+ for (String registration : eventProcessors.keySet()) {
LOGGER.debug("Disconnecting registration '" + registration + "'.");
deregister(registration);
}
-
+
try {
executor.shutdown();
boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS);
- if (!terminated)
- {
+ if (!terminated) {
throw new NotificationException("Could not close all registrations!");
}
} catch (InterruptedException e) {
throw new NotificationException("Could not close all registrations!", e);
- }
+ }
}
-
- void processException(Exception e)
- {
+
+ void processException(Exception e) {
LOGGER.error("Exception during notification processing!", e);
}
-
- void processNotification(short mode, T_LONGLONG aeId, T_LONGLONG ieId, T_LONGLONG userId,
- String timestamp, NotificationListener notificationListener) {
-
- try {
- User user = loader.load(new Key<>(User.class), ODSConverter.fromODSLong(userId));
- LOGGER.debug("User loaded");
-
- EntityType entityType = modelManager.getEntityType(ODSConverter.fromODSLong(aeId));
- List<Long> ids = Arrays.asList(ODSConverter.fromODSLong(ieId));
- if (LOGGER.isTraceEnabled())
- {
- LOGGER.trace("Notification event with: entityType=" + entityType + ", user=" + user);
+ void processNotification(short mode, T_LONGLONG aeId, T_LONGLONG ieId, T_LONGLONG userId, String timestamp,
+ NotificationListener notificationListener) {
+
+ try {
+ User user = loader.load(new Key<>(User.class), Long.toString(ODSConverter.fromODSLong(userId)));
+ LOGGER.debug("User loaded");
+
+ EntityType entityType = modelManager.getEntityType(Long.toString(ODSConverter.fromODSLong(aeId)));
+ List<String> ids = Arrays.asList(Long.toString(ODSConverter.fromODSLong(ieId)));
+
+ if (LOGGER.isTraceEnabled()) {
+ LOGGER.trace("Notification event with: entityType=" + entityType + ", user=" + user);
}
-
- switch (mode)
- {
+
+ switch (mode) {
case MODE_INSERT.value:
notificationListener.instanceCreated(loader.loadEntities(entityType, ids), user);
break;
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/EventProcessor.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/EventProcessor.java
index 74047b8..05cdd92 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/EventProcessor.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/avalon/EventProcessor.java
@@ -30,7 +30,7 @@
import com.highqsoft.avalonCorbaNotification.notification.AvalonNotificationCorbaEventHelper;
/**
- * Event processor responsible for receiving avalon events from the notification
+ * Event processor responsible for receiving avalon events from the notification
* service and redirect them to the manager.
*
* @since 1.0.0
@@ -42,7 +42,7 @@
private static final Logger LOGGER = LoggerFactory.getLogger(EventProcessor.class);
private static final String eventDomainName = "AVALON";
-
+
private final ORB orb;
private final NotificationListener listener;
private final AvalonNotificationManager manager;
@@ -51,55 +51,54 @@
private EventChannel eventChannel;
private StructuredProxyPullSupplier proxyPullSupplier;
-
+
private boolean connected = false;
-
+
private ScheduledFuture<?> future;
-
+
/**
* Creates a new event processor.
- * @param orb CORBA orb to use
- * @param listener notification listener consuming the received events
- * @param manager notification manager responsible for processing the events
- * @param serviceName service name of the CORBA notification service
+ *
+ * @param orb
+ * CORBA orb to use
+ * @param listener
+ * notification listener consuming the received events
+ * @param manager
+ * notification manager responsible for processing the events
+ * @param serviceName
+ * service name of the CORBA notification service
*/
- public EventProcessor(ORB orb, NotificationListener listener, AvalonNotificationManager manager, String nameserviceUrl, String serviceName)
- {
+ public EventProcessor(ORB orb, NotificationListener listener, AvalonNotificationManager manager,
+ String nameserviceUrl, String serviceName) {
this.orb = orb;
this.nameserviceUrl = nameserviceUrl;
this.listener = listener;
this.manager = manager;
this.serviceName = String.format("com/highqsoft/avalon/notification/%s.Notification", serviceName);
}
-
+
/**
* Connect the event processor to the notification service.
- * @throws NotificationException in case the notification service cannot be connected.
+ *
+ * @throws NotificationException
+ * in case the notification service cannot be connected.
*/
- public synchronized void connect() throws NotificationException
- {
- if (isConnected())
- {
+ public synchronized void connect() throws NotificationException {
+ if (isConnected()) {
return;
}
-
- try
- {
+
+ try {
NamingContextExt nc = NamingContextExtHelper.narrow(orb.string_to_object(nameserviceUrl));
-
+
eventChannel = EventChannelHelper.narrow(nc.resolve(nc.to_name(serviceName)));
-
- proxyPullSupplier =
- StructuredProxyPullSupplierHelper.narrow(
- eventChannel.default_consumer_admin().obtain_notification_pull_supplier(
- ClientType.STRUCTURED_EVENT,
- new org.omg.CORBA.IntHolder()));
-
+
+ proxyPullSupplier = StructuredProxyPullSupplierHelper.narrow(eventChannel.default_consumer_admin()
+ .obtain_notification_pull_supplier(ClientType.STRUCTURED_EVENT, new org.omg.CORBA.IntHolder()));
+
proxyPullSupplier.connect_structured_pull_consumer(this._this(orb));
connected = true;
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
throw new NotificationException("Cannot connect to notification service!", e);
}
}
@@ -108,178 +107,164 @@
* Disconnect the event processor from the notification service.
*/
public synchronized void disconnect() {
- if (isConnected())
- {
- if (future != null)
- {
- future.cancel(false);
- }
-
- proxyPullSupplier = null;
-
- eventChannel._release();
- eventChannel = null;
-
- connected = false;
+ if (isConnected()) {
+ if (future != null) {
+ future.cancel(false);
+ }
+
+ proxyPullSupplier = null;
+
+ eventChannel._release();
+ eventChannel = null;
+
+ connected = false;
}
}
/**
- * @return true if the event processor is connected to the notification service
+ * @return true if the event processor is connected to the notification
+ * service
*/
- public synchronized boolean isConnected()
- {
+ public synchronized boolean isConnected() {
return connected;
}
-
+
/**
* Sets the event filter.
- * @param aids List with application element IDs to filter for. Empty list means no all.
- * @param modificationTypes Collection of modification types to filter for.
- * @throws NotificationException if the filter cannot be set
+ *
+ * @param aids
+ * List with application element IDs to filter for. Empty list
+ * means no all.
+ * @param modificationTypes
+ * Collection of modification types to filter for.
+ * @throws NotificationException
+ * if the filter cannot be set
*/
- public void setFilter(List<Long> aids, Set<ModificationType> modificationTypes) throws NotificationException
- {
- if (!isConnected())
- {
+ public void setFilter(List<String> aids, Set<ModificationType> modificationTypes) throws NotificationException {
+ if (!isConnected()) {
throw new IllegalStateException("Cannot set filter when disconnected. Please connect first.");
}
-
- try
- {
- FilterFactory filterFactory = eventChannel.default_filter_factory();
- if(filterFactory == null)
- {
- throw new NotificationException("No default filter factory found!");
- }
-
- Filter filter = filterFactory.create_filter("EXTENDED_TCL");
- filter.add_constraints( new ConstraintExp[]{ new ConstraintExp ( getEventTypes(modificationTypes), getConstraintFilter(aids) ) } );
+
+ try {
+ FilterFactory filterFactory = eventChannel.default_filter_factory();
+ if (filterFactory == null) {
+ throw new NotificationException("No default filter factory found!");
+ }
+
+ Filter filter = filterFactory.create_filter("EXTENDED_TCL");
+ filter.add_constraints(new ConstraintExp[] {
+ new ConstraintExp(getEventTypes(modificationTypes), getConstraintFilter(aids)) });
proxyPullSupplier.add_filter(filter);
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
throw new NotificationException("Exception when creating filter.", e);
}
}
-
+
/**
- * Sets the ScheduledFuture that will be used to stop the event processor task.
- * @param future ScheduledFuture
+ * Sets the ScheduledFuture that will be used to stop the event processor
+ * task.
+ *
+ * @param future
+ * ScheduledFuture
*/
public void setFuture(ScheduledFuture<?> future) {
- this.future = future;
+ this.future = future;
}
@Override
- public synchronized void run()
- {
- if (isConnected())
- {
+ public synchronized void run() {
+ if (isConnected()) {
org.omg.CORBA.BooleanHolder bh = new org.omg.CORBA.BooleanHolder();
- try
- {
+ try {
LOGGER.trace("Looking for structured events....");
- // try to pull an event
- StructuredEvent event = proxyPullSupplier.try_pull_structured_event(bh);
- if(bh.value)
- {
- AvalonNotificationCorbaEvent ev = AvalonNotificationCorbaEventHelper.extract(event.remainder_of_body);
- manager.processNotification(ev.mode, ev.aeId, ev.ieId, ev.userId, ev.timestamp, listener);
- }
- else
- {
- LOGGER.trace("No structured events found.");
- }
- }
- catch (Exception e)
- {
- manager.processException(e);
- }
- }
- else
- {
+ // try to pull an event
+ StructuredEvent event = proxyPullSupplier.try_pull_structured_event(bh);
+ if (bh.value) {
+ AvalonNotificationCorbaEvent ev = AvalonNotificationCorbaEventHelper
+ .extract(event.remainder_of_body);
+ manager.processNotification(ev.mode, ev.aeId, ev.ieId, ev.userId, ev.timestamp, listener);
+ } else {
+ LOGGER.trace("No structured events found.");
+ }
+ } catch (Exception e) {
+ manager.processException(e);
+ }
+ } else {
LOGGER.warn("Disconnected.");
manager.processException(new NotificationException("Not connected"));
- if (future != null)
- {
+ if (future != null) {
future.cancel(false);
}
}
}
-
+
@Override
public void disconnect_structured_pull_consumer() {
LOGGER.info("Disconnected!");
- connected = false;
+ connected = false;
}
@Override
public void offer_change(EventType[] added, EventType[] removed) throws InvalidEventType {
// TODO Auto-generated method stub
-
+
}
-
+
/**
* Constructs a constraint filter.
- * @param aids Application Element IDs used for filtering. Empty list means no filter.
+ *
+ * @param aids
+ * Application Element IDs used for filtering. Empty list means
+ * no filter.
* @return Constraint filter containing the given aids
*/
- private String getConstraintFilter(List<Long> aids) {
- if (aids.isEmpty())
- {
+ private String getConstraintFilter(List<String> aids) {
+ if (aids.isEmpty()) {
return "TRUE";
- }
- else
- {
- return aids.stream()
- .map(aid -> String.format("$.filterable_data(%s) == %s", "ApplicationElement", aid))
- .collect(Collectors.joining(" or "));
+ } else {
+ return aids.stream().map(aid -> String.format("$.filterable_data(%s) == %s", "ApplicationElement", aid))
+ .collect(Collectors.joining(" or "));
}
}
-
+
/**
* Converts ModificationTypes in EventTypes.
+ *
* @param modificationTypes
* @return Array with EventTypes
*/
private EventType[] getEventTypes(Set<ModificationType> modificationTypes) {
- if (modificationTypes.isEmpty())
- {
+ if (modificationTypes.isEmpty()) {
return new EventType[0];
- }
- else
- {
- return modificationTypes.stream()
- .map(s -> new EventType(eventDomainName, toAvalonString(s)))
- .collect(Collectors.toList())
- .toArray(new EventType[0]);
+ } else {
+ return modificationTypes.stream().map(s -> new EventType(eventDomainName, toAvalonString(s)))
+ .collect(Collectors.toList()).toArray(new EventType[0]);
}
}
-
+
/**
- * Converts a {@link ModificationType} enum value to a event type name for the
- * CORBA notification service.
- * @param t a modification type
+ * Converts a {@link ModificationType} enum value to a event type name for
+ * the CORBA notification service.
+ *
+ * @param t
+ * a modification type
* @return event type name
*/
- private String toAvalonString(ModificationType t)
- {
- switch (t)
- {
- case INSTANCE_CREATED:
- return "INSERT";
- case INSTANCE_MODIFIED:
- return "REPLACE";
- case INSTANCE_DELETED:
- return "DELETE";
- case SECURITY_MODIFIED:
- return "MODIFYRIGHTS";
- case MODEL_MODIFIED:
- throw new IllegalArgumentException(t.name() + " not supported!");
- default:
- throw new IllegalArgumentException("Invalid enum value!");
+ private String toAvalonString(ModificationType t) {
+ switch (t) {
+ case INSTANCE_CREATED:
+ return "INSERT";
+ case INSTANCE_MODIFIED:
+ return "REPLACE";
+ case INSTANCE_DELETED:
+ return "DELETE";
+ case SECURITY_MODIFIED:
+ return "MODIFYRIGHTS";
+ case MODEL_MODIFIED:
+ throw new IllegalArgumentException(t.name() + " not supported!");
+ default:
+ throw new IllegalArgumentException("Invalid enum value!");
}
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/EventProcessor.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/EventProcessor.java
index 6c41907..7d578a2 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/EventProcessor.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/EventProcessor.java
@@ -13,8 +13,8 @@
import com.peaksolution.ods.notification.protobuf.NotificationProtos.Notification;
/**
- * Event processor responsible for receiving notification events from the notification
- * server and redirect them to the manager.
+ * Event processor responsible for receiving notification events from the
+ * notification server and redirect them to the manager.
*
* @since 1.0.0
* @author Matthias Koller, Peak Solution GmbH
@@ -25,18 +25,19 @@
private static final Logger LOGGER = LoggerFactory.getLogger(EventProcessor.class);
private EventInput eventInput;
- private NotificationListener listener;
+ private NotificationListener listener;
private PeakNotificationManager odsNotificationManager;
private MediaType eventMediaType;
private boolean closeInvoked = false;
-
- public EventProcessor(EventInput eventInput, NotificationListener listener, PeakNotificationManager odsNotificationManager, MediaType eventMediaType) {
+
+ public EventProcessor(EventInput eventInput, NotificationListener listener,
+ PeakNotificationManager odsNotificationManager, MediaType eventMediaType) {
this.eventInput = eventInput;
this.listener = listener;
this.odsNotificationManager = odsNotificationManager;
this.eventMediaType = eventMediaType;
}
-
+
@Override
public void run() {
@@ -45,25 +46,22 @@
final InboundEvent inboundEvent = eventInput.read();
if (inboundEvent == null) {
- if (!closeInvoked)
- {
- odsNotificationManager.processException(new NotificationException("Inbound event input stream closed!"));
+ if (!closeInvoked) {
+ odsNotificationManager
+ .processException(new NotificationException("Inbound event input stream closed!"));
}
return;
}
- try
- {
- if (LOGGER.isDebugEnabled())
- {
+ try {
+ if (LOGGER.isDebugEnabled()) {
LOGGER.trace("Received event: " + inboundEvent);
}
Notification n = inboundEvent.readData(Notification.class, eventMediaType);
odsNotificationManager.processNotification(n, getListener());
- }
- catch (ProcessingException e)
- {
- odsNotificationManager.processException(new NotificationException("Cannot deserialize notification event!", e));
+ } catch (ProcessingException e) {
+ odsNotificationManager
+ .processException(new NotificationException("Cannot deserialize notification event!", e));
return;
}
}
@@ -71,10 +69,12 @@
public void stop() {
closeInvoked = true;
- // EventInput is closed by the server side after invoking DELETE /events/{registrationName}. Otherwise we run into a deadlock with eventInput#read()
+ // EventInput is closed by the server side after invoking DELETE
+ // /events/{registrationName}. Otherwise we run into a deadlock with
+ // eventInput#read()
}
-
+
public NotificationListener getListener() {
return listener;
- }
+ }
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/JsonMessageBodyProvider.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/JsonMessageBodyProvider.java
index b7772c5..342f3c9 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/JsonMessageBodyProvider.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/JsonMessageBodyProvider.java
@@ -35,67 +35,51 @@
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class JsonMessageBodyProvider implements MessageBodyReader<Message>,
- MessageBodyWriter<Message>
-{
- private static final Charset charset = Charsets.UTF_8;
- private Printer jsonPrinter = JsonFormat.printer();
- private Parser jsonParser = JsonFormat.parser();
+public class JsonMessageBodyProvider implements MessageBodyReader<Message>, MessageBodyWriter<Message> {
+ private static final Charset charset = Charsets.UTF_8;
+ private Printer jsonPrinter = JsonFormat.printer();
+ private Parser jsonParser = JsonFormat.parser();
- public JsonMessageBodyProvider()
- {
+ public JsonMessageBodyProvider() {
- }
+ }
- @Override
- public boolean isReadable(final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType)
- {
- return Message.class.isAssignableFrom(type);
- }
+ @Override
+ public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return Message.class.isAssignableFrom(type);
+ }
- @Override
- public Message readFrom(final Class<Message> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders,
- final InputStream entityStream) throws IOException
- {
- try
- {
- final Method newBuilder = type.getMethod("newBuilder");
- final GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder
- .invoke(type);
- jsonParser.merge(new InputStreamReader(entityStream, charset), builder);
- return builder.build();
- }
- catch (Exception e)
- {
- throw new WebApplicationException(e);
- }
- }
+ @Override
+ public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
+ throws IOException {
+ try {
+ final Method newBuilder = type.getMethod("newBuilder");
+ final GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder.invoke(type);
+ jsonParser.merge(new InputStreamReader(entityStream, charset), builder);
+ return builder.build();
+ } catch (Exception e) {
+ throw new WebApplicationException(e);
+ }
+ }
- @Override
- public long getSize(final Message m, final Class<?> type,
- final Type genericType, final Annotation[] annotations,
- final MediaType mediaType)
- {
- return -1;
- }
+ @Override
+ public long getSize(final Message m, final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return -1;
+ }
- @Override
- public boolean isWriteable(final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType)
- {
- return Message.class.isAssignableFrom(type);
- }
+ @Override
+ public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return Message.class.isAssignableFrom(type);
+ }
- @Override
- public void writeTo(final Message m, final Class<?> type,
- final Type genericType, final Annotation[] annotations,
- final MediaType mediaType,
- final MultivaluedMap<String, Object> httpHeaders,
- final OutputStream entityStream) throws IOException
- {
- entityStream.write(jsonPrinter.print(m).getBytes(charset));
- }
+ @Override
+ public void writeTo(final Message m, final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
+ final OutputStream entityStream) throws IOException {
+ entityStream.write(jsonPrinter.print(m).getBytes(charset));
+ }
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationManager.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationManager.java
index 2ffcf0c..1bb2bd7 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationManager.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationManager.java
@@ -4,6 +4,7 @@
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.stream.Collectors;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
@@ -30,7 +31,8 @@
import com.peaksolution.ods.notification.protobuf.NotificationProtos.Notification;
/**
- * Notification manager for handling notifications from the Peak ODS Server Notification Plugin
+ * Notification manager for handling notifications from the Peak ODS Server
+ * Notification Plugin
*
* @since 1.0.0
* @author Matthias Koller, Peak Solution GmbH
@@ -42,195 +44,185 @@
private final Client client;
private final WebTarget endpoint;
-
+
private final Map<String, EventProcessor> processors = new HashMap<>();
-
+
private final ExecutorService executor = Executors.newCachedThreadPool();
-
+
private final MediaType eventMediaType;
private final ODSModelManager modelManager;
private final NotificationEntityLoader loader;
-
+
/**
* @param modelManager
- * @param url URL of the notification plugin
- * @param eventMediaType MediaType to use.
- * @param loadContextDescribable if true, the corresponding context describable is loaded if a notification for a context root or context component is received.
- * @throws NotificationException Thrown if the manager cannot connect to the notification server.
+ * @param url
+ * URL of the notification plugin
+ * @param eventMediaType
+ * MediaType to use.
+ * @param loadContextDescribable
+ * if true, the corresponding context describable is loaded if a
+ * notification for a context root or context component is
+ * received.
+ * @throws NotificationException
+ * Thrown if the manager cannot connect to the notification
+ * server.
*/
- public PeakNotificationManager(ODSModelManager modelManager, String url, String eventMediaType, boolean loadContextDescribable) throws NotificationException {
+ public PeakNotificationManager(ODSModelManager modelManager, String url, String eventMediaType,
+ boolean loadContextDescribable) throws NotificationException {
this.modelManager = modelManager;
loader = new NotificationEntityLoader(modelManager, loadContextDescribable);
-
- try
- {
- if (Strings.isNullOrEmpty(eventMediaType) || MediaType.APPLICATION_JSON.equalsIgnoreCase(eventMediaType))
- {
+
+ try {
+ if (Strings.isNullOrEmpty(eventMediaType) || MediaType.APPLICATION_JSON.equalsIgnoreCase(eventMediaType)) {
this.eventMediaType = MediaType.APPLICATION_JSON_TYPE;
- }
- else
- {
+ } else {
this.eventMediaType = ProtobufMessageBodyProvider.APPLICATION_PROTOBUF_TYPE;
}
-
- client = ClientBuilder.newBuilder()
- .register(SseFeature.class)
- .register(ProtobufMessageBodyProvider.class)
- .register(JsonMessageBodyProvider.class)
- .build();
-
- endpoint = client.target(url)
- .path("events");
- }
- catch (Exception e)
- {
+
+ client = ClientBuilder.newBuilder().register(SseFeature.class).register(ProtobufMessageBodyProvider.class)
+ .register(JsonMessageBodyProvider.class).build();
+
+ endpoint = client.target(url).path("events");
+ } catch (Exception e) {
throw new NotificationException("Could not create " + PeakNotificationManager.class.getName() + "!", e);
}
}
-
- /* (non-Javadoc)
- * @see org.eclipse.mdm.api.base.notification.NotificationManager#register(java.lang.String, org.eclipse.mdm.api.base.notification.NotificationFilter, org.eclipse.mdm.api.base.notification.NotificationListener)
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.mdm.api.base.notification.NotificationManager#register(java.
+ * lang.String, org.eclipse.mdm.api.base.notification.NotificationFilter,
+ * org.eclipse.mdm.api.base.notification.NotificationListener)
*/
@Override
- public void register(String registration, NotificationFilter filter, NotificationListener listener) throws NotificationException
- {
- Response response = endpoint.path(registration)
- .request()
- .post(javax.ws.rs.client.Entity.entity(ProtobufConverter.from(filter), ProtobufMessageBodyProvider.APPLICATION_PROTOBUF_TYPE));
+ public void register(String registration, NotificationFilter filter, NotificationListener listener)
+ throws NotificationException {
+ Response response = endpoint.path(registration).request().post(javax.ws.rs.client.Entity
+ .entity(ProtobufConverter.from(filter), ProtobufMessageBodyProvider.APPLICATION_PROTOBUF_TYPE));
- if (response.getStatusInfo().getStatusCode() == Status.CONFLICT.getStatusCode())
- {
+ if (response.getStatusInfo().getStatusCode() == Status.CONFLICT.getStatusCode()) {
LOGGER.info("A registration with the name already exists: " + response.readEntity(String.class));
LOGGER.info("Trying to reregister...");
deregister(registration);
register(registration, filter, listener);
return;
}
-
- if (response.getStatusInfo().getStatusCode() != Status.OK.getStatusCode())
- {
- throw new NotificationException("Could not create registration at notification service: " + response.readEntity(String.class));
+
+ if (response.getStatusInfo().getStatusCode() != Status.OK.getStatusCode()) {
+ throw new NotificationException(
+ "Could not create registration at notification service: " + response.readEntity(String.class));
}
- try
- {
- EventInput eventInput = endpoint.path(registration)
- .request()
- .get(EventInput.class);
-
+ try {
+ EventInput eventInput = endpoint.path(registration).request().get(EventInput.class);
+
EventProcessor processor = new EventProcessor(eventInput, listener, this, eventMediaType);
-
+
executor.submit(processor);
-
+
processors.put(registration, processor);
- }
- catch (Exception e)
- {
- try
- {
+ } catch (Exception e) {
+ try {
deregister(registration);
- }
- catch (Exception ex)
- {
+ } catch (Exception ex) {
LOGGER.error("Exception upon deregistering!");
}
throw new NotificationException("Could not create event input stream!", e);
}
-
+
}
- /* (non-Javadoc)
- * @see org.eclipse.mdm.api.base.notification.NotificationManager#deregister(java.lang.String)
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.mdm.api.base.notification.NotificationManager#deregister(java
+ * .lang.String)
*/
@Override
- public void deregister(String registration)
- {
- if (processors.containsKey(registration))
- {
+ public void deregister(String registration) {
+ if (processors.containsKey(registration)) {
close(registration);
- }
-
- endpoint.path(registration)
- .request()
- .delete();
+ }
+
+ endpoint.path(registration).request().delete();
}
-
+
@Override
public void close(boolean isDeregisterAll) throws NotificationException {
LOGGER.info("Closing NotificationManager...");
-
- for (String registration : processors.keySet())
- {
- if (isDeregisterAll)
- {
+
+ for (String registration : processors.keySet()) {
+ if (isDeregisterAll) {
LOGGER.debug("Deregistering '" + registration + "'.");
deregister(registration);
- }
- else
- {
+ } else {
LOGGER.debug("Disconnecting '" + registration + "'.");
close(registration);
}
}
}
-
- private void close(String registration)
- {
- if (processors.containsKey(registration))
- {
+
+ private void close(String registration) {
+ if (processors.containsKey(registration)) {
EventProcessor processor = processors.get(registration);
processor.stop();
processors.remove(registration);
}
}
-
+
/**
* Handler for Exceptions during event processing.
- * @param e Exception which occured during event processing.
+ *
+ * @param e
+ * Exception which occured during event processing.
*/
- void processException(Exception e)
- {
+ void processException(Exception e) {
LOGGER.error("Exception during notification processing!", e);
}
-
+
/**
* Handler for notifications.
- * @param n notification to process.
- * @param notificationListener notification listener for handling the notification.
+ *
+ * @param n
+ * notification to process.
+ * @param notificationListener
+ * notification listener for handling the notification.
*/
void processNotification(Notification n, NotificationListener notificationListener) {
- if (LOGGER.isDebugEnabled())
- {
+ if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Processing notification event: " + n);
}
-
+
try {
- User user = loader.load(new Key<>(User.class), n.getUserId());
+ User user = loader.load(new Key<>(User.class), Long.toString(n.getUserId()));
- EntityType entityType = modelManager.getEntityType(n.getAid());
+ EntityType entityType = modelManager.getEntityType(Long.toString(n.getAid()));
- if (LOGGER.isTraceEnabled())
- {
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Notification event with: entityType=" + entityType + ", user=" + user);
}
-
- switch (n.getType())
- {
+
+ switch (n.getType()) {
case NEW:
- notificationListener.instanceCreated(loader.loadEntities(entityType, n.getIidList()), user);
+ notificationListener.instanceCreated(loader.loadEntities(entityType, n.getIidList().stream().map(id -> id.toString()).collect(Collectors.toList())), user);
break;
case MODIFY:
- notificationListener.instanceModified(loader.loadEntities(entityType, n.getIidList()), user);
+ notificationListener.instanceModified(loader.loadEntities(entityType, n.getIidList().stream().map(id -> id.toString()).collect(Collectors.toList())), user);
break;
case DELETE:
- notificationListener.instanceDeleted(entityType, n.getIidList(), user);
+ notificationListener.instanceDeleted(entityType,
+ n.getIidList().stream().map(id -> id.toString()).collect(Collectors.toList()), user);
break;
case MODEL:
notificationListener.modelModified(entityType, user);
break;
case SECURITY:
- notificationListener.securityModified(entityType, n.getIidList(), user);
+ notificationListener.securityModified(entityType,
+ n.getIidList().stream().map(id -> id.toString()).collect(Collectors.toList()), user);
break;
default:
processException(new NotificationException("Invalid notification type!"));
@@ -240,6 +232,4 @@
}
}
-
-
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufConverter.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufConverter.java
index d7199a0..73a35dd 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufConverter.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufConverter.java
@@ -16,64 +16,65 @@
*
*/
public class ProtobufConverter {
-
+
/**
* Convert a notification filter to a registration.
- * @param filter notification filter.
+ *
+ * @param filter
+ * notification filter.
* @return registration corresponding to the given filter.
*/
- public static Registration from(NotificationFilter filter)
- {
- return Registration.newBuilder()
- .setMode(NotificationMode.PUSH)
- .addAllAid(filter.getEntityTypes().stream().map(e -> e.getId()).collect(Collectors.toList()))
+ public static Registration from(NotificationFilter filter) {
+ return Registration.newBuilder().setMode(NotificationMode.PUSH)
+ .addAllAid(
+ filter.getEntityTypes().stream().map(e -> Long.valueOf(e.getId())).collect(Collectors.toList()))
.addAllType(filter.getTypes().stream().map(t -> ProtobufConverter.from(t)).collect(Collectors.toList()))
.build();
}
-
+
/**
- * @param t mdm modification type.
+ * @param t
+ * mdm modification type.
* @return protobuf notification type.
*/
- public static com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType from(ModificationType t)
- {
- switch (t)
- {
- case INSTANCE_CREATED:
- return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.NEW;
- case INSTANCE_MODIFIED:
- return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.MODIFY;
- case INSTANCE_DELETED:
- return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.DELETE;
- case MODEL_MODIFIED:
- return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.MODEL;
- case SECURITY_MODIFIED:
- return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.SECURITY;
- default:
- throw new IllegalArgumentException("Invalid enum value!"); // TODO
+ public static com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType from(
+ ModificationType t) {
+ switch (t) {
+ case INSTANCE_CREATED:
+ return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.NEW;
+ case INSTANCE_MODIFIED:
+ return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.MODIFY;
+ case INSTANCE_DELETED:
+ return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.DELETE;
+ case MODEL_MODIFIED:
+ return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.MODEL;
+ case SECURITY_MODIFIED:
+ return com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType.SECURITY;
+ default:
+ throw new IllegalArgumentException("Invalid enum value!"); // TODO
}
}
-
+
/**
- * @param t protobuf notification type
+ * @param t
+ * protobuf notification type
* @return mdm notification type
*/
- public static ModificationType to(com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType t)
- {
- switch (t)
- {
- case NEW:
- return ModificationType.INSTANCE_CREATED;
- case MODIFY:
- return ModificationType.INSTANCE_MODIFIED;
- case DELETE:
- return ModificationType.INSTANCE_DELETED;
- case MODEL:
- return ModificationType.MODEL_MODIFIED;
- case SECURITY:
- return ModificationType.SECURITY_MODIFIED;
- default:
- throw new IllegalArgumentException("Invalid enum value!"); // TODO
+ public static ModificationType to(
+ com.peaksolution.ods.notification.protobuf.NotificationProtos.ModificationType t) {
+ switch (t) {
+ case NEW:
+ return ModificationType.INSTANCE_CREATED;
+ case MODIFY:
+ return ModificationType.INSTANCE_MODIFIED;
+ case DELETE:
+ return ModificationType.INSTANCE_DELETED;
+ case MODEL:
+ return ModificationType.MODEL_MODIFIED;
+ case SECURITY:
+ return ModificationType.SECURITY_MODIFIED;
+ default:
+ throw new IllegalArgumentException("Invalid enum value!"); // TODO
}
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufMessageBodyProvider.java b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufMessageBodyProvider.java
index 4c8a94d..4fc177e 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufMessageBodyProvider.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/notification/peak/ProtobufMessageBodyProvider.java
@@ -29,68 +29,54 @@
@Provider
@Consumes(ProtobufMessageBodyProvider.APPLICATION_PROTOBUF)
@Produces(ProtobufMessageBodyProvider.APPLICATION_PROTOBUF)
-public class ProtobufMessageBodyProvider implements MessageBodyReader<Message>,
- MessageBodyWriter<Message>
-{
- /**
- * application/x-protobuf
- */
- public final static String APPLICATION_PROTOBUF = "application/x-protobuf";
-
- /**
- * application/x-protobuf
- */
- public final static MediaType APPLICATION_PROTOBUF_TYPE = new MediaType("application", "x-protobuf");
-
- @Override
- public boolean isReadable(final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType)
- {
- return Message.class.isAssignableFrom(type);
- }
+public class ProtobufMessageBodyProvider implements MessageBodyReader<Message>, MessageBodyWriter<Message> {
+ /**
+ * application/x-protobuf
+ */
+ public final static String APPLICATION_PROTOBUF = "application/x-protobuf";
- @Override
- public Message readFrom(final Class<Message> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders,
- final InputStream entityStream) throws IOException
- {
+ /**
+ * application/x-protobuf
+ */
+ public final static MediaType APPLICATION_PROTOBUF_TYPE = new MediaType("application", "x-protobuf");
- try
- {
- final Method newBuilder = type.getMethod("newBuilder");
- final GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder.invoke(type);
-
- return builder.mergeFrom(entityStream).build();
- }
- catch (Exception e)
- {
- throw new WebApplicationException(e);
- }
- }
+ @Override
+ public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return Message.class.isAssignableFrom(type);
+ }
- @Override
- public long getSize(final Message m, final Class<?> type,
- final Type genericType, final Annotation[] annotations,
- final MediaType mediaType)
- {
- return m.getSerializedSize();
- }
+ @Override
+ public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
+ throws IOException {
- @Override
- public boolean isWriteable(final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType)
- {
- return Message.class.isAssignableFrom(type);
- }
+ try {
+ final Method newBuilder = type.getMethod("newBuilder");
+ final GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder.invoke(type);
- @Override
- public void writeTo(final Message m, final Class<?> type,
- final Type genericType, final Annotation[] annotations,
- final MediaType mediaType,
- final MultivaluedMap<String, Object> httpHeaders,
- final OutputStream entityStream) throws IOException
- {
- m.writeTo(entityStream);
- }
+ return builder.mergeFrom(entityStream).build();
+ } catch (Exception e) {
+ throw new WebApplicationException(e);
+ }
+ }
+
+ @Override
+ public long getSize(final Message m, final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return m.getSerializedSize();
+ }
+
+ @Override
+ public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType) {
+ return Message.class.isAssignableFrom(type);
+ }
+
+ @Override
+ public void writeTo(final Message m, final Class<?> type, final Type genericType, final Annotation[] annotations,
+ final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
+ final OutputStream entityStream) throws IOException {
+ m.writeTo(entityStream);
+ }
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSAttribute.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSAttribute.java
index cab4cf4..8b91f88 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSAttribute.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSAttribute.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -9,11 +9,15 @@
package org.eclipse.mdm.api.odsadapter.query;
import java.util.Objects;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
import org.asam.ods.ApplAttr;
+import org.eclipse.mdm.api.base.model.Value;
import org.eclipse.mdm.api.base.model.ValueType;
import org.eclipse.mdm.api.base.query.Attribute;
import org.eclipse.mdm.api.base.query.EntityType;
+import org.eclipse.mdm.api.base.query.Relation;
import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
/**
@@ -22,7 +26,7 @@
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
-final class ODSAttribute implements Attribute {
+public class ODSAttribute implements Attribute {
// ======================================================================
// Instance variables
@@ -33,6 +37,7 @@
private final String unit;
private final EntityType entityType;
private final ValueType valueType;
+ private final boolean isIdAttribute;
// ======================================================================
// Constructors
@@ -41,25 +46,48 @@
/**
* Constructor.
*
- * @param entityType The parent {@link EntityType}.
- * @param applAttr The ODS meta data for this attribute.
- * @param unit The unit name.
- * @param enumClass The enumeration class, may be null.
+ * @param entityType
+ * The parent {@link EntityType}.
+ * @param applAttr
+ * The ODS meta data for this attribute.
+ * @param unit
+ * The unit name.
+ * @param enumClass
+ * The enumeration class, may be null.
*/
ODSAttribute(EntityType entityType, ApplAttr applAttr, String unit, Class<? extends Enum<?>> enumClass) {
this.entityType = entityType;
name = applAttr.aaName;
this.unit = unit == null ? "" : unit;
- valueType = ODSUtils.VALUETYPES.revert(applAttr.dType);
- if(valueType.isEnumerationType() && enumClass == null) {
- throw new IllegalStateException("A modeled attribute with an enumeration vaue type must have an "
- + "enumeration definition.");
+ if (isIDAttribute(entityType, applAttr)) {
+ valueType = ValueType.STRING;
+ isIdAttribute = true;
+ } else {
+ valueType = ODSUtils.VALUETYPES.revert(applAttr.dType);
+ isIdAttribute = false;
+ }
+
+ if (valueType.isEnumerationType() && enumClass == null) {
+ throw new IllegalStateException(
+ "A modeled attribute with an enumeration vaue type must have an " + "enumeration definition.");
}
this.enumClass = enumClass;
}
+ private boolean isIDAttribute(EntityType entityType, ApplAttr applAttr) {
+ for (Relation r : entityType.getRelations()) {
+ if (applAttr.aaName.equalsIgnoreCase(r.getName())) {
+ return true;
+ }
+ }
+ return "id".equalsIgnoreCase(applAttr.baName);
+ }
+
+ public boolean isIdAttribute() {
+ return isIdAttribute;
+ }
// ======================================================================
// Public methods
// ======================================================================
@@ -101,13 +129,45 @@
*/
@Override
public Class<? extends Enum<?>> getEnumClass() {
- if(getValueType().isEnumerationType()) {
+ if (getValueType().isEnumerationType()) {
return enumClass;
}
throw new IllegalStateException("The value type of this attribute is not an enumeration type.");
}
+ @Override
+ public Value createValue(String unit, boolean valid, Object input) {
+ return Attribute.super.createValue(unit, valid, convertInputForIdAttribute(input));
+ }
+
+ @Override
+ public Value createValueSeq(String unit, Object input) {
+ return Attribute.super.createValueSeq(unit, convertInputForIdAttribute(input));
+ }
+
+ /**
+ * Converts the input object from long/long-array/int/int-array to a
+ * String/String-array
+ *
+ * @param input
+ * The input to convert
+ * @return The converted input
+ */
+ private Object convertInputForIdAttribute(Object input) {
+ if (isIdAttribute) {
+ if (input instanceof Long || input instanceof Integer) {
+ return input.toString();
+ } else if (input instanceof long[]) {
+ return LongStream.of((long[]) input).mapToObj(Long::toString).toArray(String[]::new);
+ } else if (input instanceof int[]) {
+ return IntStream.of((int[]) input).mapToObj(Integer::toString).toArray(String[]::new);
+ }
+ }
+
+ return input;
+ }
+
/**
* {@inheritDoc}
*/
@@ -121,7 +181,7 @@
*/
@Override
public boolean equals(Object object) {
- if(object instanceof ODSAttribute) {
+ if (object instanceof ODSAttribute) {
Attribute attribute = (Attribute) object;
return getEntityType().equals(attribute.getEntityType()) && getName().equals(attribute.getName());
}
@@ -136,5 +196,4 @@
public String toString() {
return getName();
}
-
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityFactory.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityFactory.java
index 22b5cf4..af50bad 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityFactory.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityFactory.java
@@ -70,8 +70,10 @@
/**
* Constructor.
*
- * @param modelManager Used to create {@link Core}s.
- * @param loggedInUser The logged in {@link User}.
+ * @param modelManager
+ * Used to create {@link Core}s.
+ * @param loggedInUser
+ * The logged in {@link User}.
*/
public ODSEntityFactory(ODSModelManager modelManager, User loggedInUser) {
this.modelManager = modelManager;
@@ -112,9 +114,9 @@
@Override
protected <T extends Entity> Core createCore(String name, Class<T> entityClass) {
EntityConfig<?> entityConfig = modelManager.getEntityConfig(modelManager.getEntityType(name));
- if(!entityClass.equals(entityConfig.getEntityClass())) {
+ if (!entityClass.equals(entityConfig.getEntityClass())) {
throw new IllegalArgumentException("Incompatible entity class expected '" + entityClass.getName()
- + "' but got '" + entityConfig.getEntityClass().getName() + "'");
+ + "' but got '" + entityConfig.getEntityClass().getName() + "'");
}
Core core = new DefaultCore(entityConfig.getEntityType());
core.getValues().get(Entity.ATTR_MIMETYPE).set(entityConfig.getMimeType());
@@ -127,8 +129,9 @@
*/
@Override
protected void validateEnum(Class<? extends Enum<?>> enumClass) {
- if(ENUM_CLASSES.contains(enumClass)) {
- // given enumeration class is a default one, which is always supported
+ if (ENUM_CLASSES.contains(enumClass)) {
+ // given enumeration class is a default one, which is always
+ // supported
return;
}
@@ -144,8 +147,10 @@
/**
* Creates a configured {@link Core} for given {@link Key}.
*
- * @param <T> The entity type.
- * @param key Used as identifier to resolve the {@link EntityConfig}.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used as identifier to resolve the {@link EntityConfig}.
* @return The created {@code Core} is returned.
*/
private <T extends Entity> Core createCore(Key<T> key) {
@@ -153,7 +158,7 @@
Core core = new DefaultCore(entityConfig.getEntityType());
core.getValues().get(Entity.ATTR_MIMETYPE).set(entityConfig.getMimeType());
- if(CatalogAttribute.class.equals(entityConfig.getEntityClass())) {
+ if (CatalogAttribute.class.equals(entityConfig.getEntityClass())) {
core.getValues().put(VATTR_ENUMERATION_CLASS, ValueType.STRING.create(VATTR_ENUMERATION_CLASS));
core.getValues().put(VATTR_SCALAR_TYPE, ValueType.ENUMERATION.create(ScalarType.class, VATTR_SCALAR_TYPE));
core.getValues().put(VATTR_SEQUENCE, ValueType.BOOLEAN.create(VATTR_SEQUENCE));
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityType.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityType.java
index a3b610e..0cba1dd 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityType.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSEntityType.java
@@ -64,21 +64,26 @@
/**
* Constructor.
*
- * @param sourceName Name of the data source.
- * @param applElem The ODS meta data for this entity type.
- * @param units The unit {@code Map} for unit mapping of attributes.
- * @param enumClasses The enumeration class {@code Map} for enum mapping
- * of attributes.
+ * @param sourceName
+ * Name of the data source.
+ * @param applElem
+ * The ODS meta data for this entity type.
+ * @param units
+ * The unit {@code Map} for unit mapping of attributes.
+ * @param enumClasses
+ * The enumeration class {@code Map} for enum mapping of
+ * attributes.
*/
- ODSEntityType(String sourceName, ApplElem applElem, Map<Long, String> units,
+ ODSEntityType(String sourceName, ApplElem applElem, Map<String, String> units,
Map<String, Class<? extends Enum<?>>> enumClasses) {
this.sourceName = sourceName;
baseName = applElem.beName;
name = applElem.aeName;
odsID = applElem.aid;
- attributeByName = Arrays.stream(applElem.attributes)
- .map(a -> new ODSAttribute(this, a, units.get(ODSConverter.fromODSLong(a.unitId)),
+ attributeByName = Arrays
+ .stream(applElem.attributes).map(a -> new ODSAttribute(this, a,
+ units.get(Long.toString(ODSConverter.fromODSLong(a.unitId))),
enumClasses.get(a.aaName)))
.collect(toMap(Attribute::getName, Function.identity()));
}
@@ -126,11 +131,10 @@
@Override
public Attribute getAttribute(String name) {
Attribute attribute = attributeByName.get(name);
- if(attribute == null) {
+ if (attribute == null) {
Optional<Relation> relation = getRelations().stream().filter(r -> r.getName().equals(name)).findAny();
- return relation.map(Relation::getAttribute)
- .orElseThrow(() -> new IllegalArgumentException("Attribute with name '" + name
- + "' not found at entity type '" + getName() + "'."));
+ return relation.map(Relation::getAttribute).orElseThrow(() -> new IllegalArgumentException(
+ "Attribute with name '" + name + "' not found at entity type '" + getName() + "'."));
}
return attribute;
}
@@ -148,8 +152,8 @@
* {@inheritDoc}
*/
@Override
- public long getId() {
- return ODSConverter.fromODSLong(odsID);
+ public String getId() {
+ return Long.toString(ODSConverter.fromODSLong(odsID));
}
@Override
@@ -163,8 +167,7 @@
@Override
public List<Relation> getParentRelations() {
return getRelations(Relationship.FATHER_CHILD).stream()
- .filter(r -> ((ODSRelation) r).isOutgoing(Relationship.FATHER_CHILD))
- .collect(Collectors.toList());
+ .filter(r -> ((ODSRelation) r).isOutgoing(Relationship.FATHER_CHILD)).collect(Collectors.toList());
}
/**
@@ -173,8 +176,7 @@
@Override
public List<Relation> getChildRelations() {
return getRelations(Relationship.FATHER_CHILD).stream()
- .filter(r -> ((ODSRelation) r).isIncoming(Relationship.FATHER_CHILD))
- .collect(Collectors.toList());
+ .filter(r -> ((ODSRelation) r).isIncoming(Relationship.FATHER_CHILD)).collect(Collectors.toList());
}
/**
@@ -182,8 +184,7 @@
*/
@Override
public List<Relation> getInfoRelations() {
- return getRelations(Relationship.INFO).stream()
- .filter(r -> ((ODSRelation) r).isOutgoing(Relationship.INFO))
+ return getRelations(Relationship.INFO).stream().filter(r -> ((ODSRelation) r).isOutgoing(Relationship.INFO))
.collect(Collectors.toList());
}
@@ -202,10 +203,10 @@
@Override
public Relation getRelation(EntityType target) {
Relation relation = relationsByEntity.get(target);
- if(relation == null) {
+ if (relation == null) {
// multiple relations to target exist, try to use a default
Map<String, Relation> relationsByName = relationsByEntityName.get(target);
- if(relationsByName == null) {
+ if (relationsByName == null) {
throw new IllegalArgumentException("Relations to '" + target + "' not found!");
}
@@ -220,12 +221,12 @@
@Override
public Relation getRelation(EntityType target, String name) {
Map<String, Relation> relationsByName = relationsByEntityName.get(target);
- if(relationsByName == null) {
+ if (relationsByName == null) {
throw new IllegalArgumentException("Relations to '" + target + "' not found!");
}
Relation relation = relationsByName.get(name);
- if(relation == null) {
+ if (relation == null) {
throw new IllegalArgumentException("Relation to '" + target + "' with name '" + name + "' not found!");
}
return relation;
@@ -244,7 +245,7 @@
*/
@Override
public boolean equals(Object object) {
- if(object instanceof ODSEntityType) {
+ if (object instanceof ODSEntityType) {
return getName().equals(((EntityType) object).getName());
}
@@ -266,20 +267,20 @@
/**
* Adds given {@link Relation}s.
*
- * @param relations {@code Relation}s which will be added.
+ * @param relations
+ * {@code Relation}s which will be added.
*/
void setRelations(List<Relation> relations) {
Map<EntityType, List<Relation>> entityRelationsByTarget = relations.stream().distinct()
- .filter(r -> equals(r.getSource()))
- .collect(groupingBy(Relation::getTarget));
+ .filter(r -> equals(r.getSource())).collect(groupingBy(Relation::getTarget));
- for(Entry<EntityType, List<Relation>> entry : entityRelationsByTarget.entrySet()) {
+ for (Entry<EntityType, List<Relation>> entry : entityRelationsByTarget.entrySet()) {
List<Relation> entityTypeRelations = entry.getValue();
EntityType target = entry.getKey();
entityTypeRelations.forEach(this::addRelation);
- if(entityTypeRelations.size() > 1) {
+ if (entityTypeRelations.size() > 1) {
relationsByEntityName.put(target,
entityTypeRelations.stream().collect(toMap(Relation::getName, identity())));
} else {
@@ -293,24 +294,25 @@
// ======================================================================
/**
- * Tries to find a parent {@link Relation} to given target {@link
- * EntityType}.
+ * Tries to find a parent {@link Relation} to given target
+ * {@link EntityType}.
*
- * @param target The target {@code EntityType}.
+ * @param target
+ * The target {@code EntityType}.
* @return The requested parent {@code Relation} is returned.
- * @throws IllegalArgumentException Thrown if no such {@code Relation}
- * exists.
+ * @throws IllegalArgumentException
+ * Thrown if no such {@code Relation} exists.
*/
private Relation getParentRelation(EntityType target) {
- return getParentRelations().stream().filter(et -> et.getTarget().equals(target)).findAny()
- .orElseThrow(() -> new IllegalArgumentException("Relation to entity type '" + target
- + "' does not exist."));
+ return getParentRelations().stream().filter(et -> et.getTarget().equals(target)).findAny().orElseThrow(
+ () -> new IllegalArgumentException("Relation to entity type '" + target + "' does not exist."));
}
/**
* Adds given {@link Relation}.
*
- * @param relation {@code Relation} which will be added.
+ * @param relation
+ * {@code Relation} which will be added.
*/
private void addRelation(Relation relation) {
relationsByType.computeIfAbsent(relation.getRelationship(), k -> new ArrayList<>()).add(relation);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSModelManager.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSModelManager.java
index 978f971..af599b0 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSModelManager.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSModelManager.java
@@ -123,10 +123,14 @@
/**
* Constructor.
*
- * @param orb Used to activate CORBA service objects.
- * @param aoSession The underlying ODS session.
- * @param fileServer Used for file transfers.
- * @throws AoException Thrown on errors.
+ * @param orb
+ * Used to activate CORBA service objects.
+ * @param aoSession
+ * The underlying ODS session.
+ * @param fileServer
+ * Used for file transfers.
+ * @throws AoException
+ * Thrown on errors.
*/
public ODSModelManager(ORB orb, AoSession aoSession, CORBAFileServerIF fileServer) throws AoException {
this.fileServer = fileServer;
@@ -151,7 +155,8 @@
* Returns a new {@link ODSModelManager} with a new ODS co-session.
*
* @return The created {@code ODSModelManager} is returned.
- * @throws AoException Thrown on errors.
+ * @throws AoException
+ * Thrown on errors.
*/
public ODSModelManager newSession() throws AoException {
return new ODSModelManager(orb, getAoSession().createCoSession(), fileServer);
@@ -178,8 +183,10 @@
/**
* Returns the non root {@link EntityConfig} for given {@link Key}.
*
- * @param <T> The concrete entity type.
- * @param key Used as identifier.
+ * @param <T>
+ * The concrete entity type.
+ * @param key
+ * Used as identifier.
* @return The non root {@code EntityConfig} is returned.
*/
public <T extends Entity> EntityConfig<T> findEntityConfig(Key<T> key) {
@@ -195,8 +202,10 @@
/**
* Returns the root {@link EntityConfig} for given {@link Key}.
*
- * @param <T> The concrete entity type.
- * @param key Used as identifier.
+ * @param <T>
+ * The concrete entity type.
+ * @param key
+ * Used as identifier.
* @return The root {@code EntityConfig} is returned.
*/
public <T extends Entity> EntityConfig<T> getEntityConfig(Key<T> key) {
@@ -210,9 +219,11 @@
}
/**
- * Returns the {@link EntityConfig} associated with given {@link EntityType}.
+ * Returns the {@link EntityConfig} associated with given
+ * {@link EntityType}.
*
- * @param entityType Used as identifier.
+ * @param entityType
+ * Used as identifier.
* @return The {@code EntityConfig} is returned.
*/
public EntityConfig<?> getEntityConfig(EntityType entityType) {
@@ -260,7 +271,7 @@
public EntityType getEntityType(Class<? extends Entity> entityClass) {
read.lock();
- try{
+ try {
return getEntityConfig(new Key<>(entityClass)).getEntityType();
} finally {
read.unlock();
@@ -274,7 +285,7 @@
public EntityType getEntityType(Class<? extends Entity> entityClass, ContextType contextType) {
read.lock();
- try{
+ try {
return getEntityConfig(new Key<>(entityClass, contextType)).getEntityType();
} finally {
read.unlock();
@@ -290,7 +301,7 @@
try {
EntityType entityType = entityTypesByName.get(name);
- if(entityType == null) {
+ if (entityType == null) {
throw new IllegalArgumentException("Entity with name '" + name + "' not found.");
}
@@ -301,9 +312,9 @@
}
@Override
- public EntityType getEntityType(long id) {
+ public EntityType getEntityTypeById(String id) {
EntityType entityType = listEntityTypes().stream().filter(et -> et.getId() == id).findFirst().get();
- if(entityType == null) {
+ if (entityType == null) {
throw new IllegalArgumentException("Entity with id '" + id + "' not found.");
}
@@ -343,7 +354,8 @@
/**
* Closes the ODS connection.
*
- * @throws AoException Thrown on errors.
+ * @throws AoException
+ * Thrown on errors.
*/
public void close() throws AoException {
read.lock();
@@ -371,7 +383,7 @@
aoSession = aoSession.createCoSession();
applElemAccess = aoSession.getApplElemAccess();
initialize();
- } catch(AoException e) {
+ } catch (AoException e) {
LOGGER.error("Unable to reload the application model due to: " + e.reason, e);
} finally {
write.unlock();
@@ -380,7 +392,7 @@
try {
applElemAccessOld._release();
aoSessionOld.close();
- } catch(AoException e) {
+ } catch (AoException e) {
LOGGER.debug("Unable to close replaced session due to: " + e.reason, e);
} finally {
aoSessionOld._release();
@@ -395,7 +407,8 @@
* Initializes this model manager by caching the application model and
* loading the {@link EntityConfig}s.
*
- * @throws AoException Thrown on errors.
+ * @throws AoException
+ * Thrown on errors.
*/
private void initialize() throws AoException {
loadApplicationModel();
@@ -405,26 +418,28 @@
/**
* Caches the whole application model as provided by the ODS session.
*
- * @throws AoException Thrown on errors.
+ * @throws AoException
+ * Thrown on errors.
*/
private void loadApplicationModel() throws AoException {
LOGGER.debug("Reading the application model...");
long start = System.currentTimeMillis();
// enumeration mappings (aeID -> (aaName -> enumClass))
- Map<Long, Map<String, Class<? extends Enum<?>>>> enumClassMap = new HashMap<>();
- for(EnumerationAttributeStructure eas : aoSession.getEnumerationAttributes()) {
- enumClassMap.computeIfAbsent(ODSConverter.fromODSLong(eas.aid), k -> new HashMap<>())
- .put(eas.aaName, ODSEnumerations.getEnumClass(eas.enumName));
+ Map<String, Map<String, Class<? extends Enum<?>>>> enumClassMap = new HashMap<>();
+ for (EnumerationAttributeStructure eas : aoSession.getEnumerationAttributes()) {
+ enumClassMap.computeIfAbsent(Long.toString(ODSConverter.fromODSLong(eas.aid)), k -> new HashMap<>())
+ .put(eas.aaName,
+ ODSEnumerations.getEnumClass(eas.enumName));
}
ApplicationStructureValue applicationStructureValue = aoSession.getApplicationStructureValue();
- Map<Long, String> units = getUnitMapping(applicationStructureValue.applElems);
+ Map<String, String> units = getUnitMapping(applicationStructureValue.applElems);
// create entity types (incl. attributes)
- Map<Long, ODSEntityType> entityTypesByID = new HashMap<>();
+ Map<String, ODSEntityType> entityTypesByID = new HashMap<>();
String sourceName = aoSession.getName();
- for(ApplElem applElem : applicationStructureValue.applElems) {
- Long odsID = ODSConverter.fromODSLong(applElem.aid);
+ for (ApplElem applElem : applicationStructureValue.applElems) {
+ String odsID = Long.toString(ODSConverter.fromODSLong(applElem.aid));
Map<String, Class<? extends Enum<?>>> entityEnumMap = enumClassMap.getOrDefault(odsID, new HashMap<>());
ODSEntityType entityType = new ODSEntityType(sourceName, applElem, units, entityEnumMap);
@@ -434,45 +449,48 @@
// create relations
List<Relation> relations = new ArrayList<>();
- for(ApplRel applRel : applicationStructureValue.applRels) {
- EntityType source = entityTypesByID.get(ODSConverter.fromODSLong(applRel.elem1));
- EntityType target = entityTypesByID.get(ODSConverter.fromODSLong(applRel.elem2));
+ for (ApplRel applRel : applicationStructureValue.applRels) {
+ EntityType source = entityTypesByID.get(Long.toString(ODSConverter.fromODSLong(applRel.elem1)));
+ EntityType target = entityTypesByID.get(Long.toString(ODSConverter.fromODSLong(applRel.elem2)));
relations.add(new ODSRelation(applRel, source, target));
}
// assign relations to their source entity types
relations.stream().collect(groupingBy(Relation::getSource))
- .forEach((e, r) -> ((ODSEntityType) e).setRelations(r));
+ .forEach((e, r) -> ((ODSEntityType) e).setRelations(r));
long stop = System.currentTimeMillis();
- LOGGER.debug("{} entity types with {} relations found in {} ms.",
- entityTypesByName.size(), relations.size(), stop - start);
+ LOGGER.debug("{} entity types with {} relations found in {} ms.", entityTypesByName.size(), relations.size(),
+ stop - start);
}
/**
* Loads all available {@link Unit} names mapped by their instance IDs.
*
- * @param applElems The application element meta data instances.
+ * @param applElems
+ * The application element meta data instances.
* @return The unit names mapped by the corresponding instance IDs.
- * @throws AoException Thrown if unable to load the unit mappings.
+ * @throws AoException
+ * Thrown if unable to load the unit mappings.
*/
- private Map<Long, String> getUnitMapping(ApplElem[] applElems) throws AoException {
+ private Map<String, String> getUnitMapping(ApplElem[] applElems) throws AoException {
ApplElem unitElem = Stream.of(applElems).filter(ae -> ae.beName.equals("AoUnit")).findAny()
.orElseThrow(() -> new IllegalStateException("Application element 'Unit' is not defined."));
QueryStructureExt qse = new QueryStructureExt();
qse.anuSeq = new SelAIDNameUnitId[] {
new SelAIDNameUnitId(new AIDName(unitElem.aid, "Id"), new T_LONGLONG(), AggrFunc.NONE),
- new SelAIDNameUnitId(new AIDName(unitElem.aid, "Name"), new T_LONGLONG(), AggrFunc.NONE)};
+ new SelAIDNameUnitId(new AIDName(unitElem.aid, "Name"), new T_LONGLONG(), AggrFunc.NONE) };
qse.condSeq = new SelItem[0];
qse.groupBy = new AIDName[0];
qse.joinSeq = new JoinDef[0];
qse.orderBy = new SelOrder[0];
- Map<Long, String> units = new HashMap<>();
+ Map<String, String> units = new HashMap<>();
ElemResultSetExt unitResultSetExt = getApplElemAccess().getInstancesExt(qse, 0)[0].firstElems[0];
- for(int i = 0; i < unitResultSetExt.values[0].value.flag.length; i++) {
- Long unitID = ODSConverter.fromODSLong(unitResultSetExt.values[0].value.u.longlongVal()[i]);
+ for (int i = 0; i < unitResultSetExt.values[0].value.flag.length; i++) {
+ String unitID = Long
+ .toString(ODSConverter.fromODSLong(unitResultSetExt.values[0].value.u.longlongVal()[i]));
String unitName = unitResultSetExt.values[1].value.u.stringVal()[i];
units.put(unitID, unitName);
}
@@ -489,7 +507,8 @@
entityConfigRepository = new EntityConfigRepository();
- // Environment | Project | Pool | PhysicalDimension | User | Measurement | ChannelGroup
+ // Environment | Project | Pool | PhysicalDimension | User | Measurement
+ // | ChannelGroup
entityConfigRepository.register(create(new Key<>(Environment.class), "Environment", false));
entityConfigRepository.register(create(new Key<>(Project.class), "Project", false));
entityConfigRepository.register(create(new Key<>(Pool.class), "StructureLevel", true));
@@ -515,8 +534,8 @@
entityConfigRepository.register(channelConfig);
// ValueList
- EntityConfig<ValueListValue> valueListValueConfig = create(new Key<>(ValueListValue.class),
- "ValueListValue", true);
+ EntityConfig<ValueListValue> valueListValueConfig = create(new Key<>(ValueListValue.class), "ValueListValue",
+ true);
valueListValueConfig.setComparator(Sortable.COMPARATOR);
EntityConfig<ValueList> valueListConfig = create(new Key<>(ValueList.class), "ValueList", true);
valueListConfig.addChild(valueListValueConfig);
@@ -525,8 +544,8 @@
// ParameterSet
EntityConfig<Parameter> parameterConfig = create(new Key<>(Parameter.class), "ResultParameter", true);
parameterConfig.addOptional(entityConfigRepository.findRoot(new Key<>(Unit.class)));
- EntityConfig<ParameterSet> parameterSetConfig = create(new Key<>(ParameterSet.class),
- "ResultParameterSet", true);
+ EntityConfig<ParameterSet> parameterSetConfig = create(new Key<>(ParameterSet.class), "ResultParameterSet",
+ true);
parameterSetConfig.addChild(parameterConfig);
entityConfigRepository.register(parameterSetConfig);
@@ -541,24 +560,26 @@
registerTemplateRoot(ContextType.TESTEQUIPMENT);
// TemplateTestStep
- EntityConfig<TemplateTestStep> templateTestStepConfig = create(new Key<>(TemplateTestStep.class),
- "TplTestStep", true);
- templateTestStepConfig.addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class,
- ContextType.UNITUNDERTEST)));
- templateTestStepConfig.addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class,
- ContextType.TESTSEQUENCE)));
- templateTestStepConfig.addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class,
- ContextType.TESTEQUIPMENT)));
+ EntityConfig<TemplateTestStep> templateTestStepConfig = create(new Key<>(TemplateTestStep.class), "TplTestStep",
+ true);
+ templateTestStepConfig
+ .addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class, ContextType.UNITUNDERTEST)));
+ templateTestStepConfig
+ .addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class, ContextType.TESTSEQUENCE)));
+ templateTestStepConfig
+ .addOptional(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class, ContextType.TESTEQUIPMENT)));
templateTestStepConfig.setComparator(Versionable.COMPARATOR);
entityConfigRepository.register(templateTestStepConfig);
// Status TestStep
// TODO check MIME type genration
- // entityConfigRepository.register(create(new Key<>(Status.class, TestStep.class), "StatusTestStep", true));
+ // entityConfigRepository.register(create(new Key<>(Status.class,
+ // TestStep.class), "StatusTestStep", true));
// TestStep
EntityConfig<TestStep> testStepConfig = create(new Key<>(TestStep.class), "TestStep", true);
- // testStepConfig.addMandatory(entityConfigRepository.findRoot(new Key<>(Status.class, TestStep.class)));
+ // testStepConfig.addMandatory(entityConfigRepository.findRoot(new
+ // Key<>(Status.class, TestStep.class)));
testStepConfig.addOptional(entityConfigRepository.findRoot(new Key<>(TemplateTestStep.class)));
testStepConfig.setComparator(Sortable.COMPARATOR);
entityConfigRepository.register(testStepConfig);
@@ -575,16 +596,17 @@
// Status Test
// TODO check MIME type genration
- // entityConfigRepository.register(create(new Key<>(Status.class, Test.class), "StatusTest", true));
+ // entityConfigRepository.register(create(new Key<>(Status.class,
+ // Test.class), "StatusTest", true));
// Test
EntityConfig<Test> testConfig = create(new Key<>(Test.class), "Test", true);
testConfig.addMandatory(entityConfigRepository.findRoot(new Key<>(User.class)));
- // testConfig.addMandatory(entityConfigRepository.findRoot(new Key<>(Status.class, Test.class)));
+ // testConfig.addMandatory(entityConfigRepository.findRoot(new
+ // Key<>(Status.class, Test.class)));
testConfig.addOptional(entityConfigRepository.findRoot(new Key<>(TemplateTest.class)));
entityConfigRepository.register(testConfig);
-
// ContextRoots
registerContextRoot(ContextType.UNITUNDERTEST);
registerContextRoot(ContextType.TESTSEQUENCE);
@@ -597,26 +619,27 @@
* Loads the {@link EntityConfig}s required for {@link ContextRoot} with
* given {@link ContextType}.
*
- * @param contextType The {@code ContextType}.
+ * @param contextType
+ * The {@code ContextType}.
*/
private void registerContextRoot(ContextType contextType) {
EntityConfig<ContextRoot> contextRootConfig = create(new Key<>(ContextRoot.class, contextType),
ODSUtils.CONTEXTTYPES.convert(contextType), true);
contextRootConfig.addMandatory(entityConfigRepository.findRoot(new Key<>(TemplateRoot.class, contextType)));
- for(Relation contextComponentRelation : contextRootConfig.getEntityType().getChildRelations()) {
+ for (Relation contextComponentRelation : contextRootConfig.getEntityType().getChildRelations()) {
EntityType contextComponentEntityType = contextComponentRelation.getTarget();
- EntityConfig<ContextComponent> contextComponentConfig =
- create(new Key<>(ContextComponent.class, contextType), contextComponentEntityType.getName(), true);
- contextComponentConfig.addInherited(entityConfigRepository.findImplicit(new Key<>(TemplateComponent.class,
- contextType)));
+ EntityConfig<ContextComponent> contextComponentConfig = create(
+ new Key<>(ContextComponent.class, contextType), contextComponentEntityType.getName(), true);
+ contextComponentConfig
+ .addInherited(entityConfigRepository.findImplicit(new Key<>(TemplateComponent.class, contextType)));
contextRootConfig.addChild(contextComponentConfig);
- if(contextType.isTestEquipment()) {
- for(Relation contextSensorRelation : contextComponentEntityType.getChildRelations()) {
+ if (contextType.isTestEquipment()) {
+ for (Relation contextSensorRelation : contextComponentEntityType.getChildRelations()) {
EntityType contextSensorEntityType = contextSensorRelation.getTarget();
EntityConfig<ContextSensor> contextSensorConfig = create(new Key<>(ContextSensor.class),
contextSensorEntityType.getName(), true);
- contextSensorConfig.addInherited(entityConfigRepository
- .findImplicit(new Key<>(TemplateSensor.class)));
+ contextSensorConfig
+ .addInherited(entityConfigRepository.findImplicit(new Key<>(TemplateSensor.class)));
contextComponentConfig.addChild(contextSensorConfig);
}
}
@@ -628,38 +651,39 @@
* Loads the {@link EntityConfig}s required for {@link TemplateRoot} with
* given {@link ContextType}.
*
- * @param contextType The {@code ContextType}.
+ * @param contextType
+ * The {@code ContextType}.
*/
private void registerTemplateRoot(ContextType contextType) {
String odsName = ODSUtils.CONTEXTTYPES.convert(contextType);
- EntityConfig<TemplateAttribute> templateAttributeConfig =
- create(new Key<>(TemplateAttribute.class, contextType), "Tpl" + odsName + "Attr", true);
- templateAttributeConfig.addInherited(entityConfigRepository
- .findImplicit(new Key<>(CatalogAttribute.class, contextType)));
+ EntityConfig<TemplateAttribute> templateAttributeConfig = create(
+ new Key<>(TemplateAttribute.class, contextType), "Tpl" + odsName + "Attr", true);
+ templateAttributeConfig
+ .addInherited(entityConfigRepository.findImplicit(new Key<>(CatalogAttribute.class, contextType)));
templateAttributeConfig.setComparator(TemplateAttribute.COMPARATOR);
- EntityConfig<TemplateComponent> templateComponentConfig =
- create(new Key<>(TemplateComponent.class, contextType), "Tpl" + odsName + "Comp", true);
+ EntityConfig<TemplateComponent> templateComponentConfig = create(
+ new Key<>(TemplateComponent.class, contextType), "Tpl" + odsName + "Comp", true);
templateComponentConfig.addChild(templateAttributeConfig);
- templateComponentConfig.addMandatory(entityConfigRepository
- .findRoot(new Key<>(CatalogComponent.class, contextType)));
+ templateComponentConfig
+ .addMandatory(entityConfigRepository.findRoot(new Key<>(CatalogComponent.class, contextType)));
templateComponentConfig.addChild(templateComponentConfig);
templateComponentConfig.setComparator(Sortable.COMPARATOR);
- if(contextType.isTestEquipment()) {
- EntityConfig<TemplateAttribute> templateSensorAttributeConfig =
- create(new Key<>(TemplateAttribute.class), "TplSensorAttr", true);
+ if (contextType.isTestEquipment()) {
+ EntityConfig<TemplateAttribute> templateSensorAttributeConfig = create(new Key<>(TemplateAttribute.class),
+ "TplSensorAttr", true);
templateSensorAttributeConfig.setComparator(TemplateAttribute.COMPARATOR);
- templateSensorAttributeConfig.addInherited(entityConfigRepository
- .findImplicit(new Key<>(CatalogAttribute.class)));
- EntityConfig<TemplateSensor> templateSensorConfig =
- create(new Key<>(TemplateSensor.class), "TplSensor", true);
+ templateSensorAttributeConfig
+ .addInherited(entityConfigRepository.findImplicit(new Key<>(CatalogAttribute.class)));
+ EntityConfig<TemplateSensor> templateSensorConfig = create(new Key<>(TemplateSensor.class), "TplSensor",
+ true);
templateSensorConfig.addChild(templateSensorAttributeConfig);
templateSensorConfig.addMandatory(entityConfigRepository.findRoot(new Key<>(Quantity.class)));
templateSensorConfig.addInherited(entityConfigRepository.findImplicit(new Key<>(CatalogSensor.class)));
templateSensorConfig.setComparator(Sortable.COMPARATOR);
templateComponentConfig.addChild(templateSensorConfig);
}
- EntityConfig<TemplateRoot> templateRootConfig =
- create(new Key<>(TemplateRoot.class, contextType), "Tpl" + odsName + "Root", true);
+ EntityConfig<TemplateRoot> templateRootConfig = create(new Key<>(TemplateRoot.class, contextType),
+ "Tpl" + odsName + "Root", true);
templateRootConfig.addChild(templateComponentConfig);
templateRootConfig.setComparator(Versionable.COMPARATOR);
entityConfigRepository.register(templateRootConfig);
@@ -669,20 +693,21 @@
* Loads the {@link EntityConfig}s required for {@link CatalogComponent}
* with given {@link ContextType}.
*
- * @param contextType The {@code ContextType}.
+ * @param contextType
+ * The {@code ContextType}.
*/
private void registerCatalogComponent(ContextType contextType) {
String odsName = ODSUtils.CONTEXTTYPES.convert(contextType);
- EntityConfig<CatalogAttribute> catalogAttributeConfig =
- create(new Key<>(CatalogAttribute.class, contextType), "Cat" + odsName + "Attr", true);
+ EntityConfig<CatalogAttribute> catalogAttributeConfig = create(new Key<>(CatalogAttribute.class, contextType),
+ "Cat" + odsName + "Attr", true);
catalogAttributeConfig.addOptional(entityConfigRepository.findRoot(new Key<>(ValueList.class)));
catalogAttributeConfig.setComparator(Sortable.COMPARATOR);
- EntityConfig<CatalogComponent> catalogComponentConfig =
- create(new Key<>(CatalogComponent.class, contextType), "Cat" + odsName + "Comp", true);
+ EntityConfig<CatalogComponent> catalogComponentConfig = create(new Key<>(CatalogComponent.class, contextType),
+ "Cat" + odsName + "Comp", true);
catalogComponentConfig.addChild(catalogAttributeConfig);
- if(contextType.isTestEquipment()) {
- EntityConfig<CatalogAttribute> catalogSensorAttributeConfig =
- create(new Key<>(CatalogAttribute.class), "CatSensorAttr", true);
+ if (contextType.isTestEquipment()) {
+ EntityConfig<CatalogAttribute> catalogSensorAttributeConfig = create(new Key<>(CatalogAttribute.class),
+ "CatSensorAttr", true);
catalogSensorAttributeConfig.addOptional(entityConfigRepository.findRoot(new Key<>(ValueList.class)));
EntityConfig<CatalogSensor> catalogSensorConfig = create(new Key<>(CatalogSensor.class), "CatSensor", true);
catalogSensorConfig.addChild(catalogSensorAttributeConfig);
@@ -694,11 +719,15 @@
/**
* Creates a new {@link EntityConfig}.
*
- * @param <T> The entity type.
- * @param key Used as identifier.
- * @param typeName Name of the associated {@link EntityType}.
- * @param appendName Flag indicates whether to append the entity types base
- * name to the MIME type.
+ * @param <T>
+ * The entity type.
+ * @param key
+ * Used as identifier.
+ * @param typeName
+ * Name of the associated {@link EntityType}.
+ * @param appendName
+ * Flag indicates whether to append the entity types base name to
+ * the MIME type.
* @return The created {@code EntityConfig} is returned.
*/
private <T extends Entity> EntityConfig<T> create(Key<T> key, String typeName, boolean appendName) {
@@ -712,16 +741,18 @@
/**
* Creates a default MIME type for given {@link EntityType}.
*
- * @param entityType The {@code EntityType}.
- * @param appendName Flag indicates whether to append the entity types base
- * name to the MIME type.
+ * @param entityType
+ * The {@code EntityType}.
+ * @param appendName
+ * Flag indicates whether to append the entity types base name to
+ * the MIME type.
* @return The created MIME type {@code String} is returned.
*/
private String buildDefaultMimeType(ODSEntityType entityType, boolean appendName) {
StringBuilder sb = new StringBuilder();
sb.append("application/x-asam.");
sb.append(entityType.getBaseName().toLowerCase(Locale.ROOT));
- if(appendName) {
+ if (appendName) {
sb.append('.').append(entityType.getName().toLowerCase(Locale.ROOT));
}
return sb.toString();
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSQuery.java
index 08eac90..2f5b018 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSQuery.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -73,7 +73,7 @@
// Instance variables
// ======================================================================
- private final Map<Long, EntityType> entityTypesByID = new HashMap<>();
+ private final Map<String, EntityType> entityTypesByID = new HashMap<>();
private final Set<EntityType> queriedEntityTypes = new HashSet<>();
private final List<SelAIDNameUnitId> anuSeq = new ArrayList<>();
private final List<JoinDef> joinSeq = new ArrayList<>();
@@ -89,7 +89,8 @@
/**
* Constructor.
*
- * @param applElemAccess Used to execute the query.
+ * @param applElemAccess
+ * Used to execute the query.
*/
ODSQuery(ApplElemAccess applElemAccess) {
this.applElemAccess = applElemAccess;
@@ -113,7 +114,8 @@
@Override
public Query select(Attribute attribute, Aggregation aggregation) {
EntityType entityType = attribute.getEntityType();
- entityTypesByID.put(ODSConverter.fromODSLong(((ODSEntityType) entityType).getODSID()), entityType);
+ entityTypesByID.put(Long.toString(ODSConverter.fromODSLong(((ODSEntityType) entityType).getODSID())),
+ entityType);
queriedEntityTypes.add(entityType);
anuSeq.add(createSelect(attribute, aggregation));
return this;
@@ -165,9 +167,9 @@
@Override
public Optional<Result> fetchSingleton(Filter filter) throws DataAccessException {
List<Result> results = fetch(filter);
- if(results.isEmpty()) {
+ if (results.isEmpty()) {
return Optional.empty();
- } else if(results.size() > 1) {
+ } else if (results.size() > 1) {
throw new DataAccessException("Multiple results found after executing the singleton query!");
}
@@ -183,11 +185,11 @@
List<SelItem> condSeq = new ArrayList<>();
int condCount = 0;
- for(FilterItem conditionItem : filter) {
+ for (FilterItem conditionItem : filter) {
SelItem selItem = new SelItem();
- if(conditionItem.isCondition()) {
+ if (conditionItem.isCondition()) {
selItem.value(createCondition(conditionItem.getCondition()));
- } else if(conditionItem.isOperator()) {
+ } else if (conditionItem.isOperator()) {
selItem._operator(ODSUtils.OPERATORS.convert(conditionItem.getOperator()));
condCount++;
} else {
@@ -206,7 +208,7 @@
List<Result> results = new ArrayList<>();
long start = System.currentTimeMillis();
- for(Result result : new ResultFactory(entityTypesByID, applElemAccess.getInstancesExt(qse, 0)[0])) {
+ for (Result result : new ResultFactory(entityTypesByID, applElemAccess.getInstancesExt(qse, 0)[0])) {
results.add(result);
}
long stop = System.currentTimeMillis();
@@ -214,7 +216,7 @@
LOGGER.debug("Query executed in {} ms and retrieved {} result rows ({} selections, {} conditions, "
+ "{} joins).", stop - start, results.size(), anuSeq.size(), condCount, joinSeq.size());
return results;
- } catch(AoException aoe) {
+ } catch (AoException aoe) {
throw new DataAccessException(aoe.reason, aoe);
}
}
@@ -227,8 +229,10 @@
* Converts given {@link Attribute} and {@link Aggregation} to an ODS
* {@link SelAIDNameUnitId}.
*
- * @param attribute The {@code Attribute}.
- * @param aggregation The {@code Aggregation}.
+ * @param attribute
+ * The {@code Attribute}.
+ * @param aggregation
+ * The {@code Aggregation}.
* @return The corresponding {@code SelAIDNameUnitId} is returned.
*/
private SelAIDNameUnitId createSelect(Attribute attribute, Aggregation aggregation) {
@@ -244,9 +248,11 @@
/**
* Converts given {@link Condition} to an ODS {@link SelValueExt}.
*
- * @param condition The {@code Condition}.
+ * @param condition
+ * The {@code Condition}.
* @return The corresponding {@code SelValueExt} is returned.
- * @throws DataAccessException Thrown in case of errors.
+ * @throws DataAccessException
+ * Thrown in case of errors.
*/
private SelValueExt createCondition(Condition condition) throws DataAccessException {
SelValueExt sve = new SelValueExt();
@@ -255,17 +261,19 @@
sve.attr = new AIDNameUnitId();
sve.attr.unitId = new T_LONGLONG();
sve.attr.attr = createAIDName(condition.getAttribute());
- sve.value = ODSConverter.toODSValue(condition.getValue());
+ sve.value = ODSConverter.toODSValue(condition.getAttribute(), condition.getValue());
return sve;
}
/**
- * Converts given {@link Relation} and {@link Join} to an ODS {@link
- * JoinDef}.
+ * Converts given {@link Relation} and {@link Join} to an ODS
+ * {@link JoinDef}.
*
- * @param relation The {@code Relation}.
- * @param join The {@code Join}.
+ * @param relation
+ * The {@code Relation}.
+ * @param join
+ * The {@code Join}.
* @return The corresponding {@code JoinDef} is returned.
*/
private JoinDef createJoin(Relation relation, Join join) {
@@ -280,11 +288,13 @@
}
/**
- * Converts given {@link Attribute} and sort order flag to an ODS {@link
- * SelOrder}.
+ * Converts given {@link Attribute} and sort order flag to an ODS
+ * {@link SelOrder}.
*
- * @param attribute The {@code Attribute}.
- * @param ascending The sort order.
+ * @param attribute
+ * The {@code Attribute}.
+ * @param ascending
+ * The sort order.
* @return The corresponding {@code SelOrder} is returned.
*/
private SelOrder createOrderBy(Attribute attribute, boolean ascending) {
@@ -299,7 +309,8 @@
/**
* Converts given {@link Attribute} to an ODS {@link AIDName}.
*
- * @param attribute The {@code Attribute}.
+ * @param attribute
+ * The {@code Attribute}.
* @return The corresponding {@code AIDName} is returned.
*/
private AIDName createAIDName(Attribute attribute) {
@@ -336,13 +347,17 @@
/**
* Constructor.
*
- * @param entityTypes Used to access {@link EntityType} by its ODS ID.
- * @param resultSetExt The ODS values sequence containers.
- * @throws DataAccessException Thrown on conversion errors.
+ * @param entityTypes
+ * Used to access {@link EntityType} by its ODS ID.
+ * @param resultSetExt
+ * The ODS values sequence containers.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
- public ResultFactory(Map<Long, EntityType> entityTypes, ResultSetExt resultSetExt) throws DataAccessException {
- for(ElemResultSetExt elemResultSetExt : resultSetExt.firstElems) {
- EntityType entityType = entityTypes.get(ODSConverter.fromODSLong(elemResultSetExt.aid));
+ public ResultFactory(Map<String, EntityType> entityTypes, ResultSetExt resultSetExt)
+ throws DataAccessException {
+ for (ElemResultSetExt elemResultSetExt : resultSetExt.firstElems) {
+ EntityType entityType = entityTypes.get(Long.toString(ODSConverter.fromODSLong(elemResultSetExt.aid)));
recordFactories.add(new RecordFactory(entityType, elemResultSetExt.values));
}
@@ -366,12 +381,12 @@
*/
@Override
public Result next() {
- if(!hasNext()) {
+ if (!hasNext()) {
throw new NoSuchElementException("No such element available.");
}
Result result = new Result();
- for(RecordFactory recordFactory : recordFactories) {
+ for (RecordFactory recordFactory : recordFactories) {
result.addRecord(recordFactory.createRecord(index));
}
@@ -390,8 +405,8 @@
}
/**
- * Creates a {@link Record} for given index from the original
- * ODS values sequence for a given {@link EntityType}.
+ * Creates a {@link Record} for given index from the original ODS values
+ * sequence for a given {@link EntityType}.
*/
private static final class RecordFactory {
@@ -409,9 +424,12 @@
/**
* Constructor.
*
- * @param entityType The associated {@link EntityType}.
- * @param nvsuis The ODS value sequence containers.
- * @throws DataAccessException Thrown on conversion errors.
+ * @param entityType
+ * The associated {@link EntityType}.
+ * @param nvsuis
+ * The ODS value sequence containers.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
private RecordFactory(EntityType entityType, NameValueSeqUnitId[] nvsuis) throws DataAccessException {
this.entityType = entityType;
@@ -432,7 +450,7 @@
private Record createRecord(int index) {
Record record = new Record(entityType);
- for(ValueFactory valueFactory : valueFactories) {
+ for (ValueFactory valueFactory : valueFactories) {
record.addValue(valueFactory.createValue(index));
}
@@ -442,8 +460,8 @@
}
/**
- * Creates a {@link Value} container for given index from the original
- * ODS value sequence for a given {@link Attribute}.
+ * Creates a {@link Value} container for given index from the original ODS
+ * value sequence for a given {@link Attribute}.
*/
private static final class ValueFactory {
@@ -462,9 +480,12 @@
/**
* Constructor.
*
- * @param attribute The associated {@link Attribute}.
- * @param nvsui The ODS value sequence container.
- * @throws DataAccessException Thrown on conversion errors.
+ * @param attribute
+ * The associated {@link Attribute}.
+ * @param nvsui
+ * The ODS value sequence container.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
private ValueFactory(Attribute attribute, NameValueSeqUnitId nvsui) throws DataAccessException {
length = nvsui.value.flag.length;
@@ -488,7 +509,8 @@
/**
* Returns the {@link Value} for given index.
*
- * @param index Index within the sequence.
+ * @param index
+ * Index within the sequence.
* @return The corresponding {@code Value} is returned.
*/
private Value createValue(int index) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSRelation.java b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSRelation.java
index 1a8b94d..b90ced7 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSRelation.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/query/ODSRelation.java
@@ -47,9 +47,12 @@
/**
* Constructor.
*
- * @param applRel The ODS meta data for this relation.
- * @param source The source {@link EntityType}.
- * @param target The target {@code EntityType}.
+ * @param applRel
+ * The ODS meta data for this relation.
+ * @param source
+ * The source {@link EntityType}.
+ * @param target
+ * The target {@code EntityType}.
*/
ODSRelation(ApplRel applRel, EntityType source, EntityType target) {
this.source = source;
@@ -100,9 +103,9 @@
*/
@Override
public Attribute getAttribute() {
- if(attribute == null) {
- attribute = new ODSAttribute(getSource(), new ApplAttr(getName(), "", DataType.DT_LONGLONG, 0,
- true, false, null), null, null);
+ if (attribute == null) {
+ attribute = new ODSAttribute(getSource(),
+ new ApplAttr(getName(), "", DataType.DT_LONGLONG, 0, true, false, null), null, null);
}
return attribute;
@@ -121,11 +124,10 @@
*/
@Override
public boolean equals(Object object) {
- if(object instanceof ODSRelation) {
+ if (object instanceof ODSRelation) {
Relation relation = (Relation) object;
- return getSource().equals(relation.getSource()) &&
- getTarget().equals(relation.getTarget()) &&
- getName().equals(relation.getName());
+ return getSource().equals(relation.getSource()) && getTarget().equals(relation.getTarget())
+ && getName().equals(relation.getName());
}
return false;
@@ -148,9 +150,10 @@
* given one and whether the foreign key is in the table of the source
* entity type.
*
- * @param relationship The {@code Relationship}.
+ * @param relationship
+ * The {@code Relationship}.
* @return Returns {@code true} this relation's {@code Relationship} is
- * equal with the given one and it is is an outgoing relation.
+ * equal with the given one and it is is an outgoing relation.
*/
boolean isOutgoing(Relationship relationship) {
return relationship.equals(getRelationship()) && rangeMax == 1;
@@ -161,9 +164,10 @@
* given one and whether the foreign key is in the table of the target
* entity type.
*
- * @param relationship The {@code Relationship}.
+ * @param relationship
+ * The {@code Relationship}.
* @return Returns {@code true} this relation's {@code Relationship} is
- * equal with the given one and it is is an incoming relation.
+ * equal with the given one and it is is an incoming relation.
*/
boolean isIncoming(Relationship relationship) {
return relationship.equals(getRelationship()) && rangeMax == -1;
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/BaseEntitySearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/BaseEntitySearchQuery.java
index dceb1e9..28cddaa 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/BaseEntitySearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/BaseEntitySearchQuery.java
@@ -68,9 +68,12 @@
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param entityClass The source entity class of this search query.
- * @param rootEntityClass The root entity class of this search query.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param entityClass
+ * The source entity class of this search query.
+ * @param rootEntityClass
+ * The root entity class of this search query.
*/
protected BaseEntitySearchQuery(ODSModelManager modelManager, Class<? extends Entity> entityClass,
Class<? extends Entity> rootEntityClass) {
@@ -81,13 +84,11 @@
EntityConfig<?> entityConfig = modelManager.getEntityConfig(new Key<>(entityClass));
EntityType source = entityConfig.getEntityType();
- entityConfig.getOptionalConfigs().stream().map(EntityConfig::getEntityType)
- .forEach(entityType -> {
+ entityConfig.getOptionalConfigs().stream().map(EntityConfig::getEntityType).forEach(entityType -> {
joinTree.addNode(source, entityType, true, Join.OUTER);
});
- entityConfig.getMandatoryConfigs().stream().map(EntityConfig::getEntityType)
- .forEach(entityType -> {
+ entityConfig.getMandatoryConfigs().stream().map(EntityConfig::getEntityType).forEach(entityType -> {
joinTree.addNode(source, entityType, true, Join.INNER);
});
}
@@ -114,10 +115,10 @@
};
Map<String, SearchableNode> nodes = new HashMap<>();
- for(Entry<String, List<String>> entry : joinTree.getTree().entrySet()) {
+ for (Entry<String, List<String>> entry : joinTree.getTree().entrySet()) {
SearchableNode parent = nodes.computeIfAbsent(entry.getKey(), factory);
- for(String childName : entry.getValue()) {
+ for (String childName : entry.getValue()) {
parent.addRelated(nodes.computeIfAbsent(childName, factory));
}
}
@@ -133,8 +134,7 @@
Query query = modelManager.createQuery().select(attribute, Aggregation.DISTINCT).group(attribute);
// add required joins
- filter.stream().filter(FilterItem::isCondition).map(FilterItem::getCondition)
- .forEach(c -> {
+ filter.stream().filter(FilterItem::isCondition).map(FilterItem::getCondition).forEach(c -> {
addJoins(query, c.getAttribute().getEntityType());
});
@@ -178,10 +178,10 @@
// ======================================================================
/**
- * Adds given {@link JoinConfig} to the internally managed {@link
- * JoinTree}.
+ * Adds given {@link JoinConfig} to the internally managed {@link JoinTree}.
*
- * @param joinConfig Will be added.
+ * @param joinConfig
+ * Will be added.
*/
protected final void addJoinConfig(JoinConfig joinConfig) {
EntityConfig<?> targetEntityConfig = modelManager.getEntityConfig(new Key<>(joinConfig.target));
@@ -191,14 +191,12 @@
joinTree.addNode(modelManager.getEntityType(joinConfig.source), target, joinConfig.viaParent, Join.INNER);
// add target's optional dependencies
- targetEntityConfig.getOptionalConfigs().stream().map(EntityConfig::getEntityType)
- .forEach(entityType -> {
+ targetEntityConfig.getOptionalConfigs().stream().map(EntityConfig::getEntityType).forEach(entityType -> {
joinTree.addNode(target, entityType, true, Join.OUTER);
});
// add target's mandatory dependencies
- targetEntityConfig.getMandatoryConfigs().stream().map(EntityConfig::getEntityType)
- .forEach(entityType -> {
+ targetEntityConfig.getMandatoryConfigs().stream().map(EntityConfig::getEntityType).forEach(entityType -> {
joinTree.addNode(target, entityType, true, Join.INNER);
});
}
@@ -206,21 +204,22 @@
/**
* Adds joins to context data according to the given {@link ContextState}.
*
- * @param contextState The {@code ContextState}.
+ * @param contextState
+ * The {@code ContextState}.
*/
protected final void addJoinConfig(ContextState contextState) {
- if(contextState == null) {
+ if (contextState == null) {
// nothing to do
return;
}
Class<? extends Entity> source = contextState.isOrdered() ? TestStep.class : Measurement.class;
- for(ContextType contextType : ContextType.values()) {
+ for (ContextType contextType : ContextType.values()) {
EntityType rootEntityType = modelManager.getEntityType(ContextRoot.class, contextType);
- for(Relation componentRelation : rootEntityType.getChildRelations()) {
+ for (Relation componentRelation : rootEntityType.getChildRelations()) {
joinTree.addNode(componentRelation.getSource(), componentRelation.getTarget(), true, Join.OUTER);
- for(Relation sensorRelation : componentRelation.getTarget().getChildRelations()) {
+ for (Relation sensorRelation : componentRelation.getTarget().getChildRelations()) {
joinTree.addNode(sensorRelation.getSource(), sensorRelation.getTarget(), true, Join.OUTER);
}
}
@@ -237,14 +236,17 @@
* Executes given {@link Query} using given {@link Filter}. Joins required
* for the given {@code Filter} will be implicitly added as needed.
*
- * @param query Will be executed.
- * @param filter The query filtering sequence.
+ * @param query
+ * Will be executed.
+ * @param filter
+ * The query filtering sequence.
* @return Returns the {@link Result}s in a {@code List}.
- * @throws DataAccessException Thrown if failed to execute given {@code Query}.
+ * @throws DataAccessException
+ * Thrown if failed to execute given {@code Query}.
*/
private List<Result> fetch(Query query, Filter filter) throws DataAccessException {
filter.stream().filter(FilterItem::isCondition).map(FilterItem::getCondition)
- .forEach(c -> addJoins(query, c.getAttribute().getEntityType()));
+ .forEach(c -> addJoins(query, c.getAttribute().getEntityType()));
EntityType entityType = modelManager.getEntityType(entityClass);
return query.order(entityType.getIDAttribute()).fetch(filter).stream()
@@ -255,14 +257,16 @@
}
/**
- * Adds join statements to given target {@link EntityType} as needed to
- * be able to execute given {@code Query}.
+ * Adds join statements to given target {@link EntityType} as needed to be
+ * able to execute given {@code Query}.
*
- * @param query The {@link Query}.
- * @param entityType The target {@link EntityType}.
+ * @param query
+ * The {@link Query}.
+ * @param entityType
+ * The target {@link EntityType}.
*/
private void addJoins(Query query, EntityType entityType) {
- if(query.isQueried(entityType)) {
+ if (query.isQueried(entityType)) {
return;
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelGroupSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelGroupSearchQuery.java
index 5d688e5..b551c55 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelGroupSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelGroupSearchQuery.java
@@ -25,15 +25,17 @@
* type.
*
* @since 1.0.0
- * @author
+ * @author
*/
final class ChannelGroupSearchQuery extends BaseEntitySearchQuery {
-
+
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
ChannelGroupSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, ChannelGroup.class, Project.class);
@@ -45,7 +47,7 @@
addJoinConfig(JoinConfig.up(Measurement.class, TestStep.class));
addJoinConfig(JoinConfig.up(ChannelGroup.class, Measurement.class));
addJoinConfig(JoinConfig.down(Measurement.class, Channel.class));
-
+
// context
addJoinConfig(contextState);
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelSearchQuery.java
index 11cde6f..c8e22fa 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ChannelSearchQuery.java
@@ -21,19 +21,20 @@
import org.eclipse.mdm.api.odsadapter.search.JoinTree.JoinConfig;
/**
- * {@link SearchQuery} implementation for {@link Channel} as source entity
- * type.
+ * {@link SearchQuery} implementation for {@link Channel} as source entity type.
*
* @since 1.0.0
* @author jst, Peak Solution GmbH
*/
final class ChannelSearchQuery extends BaseEntitySearchQuery {
-
+
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
ChannelSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, Channel.class, Project.class);
@@ -45,11 +46,12 @@
addJoinConfig(JoinConfig.up(Measurement.class, TestStep.class));
addJoinConfig(JoinConfig.up(Channel.class, Measurement.class));
addJoinConfig(JoinConfig.down(Measurement.class, ChannelGroup.class));
-
+
// context
addJoinConfig(contextState);
- // TODO join to sensor tables.... || this will break the joins to context data
+ // TODO join to sensor tables.... || this will break the joins to
+ // context data
// multiple outer join to the same table...
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/JoinTree.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/JoinTree.java
index 114fc6a..8c35182 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/JoinTree.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/JoinTree.java
@@ -35,8 +35,8 @@
// ======================================================================
/**
- * Returns the tree configuration. It mapps a source entity type names
- * to supported target entity type names.
+ * Returns the tree configuration. It mapps a source entity type names to
+ * supported target entity type names.
*
* @return The returned {@code Map} is unmodifiable.
*/
@@ -57,15 +57,16 @@
/**
* Returns the {@link JoinNode} for given target entity type name.
*
- * @param target The target entity type name.
+ * @param target
+ * The target entity type name.
* @return The {@code JoinNode} for given target entity type name is
- * returned.
- * @throws IllegalArgumentException Thrown if no such {@code JoinNode}
- * exists.
+ * returned.
+ * @throws IllegalArgumentException
+ * Thrown if no such {@code JoinNode} exists.
*/
public JoinNode getJoinNode(String target) {
JoinNode joinNode = joinNodes.get(target);
- if(joinNode == null) {
+ if (joinNode == null) {
throw new IllegalArgumentException("Relation to '" + target + "' not possible.");
}
@@ -75,24 +76,27 @@
/**
* Adds given dependency setup to this join tree.
*
- * @param source The source entity type name.
- * @param target The target entity type name.
- * @param viaParent If true, then source is the considered parent of
- * the target.
- * @param join Either inner or outer join.
- * @throws IllegalArgumentException Thrown if given setup overrides an
- * existing one (a target entity type is allowed to be joined only
- * once).
+ * @param source
+ * The source entity type name.
+ * @param target
+ * The target entity type name.
+ * @param viaParent
+ * If true, then source is the considered parent of the target.
+ * @param join
+ * Either inner or outer join.
+ * @throws IllegalArgumentException
+ * Thrown if given setup overrides an existing one (a target
+ * entity type is allowed to be joined only once).
*/
public void addNode(EntityType source, EntityType target, boolean viaParent, Join join) {
String sourceName = source.getName();
String targetName = target.getName();
- if(joinNodes.put(targetName, new JoinNode(sourceName, targetName, join)) != null) {
+ if (joinNodes.put(targetName, new JoinNode(sourceName, targetName, join)) != null) {
throw new IllegalArgumentException("It is not allowed to override join nodes.");
}
- if(viaParent) {
+ if (viaParent) {
tree.computeIfAbsent(sourceName, k -> new ArrayList<>()).add(targetName);
} else {
tree.computeIfAbsent(targetName, k -> new ArrayList<>()).add(sourceName);
@@ -126,9 +130,12 @@
/**
* Constructor.
*
- * @param source The source entity type name.
- * @param target The target entity type name.
- * @param join Either inner or outer {@link Join}.
+ * @param source
+ * The source entity type name.
+ * @param target
+ * The target entity type name.
+ * @param join
+ * Either inner or outer {@link Join}.
*/
private JoinNode(String source, String target, Join join) {
this.source = source;
@@ -158,10 +165,13 @@
/**
* Constructor.
*
- * @param source The source entity type name.
- * @param target The target entity type name.
- * @param viaParent If true, then source is the considered parent of
- * the target.
+ * @param source
+ * The source entity type name.
+ * @param target
+ * The target entity type name.
+ * @param viaParent
+ * If true, then source is the considered parent of the
+ * target.
*/
private JoinConfig(Class<? extends Entity> source, Class<? extends Entity> target, boolean viaParent) {
this.source = source;
@@ -174,11 +184,13 @@
// ======================================================================
/**
- * Creates a new {@link JoinConfig} where given source is considered
- * as the child of given target.
+ * Creates a new {@link JoinConfig} where given source is considered as
+ * the child of given target.
*
- * @param source The source entity type name.
- * @param target The target entity type name.
+ * @param source
+ * The source entity type name.
+ * @param target
+ * The target entity type name.
* @return The created {@code JoinConfig} is returned.
*/
static JoinConfig up(Class<? extends Entity> source, Class<? extends Entity> target) {
@@ -186,11 +198,13 @@
}
/**
- * Creates a new {@link JoinConfig} where given source is considered
- * as the parent of given target.
+ * Creates a new {@link JoinConfig} where given source is considered as
+ * the parent of given target.
*
- * @param source The source entity type name.
- * @param target The target entity type name.
+ * @param source
+ * The source entity type name.
+ * @param target
+ * The target entity type name.
* @return The created {@code JoinConfig} is returned.
*/
static JoinConfig down(Class<? extends Entity> source, Class<? extends Entity> target) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/MeasurementSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/MeasurementSearchQuery.java
index 1185ef5..538be58 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/MeasurementSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/MeasurementSearchQuery.java
@@ -32,8 +32,10 @@
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
MeasurementSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, Measurement.class, Project.class);
@@ -45,7 +47,7 @@
addJoinConfig(JoinConfig.up(Measurement.class, TestStep.class));
addJoinConfig(JoinConfig.down(Measurement.class, Channel.class));
addJoinConfig(JoinConfig.down(Measurement.class, ChannelGroup.class));
-
+
// context
addJoinConfig(contextState);
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/MergedSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/MergedSearchQuery.java
index 082cf7a..1dc797d 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/MergedSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/MergedSearchQuery.java
@@ -114,8 +114,10 @@
* Merges given {@link Result}s to one using the root entity type of this
* search query.
*
- * @param results1 The first {@code Result}.
- * @param results2 The second {@code Result}.
+ * @param results1
+ * The first {@code Result}.
+ * @param results2
+ * The second {@code Result}.
* @return The merged {@link Result} is returned.
*/
private List<Result> mergeResults(List<Result> results1, List<Result> results2) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearch.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearch.java
index 86a8505..c28e599 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearch.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearch.java
@@ -36,69 +36,54 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-/**
- * This class handles the requests which are sent to the FreeTextSearch
- *
- * @author Christian Weyermann
- *
- */
-public class ODSFreeTextSearch {
-
- /**
- * This is the payload which needs to be added to the post to add a
- */
- private static final String ES_POSTDATA = "{\"query\":{\"simple_query_string\":{\"query\":\"%s\",\"default_operator\":\"or\",\"lenient\":\"true\",\"fields\":[\"name^2\",\"_all\"]}}}";
-
- /**
- * mainly logs requests on INFO
- */
- private static final Logger LOGGER = LoggerFactory.getLogger(ODSFreeTextSearch.class);
-
- /**
- * Used to finally load the Entites
- */
- private EntityLoader loader;
-
- /**
- * The URL is hard coded
- */
- private String url;
-
- /**
- * The client is created once and reused
- */
- private HttpClient client;
-
- /**
- * This will start up the FreeText Search. No upfron querries are done. Thus
- * this can be called as often as desired without any major performance loss
- *
- * @param entityLoader
- * @param sourceName
- * @throws DataAccessException
- */
- public ODSFreeTextSearch(EntityLoader entityLoader, String sourceName, String host) throws DataAccessException {
+/**
+ * This class handles the requests which are sent to the FreeTextSearch
+ *
+ * @author Christian Weyermann
+ *
+ */
+public class ODSFreeTextSearch {
+
+ /**
+ * This is the payload which needs to be added to the post to add a
+ */
+ private static final String ES_POSTDATA = "{\"query\":{\"simple_query_string\":{\"query\":\"%s\",\"default_operator\":\"or\",\"lenient\":\"true\",\"fields\":[\"name^2\",\"_all\"]}}}";
+
+ /**
+ * mainly logs requests on INFO
+ */
+ private static final Logger LOGGER = LoggerFactory.getLogger(ODSFreeTextSearch.class);
+
+ /**
+ * Used to finally load the Entites
+ */
+ private EntityLoader loader;
+
+ /**
+ * The URL is hard coded
+ */
+ private String url;
+
+ /**
+ * The client is created once and reused
+ */
+ private HttpClient client;
+
+ /**
+ * This will start up the FreeText Search. No upfron querries are done. Thus
+ * this can be called as often as desired without any major performance loss
+ *
+ * @param entityLoader
+ * @param sourceName
+ * @throws DataAccessException
+ */
+ public ODSFreeTextSearch(EntityLoader entityLoader, String sourceName, String host) throws DataAccessException {
this.loader = entityLoader;
-
- url = host + "/" + sourceName.toLowerCase() + "/_search?fields=_type,_id,_index&size=50";
-
- client = new HttpClient();
- }
-
- /**
- * A search which is compatible to the Search as defined in the rest of the
- * API.
- *
- * @param inputQuery
- * @return never null, but maybe empty
- */
- public Map<Class<? extends Entity>, List<Entity>> search(String inputQuery) {
- Map<Class<? extends Entity>, List<Entity>> result = new HashMap<>();
-
- Map<Class<? extends Entity>, List<Long>> instances = searchIds(inputQuery);
- instances.keySet().forEach(type -> convertIds2Entities(result, instances, type));
- return result;
- }
+
+ url = host + "/" + sourceName.toLowerCase() + "/_search?fields=_type,_id,_index&size=50";
+
+ client = new HttpClient();
+ }
/**
* A search which is compatible to the Search as defined in the rest of the
@@ -107,171 +92,186 @@
* @param inputQuery
* @return never null, but maybe empty
*/
- public Map<Class<? extends Entity>, List<Long>> searchIds(String inputQuery) {
- Map<Class<? extends Entity>, List<Long>> instanceIds = new HashMap<>();
+ public Map<Class<? extends Entity>, List<Entity>> search(String inputQuery) {
+ Map<Class<? extends Entity>, List<Entity>> result = new HashMap<>();
+
+ Map<Class<? extends Entity>, List<String>> instances = searchIds(inputQuery);
+ instances.keySet().forEach(type -> convertIds2Entities(result, instances, type));
+ return result;
+ }
+
+ /**
+ * A search which is compatible to the Search as defined in the rest of the
+ * API.
+ *
+ * @param inputQuery
+ * @return never null, but maybe empty
+ */
+ public Map<Class<? extends Entity>, List<String>> searchIds(String inputQuery) {
+ Map<Class<? extends Entity>, List<String>> instanceIds = new HashMap<>();
JsonElement root = queryElasticSearch(inputQuery);
if (root != null) {
JsonArray hits = root.getAsJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
hits.forEach(e -> put(e, instanceIds));
-
+
}
return instanceIds;
}
-
- /**
- * Converts all instances to entities
- *
- * @param convertedMap
- * it will
- * @param map
- * @param type
- */
- private void convertIds2Entities(Map<Class<? extends Entity>, List<Entity>> convertedMap,
- Map<Class<? extends Entity>, List<Long>> map, Class<? extends Entity> type) {
- try {
- List<Entity> list = new ArrayList<>();
- list.addAll(loader.loadAll(new Key<>(type), map.get(type)));
-
- convertedMap.put(type, list);
- } catch (DataAccessException e) {
- throw new IllegalStateException("Cannot load ids from ODS. This means no results are available", e);
- }
-
- }
-
- /**
- * Puts all the hits in elasticsearch
- *
- * @param hit
- * a hit as given from ElasticSearch
- * @param map
- * the map of all ids for the class of the entity
- */
- private void put(JsonElement hit, Map<Class<? extends Entity>, List<Long>> map) {
- JsonObject object = hit.getAsJsonObject();
-
- String type = object.get("_type").getAsString();
- Class<? extends Entity> clazz = getClass4Type(type);
-
- if (clazz != null) {
- if (!map.containsKey(clazz)) {
- List<Long> list = new ArrayList<>();
- map.put(clazz, list);
- }
-
- List<Long> list = map.get(clazz);
- list.add((long) object.get("_id").getAsInt());
- }
- }
-
- /**
- *
- * @param type
- * the type as given by elasticsearch
- * @return the class of each element
- */
- private Class<? extends Entity> getClass4Type(String type) {
- Class<? extends Entity> clazz;
- switch (type) {
- case "TestStep":
- clazz = TestStep.class;
- break;
- case "Measurement":
- clazz = Measurement.class;
- break;
- case "Test":
- clazz = Test.class;
- break;
- default:
- clazz = null;
- }
- return clazz;
- }
-
- /**
- * This method actually querries ElasticSearch.
- *
- * @param inputQuery
- * @return
- */
- private JsonElement queryElasticSearch(String inputQuery) {
- PostMethod post = new PostMethod(url);
-
- String requestJson = buildRequestJson(inputQuery);
-
- LOGGER.info("POST: " + url);
- LOGGER.info("Asking: " + requestJson);
- byte[] json = requestJson.getBytes();
- post.setRequestEntity(new ByteArrayRequestEntity(json, "application/json"));
-
- JsonElement result = execute(post);
- LOGGER.info("Answered:" + result);
-
- return result;
- }
-
- /**
- * Actually builds the json
- *
- * @param inputQuery
- * @return
- */
- private String buildRequestJson(String inputQuery) {
- String query = StringEscapeUtils.escapeJson(inputQuery);
- return String.format(ES_POSTDATA, query);
- }
-
- /**
- * Executes the HTTP method and expects a json in the return payload, which
- * is then returned
- *
- * @param method
- * @return
- */
- private JsonElement execute(HttpMethod method) {
- try {
- int status = client.executeMethod(method);
- if (status == 404) {
- return null;
- }
-
- checkError(status);
- return buildResponseJson(method);
- } catch (IOException e) {
- throw new IllegalStateException("Problems querying ElasticSearch.", e);
- }
- }
-
- /**
- * Reads out the http method and builds the JSON via GSON
- *
- * @param method
- * @return
- * @throws IOException
- */
- private JsonElement buildResponseJson(HttpMethod method) throws IOException {
- JsonElement res = null;
-
- InputStream in = method.getResponseBodyAsStream();
- try (InputStreamReader reader = new InputStreamReader(in)) {
- res = new JsonParser().parse(reader);
- }
-
- return res;
- }
-
- /**
- * If an error occured an appropriate exception is thrown.
- *
- * @param status
- */
- private void checkError(int status) {
- String text = String.format("ElasticSearch answered %d. ", status);
-
- if (status / 100 != 2) {
- throw new IllegalStateException(text);
- }
- }
+
+ /**
+ * Converts all instances to entities
+ *
+ * @param convertedMap
+ * it will
+ * @param map
+ * @param type
+ */
+ private void convertIds2Entities(Map<Class<? extends Entity>, List<Entity>> convertedMap,
+ Map<Class<? extends Entity>, List<String>> map, Class<? extends Entity> type) {
+ try {
+ List<Entity> list = new ArrayList<>();
+ list.addAll(loader.loadAll(new Key<>(type), map.get(type)));
+
+ convertedMap.put(type, list);
+ } catch (DataAccessException e) {
+ throw new IllegalStateException("Cannot load ids from ODS. This means no results are available", e);
+ }
+
+ }
+
+ /**
+ * Puts all the hits in elasticsearch
+ *
+ * @param hit
+ * a hit as given from ElasticSearch
+ * @param map
+ * the map of all ids for the class of the entity
+ */
+ private void put(JsonElement hit, Map<Class<? extends Entity>, List<String>> map) {
+ JsonObject object = hit.getAsJsonObject();
+
+ String type = object.get("_type").getAsString();
+ Class<? extends Entity> clazz = getClass4Type(type);
+
+ if (clazz != null) {
+ if (!map.containsKey(clazz)) {
+ List<String> list = new ArrayList<>();
+ map.put(clazz, list);
+ }
+
+ List<String> list = map.get(clazz);
+ list.add((String) object.get("_id").getAsString());
+ }
+ }
+
+ /**
+ *
+ * @param type
+ * the type as given by elasticsearch
+ * @return the class of each element
+ */
+ private Class<? extends Entity> getClass4Type(String type) {
+ Class<? extends Entity> clazz;
+ switch (type) {
+ case "TestStep":
+ clazz = TestStep.class;
+ break;
+ case "Measurement":
+ clazz = Measurement.class;
+ break;
+ case "Test":
+ clazz = Test.class;
+ break;
+ default:
+ clazz = null;
+ }
+ return clazz;
+ }
+
+ /**
+ * This method actually querries ElasticSearch.
+ *
+ * @param inputQuery
+ * @return
+ */
+ private JsonElement queryElasticSearch(String inputQuery) {
+ PostMethod post = new PostMethod(url);
+
+ String requestJson = buildRequestJson(inputQuery);
+
+ LOGGER.info("POST: " + url);
+ LOGGER.info("Asking: " + requestJson);
+ byte[] json = requestJson.getBytes();
+ post.setRequestEntity(new ByteArrayRequestEntity(json, "application/json"));
+
+ JsonElement result = execute(post);
+ LOGGER.info("Answered:" + result);
+
+ return result;
+ }
+
+ /**
+ * Actually builds the json
+ *
+ * @param inputQuery
+ * @return
+ */
+ private String buildRequestJson(String inputQuery) {
+ String query = StringEscapeUtils.escapeJson(inputQuery);
+ return String.format(ES_POSTDATA, query);
+ }
+
+ /**
+ * Executes the HTTP method and expects a json in the return payload, which
+ * is then returned
+ *
+ * @param method
+ * @return
+ */
+ private JsonElement execute(HttpMethod method) {
+ try {
+ int status = client.executeMethod(method);
+ if (status == 404) {
+ return null;
+ }
+
+ checkError(status);
+ return buildResponseJson(method);
+ } catch (IOException e) {
+ throw new IllegalStateException("Problems querying ElasticSearch.", e);
+ }
+ }
+
+ /**
+ * Reads out the http method and builds the JSON via GSON
+ *
+ * @param method
+ * @return
+ * @throws IOException
+ */
+ private JsonElement buildResponseJson(HttpMethod method) throws IOException {
+ JsonElement res = null;
+
+ InputStream in = method.getResponseBodyAsStream();
+ try (InputStreamReader reader = new InputStreamReader(in)) {
+ res = new JsonParser().parse(reader);
+ }
+
+ return res;
+ }
+
+ /**
+ * If an error occured an appropriate exception is thrown.
+ *
+ * @param status
+ */
+ private void checkError(int status) {
+ String text = String.format("ElasticSearch answered %d. ", status);
+
+ if (status / 100 != 2) {
+ throw new IllegalStateException(text);
+ }
+ }
}
\ No newline at end of file
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchService.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchService.java
index 6104241..2edaaf6 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchService.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchService.java
@@ -54,12 +54,14 @@
private final EntityLoader entityLoader;
private final String esHost;
private ODSFreeTextSearch freeTextSearch;
-
+
/**
* Constructor.
*
- * @param modelManager Used to retrieve {@link EntityType}s.
- * @param entityLoader Used to load complete {@link Entity}s.
+ * @param modelManager
+ * Used to retrieve {@link EntityType}s.
+ * @param entityLoader
+ * Used to load complete {@link Entity}s.
*/
public ODSSearchService(ODSModelManager modelManager, EntityLoader entityLoader, String host) {
this.modelManager = modelManager;
@@ -121,8 +123,8 @@
* {@inheritDoc}
*/
@Override
- public <T extends Entity> Map<T, Result> fetch(Class<T> entityClass, List<Attribute> attributes,
- Filter filter) throws DataAccessException {
+ public <T extends Entity> Map<T, Result> fetch(Class<T> entityClass, List<Attribute> attributes, Filter filter)
+ throws DataAccessException {
return createResult(entityClass, findSearchQuery(entityClass).fetch(attributes, filter));
}
@@ -130,22 +132,22 @@
* {@inheritDoc}
*/
@Override
- public List<Result> fetchResults(Class<? extends Entity> entityClass, List<Attribute> attributes, Filter filter, String query)
- throws DataAccessException {
+ public List<Result> fetchResults(Class<? extends Entity> entityClass, List<Attribute> attributes, Filter filter,
+ String query) throws DataAccessException {
Filter mergedFilter = getMergedFilter(filter, query);
if (mergedFilter.isEmtpty()) {
return Collections.emptyList();
}
-
+
EntityType entityType = modelManager.getEntityType(entityClass);
- Map<Long, Result> recordsByEntityID = new HashMap<>();
+ Map<String, Result> recordsByEntityID = new HashMap<>();
for (Result result : findSearchQuery(entityClass).fetch(attributes, mergedFilter)) {
recordsByEntityID.put(result.getRecord(entityType).getID(), result);
}
-
+
return new ArrayList<>(recordsByEntityID.values());
}
-
+
@Override
public Map<Class<? extends Entity>, List<Entity>> fetch(String query) throws DataAccessException {
if (freeTextSearch == null) {
@@ -159,18 +161,24 @@
public boolean isTextSearchAvailable() {
return true;
}
-
+
/**
- * Returns a filter merged from an existing filter and a filter resulting from a freetext search result.
+ * Returns a filter merged from an existing filter and a filter resulting
+ * from a freetext search result.
*
- * @param filter first filter to merge
- * @param query freetext query, which returns the ids to generate the second filer to merge
+ * @param filter
+ * first filter to merge
+ * @param query
+ * freetext query, which returns the ids to generate the second
+ * filer to merge
* @return conjunction of the first and second filter
- * @throws DataAccessException Thrown if {@link ODSFreeTextSearch} is unavailable or cannot execute the query.
+ * @throws DataAccessException
+ * Thrown if {@link ODSFreeTextSearch} is unavailable or cannot
+ * execute the query.
*/
protected Filter getMergedFilter(Filter filter, String query) throws DataAccessException {
Preconditions.checkNotNull(filter, "Filter cannot be null!");
-
+
Filter freetextIdsFilter = getFilterForFreetextQuery(query);
if (filter.isEmtpty()) {
return freetextIdsFilter;
@@ -184,11 +192,14 @@
/**
* Executes a free text search and returns the IDs of the matching enities.
*
- * @param query search query
- * @return found entity IDs grouped by entity.
- * @throws DataAccessException Thrown if {@link ODSFreeTextSearch} is unavailable or cannot execute the query.
+ * @param query
+ * search query
+ * @return found entity IDs grouped by entity.
+ * @throws DataAccessException
+ * Thrown if {@link ODSFreeTextSearch} is unavailable or cannot
+ * execute the query.
*/
- protected Map<Class<? extends Entity>, List<Long>> fetchIds(String query) throws DataAccessException {
+ protected Map<Class<? extends Entity>, List<String>> fetchIds(String query) throws DataAccessException {
if (Strings.isNullOrEmpty(query)) {
return Collections.emptyMap();
}
@@ -196,46 +207,53 @@
if (freeTextSearch == null) {
initFreetextSearch();
}
-
+
return freeTextSearch.searchIds(query);
}
/**
- * Delegates to {@link ODSFreeTextSearch} to retrieves a map of all entity IDs found by the given query.
- * With the results a filter is generated, which can be used to query the entity instances of result of the free text query.
+ * Delegates to {@link ODSFreeTextSearch} to retrieves a map of all entity
+ * IDs found by the given query. With the results a filter is generated,
+ * which can be used to query the entity instances of result of the free
+ * text query.
*
- * @param query fulltext search query
+ * @param query
+ * fulltext search query
* @return A map with the found entity IDs grouped by {@link Entity} class.
- * @throws DataAccessException Thrown if {@link ODSFreeTextSearch} is unavailable or cannot execute the query.
- */
+ * @throws DataAccessException
+ * Thrown if {@link ODSFreeTextSearch} is unavailable or cannot
+ * execute the query.
+ */
private Filter getFilterForFreetextQuery(String query) throws DataAccessException {
-
+
Filter freeTextResultsFilter = Filter.or();
- for (Map.Entry<Class<? extends Entity>, List<Long>> entry : fetchIds(query).entrySet()) {
+ for (Map.Entry<Class<? extends Entity>, List<String>> entry : fetchIds(query).entrySet()) {
if (!entry.getValue().isEmpty()) {
- freeTextResultsFilter.ids(
- modelManager.getEntityType(entry.getKey()),
- entry.getValue());
+ freeTextResultsFilter.ids(modelManager.getEntityType(entry.getKey()), entry.getValue());
}
}
-
+
return freeTextResultsFilter;
}
/**
* Loads {@link Entity}s of given entity class for given {@link Result}s.
*
- * @param <T> The entity type.
- * @param entityClass Entity class of the loaded {@code Entity}s.
- * @param results The queried {@code Result}s.
+ * @param <T>
+ * The entity type.
+ * @param entityClass
+ * Entity class of the loaded {@code Entity}s.
+ * @param results
+ * The queried {@code Result}s.
* @return All Results are returned in a Map, which maps entities to the
- * corresponding results.
- * @throws DataAccessException Thrown if unable to load the {@code Entity}s.
+ * corresponding results.
+ * @throws DataAccessException
+ * Thrown if unable to load the {@code Entity}s.
*/
private <T extends Entity> Map<T, Result> createResult(Class<T> entityClass, List<Result> results)
throws DataAccessException {
EntityType entityType = modelManager.getEntityType(entityClass);
- Map<Long, Result> recordsByEntityID = new HashMap<>();
+ Map<String, Result> recordsByEntityID = new HashMap<>();
for (Result result : results) {
recordsByEntityID.put(result.getRecord(entityType).getID(), result);
}
@@ -251,14 +269,15 @@
/**
* Returns the {@link SearchQuery} for given entity class.
*
- * @param entityClass Used as identifier.
+ * @param entityClass
+ * Used as identifier.
* @return The {@link SearchQuery}
*/
private SearchQuery findSearchQuery(Class<? extends Entity> entityClass) {
SearchQuery searchQuery = searchQueries.get(entityClass);
- if(searchQuery == null) {
- throw new IllegalArgumentException("Search query for type '" + entityClass.getSimpleName()
- + "' not found.");
+ if (searchQuery == null) {
+ throw new IllegalArgumentException(
+ "Search query for type '" + entityClass.getSimpleName() + "' not found.");
}
return searchQuery;
@@ -267,8 +286,10 @@
/**
* Registers a {@link SearchQuery} for given entity class.
*
- * @param entityClass The entity class produced by using this query.
- * @param factory The {@code SearchQuery} factory.
+ * @param entityClass
+ * The entity class produced by using this query.
+ * @param factory
+ * The {@code SearchQuery} factory.
*/
private void registerMergedSearchQuery(Class<? extends Entity> entityClass,
Function<ContextState, BaseEntitySearchQuery> factory) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/PoolSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/PoolSearchQuery.java
index 925ac6e..4878e2f 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/PoolSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/PoolSearchQuery.java
@@ -31,8 +31,10 @@
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
PoolSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, Pool.class, Project.class);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ProjectSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ProjectSearchQuery.java
index ee0bf8c..54e3a74 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/ProjectSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/ProjectSearchQuery.java
@@ -27,12 +27,14 @@
* @author jst, Peak Solution GmbH
*/
final class ProjectSearchQuery extends BaseEntitySearchQuery {
-
+
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
ProjectSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, Project.class, Project.class);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/SearchableNode.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/SearchableNode.java
index 3415488..72218f6 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/SearchableNode.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/SearchableNode.java
@@ -39,7 +39,8 @@
/**
* Constructor.
*
- * @param entityType The associated {@link EntityType}.
+ * @param entityType
+ * The associated {@link EntityType}.
*/
SearchableNode(EntityType entityType) {
this.entityType = entityType;
@@ -72,11 +73,9 @@
public String toString() {
StringBuilder sb = new StringBuilder("Searchable(").append("EntityType = ").append(entityType);
- if(!isLeaf()) {
- sb.append(", relatedSearchables = ").append(
- relatedSearchables.stream()
- .map(Searchable::getEntityType)
- .collect(Collectors.toList()));
+ if (!isLeaf()) {
+ sb.append(", relatedSearchables = ")
+ .append(relatedSearchables.stream().map(Searchable::getEntityType).collect(Collectors.toList()));
}
return sb.append(')').toString();
@@ -89,7 +88,8 @@
/**
* Adds given {@link Searchable} as a child to this searchable.
*
- * @param searchable Will be added a child.
+ * @param searchable
+ * Will be added a child.
*/
void addRelated(Searchable searchable) {
relatedSearchables.add(searchable);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestSearchQuery.java
index 04a4027..8208d4a 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestSearchQuery.java
@@ -31,8 +31,10 @@
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
TestSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, Test.class, Project.class);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestStepSearchQuery.java b/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestStepSearchQuery.java
index c73fb13..aeb91e7 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestStepSearchQuery.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/search/TestStepSearchQuery.java
@@ -32,8 +32,10 @@
/**
* Constructor.
*
- * @param modelManager Used to load {@link EntityType}s.
- * @param contextState The {@link ContextState}.
+ * @param modelManager
+ * Used to load {@link EntityType}s.
+ * @param contextState
+ * The {@link ContextState}.
*/
TestStepSearchQuery(ODSModelManager modelManager, ContextState contextState) {
super(modelManager, TestStep.class, Project.class);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/BaseStatement.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/BaseStatement.java
index 580559f..4322cfd 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/BaseStatement.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/BaseStatement.java
@@ -42,8 +42,8 @@
GET_CORE_METHOD = BaseEntity.class.getDeclaredMethod("getCore");
GET_CORE_METHOD.setAccessible(true);
} catch (NoSuchMethodException | SecurityException e) {
- throw new IllegalStateException("Unable to load 'getCore()' in class '" + BaseEntity.class.getSimpleName()
- + "'.", e);
+ throw new IllegalStateException(
+ "Unable to load 'getCore()' in class '" + BaseEntity.class.getSimpleName() + "'.", e);
}
}
@@ -61,8 +61,10 @@
/**
* Constructor.
*
- * @param transaction The owning {@link ODSTransaction}.
- * @param entityType The associated {@link EntityType}.
+ * @param transaction
+ * The owning {@link ODSTransaction}.
+ * @param entityType
+ * The associated {@link EntityType}.
*/
protected BaseStatement(ODSTransaction transaction, EntityType entityType) {
this.transaction = transaction;
@@ -76,10 +78,14 @@
/**
* Executes this statement for given {@link Entity}s.
*
- * @param entities The processed {@code Entity}s.
- * @throws AoException Thrown if the execution fails.
- * @throws DataAccessException Thrown if the execution fails.
- * @throws IOException Thrown if a file transfer operation fails.
+ * @param entities
+ * The processed {@code Entity}s.
+ * @throws AoException
+ * Thrown if the execution fails.
+ * @throws DataAccessException
+ * Thrown if the execution fails.
+ * @throws IOException
+ * Thrown if a file transfer operation fails.
*/
public abstract void execute(Collection<Entity> entities) throws AoException, DataAccessException, IOException;
@@ -90,15 +96,16 @@
/**
* Returns the {@link Core} of given {@link Entity}.
*
- * @param entity The {@code Entity} whose {@code Core} will be returned.
+ * @param entity
+ * The {@code Entity} whose {@code Core} will be returned.
* @return The {@code Core} is returned.
*/
protected Core extract(Entity entity) {
try {
return (Core) GET_CORE_METHOD.invoke(entity);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new IllegalArgumentException("Entity of type '" + entity.getClass().getSimpleName() +
- "' does not extend '" + BaseEntity.class.getName() + "'", e);
+ throw new IllegalArgumentException("Entity of type '" + entity.getClass().getSimpleName()
+ + "' does not extend '" + BaseEntity.class.getName() + "'", e);
}
}
@@ -124,7 +131,8 @@
* Returns the {@link ApplElemAccess}.
*
* @return The {@code ApplElemAccess} is returned.
- * @throws AoException Thrown in case of errors.
+ * @throws AoException
+ * Thrown in case of errors.
*/
protected ApplElemAccess getApplElemAccess() throws AoException {
return transaction.getModelManager().getApplElemAccess();
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/CatalogManager.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/CatalogManager.java
index cc444fb..fd338bd 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/CatalogManager.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/CatalogManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -43,9 +43,9 @@
import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
/**
- * Used to create, update or delete {@link CatalogComponent}, {@link
- * CatalogSensor} and {@link CatalogAttribute} entities. Modifications
- * of the listed types results in modifications of the application model.
+ * Used to create, update or delete {@link CatalogComponent},
+ * {@link CatalogSensor} and {@link CatalogAttribute} entities. Modifications of
+ * the listed types results in modifications of the application model.
*
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
@@ -68,7 +68,8 @@
/**
* Constructor.
*
- * @param transaction The {@link ODSTransaction}.
+ * @param transaction
+ * The {@link ODSTransaction}.
*/
CatalogManager(ODSTransaction transaction) {
this.transaction = transaction;
@@ -82,23 +83,25 @@
* Creates for each given {@link CatalogComponent} a corresponding
* application element including all required application relations.
*
- * @param catalogComponents The {@code CatalogComponent}s.
- * @throws AoException Thrown in case of errors.
+ * @param catalogComponents
+ * The {@code CatalogComponent}s.
+ * @throws AoException
+ * Thrown in case of errors.
*/
public void createCatalogComponents(Collection<CatalogComponent> catalogComponents) throws AoException {
Map<ContextType, List<CatalogComponent>> catalogComponentsByContextType = catalogComponents.stream()
.collect(Collectors.groupingBy(CatalogComponent::getContextType));
- for(Entry<ContextType, List<CatalogComponent>> entry : catalogComponentsByContextType.entrySet()) {
+ for (Entry<ContextType, List<CatalogComponent>> entry : catalogComponentsByContextType.entrySet()) {
String odsContextTypeName = ODSUtils.CONTEXTTYPES.convert(entry.getKey());
- ApplicationElement contextRootApplicationElement =
- getApplicationStructure().getElementByName(odsContextTypeName);
+ ApplicationElement contextRootApplicationElement = getApplicationStructure()
+ .getElementByName(odsContextTypeName);
BaseElement contextRootBaseElement = contextRootApplicationElement.getBaseElement();
- ApplicationElement contextTemplateComponentApplicationElement =
- getApplicationStructure().getElementByName("Tpl" + odsContextTypeName + "Comp");
+ ApplicationElement contextTemplateComponentApplicationElement = getApplicationStructure()
+ .getElementByName("Tpl" + odsContextTypeName + "Comp");
BaseElement baseElement = getBaseStructure().getElementByType("Ao" + odsContextTypeName + "Part");
- for(CatalogComponent catalogComponent : entry.getValue()) {
+ for (CatalogComponent catalogComponent : entry.getValue()) {
ApplicationElement applicationElement = createApplicationElement(catalogComponent.getName(),
baseElement);
@@ -108,8 +111,8 @@
applicationRelation.setElem2(applicationElement);
applicationRelation.setRelationName(catalogComponent.getName());
applicationRelation.setInverseRelationName(odsContextTypeName);
- applicationRelation.setBaseRelation(getBaseStructure()
- .getRelation(contextRootBaseElement, baseElement));
+ applicationRelation
+ .setBaseRelation(getBaseStructure().getRelation(contextRootBaseElement, baseElement));
applicationRelation._release();
// relation template component to context component
@@ -135,11 +138,13 @@
}
/**
- * Creates for each given {@link CatalogSensor} a corresponding
- * application element including all required application relations.
+ * Creates for each given {@link CatalogSensor} a corresponding application
+ * element including all required application relations.
*
- * @param catalogSensors The {@code CatalogSensor}s.
- * @throws AoException Thrown in case of errors.
+ * @param catalogSensors
+ * The {@code CatalogSensor}s.
+ * @throws AoException
+ * Thrown in case of errors.
*/
public void createCatalogSensors(Collection<CatalogSensor> catalogSensors) throws AoException {
Map<String, List<CatalogSensor>> catalogSensorsByCatalogComponent = catalogSensors.stream()
@@ -148,15 +153,15 @@
ApplicationElement channelApplicationElement = getApplicationStructure().getElementByName("MeaQuantity");
BaseElement channelBaseElement = channelApplicationElement.getBaseElement();
- for(Entry<String, List<CatalogSensor>> entry : catalogSensorsByCatalogComponent.entrySet()) {
- ApplicationElement contextComponentApplicationElement =
- getApplicationStructure().getElementByName(entry.getKey());
+ for (Entry<String, List<CatalogSensor>> entry : catalogSensorsByCatalogComponent.entrySet()) {
+ ApplicationElement contextComponentApplicationElement = getApplicationStructure()
+ .getElementByName(entry.getKey());
BaseElement contextComponentBaseElement = contextComponentApplicationElement.getBaseElement();
- ApplicationElement contextTemplateSensorApplicationElement =
- getApplicationStructure().getElementByName("TplSensor");
+ ApplicationElement contextTemplateSensorApplicationElement = getApplicationStructure()
+ .getElementByName("TplSensor");
BaseElement baseElement = getBaseStructure().getElementByType("AoTestEquipmentPart");
- for(CatalogSensor catalogSensor : entry.getValue()) {
+ for (CatalogSensor catalogSensor : entry.getValue()) {
ApplicationElement applicationElement = createApplicationElement(catalogSensor.getName(), baseElement);
// relation context component to context sensor
@@ -165,8 +170,8 @@
applicationRelation.setElem2(applicationElement);
applicationRelation.setRelationName(catalogSensor.getName());
applicationRelation.setInverseRelationName(entry.getKey());
- applicationRelation.setBaseRelation(getBaseStructure()
- .getRelation(contextComponentBaseElement, baseElement));
+ applicationRelation
+ .setBaseRelation(getBaseStructure().getRelation(contextComponentBaseElement, baseElement));
applicationRelation._release();
// relation template sensor to context sensor
@@ -208,30 +213,31 @@
* Creates for each given {@link CatalogAttribute} a corresponding
* application attribute.
*
- * @param catalogAttributes The {@code CatalogAttribute}s.
- * @throws AoException Thrown in case of errors.
+ * @param catalogAttributes
+ * The {@code CatalogAttribute}s.
+ * @throws AoException
+ * Thrown in case of errors.
*/
public void createCatalogAttributes(Collection<CatalogAttribute> catalogAttributes) throws AoException {
Map<String, List<CatalogAttribute>> catalogAttributesByCatalogComponent = catalogAttributes.stream()
.collect(Collectors.groupingBy(CatalogManager::getParentName));
- for(Entry<String, List<CatalogAttribute>> entry : catalogAttributesByCatalogComponent.entrySet()) {
+ for (Entry<String, List<CatalogAttribute>> entry : catalogAttributesByCatalogComponent.entrySet()) {
ApplicationElement applicationElement = getApplicationStructure().getElementByName(entry.getKey());
- for(CatalogAttribute catalogAttribute : entry.getValue()) {
+ for (CatalogAttribute catalogAttribute : entry.getValue()) {
ApplicationAttribute applicationAttribute = applicationElement.createAttribute();
DataType dataType = ODSUtils.VALUETYPES.convert(catalogAttribute.getValueType());
applicationAttribute.setDataType(dataType);
applicationAttribute.setName(catalogAttribute.getName());
if (dataType == DataType.DT_ENUM) {
- applicationAttribute.setEnumerationDefinition(getApplicationStructure()
- .getEnumerationDefinition(ODSEnumerations
- .getEnumName(catalogAttribute.getEnumerationClass())));
+ applicationAttribute.setEnumerationDefinition(getApplicationStructure().getEnumerationDefinition(
+ ODSEnumerations.getEnumName(catalogAttribute.getEnumerationClass())));
}
Optional<Unit> unit = catalogAttribute.getUnit();
- if(unit.isPresent()) {
- applicationAttribute.setUnit(ODSConverter.toODSLong(unit.get().getID()));
+ if (unit.isPresent()) {
+ applicationAttribute.setUnit(ODSConverter.toODSID(unit.get().getID()));
}
// release resources
@@ -244,27 +250,29 @@
}
/**
- * Updates the application attribute for each given {@link
- * CatalogAttribute}.
+ * Updates the application attribute for each given
+ * {@link CatalogAttribute}.
*
- * @param catalogAttributes The {@code CatalogAttribute}s.
- * @throws AoException Thrown in case of errors.
+ * @param catalogAttributes
+ * The {@code CatalogAttribute}s.
+ * @throws AoException
+ * Thrown in case of errors.
*/
public void updateCatalogAttributes(List<CatalogAttribute> catalogAttributes) throws AoException {
Map<String, List<CatalogAttribute>> catalogAttributesByCatalogComponent = catalogAttributes.stream()
.collect(Collectors.groupingBy(CatalogManager::getParentName));
- for(Entry<String, List<CatalogAttribute>> entry : catalogAttributesByCatalogComponent.entrySet()) {
+ for (Entry<String, List<CatalogAttribute>> entry : catalogAttributesByCatalogComponent.entrySet()) {
ApplicationElement applicationElement = getApplicationStructure().getElementByName(entry.getKey());
- for(CatalogAttribute catalogAttribute : entry.getValue()) {
+ for (CatalogAttribute catalogAttribute : entry.getValue()) {
- ApplicationAttribute applicationAttribute =
- applicationElement.getAttributeByName(catalogAttribute.getName());
+ ApplicationAttribute applicationAttribute = applicationElement
+ .getAttributeByName(catalogAttribute.getName());
Optional<Unit> unit = catalogAttribute.getUnit();
- if(unit.isPresent()) {
- applicationAttribute.setUnit(ODSConverter.toODSLong(unit.get().getID()));
+ if (unit.isPresent()) {
+ applicationAttribute.setUnit(ODSConverter.toODSID(unit.get().getID()));
}
// release resources
@@ -277,17 +285,21 @@
}
/**
- * Deletes the corresponding application element for each given {@link
- * CatalogComponent}. Deleting a {@code CatalogComponent} is only allowed
- * if it is not used in templates and all of its children could be deleted.
- * So at first it is tried to delete its {@link CatalogAttribute}s and
- * {@link CatalogSensor}s. On success it is ensured none of the given {@code
+ * Deletes the corresponding application element for each given
+ * {@link CatalogComponent}. Deleting a {@code CatalogComponent} is only
+ * allowed if it is not used in templates and all of its children could be
+ * deleted. So at first it is tried to delete its {@link CatalogAttribute}s
+ * and {@link CatalogSensor}s. On success it is ensured none of the given
+ * {@code
* CatalogComponent}s is used in templates. Finally the corresponding
* application elements are deleted.
*
- * @param catalogComponents The {@code CatalogComponent}s.
- * @throws AoException Thrown in case of errors.
- * @throws DataAccessException Thrown in case of errors.
+ * @param catalogComponents
+ * The {@code CatalogComponent}s.
+ * @throws AoException
+ * Thrown in case of errors.
+ * @throws DataAccessException
+ * Thrown in case of errors.
*/
public void deleteCatalogComponents(Collection<CatalogComponent> catalogComponents)
throws AoException, DataAccessException {
@@ -300,15 +312,15 @@
transaction.delete(sensors);
transaction.delete(attributes);
- if(areReferencedInTemplates(catalogComponents)) {
- throw new DataAccessException("Unable to delete given catalog components since at least "
- + "one is used in templates.");
+ if (areReferencedInTemplates(catalogComponents)) {
+ throw new DataAccessException(
+ "Unable to delete given catalog components since at least " + "one is used in templates.");
}
- for(CatalogComponent catalogComponent : catalogComponents) {
+ for (CatalogComponent catalogComponent : catalogComponents) {
ApplicationElement applicationElement = getApplicationStructure()
.getElementByName(catalogComponent.getName());
- for(ApplicationRelation applicationRelation : applicationElement.getAllRelations()) {
+ for (ApplicationRelation applicationRelation : applicationElement.getAllRelations()) {
getApplicationStructure().removeRelation(applicationRelation);
// release resources
@@ -322,16 +334,19 @@
}
/**
- * Deletes the corresponding application element for each given {@link
- * CatalogSensor}. Deleting a {@code CatalogSensor} is only allowed if it
- * is not used in templates and all of its children could be deleted. So at
- * first it is tried to delete its {@link CatalogAttribute}s. On success it
- * is ensured none of the given {@code CatalogSensor}s is used in templates.
- * Finally the corresponding application elements are deleted.
+ * Deletes the corresponding application element for each given
+ * {@link CatalogSensor}. Deleting a {@code CatalogSensor} is only allowed
+ * if it is not used in templates and all of its children could be deleted.
+ * So at first it is tried to delete its {@link CatalogAttribute}s. On
+ * success it is ensured none of the given {@code CatalogSensor}s is used in
+ * templates. Finally the corresponding application elements are deleted.
*
- * @param catalogSensors The {@code CatalogSensor}s.
- * @throws AoException Thrown in case of errors.
- * @throws DataAccessException Thrown in case of errors.
+ * @param catalogSensors
+ * The {@code CatalogSensor}s.
+ * @throws AoException
+ * Thrown in case of errors.
+ * @throws DataAccessException
+ * Thrown in case of errors.
*/
public void deleteCatalogSensors(Collection<CatalogSensor> catalogSensors) throws AoException, DataAccessException {
List<CatalogAttribute> attributes = new ArrayList<>();
@@ -340,14 +355,14 @@
}
transaction.delete(attributes);
- if(areReferencedInTemplates(catalogSensors)) {
- throw new DataAccessException("Unable to delete given catalog sensors since at "
- + "least one is used in templates.");
+ if (areReferencedInTemplates(catalogSensors)) {
+ throw new DataAccessException(
+ "Unable to delete given catalog sensors since at " + "least one is used in templates.");
}
- for(CatalogSensor catalogSensor : catalogSensors) {
+ for (CatalogSensor catalogSensor : catalogSensors) {
ApplicationElement applicationElement = getApplicationStructure().getElementByName(catalogSensor.getName());
- for(ApplicationRelation applicationRelation : applicationElement.getAllRelations()) {
+ for (ApplicationRelation applicationRelation : applicationElement.getAllRelations()) {
getApplicationStructure().removeRelation(applicationRelation);
// release resources
@@ -362,30 +377,33 @@
}
/**
- * Deletes the corresponding application attributes for each given {@link
- * CatalogAttribute}. Deleting a {@code CatalogAttribute} is only allowed
- * if it is not used in templates. So at first it is ensured none of the
- * given {@code CatalogAttribute}s is used in templates and finally the
+ * Deletes the corresponding application attributes for each given
+ * {@link CatalogAttribute}. Deleting a {@code CatalogAttribute} is only
+ * allowed if it is not used in templates. So at first it is ensured none of
+ * the given {@code CatalogAttribute}s is used in templates and finally the
* corresponding application attributes are deleted.
*
- * @param catalogAttributes The {@code CatalogAttribute}s.
- * @throws AoException Thrown in case of errors.
- * @throws DataAccessException Thrown in case of errors.
+ * @param catalogAttributes
+ * The {@code CatalogAttribute}s.
+ * @throws AoException
+ * Thrown in case of errors.
+ * @throws DataAccessException
+ * Thrown in case of errors.
*/
public void deleteCatalogAttributes(Collection<CatalogAttribute> catalogAttributes)
throws AoException, DataAccessException {
- if(areReferencedInTemplates(catalogAttributes)) {
- throw new DataAccessException("Unable to delete given catalog attributes since at least "
- + "one is used in templates.");
+ if (areReferencedInTemplates(catalogAttributes)) {
+ throw new DataAccessException(
+ "Unable to delete given catalog attributes since at least " + "one is used in templates.");
}
Map<String, List<CatalogAttribute>> catalogAttributesByParent = catalogAttributes.stream()
.collect(Collectors.groupingBy(CatalogManager::getParentName));
- for(Entry<String, List<CatalogAttribute>> entry : catalogAttributesByParent.entrySet()) {
+ for (Entry<String, List<CatalogAttribute>> entry : catalogAttributesByParent.entrySet()) {
ApplicationElement applicationElement = getApplicationStructure().getElementByName(entry.getKey());
- for(CatalogAttribute catalogAttribute : entry.getValue()) {
+ for (CatalogAttribute catalogAttribute : entry.getValue()) {
ApplicationAttribute applicationAttribute = applicationElement
.getAttributeByName(catalogAttribute.getName());
applicationElement.removeAttribute(applicationAttribute);
@@ -403,11 +421,11 @@
* Releases cached resources.
*/
public void clear() {
- if(applicationStructure != null) {
+ if (applicationStructure != null) {
applicationStructure._release();
}
- if(baseStructure != null) {
+ if (baseStructure != null) {
baseStructure._release();
}
}
@@ -417,16 +435,19 @@
// ======================================================================
/**
- * Creates a new {@link ApplicationElement} with given name and {@link
- * BaseElement}. The returned {@code ApplicationElement} will be created
- * with the three mandatory {@link ApplicationAttribute}s for 'Id', 'Name'
- * and 'MimeType'.
+ * Creates a new {@link ApplicationElement} with given name and
+ * {@link BaseElement}. The returned {@code ApplicationElement} will be
+ * created with the three mandatory {@link ApplicationAttribute}s for 'Id',
+ * 'Name' and 'MimeType'.
*
- * @param name The name of the application element.
- * @param baseElement The {@code BaseElement} the created {@code
+ * @param name
+ * The name of the application element.
+ * @param baseElement
+ * The {@code BaseElement} the created {@code
* ApplicationElement} will be derived from.
* @return The created {@code ApplicationElement} is returned.
- * @throws AoException Thrown in case of errors.
+ * @throws AoException
+ * Thrown in case of errors.
*/
private ApplicationElement createApplicationElement(String name, BaseElement baseElement) throws AoException {
ApplicationElement applicationElement = getApplicationStructure().createElement(baseElement);
@@ -465,11 +486,12 @@
* Returns the cached {@link ApplicationStructure}.
*
* @return The {@code ApplicationStructure} is returned.
- * @throws AoException Thrown if unable to access the {@code
+ * @throws AoException
+ * Thrown if unable to access the {@code
* ApplicationStructure}.
*/
private ApplicationStructure getApplicationStructure() throws AoException {
- if(applicationStructure == null) {
+ if (applicationStructure == null) {
applicationStructure = transaction.getModelManager().getAoSession().getApplicationStructure();
}
@@ -480,11 +502,12 @@
* Returns the cached {@link BaseStructure}.
*
* @return The {@code BaseStructure} is returned.
- * @throws AoException Thrown if unable to access the {@code
+ * @throws AoException
+ * Thrown if unable to access the {@code
* BaseStructure}.
*/
private BaseStructure getBaseStructure() throws AoException {
- if(baseStructure == null) {
+ if (baseStructure == null) {
baseStructure = transaction.getModelManager().getAoSession().getBaseStructure();
}
@@ -494,27 +517,30 @@
/**
* Checks whether given {@link Entity}s are referenced in templates.
*
- * @param entities The checked entities ({@link CatalogComponent}, {@link
- * CatalogSensor} or {@link CatalogAttribute}).
+ * @param entities
+ * The checked entities ({@link CatalogComponent},
+ * {@link CatalogSensor} or {@link CatalogAttribute}).
* @return Returns {@code true} if at least one entity is referenced in a
- * template.
- * @throws AoException Thrown on errors.
- * @throws DataAccessException Thrown on errors.
+ * template.
+ * @throws AoException
+ * Thrown on errors.
+ * @throws DataAccessException
+ * Thrown on errors.
*/
private boolean areReferencedInTemplates(Collection<? extends Entity> entities)
throws AoException, DataAccessException {
Map<EntityType, List<Entity>> entitiesByEntityType = entities.stream()
.collect(Collectors.groupingBy(transaction.getModelManager()::getEntityType));
- for(Entry<EntityType, List<Entity>> entry : entitiesByEntityType.entrySet()) {
+ for (Entry<EntityType, List<Entity>> entry : entitiesByEntityType.entrySet()) {
EntityType source = entry.getKey();
EntityType target = transaction.getModelManager().getEntityType(source.getName().replace("Cat", "Tpl"));
Query query = transaction.getModelManager().createQuery().selectID(target).join(source, target);
- List<Result> results = query.fetch(Filter.and().add(Operation.IN_SET.create(source.getIDAttribute(),
- collectInstanceIDs(entry.getValue()))));
- if(results.size() > 0) {
+ List<Result> results = query.fetch(Filter.and()
+ .add(Operation.IN_SET.create(source.getIDAttribute(), collectInstanceIDs(entry.getValue()))));
+ if (results.size() > 0) {
return true;
}
}
@@ -525,13 +551,14 @@
/**
* Collect the instance IDs of all given {@link Entity}s.
*
- * @param entities The {@link Entity}s.
- * @return The instance IDs a {@code long[]} are turned.
+ * @param entities
+ * The {@link Entity}s.
+ * @return The instance IDs a {@code String[]} are turned.
*/
- private static long[] collectInstanceIDs(List<Entity> entities) {
- long[] ids = new long[entities.size()];
+ private static String[] collectInstanceIDs(List<Entity> entities) {
+ String[] ids = new String[entities.size()];
- for(int i = 0; i < ids.length; i++) {
+ for (int i = 0; i < ids.length; i++) {
ids[i] = entities.get(i).getID();
}
@@ -541,12 +568,13 @@
/**
* Returns the parent name for given {@link CatalogAttribute}.
*
- * @param catalogAttribute The {@code CatalogAttribute}.
+ * @param catalogAttribute
+ * The {@code CatalogAttribute}.
* @return The parent name is returned.
*/
private static String getParentName(CatalogAttribute catalogAttribute) {
Optional<CatalogComponent> catalogComponent = catalogAttribute.getCatalogComponent();
- if(catalogComponent.isPresent()) {
+ if (catalogComponent.isPresent()) {
return catalogComponent.get().getName();
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/DeleteStatement.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/DeleteStatement.java
index 58b6090..addd473 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/DeleteStatement.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/DeleteStatement.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -57,8 +57,8 @@
// Class variables
// ======================================================================
- private static final List<String> AUTO_DELETABLE =
- Arrays.asList("MeaQuantity", "SubMatrix", "LocalColumn", "ExternalComponent");
+ private static final List<String> AUTO_DELETABLE = Arrays.asList("MeaQuantity", "SubMatrix", "LocalColumn",
+ "ExternalComponent");
private static final Logger LOGGER = LoggerFactory.getLogger(DeleteStatement.class);
private final boolean useAutoDelete;
@@ -70,10 +70,13 @@
/**
* Constructor.
*
- * @param transaction The owning {@link ODSTransaction}.
- * @param entityType The associated {@link EntityType}.
- * @param useAutoDelete If {@code true} child relations of {@link
- * Measurement} entities are not followed.
+ * @param transaction
+ * The owning {@link ODSTransaction}.
+ * @param entityType
+ * The associated {@link EntityType}.
+ * @param useAutoDelete
+ * If {@code true} child relations of {@link Measurement}
+ * entities are not followed.
*/
DeleteStatement(ODSTransaction transaction, EntityType entityType, boolean useAutoDelete) {
super(transaction, entityType);
@@ -89,7 +92,7 @@
*/
@Override
public void execute(Collection<Entity> entities) throws AoException, DataAccessException {
- if(entities.stream().filter(e -> !e.getTypeName().equals(getEntityType().getName())).findAny().isPresent()) {
+ if (entities.stream().filter(e -> !e.getTypeName().equals(getEntityType().getName())).findAny().isPresent()) {
throw new IllegalArgumentException("At least one given entity is of incompatible type.");
}
@@ -103,37 +106,43 @@
// ======================================================================
/**
- * Recursively follows child relations of given entities and deletes
- * all child entities before deleting parent entities.
+ * Recursively follows child relations of given entities and deletes all
+ * child entities before deleting parent entities.
*
- * @param entityType {@link EntityType} of the deleted entities.
- * @param instanceIDs Instance IDs of entities which have to be deleted.
- * @param ignoreSiblings Is it required to check whether {@link Measurement}
- * siblings share a common {@link ContextRoot}s.
+ * @param entityType
+ * {@link EntityType} of the deleted entities.
+ * @param instanceIDs
+ * Instance IDs of entities which have to be deleted.
+ * @param ignoreSiblings
+ * Is it required to check whether {@link Measurement} siblings
+ * share a common {@link ContextRoot}s.
* @return Returns the total number of deleted instances.
- * @throws AoException Thrown if unable to delete entities.
- * @throws DataAccessException Thrown if unable to query child entities.
+ * @throws AoException
+ * Thrown if unable to delete entities.
+ * @throws DataAccessException
+ * Thrown if unable to query child entities.
*/
- private int delete(EntityType entityType, Collection<Long> instanceIDs, boolean ignoreSiblings)
+ private int delete(EntityType entityType, Collection<String> instanceIDs, boolean ignoreSiblings)
throws AoException, DataAccessException {
- if(instanceIDs.isEmpty()) {
+ if (instanceIDs.isEmpty()) {
return 0;
}
Query query = getModelManager().createQuery().selectID(entityType);
- for(Relation relation : entityType.getChildRelations()) {
- if(useAutoDelete && AUTO_DELETABLE.contains(relation.getTarget().getName())) {
+ for (Relation relation : entityType.getChildRelations()) {
+ if (useAutoDelete && AUTO_DELETABLE.contains(relation.getTarget().getName())) {
continue;
}
- if(!relation.getTarget().equals(relation.getSource())) {
+ if (!relation.getTarget().equals(relation.getSource())) {
query.join(relation, Join.OUTER).selectID(relation.getTarget());
}
}
- // select attributes containing file links only for entity types implementing FilesAttachable
+ // select attributes containing file links only for entity types
+ // implementing FilesAttachable
EntityConfig<?> entityConfig = getModelManager().getEntityConfig(entityType);
- if(FilesAttachable.class.isAssignableFrom(entityConfig.getEntityClass())) {
+ if (FilesAttachable.class.isAssignableFrom(entityConfig.getEntityClass())) {
entityType.getAttributes().stream().filter(a -> a.getValueType().isFileLinkType()).forEach(query::select);
}
@@ -145,12 +154,13 @@
EntityType testSequence = getModelManager().getEntityType(ContextRoot.class, ContextType.TESTSEQUENCE);
EntityType testEquipment = getModelManager().getEntityType(ContextRoot.class, ContextType.TESTEQUIPMENT);
- // type in this list must be deleted AFTER this this instances have been deleted
+ // type in this list must be deleted AFTER this this instances have been
+ // deleted
// informative relation is considered as a child relation
List<EntityType> delayedDelete = new ArrayList<>();
// join context roots
- if(measurement.equals(entityType) || testStep.equals(entityType)) {
+ if (measurement.equals(entityType) || testStep.equals(entityType)) {
query.join(entityType.getRelation(unitUnderTest), Join.OUTER).selectID(unitUnderTest);
query.join(entityType.getRelation(testSequence), Join.OUTER).selectID(testSequence);
query.join(entityType.getRelation(testEquipment), Join.OUTER).selectID(testEquipment);
@@ -158,44 +168,43 @@
}
// join parameter sets
- if(measurement.equals(entityType) || channel.equals(entityType)) {
+ if (measurement.equals(entityType) || channel.equals(entityType)) {
EntityType parameterSet = getModelManager().getEntityType(ParameterSet.class);
query.join(entityType.getRelation(parameterSet), Join.OUTER).selectID(parameterSet);
}
Filter filter = Filter.or().ids(entityType, instanceIDs);
entityType.getParentRelations().stream().filter(r -> r.getTarget().equals(entityType))
- .forEach(relation -> filter.ids(relation, instanceIDs));
+ .forEach(relation -> filter.ids(relation, instanceIDs));
// query child IDs
- Map<EntityType, Set<Long>> children = new HashMap<>();
- for(Result result : query.fetch(filter)) {
+ Map<EntityType, Set<String>> children = new HashMap<>();
+ for (Result result : query.fetch(filter)) {
// load children of other types
- result.stream().filter(r -> r.getID().longValue() > 0)
- .forEach(r -> {
+ result.stream().filter(r -> r.getID() != null && r.getID().length() > 0).forEach(r -> {
children.computeIfAbsent(r.getEntityType(), k -> new HashSet<>()).add(r.getID());
});
// collect file links to remove
List<FileLink> fileLinks = new ArrayList<>();
- for(Value value : result.getRecord(entityType).getValues().values()) {
- if(value.getValueType().isFileLink()) {
+ for (Value value : result.getRecord(entityType).getValues().values()) {
+ if (value.getValueType().isFileLink()) {
fileLinks.add(value.extract());
- } else if(value.getValueType().isFileLinkSequence()) {
+ } else if (value.getValueType().isFileLinkSequence()) {
fileLinks.addAll(Arrays.asList((FileLink[]) value.extract()));
}
}
- if(!fileLinks.isEmpty()) {
+ if (!fileLinks.isEmpty()) {
getTransaction().getUploadService().addToRemove(fileLinks);
}
}
// omit context roots with references to not removed measurements
- if(!ignoreSiblings && measurement.equals(entityType)) {
- for(EntityType contextRoot : Arrays.asList(unitUnderTest, testSequence, testEquipment)) {
- Set<Long> contextRootIDs = children.getOrDefault(contextRoot, Collections.emptySet());
- if(contextRootIDs.isEmpty()) {
+ if (!ignoreSiblings && measurement.equals(entityType)) {
+ for (EntityType contextRoot : Arrays.asList(unitUnderTest, testSequence, testEquipment)) {
+ Set<String> contextRootIDs = children.getOrDefault(contextRoot, Collections.emptySet());
+ if (contextRootIDs.isEmpty()) {
continue;
}
@@ -203,8 +212,8 @@
contextQuery.selectID(contextRoot, measurement);
contextQuery.join(contextRoot, measurement);
- for(Result result : contextQuery.fetch(Filter.idsOnly(contextRoot, contextRootIDs))) {
- if(instanceIDs.contains(result.getRecord(measurement).getID())) {
+ for (Result result : contextQuery.fetch(Filter.idsOnly(contextRoot, contextRootIDs))) {
+ if (instanceIDs.contains(result.getRecord(measurement).getID())) {
continue;
}
@@ -216,23 +225,23 @@
int amount = 0;
// delete real children
- List<Entry<EntityType, Set<Long>>> consideredChildren = new ArrayList<>();
- for(Entry<EntityType, Set<Long>> entry : children.entrySet()) {
+ List<Entry<EntityType, Set<String>>> consideredChildren = new ArrayList<>();
+ for (Entry<EntityType, Set<String>> entry : children.entrySet()) {
EntityType childType = entry.getKey();
- Set<Long> childInstanceIDs = entry.getValue();
- if(entityType.equals(childType)) {
+ Set<String> childInstanceIDs = entry.getValue();
+ if (entityType.equals(childType)) {
childInstanceIDs.removeAll(instanceIDs);
- } else if(delayedDelete.contains(entry.getKey())) {
+ } else if (delayedDelete.contains(entry.getKey())) {
consideredChildren.add(entry);
continue;
}
amount += delete(entry.getKey(), childInstanceIDs, true);
}
- getApplElemAccess().deleteInstances(((ODSEntityType)entityType).getODSID(), toODSIDs(instanceIDs));
+ getApplElemAccess().deleteInstances(((ODSEntityType) entityType).getODSID(), toODSIDs(instanceIDs));
// delete considered children (informative relation)
- for(Entry<EntityType, Set<Long>> entry : consideredChildren) {
+ for (Entry<EntityType, Set<String>> entry : consideredChildren) {
amount += delete(entry.getKey(), entry.getValue(), true);
}
@@ -240,15 +249,15 @@
}
/**
- * Converts given {@code Collection} of instance IDs to ODS a {@link
- * T_LONGLONG} array.
+ * Converts given {@code Collection} of instance IDs to ODS a
+ * {@link T_LONGLONG} array.
*
- * @param instanceIDs The instance IDs.
+ * @param instanceIDs
+ * The instance IDs.
* @return The corresponding ODS {@code T_LONGLONG[]} is returned.
*/
- private T_LONGLONG[] toODSIDs(Collection<Long> instanceIDs) {
- List<T_LONGLONG> odsIDs = instanceIDs.stream().map(ODSConverter::toODSLong).collect(Collectors.toList());
- return odsIDs.toArray(new T_LONGLONG[odsIDs.size()]);
+ private T_LONGLONG[] toODSIDs(Collection<String> instanceIDs) {
+ return instanceIDs.stream().map(ODSConverter::toODSID).toArray(T_LONGLONG[]::new);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/InsertStatement.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/InsertStatement.java
index 5442589..6bb58ad 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/InsertStatement.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/InsertStatement.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -30,6 +30,7 @@
import org.eclipse.mdm.api.base.model.TestStep;
import org.eclipse.mdm.api.base.model.Value;
import org.eclipse.mdm.api.base.query.Aggregation;
+import org.eclipse.mdm.api.base.query.Attribute;
import org.eclipse.mdm.api.base.query.DataAccessException;
import org.eclipse.mdm.api.base.query.EntityType;
import org.eclipse.mdm.api.base.query.Filter;
@@ -38,6 +39,7 @@
import org.eclipse.mdm.api.base.query.Relation;
import org.eclipse.mdm.api.base.query.Result;
import org.eclipse.mdm.api.odsadapter.utils.ODSConverter;
+import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -61,7 +63,7 @@
private final List<FileLink> fileLinkToUpload = new ArrayList<>();
- private final Map<Long, SortIndexTestSteps> sortIndexTestSteps = new HashMap<>();
+ private final Map<String, SortIndexTestSteps> sortIndexTestSteps = new HashMap<>();
private boolean loadSortIndex;
// ======================================================================
@@ -71,8 +73,10 @@
/**
* Constructor.
*
- * @param transaction The owning {@link ODSTransaction}.
- * @param entityType The associated {@link EntityType}.
+ * @param transaction
+ * The owning {@link ODSTransaction}.
+ * @param entityType
+ * The associated {@link EntityType}.
*/
InsertStatement(ODSTransaction transaction, EntityType entityType) {
super(transaction, entityType);
@@ -96,10 +100,14 @@
/**
* Executes this statement for given {@link Core}s.
*
- * @param cores The processed {@code Core}s.
- * @throws AoException Thrown if the execution fails.
- * @throws DataAccessException Thrown if the execution fails.
- * @throws IOException Thrown if a file transfer operation fails.
+ * @param cores
+ * The processed {@code Core}s.
+ * @throws AoException
+ * Thrown if the execution fails.
+ * @throws DataAccessException
+ * Thrown if the execution fails.
+ * @throws IOException
+ * Thrown if a file transfer operation fails.
*/
public void executeWithCores(Collection<Core> cores) throws AoException, DataAccessException, IOException {
cores.forEach(this::readEntityCore);
@@ -111,14 +119,17 @@
// ======================================================================
/**
- * Uploads new {@link FileLink}s, adjusts sort indices for new {@link
- * TestStep} entities and writes collected insertion data at once. Once
- * new entities are written their children are created by delegation to
+ * Uploads new {@link FileLink}s, adjusts sort indices for new
+ * {@link TestStep} entities and writes collected insertion data at once.
+ * Once new entities are written their children are created by delegation to
* the {@link ODSTransaction}.
*
- * @throws AoException Thrown if the execution fails.
- * @throws DataAccessException Thrown if the execution fails.
- * @throws IOException Thrown if a file transfer operation fails.
+ * @throws AoException
+ * Thrown if the execution fails.
+ * @throws DataAccessException
+ * Thrown if the execution fails.
+ * @throws IOException
+ * Thrown if a file transfer operation fails.
*/
private void execute() throws AoException, DataAccessException, IOException {
List<AIDNameValueSeqUnitId> anvsuList = new ArrayList<>();
@@ -126,33 +137,35 @@
// TODO tracing progress in this method...
- if(loadSortIndex && !sortIndexTestSteps.isEmpty()) {
+ if (loadSortIndex && !sortIndexTestSteps.isEmpty()) {
adjustMissingSortIndices();
}
- if(!fileLinkToUpload.isEmpty()) {
+ if (!fileLinkToUpload.isEmpty()) {
getTransaction().getUploadService().uploadParallel(fileLinkToUpload, null);
}
- for(Entry<String, List<Value>> entry : insertMap.entrySet()) {
+ for (Entry<String, List<Value>> entry : insertMap.entrySet()) {
+ Attribute attribute = getEntityType().getAttribute(entry.getKey());
+
AIDNameValueSeqUnitId anvsu = new AIDNameValueSeqUnitId();
anvsu.attr = new AIDName(aID, entry.getKey());
anvsu.unitId = ODSConverter.toODSLong(0);
- anvsu.values = ODSConverter.toODSValueSeq(entry.getValue());
+ anvsu.values = ODSConverter.toODSValueSeq(attribute, entry.getValue());
anvsuList.add(anvsu);
}
long start = System.currentTimeMillis();
ElemId[] elemIds = getApplElemAccess()
.insertInstances(anvsuList.toArray(new AIDNameValueSeqUnitId[anvsuList.size()]));
- for(int i = 0; i < elemIds.length; i++) {
- cores.get(i).setID(ODSConverter.fromODSLong(elemIds[i].iid));
+ for (int i = 0; i < elemIds.length; i++) {
+ cores.get(i).setID(Long.toString(ODSConverter.fromODSLong(elemIds[i].iid)));
}
long stop = System.currentTimeMillis();
LOGGER.debug("{} " + getEntityType() + " instances created in {} ms.", elemIds.length, stop - start);
- for(List<Entity> children : childrenMap.values()) {
+ for (List<Entity> children : childrenMap.values()) {
getTransaction().create(children);
}
}
@@ -161,32 +174,33 @@
* Reads given {@link Core} and prepares its data to be written:
*
* <ul>
- * <li>collect new {@link FileLink}s</li>
- * <li>trace missing sort indices of TestSteps</li>
- * <li>collect property {@link Value}s</li>
- * <li>collect foreign key {@code Value}s</li>
- * <li>collect child entities for recursive creation</li>
+ * <li>collect new {@link FileLink}s</li>
+ * <li>trace missing sort indices of TestSteps</li>
+ * <li>collect property {@link Value}s</li>
+ * <li>collect foreign key {@code Value}s</li>
+ * <li>collect child entities for recursive creation</li>
* </ul>
*
- * @param core The {@code Core}.
+ * @param core
+ * The {@code Core}.
*/
private void readEntityCore(Core core) {
- if(!core.getTypeName().equals(getEntityType().getName())) {
+ if (!core.getTypeName().equals(getEntityType().getName())) {
throw new IllegalArgumentException("Entity core '" + core.getTypeName()
- + "' is incompatible with current insert statement for entity type '" + getEntityType() + "'.");
+ + "' is incompatible with current insert statement for entity type '" + getEntityType() + "'.");
}
cores.add(core);
- if(loadSortIndex) {
- if((Integer) core.getValues().get(Sortable.ATTR_SORT_INDEX).extract() < 0) {
+ if (loadSortIndex) {
+ if ((Integer) core.getValues().get(Sortable.ATTR_SORT_INDEX).extract() < 0) {
sortIndexTestSteps.computeIfAbsent(core.getPermanentStore().get(Test.class).getID(),
k -> new SortIndexTestSteps()).testStepCores.add(core);
}
}
// add all entity values
- for(Value value : core.getAllValues().values()) {
+ for (Value value : core.getAllValues().values()) {
insertMap.computeIfAbsent(value.getName(), k -> new ArrayList<>()).add(value);
}
@@ -194,12 +208,12 @@
fileLinkToUpload.addAll(core.getAddedFileLinks());
// define "empty" values for informative relations
- for(Relation relation : getEntityType().getInfoRelations()) {
+ for (Relation relation : getEntityType().getInfoRelations()) {
insertMap.computeIfAbsent(relation.getName(), k -> new ArrayList<>()).add(relation.createValue());
}
// define "empty" values for parent relations
- for(Relation relation : getEntityType().getParentRelations()) {
+ for (Relation relation : getEntityType().getParentRelations()) {
insertMap.computeIfAbsent(relation.getName(), k -> new ArrayList<>()).add(relation.createValue());
}
@@ -207,8 +221,8 @@
setRelationIDs(core.getMutableStore().getCurrent());
setRelationIDs(core.getPermanentStore().getCurrent());
- for(Entry<Class<? extends Deletable>, List<? extends Deletable>> entry :
- core.getChildrenStore().getCurrent().entrySet()) {
+ for (Entry<Class<? extends Deletable>, List<? extends Deletable>> entry : core.getChildrenStore().getCurrent()
+ .entrySet()) {
childrenMap.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).addAll(entry.getValue());
}
@@ -219,17 +233,18 @@
/**
* Overwrites empty foreign key {@link Value} containers.
*
- * @param relatedEntities The related {@link Entity}s.
+ * @param relatedEntities
+ * The related {@link Entity}s.
*/
private void setRelationIDs(Collection<Entity> relatedEntities) {
- for(Entity relatedEntity : relatedEntities) {
- if(relatedEntity.getID() < 1) {
+ for (Entity relatedEntity : relatedEntities) {
+ if (!ODSUtils.isValidID(relatedEntity.getID())) {
throw new IllegalArgumentException("Related entity must be a persited entity.");
}
Relation relation = getEntityType().getRelation(getModelManager().getEntityType(relatedEntity));
List<Value> relationValues = insertMap.get(relation.getName());
- if(relationValues == null) {
+ if (relationValues == null) {
throw new IllegalStateException("Relation '" + relation + "' is incompatible with insert statement "
+ "for entity type '" + getEntityType() + "'");
}
@@ -241,7 +256,8 @@
* Adjusts missing sort indices for {@link TestStep}s by querying last used
* max sort index.
*
- * @throws DataAccessException Thrown if unable to query used sort indices.
+ * @throws DataAccessException
+ * Thrown if unable to query used sort indices.
*/
private void adjustMissingSortIndices() throws DataAccessException {
EntityType testStep = getEntityType();
@@ -253,7 +269,7 @@
.group(parentRelation.getAttribute());
Filter filter = Filter.idsOnly(parentRelation, sortIndexTestSteps.keySet());
- for(Result result : query.fetch(filter)) {
+ for (Result result : query.fetch(filter)) {
Record record = result.getRecord(testStep);
int sortIndex = (Integer) record.getValues().get(Sortable.ATTR_SORT_INDEX).extract();
sortIndexTestSteps.remove(record.getID(parentRelation).get()).setIndices(sortIndex + 1);
@@ -285,11 +301,12 @@
/**
* Assigns sort indices to {@link Core}s starting at given index.
*
- * @param startIndex The start index.
+ * @param startIndex
+ * The start index.
*/
private void setIndices(int startIndex) {
int index = startIndex;
- for(Core core : testStepCores) {
+ for (Core core : testStepCores) {
core.getValues().get(Sortable.ATTR_SORT_INDEX).set(index++);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/ODSTransaction.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/ODSTransaction.java
index 5bdeec1..989771e 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/ODSTransaction.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/ODSTransaction.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -42,6 +42,7 @@
import org.eclipse.mdm.api.dflt.model.TemplateAttribute;
import org.eclipse.mdm.api.odsadapter.filetransfer.Transfer;
import org.eclipse.mdm.api.odsadapter.query.ODSModelManager;
+import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -101,10 +102,14 @@
/**
* Constructor.
*
- * @param parentModelManager Used to access the persistence.
- * @param entity Used for security checks
- * @param transfer The file transfer type.
- * @throws AoException Thrown if unable to start a co-session.
+ * @param parentModelManager
+ * Used to access the persistence.
+ * @param entity
+ * Used for security checks
+ * @param transfer
+ * The file transfer type.
+ * @throws AoException
+ * Thrown if unable to start a co-session.
*/
public ODSTransaction(ODSModelManager parentModelManager, Entity entity, Transfer transfer) throws AoException {
this.parentModelManager = parentModelManager;
@@ -125,9 +130,9 @@
@Override
@SuppressWarnings("unchecked")
public <T extends Entity> void create(Collection<T> entities) throws DataAccessException {
- if(entities.isEmpty()) {
+ if (entities.isEmpty()) {
return;
- } else if(entities.stream().filter(e -> e.getID() > 0).findAny().isPresent()) {
+ } else if (entities.stream().filter(e -> ODSUtils.isValidID(e.getID())).findAny().isPresent()) {
throw new IllegalArgumentException("At least one given entity is already persisted.");
}
@@ -137,14 +142,16 @@
List<CatalogComponent> catalogComponents = (List<CatalogComponent>) entitiesByClassType
.get(CatalogComponent.class);
- if(catalogComponents != null) {
+ if (catalogComponents != null) {
getCatalogManager().createCatalogComponents(catalogComponents);
}
List<CatalogSensor> catalogSensors = (List<CatalogSensor>) entitiesByClassType.get(CatalogSensor.class);
- if(catalogSensors != null) {
- // TODO avalon 4.3b throws an exception in AoSession.commintTransaction() if multiple
- // catalog sensors have been deleted and leaves the application model in a broken state
+ if (catalogSensors != null) {
+ // TODO avalon 4.3b throws an exception in
+ // AoSession.commintTransaction() if multiple
+ // catalog sensors have been deleted and leaves the application
+ // model in a broken state
// getCatalogManager().createCatalogSensors(catalogSensors);
throw new DataAccessException("CURRENTLY NOT IMPLEMENTED");
@@ -152,34 +159,35 @@
List<CatalogAttribute> catalogAttributes = (List<CatalogAttribute>) entitiesByClassType
.get(CatalogAttribute.class);
- if(catalogAttributes != null) {
+ if (catalogAttributes != null) {
getCatalogManager().createCatalogAttributes(catalogAttributes);
}
List<TemplateAttribute> templateAttributes = (List<TemplateAttribute>) entitiesByClassType
.get(TemplateAttribute.class);
- if(templateAttributes != null) {
+ if (templateAttributes != null) {
List<TemplateAttribute> filtered = getFileLinkTemplateAttributes(templateAttributes);
- if(!filtered.isEmpty()) {
+ if (!filtered.isEmpty()) {
getUploadService().upload(filtered, null);
}
}
List<TestStep> testSteps = (List<TestStep>) entitiesByClassType.get(TestStep.class);
- if(testSteps != null) {
+ if (testSteps != null) {
create(testSteps.stream().map(ContextRoot::of).collect(ArrayList::new, List::addAll, List::addAll));
}
List<Measurement> measurements = (List<Measurement>) entitiesByClassType.get(Measurement.class);
- if(measurements != null) {
- // use set here, since measurement sibling point to the same context roots
+ if (measurements != null) {
+ // use set here, since measurement sibling point to the same
+ // context roots
create(measurements.stream().map(ContextRoot::of).collect(HashSet::new, Set::addAll, Set::addAll));
}
executeStatements(et -> new InsertStatement(this, et), entities);
List<ContextRoot> roots = (List<ContextRoot>) entitiesByClassType.get(ContextRoot.class);
- if(roots != null) {
+ if (roots != null) {
roots.forEach(contextRoot -> {
contextRoot.setVersion(contextRoot.getID().toString());
});
@@ -188,9 +196,9 @@
executeStatements(et -> new UpdateStatement(this, et, true), roots);
contextRoots.addAll(roots);
}
- } catch(AoException e) {
+ } catch (AoException e) {
throw new DataAccessException("Unable to write new entities due to: " + e.reason, e);
- } catch(IOException e) {
+ } catch (IOException e) {
throw new DataAccessException("Unable to write new entities due to: " + e.getMessage(), e);
}
}
@@ -201,9 +209,9 @@
@Override
@SuppressWarnings("unchecked")
public <T extends Entity> void update(Collection<T> entities) throws DataAccessException {
- if(entities.isEmpty()) {
+ if (entities.isEmpty()) {
return;
- } else if(entities.stream().filter(e -> e.getID() < 1).findAny().isPresent()) {
+ } else if (entities.stream().filter(e -> !ODSUtils.isValidID(e.getID())).findAny().isPresent()) {
throw new IllegalArgumentException("At least one given entity is not yet persisted.");
}
@@ -212,23 +220,23 @@
.collect(Collectors.groupingBy(e -> e.getClass()));
List<CatalogAttribute> catalogAttributes = (List<CatalogAttribute>) entitiesByClassType
.get(CatalogAttribute.class);
- if(catalogAttributes != null) {
+ if (catalogAttributes != null) {
getCatalogManager().updateCatalogAttributes(catalogAttributes);
}
List<TemplateAttribute> templateAttributes = (List<TemplateAttribute>) entitiesByClassType
.get(TemplateAttribute.class);
- if(templateAttributes != null) {
+ if (templateAttributes != null) {
List<TemplateAttribute> filtered = getFileLinkTemplateAttributes(templateAttributes);
- if(!filtered.isEmpty()) {
+ if (!filtered.isEmpty()) {
getUploadService().upload(filtered, null);
}
}
executeStatements(et -> new UpdateStatement(this, et, false), entities);
- } catch(AoException e) {
+ } catch (AoException e) {
throw new DataAccessException("Unable to update entities due to: " + e.reason, e);
- } catch(IOException e) {
+ } catch (IOException e) {
throw new DataAccessException("Unable to update entities due to: " + e.getMessage(), e);
}
}
@@ -239,11 +247,12 @@
@Override
@SuppressWarnings("unchecked")
public <T extends Deletable> void delete(Collection<T> entities) throws DataAccessException {
- if(entities.isEmpty()) {
+ if (entities.isEmpty()) {
return;
}
- List<T> filteredEntities = entities.stream().filter(e -> e.getID() > 0).collect(Collectors.toList());
+ List<T> filteredEntities = entities.stream().filter(e -> ODSUtils.isValidID(e.getID()))
+ .collect(Collectors.toList());
try {
Map<Class<?>, List<T>> entitiesByClassType = filteredEntities.stream()
@@ -251,14 +260,16 @@
List<CatalogComponent> catalogComponents = (List<CatalogComponent>) entitiesByClassType
.get(CatalogComponent.class);
- if(catalogComponents != null) {
+ if (catalogComponents != null) {
getCatalogManager().deleteCatalogComponents(catalogComponents);
}
List<CatalogSensor> catalogSensors = (List<CatalogSensor>) entitiesByClassType.get(CatalogSensor.class);
- if(catalogSensors != null) {
- // TODO avalon 4.3b throws an exception in AoSession.commintTransaction() if multiple
- // catalog sensors have been deleted and leaves the application model in a broken state
+ if (catalogSensors != null) {
+ // TODO avalon 4.3b throws an exception in
+ // AoSession.commintTransaction() if multiple
+ // catalog sensors have been deleted and leaves the application
+ // model in a broken state
// getCatalogManager().deleteCatalogSensors(catalogSensors);
throw new DataAccessException("CURRENTLY NOT IMPLEMENTED");
@@ -266,18 +277,19 @@
List<CatalogAttribute> catalogAttributes = (List<CatalogAttribute>) entitiesByClassType
.get(CatalogAttribute.class);
- if(catalogAttributes != null) {
+ if (catalogAttributes != null) {
getCatalogManager().deleteCatalogAttributes(catalogAttributes);
}
/*
- * TODO: for any template that has to be deleted it is required to ensure there are no links to it...
+ * TODO: for any template that has to be deleted it is required to
+ * ensure there are no links to it...
*/
executeStatements(et -> new DeleteStatement(this, et, true), filteredEntities);
} catch (AoException e) {
throw new DataAccessException("Unable to delete entities due to: " + e.reason, e);
- } catch(IOException e) {
+ } catch (IOException e) {
throw new DataAccessException("Unable to delete entities due to: " + e.getMessage(), e);
}
}
@@ -287,7 +299,7 @@
*/
@Override
public void writeMeasuredValues(Collection<WriteRequest> writeRequests) throws DataAccessException {
- if(writeRequests.isEmpty()) {
+ if (writeRequests.isEmpty()) {
return;
}
@@ -295,14 +307,15 @@
Map<ScalarType, List<WriteRequest>> writeRequestsByRawType = writeRequests.stream()
.collect(Collectors.groupingBy(WriteRequest::getRawScalarType));
- for(List<WriteRequest> writeRequestGroup : writeRequestsByRawType.values()) {
+ for (List<WriteRequest> writeRequestGroup : writeRequestsByRawType.values()) {
WriteRequestHandler writeRequestHandler = new WriteRequestHandler(this);
List<Channel> channels = new ArrayList<>();
- for(WriteRequest writeRequest : writeRequestGroup) {
+ for (WriteRequest writeRequest : writeRequestGroup) {
Channel channel = writeRequest.getChannel();
channel.setScalarType(writeRequest.getCalculatedScalarType());
- // TODO it might be required to change relation to another unit?!??
+ // TODO it might be required to change relation to another
+ // unit?!??
channels.add(channel);
writeRequestHandler.addRequest(writeRequest);
}
@@ -310,9 +323,9 @@
update(channels);
writeRequestHandler.execute();
}
- } catch(AoException e) {
+ } catch (AoException e) {
throw new DataAccessException("Unable to write measured values due to: " + e.reason, e);
- } catch(IOException e) {
+ } catch (IOException e) {
throw new DataAccessException("Unable to write measured values due to: " + e.getMessage(), e);
}
}
@@ -329,18 +342,18 @@
modified.forEach(Core::apply);
// remove deleted remote files
- if(uploadService != null) {
+ if (uploadService != null) {
uploadService.commit();
}
- if(catalogManager != null) {
+ if (catalogManager != null) {
// application model has been modified -> reload
parentModelManager.reloadApplicationModel();
}
LOGGER.debug("Transaction '{}' committed.", id);
closeSession();
- } catch(AoException e) {
+ } catch (AoException e) {
throw new DataAccessException("Unable to commit transaction '" + id + "' due to: " + e.reason, e);
}
}
@@ -351,7 +364,7 @@
@Override
public void abort() {
try {
- if(uploadService != null) {
+ if (uploadService != null) {
uploadService.abort();
}
@@ -359,13 +372,13 @@
contextRoots.forEach(cr -> cr.setVersion(null));
// reset instance IDs
- Long virtualID = Long.valueOf(0L);
+ String virtualID = "0";
created.forEach(c -> c.setID(virtualID));
modelManager.getAoSession().abortTransaction();
LOGGER.debug("Transaction '{}' aborted.", id);
- } catch(AoException e) {
+ } catch (AoException e) {
LOGGER.error("Unable to abort transaction '" + id + "' due to: " + e.reason, e);
} finally {
closeSession();
@@ -377,11 +390,12 @@
// ======================================================================
/**
- * Once {@link #abort()} is called instance ID of given {@link Core} will
- * be reset to {@code 0} which indicates a virtual {@link Entity}, not yet
+ * Once {@link #abort()} is called instance ID of given {@link Core} will be
+ * reset to {@code 0} which indicates a virtual {@link Entity}, not yet
* persisted, entity.
*
- * @param core The {@code Core} of a newly written {@code Entity}.
+ * @param core
+ * The {@code Core} of a newly written {@code Entity}.
*/
void addCreated(Core core) {
created.add(core);
@@ -391,7 +405,8 @@
* Once {@link #commit()} is {@link Core#apply()} will be called to apply
* modified {@link Value} contents and removed related entities.
*
- * @param core The {@code Core} of an updated {@code Entity}.
+ * @param core
+ * The {@code Core} of an updated {@code Entity}.
*/
void addModified(Core core) {
modified.add(core);
@@ -410,15 +425,17 @@
* Returns the {@link UploadService}.
*
* @return The {@code UploadService} is returned.
- * @throws DataAccessException Thrown if file transfer is not possible.
+ * @throws DataAccessException
+ * Thrown if file transfer is not possible.
*/
UploadService getUploadService() throws DataAccessException {
- if(uploadService == null) {
- if(modelManager.getFileServer() == null) {
+ if (uploadService == null) {
+ if (modelManager.getFileServer() == null) {
throw new DataAccessException("CORBA file server is not available.");
}
- // upload service starts a periodic session refresh task -> lazy instantiation
+ // upload service starts a periodic session refresh task -> lazy
+ // instantiation
uploadService = new UploadService(modelManager, entity, transfer);
}
@@ -435,7 +452,7 @@
* @return The {@code CatalogManager} is returned.
*/
private CatalogManager getCatalogManager() {
- if(catalogManager == null) {
+ if (catalogManager == null) {
catalogManager = new CatalogManager(this);
}
@@ -446,9 +463,10 @@
* Collects {@link TemplateAttribute}s with a valid default {@link Value} of
* type {@link ValueType#FILE_LINK} or {@link ValueType#FILE_LINK_SEQUENCE}.
*
- * @param templateAttributes The processed {@code TemplateAttribute}s.
+ * @param templateAttributes
+ * The processed {@code TemplateAttribute}s.
* @return Returns {@link TemplateAttribute} which have {@link FileLink}s
- * stored as default {@code Value}.
+ * stored as default {@code Value}.
*/
private List<TemplateAttribute> getFileLinkTemplateAttributes(List<TemplateAttribute> templateAttributes) {
return templateAttributes.stream().filter(ta -> {
@@ -460,20 +478,24 @@
/**
* Executes statements for given entities by using given statement factory.
*
- * @param <T> The entity type.
- * @param statementFactory Used to create a new statement for a given
- * {@link EntityType}.
- * @param entities The processed {@code Entity}s.
- * @throws AoException Thrown if the execution fails.
- * @throws DataAccessException Thrown if the execution fails.
- * @throws IOException Thrown if a file transfer operation fails.
+ * @param <T>
+ * The entity type.
+ * @param statementFactory
+ * Used to create a new statement for a given {@link EntityType}.
+ * @param entities
+ * The processed {@code Entity}s.
+ * @throws AoException
+ * Thrown if the execution fails.
+ * @throws DataAccessException
+ * Thrown if the execution fails.
+ * @throws IOException
+ * Thrown if a file transfer operation fails.
*/
private <T extends Entity> void executeStatements(Function<EntityType, BaseStatement> statementFactory,
- Collection<T> entities)
- throws AoException, DataAccessException, IOException {
+ Collection<T> entities) throws AoException, DataAccessException, IOException {
Map<EntityType, List<Entity>> entitiesByType = entities.stream()
.collect(Collectors.groupingBy(modelManager::getEntityType));
- for(Entry<EntityType, List<Entity>> entry : entitiesByType.entrySet()) {
+ for (Entry<EntityType, List<Entity>> entry : entitiesByType.entrySet()) {
statementFactory.apply(entry.getKey()).execute(entry.getValue());
}
}
@@ -483,13 +505,13 @@
*/
private void closeSession() {
try {
- if(catalogManager != null) {
+ if (catalogManager != null) {
catalogManager.clear();
}
modelManager.close();
LOGGER.debug("Transaction '{}' closed.", id);
- } catch(AoException e) {
+ } catch (AoException e) {
LOGGER.error("Unable to close transaction '" + id + "' due to: " + e.reason, e);
}
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UpdateStatement.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UpdateStatement.java
index dcee0e7..d2ecb04 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UpdateStatement.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UpdateStatement.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -28,11 +28,13 @@
import org.eclipse.mdm.api.base.model.FileLink;
import org.eclipse.mdm.api.base.model.FilesAttachable;
import org.eclipse.mdm.api.base.model.Value;
+import org.eclipse.mdm.api.base.query.Attribute;
import org.eclipse.mdm.api.base.query.DataAccessException;
import org.eclipse.mdm.api.base.query.EntityType;
import org.eclipse.mdm.api.base.query.Relation;
import org.eclipse.mdm.api.odsadapter.lookup.config.EntityConfig;
import org.eclipse.mdm.api.odsadapter.utils.ODSConverter;
+import org.eclipse.mdm.api.odsadapter.utils.ODSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -71,16 +73,18 @@
/**
* Constructor.
*
- * @param transaction The owning {@link ODSTransaction}.
- * @param entityType The associated {@link EntityType}.
- * @param ignoreChildren If {@code true}, then child entities won't be
- * processed.
+ * @param transaction
+ * The owning {@link ODSTransaction}.
+ * @param entityType
+ * The associated {@link EntityType}.
+ * @param ignoreChildren
+ * If {@code true}, then child entities won't be processed.
*/
UpdateStatement(ODSTransaction transaction, EntityType entityType, boolean ignoreChildren) {
super(transaction, entityType);
- nonUpdatableRelationNames = entityType.getInfoRelations().stream()
- .map(Relation::getName).collect(Collectors.toList());
+ nonUpdatableRelationNames = entityType.getInfoRelations().stream().map(Relation::getName)
+ .collect(Collectors.toList());
this.ignoreChildren = ignoreChildren;
EntityConfig<?> entityConfig = getModelManager().getEntityConfig(getEntityType());
@@ -96,7 +100,7 @@
*/
@Override
public void execute(Collection<Entity> entities) throws AoException, DataAccessException, IOException {
- for(Entity entity : entities) {
+ for (Entity entity : entities) {
readEntityCore(extract(entity));
}
@@ -105,20 +109,22 @@
List<AIDNameValueSeqUnitId> anvsuList = new ArrayList<>();
T_LONGLONG aID = getEntityType().getODSID();
- if(!fileLinkToUpload.isEmpty()) {
+ if (!fileLinkToUpload.isEmpty()) {
getTransaction().getUploadService().uploadParallel(fileLinkToUpload, null);
}
- for(Entry<String, List<Value>> entry : updateMap.entrySet()) {
- if(nonUpdatableRelationNames.contains(entry.getKey())) {
+ for (Entry<String, List<Value>> entry : updateMap.entrySet()) {
+ if (nonUpdatableRelationNames.contains(entry.getKey())) {
// skip "empty" informative relation sequence
continue;
}
+ Attribute attribute = getEntityType().getAttribute(entry.getKey());
+
AIDNameValueSeqUnitId anvsu = new AIDNameValueSeqUnitId();
anvsu.attr = new AIDName(aID, entry.getKey());
anvsu.unitId = ODSConverter.toODSLong(0);
- anvsu.values = ODSConverter.toODSValueSeq(entry.getValue());
+ anvsu.values = ODSConverter.toODSValueSeq(attribute, entry.getValue());
anvsuList.add(anvsu);
}
@@ -129,13 +135,13 @@
LOGGER.debug("{} " + getEntityType() + " instances updated in {} ms.", entities.size(), stop - start);
// delete first to make sure naming collisions do not occur!
- for(List<Deletable> children : childrenToRemove.values()) {
+ for (List<Deletable> children : childrenToRemove.values()) {
getTransaction().delete(children);
}
- for(List<Entity> children : childrenToCreate.values()) {
+ for (List<Entity> children : childrenToCreate.values()) {
getTransaction().create(children);
}
- for(List<Entity> children : childrenToUpdate.values()) {
+ for (List<Entity> children : childrenToUpdate.values()) {
getTransaction().update(children);
}
}
@@ -148,45 +154,47 @@
* Reads given {@link Core} and prepares its data to be written:
*
* <ul>
- * <li>collect new and removed {@link FileLink}s</li>
- * <li>collect property {@link Value}s</li>
- * <li>collect foreign key {@code Value}s</li>
- * <li>collect child entities for recursive create/update/delete</li>
+ * <li>collect new and removed {@link FileLink}s</li>
+ * <li>collect property {@link Value}s</li>
+ * <li>collect foreign key {@code Value}s</li>
+ * <li>collect child entities for recursive create/update/delete</li>
* </ul>
*
- * @param core The {@code Core}.
- * @throws DataAccessException Thrown in case of errors.
+ * @param core
+ * The {@code Core}.
+ * @throws DataAccessException
+ * Thrown in case of errors.
*/
private void readEntityCore(Core core) throws DataAccessException {
- if(!core.getTypeName().equals(getEntityType().getName())) {
+ if (!core.getTypeName().equals(getEntityType().getName())) {
throw new IllegalArgumentException("Entity core '" + core.getTypeName()
- + "' is incompatible with current update statement for entity type '" + getEntityType() + "'.");
+ + "' is incompatible with current update statement for entity type '" + getEntityType() + "'.");
}
// add all entity values
- for(Value value : core.getAllValues().values()) {
+ for (Value value : core.getAllValues().values()) {
updateMap.computeIfAbsent(value.getName(), k -> new ArrayList<>()).add(value);
}
// collect file links
fileLinkToUpload.addAll(core.getAddedFileLinks());
List<FileLink> fileLinksToRemove = core.getRemovedFileLinks();
- if(isFilesAttachable && !fileLinksToRemove.isEmpty()) {
+ if (isFilesAttachable && !fileLinksToRemove.isEmpty()) {
getTransaction().getUploadService().addToRemove(fileLinksToRemove);
}
updateMap.computeIfAbsent(getEntityType().getIDAttribute().getName(), k -> new ArrayList<>())
- .add(getEntityType().getIDAttribute().createValue(core.getID()));
+ .add(getEntityType().getIDAttribute().createValue(core.getID()));
// define "empty" values for ALL informative relations
- for(Relation relation : getEntityType().getInfoRelations()) {
+ for (Relation relation : getEntityType().getInfoRelations()) {
updateMap.computeIfAbsent(relation.getName(), k -> new ArrayList<>()).add(relation.createValue());
}
// preserve "empty" relation values for removed related entities
EntityStore mutableStore = core.getMutableStore();
mutableStore.getRemoved().stream().map(e -> getModelManager().getEntityType(e))
- .map(getEntityType()::getRelation).map(Relation::getName).forEach(nonUpdatableRelationNames::remove);
+ .map(getEntityType()::getRelation).map(Relation::getName).forEach(nonUpdatableRelationNames::remove);
// replace "empty" relation values with corresponding instance IDs
setRelationIDs(mutableStore.getCurrent());
@@ -199,31 +207,32 @@
/**
* Collects child entities for recursive processing.
*
- * @param core The {@link Core}.
+ * @param core
+ * The {@link Core}.
*/
private void collectChildEntities(Core core) {
- if(ignoreChildren) {
+ if (ignoreChildren) {
return;
}
- for (Entry<Class<? extends Deletable>, List<? extends Deletable>> entry :
- core.getChildrenStore().getCurrent().entrySet()) {
+ for (Entry<Class<? extends Deletable>, List<? extends Deletable>> entry : core.getChildrenStore().getCurrent()
+ .entrySet()) {
Map<Boolean, List<Entity>> patrition = entry.getValue().stream()
- .collect(Collectors.partitioningBy(e -> e.getID() < 1));
+ .collect(Collectors.partitioningBy(e -> ODSUtils.isValidID(e.getID())));
List<Entity> virtualEntities = patrition.get(Boolean.TRUE);
- if(virtualEntities != null && !virtualEntities.isEmpty()) {
+ if (virtualEntities != null && !virtualEntities.isEmpty()) {
childrenToCreate.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).addAll(virtualEntities);
}
List<Entity> existingEntities = patrition.get(Boolean.FALSE);
- if(existingEntities != null && !existingEntities.isEmpty()) {
+ if (existingEntities != null && !existingEntities.isEmpty()) {
childrenToUpdate.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).addAll(existingEntities);
}
}
- for (Entry<Class<? extends Deletable>, List<? extends Deletable>> entry :
- core.getChildrenStore().getRemoved().entrySet()) {
- List<Deletable> toDelete = entry.getValue().stream()
- .filter(e -> e.getID() > 0).collect(Collectors.toList());
+ for (Entry<Class<? extends Deletable>, List<? extends Deletable>> entry : core.getChildrenStore().getRemoved()
+ .entrySet()) {
+ List<Deletable> toDelete = entry.getValue().stream().filter(e -> ODSUtils.isValidID(e.getID()))
+ .collect(Collectors.toList());
childrenToRemove.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).addAll(toDelete);
}
}
@@ -231,17 +240,18 @@
/**
* Overwrites empty foreign key {@link Value} containers.
*
- * @param relatedEntities The related {@link Entity}s.
+ * @param relatedEntities
+ * The related {@link Entity}s.
*/
private void setRelationIDs(Collection<Entity> relatedEntities) {
- for(Entity relatedEntity : relatedEntities) {
- if(relatedEntity.getID() < 1) {
+ for (Entity relatedEntity : relatedEntities) {
+ if (!ODSUtils.isValidID(relatedEntity.getID())) {
throw new IllegalArgumentException("Related entity must be a persited entity.");
}
Relation relation = getEntityType().getRelation(getModelManager().getEntityType(relatedEntity));
List<Value> relationValues = updateMap.get(relation.getName());
- if(relationValues == null) {
+ if (relationValues == null) {
throw new IllegalStateException("Relation '" + relation
+ "' is incompatible with update statement for entity type '" + getEntityType() + "'");
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UploadService.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UploadService.java
index 2c1c90e..bd441ce 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UploadService.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/UploadService.java
@@ -51,24 +51,28 @@
/**
* Constructor.
*
- * @param modelManager Used for setup.
- * @param entity Used for security checks.
- * @param transfer The transfer type.
+ * @param modelManager
+ * Used for setup.
+ * @param entity
+ * Used for security checks.
+ * @param transfer
+ * The transfer type.
*/
- UploadService(ODSModelManager modelManager,Entity entity, Transfer transfer) {
+ UploadService(ODSModelManager modelManager, Entity entity, Transfer transfer) {
fileService = new CORBAFileService(modelManager, transfer);
this.entity = entity;
scheduler.scheduleAtFixedRate(() -> {
try {
modelManager.getAoSession().getName();
- } catch(AoException e) {
+ } catch (AoException e) {
/*
- * NOTE: This is done to keep the parent transaction's session alive
- * till its commit or abort method is called. If this session refresh
- * results in an error, then any running file transfer will abort
- * with a proper error, therefore any exception here is completely
- * ignored and explicitly NOT logged!
+ * NOTE: This is done to keep the parent transaction's session
+ * alive till its commit or abort method is called. If this
+ * session refresh results in an error, then any running file
+ * transfer will abort with a proper error, therefore any
+ * exception here is completely ignored and explicitly NOT
+ * logged!
*/
}
}, 5, 5, TimeUnit.MINUTES);
@@ -79,27 +83,30 @@
// ======================================================================
/**
- * Uploads new externally linked files stored in given {@link
- * TemplateAttribute}s. The upload progress may be traced with a progress
- * listener.
+ * Uploads new externally linked files stored in given
+ * {@link TemplateAttribute}s. The upload progress may be traced with a
+ * progress listener.
*
- * @param templateAttributes The {@link TemplateAttribute}s.
- * @param progressListener The progress listener.
- * @throws IOException Thrown if unable to upload files.
+ * @param templateAttributes
+ * The {@link TemplateAttribute}s.
+ * @param progressListener
+ * The progress listener.
+ * @throws IOException
+ * Thrown if unable to upload files.
*/
public void upload(Collection<TemplateAttribute> templateAttributes, ProgressListener progressListener)
throws IOException {
List<FileLink> fileLinks = new ArrayList<>();
- for(TemplateAttribute templateAttribute : templateAttributes) {
+ for (TemplateAttribute templateAttribute : templateAttributes) {
Value defaultValue = templateAttribute.getDefaultValue();
- if(!defaultValue.isValid()) {
+ if (!defaultValue.isValid()) {
continue;
}
- if(defaultValue.getValueType().isFileLink()) {
+ if (defaultValue.getValueType().isFileLink()) {
fileLinks.add(defaultValue.extract());
- } else if(defaultValue.getValueType().isFileLinkSequence()) {
- fileLinks.addAll(Arrays.asList((FileLink[])defaultValue.extract()));
+ } else if (defaultValue.getValueType().isFileLinkSequence()) {
+ fileLinks.addAll(Arrays.asList((FileLink[]) defaultValue.extract()));
} else {
throw new IllegalStateException("Template attribute's value type is not of type file link.");
}
@@ -107,7 +114,7 @@
templateAttributeFileLinks.put(templateAttribute, defaultValue);
}
- if(!fileLinks.isEmpty()) {
+ if (!fileLinks.isEmpty()) {
uploadParallel(fileLinks, progressListener);
// remote paths available -> update template attribute
templateAttributeFileLinks.forEach((ta, v) -> ta.setDefaultValue(v.extract()));
@@ -119,9 +126,12 @@
* multiple times are uploaded only once. The upload progress may be traced
* with a progress listener.
*
- * @param fileLinks Collection of {@code FileLink}s to upload.
- * @param progressListener The progress listener.
- * @throws IOException Thrown if unable to upload files.
+ * @param fileLinks
+ * Collection of {@code FileLink}s to upload.
+ * @param progressListener
+ * The progress listener.
+ * @throws IOException
+ * Thrown if unable to upload files.
*/
public void uploadParallel(Collection<FileLink> fileLinks, ProgressListener progressListener) throws IOException {
List<FileLink> filtered = retainForUpload(fileLinks);
@@ -139,7 +149,8 @@
* Once {@link #commit()} is called given {@link FileLink}s will be deleted
* from the remote storage.
*
- * @param fileLinks Collection of {@code FileLink}s to delete.
+ * @param fileLinks
+ * Collection of {@code FileLink}s to delete.
*/
public void addToRemove(Collection<FileLink> fileLinks) {
toRemove.addAll(fileLinks);
@@ -170,14 +181,15 @@
/**
* Filters given {@link FileLink}s by removing already uploaded ones.
*
- * @param fileLinks Will be filtered.
+ * @param fileLinks
+ * Will be filtered.
* @return Returns {@code FileLink}s which have to be uploaded.
*/
private List<FileLink> retainForUpload(Collection<FileLink> fileLinks) {
List<FileLink> filtered = new ArrayList<>(fileLinks);
- for(FileLink fileLink : fileLinks) {
+ for (FileLink fileLink : fileLinks) {
String remotePath = remotePaths.get(fileLink.getLocalPath());
- if(remotePath != null && !remotePath.isEmpty()) {
+ if (remotePath != null && !remotePath.isEmpty()) {
fileLink.setRemotePath(remotePath);
filtered.remove(fileLink);
uploaded.add(fileLink);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/WriteRequestHandler.java b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/WriteRequestHandler.java
index 0fde628..035b906 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/WriteRequestHandler.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/transaction/WriteRequestHandler.java
@@ -63,7 +63,8 @@
/**
* Constructor.
*
- * @param transaction The owning {@link ODSTransaction}.
+ * @param transaction
+ * The owning {@link ODSTransaction}.
*/
public WriteRequestHandler(ODSTransaction transaction) {
localColumnEntityType = transaction.getModelManager().getEntityType("LocalColumn");
@@ -77,7 +78,8 @@
/**
* Adds given {@link WriteRequest} to be processed.
*
- * @param writeRequest The {@code WriteRequest}.
+ * @param writeRequest
+ * The {@code WriteRequest}.
*/
public void addRequest(WriteRequest writeRequest) {
cores.add(createCore(writeRequest));
@@ -86,9 +88,12 @@
/**
* Imports given mass data configurations.
*
- * @throws AoException Thrown if the execution fails.
- * @throws DataAccessException Thrown if the execution fails.
- * @throws IOException Thrown if a file transfer operation fails.
+ * @throws AoException
+ * Thrown if the execution fails.
+ * @throws DataAccessException
+ * Thrown if the execution fails.
+ * @throws IOException
+ * Thrown if a file transfer operation fails.
*/
public void execute() throws AoException, DataAccessException, IOException {
insertStatement.executeWithCores(cores);
@@ -99,10 +104,11 @@
// ======================================================================
/**
- * Reads given {@link WriteRequest} and prepares a corresponding {@link
- * Core} for import.
+ * Reads given {@link WriteRequest} and prepares a corresponding
+ * {@link Core} for import.
*
- * @param writeRequest The mass data configuration.
+ * @param writeRequest
+ * The mass data configuration.
* @return The created {@code Core} is returned.
*/
private Core createCore(WriteRequest writeRequest) {
@@ -120,25 +126,27 @@
values.get(AE_LC_ATTR_AXISTYPE).set(writeRequest.getAxisType());
values.get(AE_LC_ATTR_PARAMETERS).set(writeRequest.getGenerationParameters());
- if(writeRequest.hasValues()) {
+ if (writeRequest.hasValues()) {
ValueType valueType = writeRequest.getRawScalarType().toValueType();
String unitName = writeRequest.getChannel().getUnit().getName();
- values.put(AE_LC_ATTR_VALUES, valueType.create(AE_LC_ATTR_VALUES, unitName, true,
- writeRequest.getValues()));
+ values.put(AE_LC_ATTR_VALUES,
+ valueType.create(AE_LC_ATTR_VALUES, unitName, true, writeRequest.getValues()));
- if(writeRequest.getSequenceRepresentation().isImplicit()) {
- // PEAK ODS server: expects values written as generation parameters
+ if (writeRequest.getSequenceRepresentation().isImplicit()) {
+ // PEAK ODS server: expects values written as generation
+ // parameters
Object genParamValues = writeRequest.getValues();
double[] genParamD = new double[Array.getLength(genParamValues)];
IntStream.range(0, genParamD.length)
- .forEach(i -> genParamD[i] = ((Number)Array.get(genParamValues, i)).doubleValue());
+ .forEach(i -> genParamD[i] = ((Number) Array.get(genParamValues, i)).doubleValue());
values.get(AE_LC_ATTR_PARAMETERS).set(genParamD);
}
- //flags
- if(writeRequest.areAllValid()) {
+ // flags
+ if (writeRequest.areAllValid()) {
values.get(AE_LC_ATTR_GLOBAL_FLAG).set((short) 15);
- // PEAK ODS server issue: though global flag is true a flags array is expected
+ // PEAK ODS server issue: though global flag is true a flags
+ // array is expected
short[] flags = new short[Array.getLength(writeRequest.getValues())];
Arrays.fill(flags, (short) 15);
values.get(AE_LC_ATTR_FLAGS).set(flags);
@@ -146,7 +154,7 @@
short[] flags = ODSConverter.toODSValidFlagSeq(writeRequest.getFlags());
values.get(AE_LC_ATTR_FLAGS).set(flags);
}
- } else if(writeRequest.hasExternalComponents()) {
+ } else if (writeRequest.hasExternalComponents()) {
// TODO
throw new UnsupportedOperationException("NOT YET IMPLEMENTED.");
} else {
@@ -157,5 +165,3 @@
}
}
-
-
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/BiDiMapper.java b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/BiDiMapper.java
index 0212ad2..ac47195 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/BiDiMapper.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/BiDiMapper.java
@@ -14,8 +14,10 @@
/**
* Bidirectional mapping of configured values.
*
- * @param <T> Mapped object type one.
- * @param <S> Mapped object type two.
+ * @param <T>
+ * Mapped object type one.
+ * @param <S>
+ * Mapped object type two.
* @since 1.0.0
* @author Viktor Stoehr, Gigatronik Ingolstadt GmbH
*/
@@ -34,7 +36,8 @@
/**
* Returns the mapping for given value.
*
- * @param input The value.
+ * @param input
+ * The value.
* @return The corresponding mapped value is returned.
*/
@SuppressWarnings("unchecked")
@@ -45,7 +48,8 @@
/**
* Returns the mapping for given value.
*
- * @param input The value.
+ * @param input
+ * The value.
* @return The corresponding mapped value is returned.
*/
@SuppressWarnings("unchecked")
@@ -60,8 +64,10 @@
/**
* Adds a new bidirectional mapping for given values.
*
- * @param t Not allowed to be null.
- * @param s Not allowed to be null.
+ * @param t
+ * Not allowed to be null.
+ * @param s
+ * Not allowed to be null.
*/
void addMappings(T t, S s) {
map.put(t, s);
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSConverter.java b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSConverter.java
index 5f3a176..57cea37 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSConverter.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSConverter.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -15,6 +15,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
import org.asam.ods.Blob;
import org.asam.ods.DataType;
@@ -37,6 +39,7 @@
import org.eclipse.mdm.api.base.model.ValueType;
import org.eclipse.mdm.api.base.query.Attribute;
import org.eclipse.mdm.api.base.query.DataAccessException;
+import org.eclipse.mdm.api.odsadapter.query.ODSAttribute;
/**
* Utility class for value conversions from/to ODS types.
@@ -69,7 +72,8 @@
/**
* Constructor.
*/
- private ODSConverter() {}
+ private ODSConverter() {
+ }
// ======================================================================
// Conversion methods
@@ -78,11 +82,15 @@
/**
* Converts given {@link TS_ValueSeq} to {@link Value}s.
*
- * @param attribute The {@link Attribute}.
- * @param unit The unit name.
- * @param odsValueSeq The {@code TS_ValueSeq}.
+ * @param attribute
+ * The {@link Attribute}.
+ * @param unit
+ * The unit name.
+ * @param odsValueSeq
+ * The {@code TS_ValueSeq}.
* @return The converted {@code Value}s are returned.
- * @throws DataAccessException Thrown on conversion errors.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
public static List<Value> fromODSValueSeq(Attribute attribute, String unit, TS_ValueSeq odsValueSeq)
throws DataAccessException {
@@ -90,151 +98,179 @@
short[] flags = odsValueSeq.flag;
List<Value> values = new ArrayList<>(flags.length);
- if(DataType.DT_STRING == dataType) {
+ if (((ODSAttribute) attribute).isIdAttribute()) {
+ if (DataType.DT_LONGLONG == dataType) {
+ T_LONGLONG[] odsValues = odsValueSeq.u.longlongVal();
+ for (int i = 0; i < flags.length; i++) {
+ values.add(attribute.createValue(unit, flags[i] == 15, Long.toString(fromODSLong(odsValues[i]))));
+ }
+ return values;
+ } else if (DataType.DS_LONGLONG == dataType) {
+ T_LONGLONG[][] odsValues = odsValueSeq.u.longlongSeq();
+ for (int i = 0; i < flags.length; i++) {
+ values.add(attribute.createValue(unit, flags[i] == 15, toString(odsValues[i])));
+ }
+ return values;
+ } else if (DataType.DT_LONG == dataType) {
+ int[] odsValues = odsValueSeq.u.longVal();
+ for (int i = 0; i < flags.length; i++) {
+ values.add(attribute.createValue(unit, flags[i] == 15, Integer.toString(odsValues[i])));
+ }
+ return values;
+ } else if (DataType.DS_LONG == dataType) {
+ int[][] odsValues = odsValueSeq.u.longSeq();
+ for (int i = 0; i < flags.length; i++) {
+ values.add(attribute.createValue(unit, flags[i] == 15, toString(odsValues[i])));
+ }
+ return values;
+ }
+ }
+
+ if (DataType.DT_STRING == dataType) {
String[] odsValues = odsValueSeq.u.stringVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_STRING == dataType) {
+ } else if (DataType.DS_STRING == dataType) {
String[][] odsValues = odsValueSeq.u.stringSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_DATE == dataType) {
+ } else if (DataType.DT_DATE == dataType) {
String[] odsValues = odsValueSeq.u.dateVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSDate(odsValues[i])));
}
- } else if(DataType.DS_DATE == dataType) {
+ } else if (DataType.DS_DATE == dataType) {
String[][] odsValues = odsValueSeq.u.dateSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSDateSeq(odsValues[i])));
}
- } else if(DataType.DT_BOOLEAN == dataType) {
+ } else if (DataType.DT_BOOLEAN == dataType) {
boolean[] odsValues = odsValueSeq.u.booleanVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_BOOLEAN == dataType) {
+ } else if (DataType.DS_BOOLEAN == dataType) {
boolean[][] odsValues = odsValueSeq.u.booleanSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_BYTE == dataType) {
+ } else if (DataType.DT_BYTE == dataType) {
byte[] odsValues = odsValueSeq.u.byteVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_BYTE == dataType) {
+ } else if (DataType.DS_BYTE == dataType) {
byte[][] odsValues = odsValueSeq.u.byteSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_SHORT == dataType) {
+ } else if (DataType.DT_SHORT == dataType) {
short[] odsValues = odsValueSeq.u.shortVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_SHORT == dataType) {
+ } else if (DataType.DS_SHORT == dataType) {
short[][] odsValues = odsValueSeq.u.shortSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_LONG == dataType) {
+ } else if (DataType.DT_LONG == dataType) {
int[] odsValues = odsValueSeq.u.longVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_LONG == dataType) {
+ } else if (DataType.DS_LONG == dataType) {
int[][] odsValues = odsValueSeq.u.longSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_LONGLONG == dataType) {
+ } else if (DataType.DT_LONGLONG == dataType) {
T_LONGLONG[] odsValues = odsValueSeq.u.longlongVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSLong(odsValues[i])));
}
- } else if(DataType.DS_LONGLONG == dataType) {
+ } else if (DataType.DS_LONGLONG == dataType) {
T_LONGLONG[][] odsValues = odsValueSeq.u.longlongSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSLongSeq(odsValues[i])));
}
- } else if(DataType.DT_FLOAT == dataType) {
+ } else if (DataType.DT_FLOAT == dataType) {
float[] odsValues = odsValueSeq.u.floatVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_FLOAT == dataType) {
+ } else if (DataType.DS_FLOAT == dataType) {
float[][] odsValues = odsValueSeq.u.floatSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_DOUBLE == dataType) {
+ } else if (DataType.DT_DOUBLE == dataType) {
double[] odsValues = odsValueSeq.u.doubleVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_DOUBLE == dataType) {
+ } else if (DataType.DS_DOUBLE == dataType) {
double[][] odsValues = odsValueSeq.u.doubleSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_BYTESTR == dataType) {
+ } else if (DataType.DT_BYTESTR == dataType) {
byte[][] odsValues = odsValueSeq.u.bytestrVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DS_BYTESTR == dataType) {
+ } else if (DataType.DS_BYTESTR == dataType) {
byte[][][] odsValues = odsValueSeq.u.bytestrSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, odsValues[i]));
}
- } else if(DataType.DT_COMPLEX == dataType) {
+ } else if (DataType.DT_COMPLEX == dataType) {
T_COMPLEX[] odsValues = odsValueSeq.u.complexVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSFloatComplex(odsValues[i])));
}
- } else if(DataType.DS_COMPLEX == dataType) {
+ } else if (DataType.DS_COMPLEX == dataType) {
T_COMPLEX[][] odsValues = odsValueSeq.u.complexSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSFloatComplexSeq(odsValues[i])));
}
- } else if(DataType.DT_DCOMPLEX == dataType) {
+ } else if (DataType.DT_DCOMPLEX == dataType) {
T_DCOMPLEX[] odsValues = odsValueSeq.u.dcomplexVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSDoubleComplex(odsValues[i])));
}
- } else if(DataType.DS_DCOMPLEX == dataType) {
+ } else if (DataType.DS_DCOMPLEX == dataType) {
T_DCOMPLEX[][] odsValues = odsValueSeq.u.dcomplexSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSDoubleComplexSeq(odsValues[i])));
}
- } else if(DataType.DT_ENUM == dataType) {
+ } else if (DataType.DT_ENUM == dataType) {
int[] odsValues = odsValueSeq.u.enumVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15,
ODSEnumerations.fromODSEnum(attribute.getEnumClass(), odsValues[i])));
}
- } else if(DataType.DS_ENUM == dataType) {
+ } else if (DataType.DS_ENUM == dataType) {
int[][] odsValues = odsValueSeq.u.enumSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15,
ODSEnumerations.fromODSEnumSeq(attribute.getEnumClass(), odsValues[i])));
}
- } else if(DataType.DT_EXTERNALREFERENCE == dataType) {
+ } else if (DataType.DT_EXTERNALREFERENCE == dataType) {
T_ExternalReference[] odsValues = odsValueSeq.u.extRefVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSExternalReference(odsValues[i])));
}
- } else if(DataType.DS_EXTERNALREFERENCE == dataType) {
+ } else if (DataType.DS_EXTERNALREFERENCE == dataType) {
T_ExternalReference[][] odsValues = odsValueSeq.u.extRefSeq();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSExternalReferenceSeq(odsValues[i])));
}
- } else if(DataType.DT_BLOB == dataType) {
+ } else if (DataType.DT_BLOB == dataType) {
Blob[] odsValues = odsValueSeq.u.blobVal();
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
values.add(attribute.createValue(unit, flags[i] == 15, fromODSBlob(odsValues[i])));
}
} else {
@@ -244,251 +280,270 @@
return values;
}
+ private static String[] toString(int[] odsValues) {
+ return IntStream.of(odsValues).mapToObj(Integer::toString).toArray(String[]::new);
+ }
+
+ private static String[] toString(T_LONGLONG[] odsValues) {
+ return Stream.of(odsValues).map(l -> Long.toString(fromODSLong(l))).toArray(String[]::new);
+ }
+
/**
* Converts given {@link Value}s to {@link TS_ValueSeq}.
*
- * @param values The {@code Value}s.
+ * @param values
+ * The {@code Value}s.
* @return The converted {@code TS_ValueSeq} is returned.
- * @throws DataAccessException Thrown on conversion errors.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
- public static TS_ValueSeq toODSValueSeq(List<Value> values) throws DataAccessException {
+ public static TS_ValueSeq toODSValueSeq(Attribute attribute, List<Value> values) throws DataAccessException {
int size = values == null ? 0 : values.size();
short[] flags = new short[size];
TS_ValueSeq odsValueSeq = new TS_ValueSeq(new TS_UnionSeq(), flags);
- if(values == null || size < 1) {
+ if (values == null || size < 1) {
odsValueSeq.u._default();
return odsValueSeq;
}
ValueType type = values.get(0).getValueType();
- if(ValueType.STRING == type) {
+ if (ValueType.STRING == type) {
String[] odsValues = new String[size];
- for(int i = 0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
- odsValueSeq.u.stringVal(odsValues);
- } else if(ValueType.STRING_SEQUENCE == type) {
+ if (((ODSAttribute) attribute).isIdAttribute()) {
+ odsValueSeq.u.longlongVal(toLongLong(odsValues));
+ } else {
+ odsValueSeq.u.stringVal(odsValues);
+ }
+ } else if (ValueType.STRING_SEQUENCE == type) {
String[][] odsValues = new String[size][];
- for(int i = 0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
- odsValueSeq.u.stringSeq(odsValues);
- } else if(ValueType.DATE == type) {
+ if (((ODSAttribute) attribute).isIdAttribute()) {
+ odsValueSeq.u.longlongSeq(toLongLongSeq(odsValues));
+ } else {
+ odsValueSeq.u.stringSeq(odsValues);
+ }
+
+ } else if (ValueType.DATE == type) {
String[] odsValues = new String[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSDate(value.extract());
}
odsValueSeq.u.dateVal(odsValues);
- } else if(ValueType.DATE_SEQUENCE == type) {
+ } else if (ValueType.DATE_SEQUENCE == type) {
String[][] odsValues = new String[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSDateSeq(value.extract());
}
odsValueSeq.u.dateSeq(odsValues);
- } else if(ValueType.BOOLEAN == type) {
+ } else if (ValueType.BOOLEAN == type) {
boolean[] odsValues = new boolean[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.booleanVal(odsValues);
- } else if(ValueType.BOOLEAN_SEQUENCE == type) {
+ } else if (ValueType.BOOLEAN_SEQUENCE == type) {
boolean[][] odsValues = new boolean[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.booleanSeq(odsValues);
- } else if(ValueType.BYTE == type) {
+ } else if (ValueType.BYTE == type) {
byte[] odsValues = new byte[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.byteVal(odsValues);
- } else if(ValueType.BYTE_SEQUENCE == type) {
+ } else if (ValueType.BYTE_SEQUENCE == type) {
byte[][] odsValues = new byte[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.byteSeq(odsValues);
- } else if(ValueType.SHORT == type) {
+ } else if (ValueType.SHORT == type) {
short[] odsValues = new short[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.shortVal(odsValues);
- } else if(ValueType.SHORT_SEQUENCE == type) {
+ } else if (ValueType.SHORT_SEQUENCE == type) {
short[][] odsValues = new short[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.shortSeq(odsValues);
- } else if(ValueType.INTEGER == type) {
+ } else if (ValueType.INTEGER == type) {
int[] odsValues = new int[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.longVal(odsValues);
- } else if(ValueType.INTEGER_SEQUENCE == type) {
+ } else if (ValueType.INTEGER_SEQUENCE == type) {
int[][] odsValues = new int[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.longSeq(odsValues);
- } else if(ValueType.LONG == type) {
+ } else if (ValueType.LONG == type) {
T_LONGLONG[] odsValues = new T_LONGLONG[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSLong(value.extract());
}
odsValueSeq.u.longlongVal(odsValues);
- } else if(ValueType.LONG_SEQUENCE == type) {
+ } else if (ValueType.LONG_SEQUENCE == type) {
T_LONGLONG[][] odsValues = new T_LONGLONG[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSLongSeq(value.extract());
}
odsValueSeq.u.longlongSeq(odsValues);
- } else if(ValueType.FLOAT == type) {
+ } else if (ValueType.FLOAT == type) {
float[] odsValues = new float[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.floatVal(odsValues);
- } else if(ValueType.FLOAT_SEQUENCE == type) {
+ } else if (ValueType.FLOAT_SEQUENCE == type) {
float[][] odsValues = new float[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.floatSeq(odsValues);
- } else if(ValueType.DOUBLE == type) {
+ } else if (ValueType.DOUBLE == type) {
double[] odsValues = new double[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.doubleVal(odsValues);
- } else if(ValueType.DOUBLE_SEQUENCE == type) {
+ } else if (ValueType.DOUBLE_SEQUENCE == type) {
double[][] odsValues = new double[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.doubleSeq(odsValues);
- } else if(ValueType.BYTE_STREAM == type) {
+ } else if (ValueType.BYTE_STREAM == type) {
byte[][] odsValues = new byte[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.bytestrVal(odsValues);
- } else if(ValueType.BYTE_STREAM_SEQUENCE == type) {
+ } else if (ValueType.BYTE_STREAM_SEQUENCE == type) {
byte[][][] odsValues = new byte[size][][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = value.extract();
}
odsValueSeq.u.bytestrSeq(odsValues);
- } else if(ValueType.FLOAT_COMPLEX == type) {
+ } else if (ValueType.FLOAT_COMPLEX == type) {
T_COMPLEX[] odsValues = new T_COMPLEX[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSFloatComplex(value.extract());
}
odsValueSeq.u.complexVal(odsValues);
- } else if(ValueType.FLOAT_COMPLEX_SEQUENCE == type) {
+ } else if (ValueType.FLOAT_COMPLEX_SEQUENCE == type) {
T_COMPLEX[][] odsValues = new T_COMPLEX[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSFloatComplexSeq(value.extract());
}
odsValueSeq.u.complexSeq(odsValues);
- } else if(ValueType.DOUBLE_COMPLEX == type) {
+ } else if (ValueType.DOUBLE_COMPLEX == type) {
T_DCOMPLEX[] odsValues = new T_DCOMPLEX[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSDoubleComplex(value.extract());
}
odsValueSeq.u.dcomplexVal(odsValues);
- } else if(ValueType.DOUBLE_COMPLEX_SEQUENCE == type) {
+ } else if (ValueType.DOUBLE_COMPLEX_SEQUENCE == type) {
T_DCOMPLEX[][] odsValues = new T_DCOMPLEX[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSDoubleComplexSeq(value.extract());
}
odsValueSeq.u.dcomplexSeq(odsValues);
- } else if(ValueType.ENUMERATION == type) {
+ } else if (ValueType.ENUMERATION == type) {
int[] odsValues = new int[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = ODSEnumerations.toODSEnum(value.extract());
}
odsValueSeq.u.enumVal(odsValues);
- } else if(ValueType.ENUMERATION_SEQUENCE == type) {
+ } else if (ValueType.ENUMERATION_SEQUENCE == type) {
int[][] odsValues = new int[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = ODSEnumerations.toODSEnumSeq(value.extract());
}
odsValueSeq.u.enumSeq(odsValues);
- } else if(ValueType.FILE_LINK == type) {
+ } else if (ValueType.FILE_LINK == type) {
T_ExternalReference[] odsValues = new T_ExternalReference[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSExternalReference(value.extract());
}
odsValueSeq.u.extRefVal(odsValues);
- } else if(ValueType.FILE_LINK_SEQUENCE == type) {
+ } else if (ValueType.FILE_LINK_SEQUENCE == type) {
T_ExternalReference[][] odsValues = new T_ExternalReference[size][];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSExternalReferenceSeq(value.extract());
}
odsValueSeq.u.extRefSeq(odsValues);
- } else if(ValueType.BLOB == type) {
+ } else if (ValueType.BLOB == type) {
Blob[] odsValues = new Blob[size];
- for(int i = 0; i < flags.length; i++) {
+ for (int i = 0; i < flags.length; i++) {
Value value = values.get(i);
flags[i] = toODSValidFlag(value.isValid());
odsValues[i] = toODSBlob(value.extract());
@@ -502,16 +557,43 @@
}
/**
+ * Converts given two dimensional String array to two dimensional
+ * {@link T_LONGLONG} array.
+ *
+ * @param value
+ * The String array.
+ * @return The converted {@link T_LONGLONG} array.
+ */
+ private static T_LONGLONG[][] toLongLongSeq(String[][] value) {
+
+ return Stream.of(value).map(ODSConverter::toLongLong).toArray(T_LONGLONG[][]::new);
+ }
+
+ /**
+ * Converts given String array to {@link T_LONGLONG} array.
+ *
+ * @param value
+ * The String array.
+ * @return The converted {@link T_LONGLONG} array.
+ */
+ private static T_LONGLONG[] toLongLong(String[] value) {
+ return Stream.of(value).map(s -> toODSID(s)).toArray(T_LONGLONG[]::new);
+ }
+
+ /**
* Converts given {@link NameValueSeqUnit[]} to {@link MeasuredValues}s.
*
- * @param odsMeasuredValuesSeq The {@code NameValueSeqUnit}s.
+ * @param odsMeasuredValuesSeq
+ * The {@code NameValueSeqUnit}s.
* @return The converted {@code MeasuredValues}s are returned.
- * @throws DataAccessException Thrown on conversion errors.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
- public static List<MeasuredValues> fromODSMeasuredValuesSeq(NameValueSeqUnit[] odsMeasuredValuesSeq) throws DataAccessException {
+ public static List<MeasuredValues> fromODSMeasuredValuesSeq(NameValueSeqUnit[] odsMeasuredValuesSeq)
+ throws DataAccessException {
List<MeasuredValues> measuredValues = new ArrayList<>(odsMeasuredValuesSeq.length);
- for(NameValueSeqUnit odsMeasuredValues : odsMeasuredValuesSeq) {
+ for (NameValueSeqUnit odsMeasuredValues : odsMeasuredValuesSeq) {
measuredValues.add(fromODSMeasuredValues(odsMeasuredValues));
}
@@ -521,9 +603,11 @@
/**
* Converts given {@link NameValueSeqUnit} to {@link MeasuredValues}.
*
- * @param odsMeasuredValues The {@code NameValueSeqUnit}.
+ * @param odsMeasuredValues
+ * The {@code NameValueSeqUnit}.
* @return The converted {@code MeasuredValues} is returned.
- * @throws DataAccessException Thrown on conversion errors.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
private static MeasuredValues fromODSMeasuredValues(NameValueSeqUnit odsMeasuredValues) throws DataAccessException {
TS_ValueSeq odsValueSeq = odsMeasuredValues.value;
@@ -531,122 +615,133 @@
ScalarType scalarType;
Object values;
- if(DataType.DT_STRING == dataType) {
+ if (DataType.DT_STRING == dataType) {
scalarType = ScalarType.STRING;
values = odsValueSeq.u.stringVal();
- } else if(DataType.DT_DATE == dataType) {
+ } else if (DataType.DT_DATE == dataType) {
scalarType = ScalarType.DATE;
values = fromODSDateSeq(odsValueSeq.u.dateVal());
- } else if(DataType.DT_BOOLEAN == dataType) {
+ } else if (DataType.DT_BOOLEAN == dataType) {
scalarType = ScalarType.BOOLEAN;
values = odsValueSeq.u.booleanVal();
- } else if(DataType.DT_BYTE == dataType) {
+ } else if (DataType.DT_BYTE == dataType) {
scalarType = ScalarType.BYTE;
values = odsValueSeq.u.byteVal();
- } else if(DataType.DT_SHORT == dataType) {
+ } else if (DataType.DT_SHORT == dataType) {
scalarType = ScalarType.SHORT;
values = odsValueSeq.u.shortVal();
- } else if(DataType.DT_LONG == dataType) {
+ } else if (DataType.DT_LONG == dataType) {
scalarType = ScalarType.INTEGER;
values = odsValueSeq.u.longVal();
- } else if(DataType.DT_LONGLONG == dataType) {
+ } else if (DataType.DT_LONGLONG == dataType) {
scalarType = ScalarType.LONG;
values = fromODSLongSeq(odsValueSeq.u.longlongVal());
- } else if(DataType.DT_FLOAT == dataType) {
+ } else if (DataType.DT_FLOAT == dataType) {
scalarType = ScalarType.FLOAT;
values = odsValueSeq.u.floatVal();
- } else if(DataType.DT_DOUBLE == dataType) {
+ } else if (DataType.DT_DOUBLE == dataType) {
scalarType = ScalarType.DOUBLE;
values = odsValueSeq.u.doubleVal();
- } else if(DataType.DT_BYTESTR == dataType) {
+ } else if (DataType.DT_BYTESTR == dataType) {
scalarType = ScalarType.BYTE_STREAM;
values = odsValueSeq.u.bytestrVal();
- } else if(DataType.DT_COMPLEX == dataType) {
+ } else if (DataType.DT_COMPLEX == dataType) {
scalarType = ScalarType.FLOAT_COMPLEX;
values = fromODSFloatComplexSeq(odsValueSeq.u.complexVal());
- } else if(DataType.DT_DCOMPLEX == dataType) {
+ } else if (DataType.DT_DCOMPLEX == dataType) {
scalarType = ScalarType.DOUBLE_COMPLEX;
values = fromODSDoubleComplexSeq(odsValueSeq.u.dcomplexVal());
- } else if(DataType.DT_EXTERNALREFERENCE == dataType) {
+ } else if (DataType.DT_EXTERNALREFERENCE == dataType) {
scalarType = ScalarType.FILE_LINK;
values = fromODSExternalReferenceSeq(odsValueSeq.u.extRefVal());
} else {
- throw new DataAccessException("Conversion for ODS measured points of type '" + dataType.toString()
- + "' does not exist.");
+ throw new DataAccessException(
+ "Conversion for ODS measured points of type '" + dataType.toString() + "' does not exist.");
}
- return scalarType.createMeasuredValues(odsMeasuredValues.valName, odsMeasuredValues.unit,
- values, fromODSValidFlagSeq(odsValueSeq.flag));
+ return scalarType.createMeasuredValues(odsMeasuredValues.valName, odsMeasuredValues.unit, values,
+ fromODSValidFlagSeq(odsValueSeq.flag));
}
/**
* Converts given {@link Value} to {@link TS_Value}.
*
- * @param value The {@code Value}.
+ * @param value
+ * The {@code Value}.
* @return The converted {@code TS_Value} is returned.
- * @throws DataAccessException Thrown on conversion errors.
+ * @throws DataAccessException
+ * Thrown on conversion errors.
*/
- public static TS_Value toODSValue(Value value) throws DataAccessException {
+ public static TS_Value toODSValue(Attribute attribute, Value value) throws DataAccessException {
TS_Value odsValue = new TS_Value(new TS_Union(), toODSValidFlag(value.isValid()));
ValueType type = value.getValueType();
- if(ValueType.STRING == type) {
- odsValue.u.stringVal(value.extract());
- } else if(ValueType.STRING_SEQUENCE == type) {
- odsValue.u.stringSeq(value.extract());
- } else if(ValueType.DATE == type) {
+ if (ValueType.STRING == type) {
+ if (((ODSAttribute) attribute).isIdAttribute()) {
+ odsValue.u.longlongVal(ODSConverter.toODSID(value.extract()));
+ } else {
+ odsValue.u.stringVal(value.extract());
+ }
+ } else if (ValueType.STRING_SEQUENCE == type) {
+ if (((ODSAttribute) attribute).isIdAttribute()) {
+ odsValue.u.longlongSeq(
+ Stream.of((String[]) value.extract()).map(ODSConverter::toODSID).toArray(T_LONGLONG[]::new));
+ } else {
+ odsValue.u.stringSeq(value.extract());
+ }
+ } else if (ValueType.DATE == type) {
odsValue.u.dateVal(toODSDate(value.extract()));
- } else if(ValueType.DATE_SEQUENCE == type) {
+ } else if (ValueType.DATE_SEQUENCE == type) {
odsValue.u.dateSeq(toODSDateSeq(value.extract()));
- } else if(ValueType.BOOLEAN == type) {
+ } else if (ValueType.BOOLEAN == type) {
odsValue.u.booleanVal(value.extract());
- } else if(ValueType.BOOLEAN_SEQUENCE == type) {
+ } else if (ValueType.BOOLEAN_SEQUENCE == type) {
odsValue.u.booleanVal(value.extract());
- } else if(ValueType.BYTE == type) {
+ } else if (ValueType.BYTE == type) {
odsValue.u.byteVal(value.extract());
- } else if(ValueType.BYTE_SEQUENCE == type) {
+ } else if (ValueType.BYTE_SEQUENCE == type) {
odsValue.u.byteSeq(value.extract());
- } else if(ValueType.SHORT == type) {
+ } else if (ValueType.SHORT == type) {
odsValue.u.shortVal(value.extract());
- } else if(ValueType.SHORT_SEQUENCE == type) {
+ } else if (ValueType.SHORT_SEQUENCE == type) {
odsValue.u.shortSeq(value.extract());
- } else if(ValueType.INTEGER == type) {
+ } else if (ValueType.INTEGER == type) {
odsValue.u.longVal(value.extract());
- } else if(ValueType.INTEGER_SEQUENCE == type) {
+ } else if (ValueType.INTEGER_SEQUENCE == type) {
odsValue.u.longSeq(value.extract());
- } else if(ValueType.LONG == type) {
+ } else if (ValueType.LONG == type) {
odsValue.u.longlongVal(toODSLong(value.extract()));
- } else if(ValueType.LONG_SEQUENCE == type) {
+ } else if (ValueType.LONG_SEQUENCE == type) {
odsValue.u.longlongSeq(toODSLongSeq(value.extract()));
- } else if(ValueType.FLOAT == type) {
+ } else if (ValueType.FLOAT == type) {
odsValue.u.floatVal(value.extract());
- } else if(ValueType.FLOAT_SEQUENCE == type) {
+ } else if (ValueType.FLOAT_SEQUENCE == type) {
odsValue.u.floatSeq(value.extract());
- } else if(ValueType.DOUBLE == type) {
+ } else if (ValueType.DOUBLE == type) {
odsValue.u.doubleVal(value.extract());
- } else if(ValueType.DOUBLE_SEQUENCE == type) {
+ } else if (ValueType.DOUBLE_SEQUENCE == type) {
odsValue.u.doubleSeq(value.extract());
- } else if(ValueType.BYTE_STREAM == type) {
+ } else if (ValueType.BYTE_STREAM == type) {
odsValue.u.bytestrVal(value.extract());
- } else if(ValueType.BYTE_STREAM_SEQUENCE == type) {
+ } else if (ValueType.BYTE_STREAM_SEQUENCE == type) {
odsValue.u.bytestrSeq(value.extract());
- } else if(ValueType.FLOAT_COMPLEX == type) {
+ } else if (ValueType.FLOAT_COMPLEX == type) {
odsValue.u.complexVal(toODSFloatComplex(value.extract()));
- } else if(ValueType.FLOAT_COMPLEX_SEQUENCE == type) {
+ } else if (ValueType.FLOAT_COMPLEX_SEQUENCE == type) {
odsValue.u.complexSeq(toODSFloatComplexSeq(value.extract()));
- } else if(ValueType.DOUBLE_COMPLEX == type) {
+ } else if (ValueType.DOUBLE_COMPLEX == type) {
odsValue.u.dcomplexVal(toODSDoubleComplex(value.extract()));
- } else if(ValueType.DOUBLE_COMPLEX_SEQUENCE == type) {
+ } else if (ValueType.DOUBLE_COMPLEX_SEQUENCE == type) {
odsValue.u.dcomplexSeq(toODSDoubleComplexSeq(value.extract()));
- } else if(ValueType.ENUMERATION == type) {
+ } else if (ValueType.ENUMERATION == type) {
odsValue.u.enumVal(ODSEnumerations.toODSEnum(value.extract()));
- } else if(ValueType.ENUMERATION_SEQUENCE == type) {
+ } else if (ValueType.ENUMERATION_SEQUENCE == type) {
odsValue.u.enumSeq(ODSEnumerations.toODSEnumSeq(value.extract()));
- } else if(ValueType.FILE_LINK == type) {
+ } else if (ValueType.FILE_LINK == type) {
odsValue.u.extRefVal(toODSExternalReference(value.extract()));
- } else if(ValueType.FILE_LINK_SEQUENCE == type) {
+ } else if (ValueType.FILE_LINK_SEQUENCE == type) {
odsValue.u.extRefSeq(toODSExternalReferenceSeq(value.extract()));
- } else if(ValueType.BLOB == type) {
+ } else if (ValueType.BLOB == type) {
odsValue.u.blobVal(toODSBlob(value.extract()));
} else {
throw new DataAccessException("Mapping for value type '" + type + "' does not exist.");
@@ -658,12 +753,13 @@
/**
* Converts given {@link short[]} to {@link boolean[]}.
*
- * @param input The {@code short}s.
+ * @param input
+ * The {@code short}s.
* @return The converted {@code boolean}s are returned.
*/
private static boolean[] fromODSValidFlagSeq(short[] input) {
boolean[] result = new boolean[input.length];
- for(int i = 0; i < result.length; i++) {
+ for (int i = 0; i < result.length; i++) {
result[i] = fromODSValidFlag(input[i]);
}
@@ -673,7 +769,8 @@
/**
* Converts given {@link short} to {@link boolean}.
*
- * @param input The {@code short}.
+ * @param input
+ * The {@code short}.
* @return The converted {@code boolean} is returned.
*/
private static boolean fromODSValidFlag(short input) {
@@ -683,12 +780,13 @@
/**
* Converts given {@link boolean[]} to {@link short[]}.
*
- * @param input The {@code boolean}s.
+ * @param input
+ * The {@code boolean}s.
* @return The converted {@code short}s are returned.
*/
public static short[] toODSValidFlagSeq(boolean[] input) {
short[] result = new short[input.length];
- for(int i = 0; i < result.length; i++) {
+ for (int i = 0; i < result.length; i++) {
result[i] = toODSValidFlag(input[i]);
}
@@ -698,7 +796,8 @@
/**
* Converts given {@link boolean} to {@link short}.
*
- * @param input The {@code boolean}.
+ * @param input
+ * The {@code boolean}.
* @return The converted {@code short} is returned.
*/
public static short toODSValidFlag(boolean input) {
@@ -708,12 +807,13 @@
/**
* Converts given {@link T_LONGLONG[]} to {@link long[]}.
*
- * @param input The {@code T_LONGLONG}s.
+ * @param input
+ * The {@code T_LONGLONG}s.
* @return The converted {@code long}s are returned.
*/
private static long[] fromODSLongSeq(T_LONGLONG[] input) {
long[] result = new long[input.length];
- for(int i = 0; i < result.length; i++) {
+ for (int i = 0; i < result.length; i++) {
result[i] = fromODSLong(input[i]);
}
@@ -723,7 +823,8 @@
/**
* Converts given {@link T_LONGLONG} to {@link long}.
*
- * @param input The {@code T_LONGLONG}.
+ * @param input
+ * The {@code T_LONGLONG}.
* @return The converted {@code long} is returned.
*/
public static long fromODSLong(T_LONGLONG input) {
@@ -734,7 +835,8 @@
/**
* Converts given {@link long[]} to {@link T_LONGLONG[]}.
*
- * @param input The {@code long}s.
+ * @param input
+ * The {@code long}s.
* @return The converted {@code T_LONGLONG}s are returned.
*/
private static T_LONGLONG[] toODSLongSeq(long[] input) {
@@ -749,7 +851,8 @@
/**
* Converts given {@link long} to {@link T_LONGLONG}.
*
- * @param input The {@code long}.
+ * @param input
+ * The {@code long}.
* @return The converted {@code T_LONGLONG} is returned.
*/
public static T_LONGLONG toODSLong(long input) {
@@ -757,15 +860,31 @@
}
/**
+ * Converts a given MDM ID string to {@link T_LONGLONG}.
+ *
+ * @param input
+ * The MDM ID string.
+ * @return The converted {@code T_LONGLONG} is returned.
+ */
+ public static T_LONGLONG toODSID(String input) {
+ try {
+ return toODSLong(Long.valueOf(input));
+ } catch (NumberFormatException e) {
+ return new T_LONGLONG();
+ }
+ }
+
+ /**
* Converts given {@link String[]} to {@link LocalDateTime[]}.
*
- * @param input The {@code String}s.
+ * @param input
+ * The {@code String}s.
* @return The converted {@code LocalDateTime}s are returned.
*/
private static LocalDateTime[] fromODSDateSeq(String[] input) {
List<LocalDateTime> result = new ArrayList<>();
- if(input != null) {
- for(String value : input) {
+ if (input != null) {
+ for (String value : input) {
result.add(fromODSDate(value));
}
}
@@ -776,7 +895,8 @@
/**
* Converts given {@link String} to {@link LocalDateTime}.
*
- * @param input The {@code T_COMPLEX}.
+ * @param input
+ * The {@code T_COMPLEX}.
* @return The converted {@code String} is returned.
*/
private static LocalDateTime fromODSDate(String input) {
@@ -799,7 +919,8 @@
/**
* Converts given {@link LocalDateTime[]} to {@link String[]}.
*
- * @param input The {@code LocalDateTime}s.
+ * @param input
+ * The {@code LocalDateTime}s.
* @return The converted {@code String}s are returned.
*/
private static String[] toODSDateSeq(LocalDateTime[] input) {
@@ -814,7 +935,8 @@
/**
* Converts given {@link LocalDateTime} to {@link String}.
*
- * @param input The {@code LocalDateTime}.
+ * @param input
+ * The {@code LocalDateTime}.
* @return The converted {@code String} is returned.
*/
private static String toODSDate(LocalDateTime input) {
@@ -824,13 +946,14 @@
/**
* Converts given {@link T_COMPLEX[]} to {@link FloatComplex[]}.
*
- * @param input The {@code T_COMPLEX}s.
+ * @param input
+ * The {@code T_COMPLEX}s.
* @return The converted {@code FloatComplex}s are returned.
*/
private static FloatComplex[] fromODSFloatComplexSeq(T_COMPLEX[] input) {
List<FloatComplex> result = new ArrayList<>();
- if(input != null) {
- for(T_COMPLEX value : input) {
+ if (input != null) {
+ for (T_COMPLEX value : input) {
result.add(fromODSFloatComplex(value));
}
}
@@ -841,7 +964,8 @@
/**
* Converts given {@link T_COMPLEX} to {@link FloatComplex}.
*
- * @param input The {@code T_COMPLEX}.
+ * @param input
+ * The {@code T_COMPLEX}.
* @return The converted {@code FloatComplex} is returned.
*/
private static FloatComplex fromODSFloatComplex(T_COMPLEX input) {
@@ -851,7 +975,8 @@
/**
* Converts given {@link FloatComplex[]} to {@link T_COMPLEX[]}.
*
- * @param input The {@code FloatComplex}s.
+ * @param input
+ * The {@code FloatComplex}s.
* @return The converted {@code T_COMPLEX}s are returned.
*/
private static T_COMPLEX[] toODSFloatComplexSeq(FloatComplex[] input) {
@@ -866,7 +991,8 @@
/**
* Converts given {@link FloatComplex} to {@link T_COMPLEX}.
*
- * @param input The {@code FloatComplex}.
+ * @param input
+ * The {@code FloatComplex}.
* @return The converted {@code T_COMPLEX} is returned.
*/
private static T_COMPLEX toODSFloatComplex(FloatComplex input) {
@@ -876,13 +1002,14 @@
/**
* Converts given {@link T_DCOMPLEX[]} to {@link DoubleComplex[]}.
*
- * @param input The {@code T_DCOMPLEX}s.
+ * @param input
+ * The {@code T_DCOMPLEX}s.
* @return The converted {@code DoubleComplex}s are returned.
*/
private static DoubleComplex[] fromODSDoubleComplexSeq(T_DCOMPLEX[] input) {
List<DoubleComplex> result = new ArrayList<>();
- if(input != null) {
- for(T_DCOMPLEX value : input) {
+ if (input != null) {
+ for (T_DCOMPLEX value : input) {
result.add(fromODSDoubleComplex(value));
}
}
@@ -893,7 +1020,8 @@
/**
* Converts given {@link T_DCOMPLEX} to {@link DoubleComplex}.
*
- * @param input The {@code T_DCOMPLEX}.
+ * @param input
+ * The {@code T_DCOMPLEX}.
* @return The converted {@code DoubleComplex} is returned.
*/
private static DoubleComplex fromODSDoubleComplex(T_DCOMPLEX input) {
@@ -903,7 +1031,8 @@
/**
* Converts given {@link DoubleComplex[]} to {@link T_DCOMPLEX[]}.
*
- * @param input The {@code DoubleComplex}s.
+ * @param input
+ * The {@code DoubleComplex}s.
* @return The converted {@code T_DCOMPLEX}s are returned.
*/
private static T_DCOMPLEX[] toODSDoubleComplexSeq(DoubleComplex[] input) {
@@ -918,7 +1047,8 @@
/**
* Converts given {@link DoubleComplex} to {@link T_DCOMPLEX}.
*
- * @param input The {@code DoubleComplex}.
+ * @param input
+ * The {@code DoubleComplex}.
* @return The converted {@code T_DCOMPLEX} is returned.
*/
private static T_DCOMPLEX toODSDoubleComplex(DoubleComplex input) {
@@ -928,13 +1058,14 @@
/**
* Converts given {@link T_ExternalReference[]} to {@link FileLink[]}.
*
- * @param input The {@code T_ExternalReference}s.
+ * @param input
+ * The {@code T_ExternalReference}s.
* @return The converted {@code FileLink}s are returned.
*/
private static FileLink[] fromODSExternalReferenceSeq(T_ExternalReference[] input) {
List<FileLink> result = new ArrayList<>();
- if(input != null) {
- for(T_ExternalReference value : input) {
+ if (input != null) {
+ for (T_ExternalReference value : input) {
result.add(fromODSExternalReference(value));
}
}
@@ -945,11 +1076,12 @@
/**
* Converts given {@link T_ExternalReference} to {@link FileLink}.
*
- * @param input The {@code T_ExternalReference}.
+ * @param input
+ * The {@code T_ExternalReference}.
* @return The converted {@code FileLink} is returned.
*/
private static FileLink fromODSExternalReference(T_ExternalReference input) {
- if(input == null) {
+ if (input == null) {
return null;
}
return FileLink.newRemote(input.location, new MimeType(input.mimeType), input.description);
@@ -958,7 +1090,8 @@
/**
* Converts given {@link FileLink[]} to {@link T_ExternalReference[]}.
*
- * @param input The {@code FileLink}s.
+ * @param input
+ * The {@code FileLink}s.
* @return The converted {@code T_ExternalReference}s are returned.
*/
private static T_ExternalReference[] toODSExternalReferenceSeq(FileLink[] input) {
@@ -973,11 +1106,12 @@
/**
* Converts given {@link FileLink} to {@link T_ExternalReference}.
*
- * @param input The {@code FileLink}.
+ * @param input
+ * The {@code FileLink}.
* @return The converted {@code T_ExternalReference} is returned.
*/
private static T_ExternalReference toODSExternalReference(FileLink input) {
- if(input == null) {
+ if (input == null) {
return new T_ExternalReference("", "", "");
}
return new T_ExternalReference(input.getDescription(), input.getMimeType().toString(), input.getRemotePath());
@@ -986,7 +1120,8 @@
/**
* Converts given {@link Blob} to {@link Object}.
*
- * @param input The {@code Blob}
+ * @param input
+ * The {@code Blob}
* @return The converted {@code Object} is returned.
*/
private static Object fromODSBlob(Blob input) {
@@ -996,7 +1131,8 @@
/**
* Converts given object to {@link Blob}.
*
- * @param input The object.
+ * @param input
+ * The object.
* @return The converted {@code Blob} is returned.
*/
private static Blob toODSBlob(Object input) {
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSEnumerations.java b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSEnumerations.java
index f1c3bc1..7c0a266 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSEnumerations.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSEnumerations.java
@@ -45,7 +45,8 @@
/**
* Constructor.
*/
- private ODSEnumerations() {}
+ private ODSEnumerations() {
+ }
// ======================================================================
// Public methods
@@ -54,24 +55,27 @@
/**
* Returns the enumeration class identified by given name.
*
- * @param <E> The enumeration type.
- * @param name The ODS name of the requested enumeration class.
+ * @param <E>
+ * The enumeration type.
+ * @param name
+ * The ODS name of the requested enumeration class.
* @return The corresponding enumeration class is returned.
- * @throws IllegalArgumentException Thrown if ODS enumeration name is unknown.
+ * @throws IllegalArgumentException
+ * Thrown if ODS enumeration name is unknown.
*/
@SuppressWarnings("unchecked")
public static <E extends Enum<?>> Class<E> getEnumClass(String name) {
- if(SCALAR_TYPE_NAME.equals(name)) {
+ if (SCALAR_TYPE_NAME.equals(name)) {
return (Class<E>) ScalarType.class;
- } else if(STATE_NAME.equals(name)) {
+ } else if (STATE_NAME.equals(name)) {
return (Class<E>) VersionState.class;
- } else if(INTERPOLATION_NAME.equals(name)) {
+ } else if (INTERPOLATION_NAME.equals(name)) {
return (Class<E>) Interpolation.class;
- } else if(AXIS_TYPE_NAME.equals(name)) {
+ } else if (AXIS_TYPE_NAME.equals(name)) {
return (Class<E>) AxisType.class;
- } else if(TYPE_SPECIFICATION_NAME.equals(name)) {
+ } else if (TYPE_SPECIFICATION_NAME.equals(name)) {
return (Class<E>) TypeSpecification.class;
- } else if(SEQUENCE_REPRESENTATION_NAME.equals(name)) {
+ } else if (SEQUENCE_REPRESENTATION_NAME.equals(name)) {
return (Class<E>) SequenceRepresentation.class;
}
@@ -81,29 +85,31 @@
/**
* Returns the ODS enumeration name for given enumeration class.
*
- * @param enumClass The enumeration class name.
+ * @param enumClass
+ * The enumeration class name.
* @return The corresponding ODS enumeration name is returned.
- * @throws IllegalArgumentException Thrown if enumeration class is unknown.
+ * @throws IllegalArgumentException
+ * Thrown if enumeration class is unknown.
*/
public static String getEnumName(Class<? extends Enum<?>> enumClass) {
- if(enumClass == null) {
+ if (enumClass == null) {
throw new IllegalArgumentException("Enumeration class is not allowed to be null.");
- } else if(ScalarType.class == enumClass) {
+ } else if (ScalarType.class == enumClass) {
return SCALAR_TYPE_NAME;
- } else if(VersionState.class == enumClass) {
+ } else if (VersionState.class == enumClass) {
return STATE_NAME;
- } else if(Interpolation.class == enumClass) {
+ } else if (Interpolation.class == enumClass) {
return INTERPOLATION_NAME;
- } else if(AxisType.class == enumClass) {
+ } else if (AxisType.class == enumClass) {
return AXIS_TYPE_NAME;
- } else if(TypeSpecification.class == enumClass) {
+ } else if (TypeSpecification.class == enumClass) {
return TYPE_SPECIFICATION_NAME;
- } else if(SequenceRepresentation.class == enumClass) {
+ } else if (SequenceRepresentation.class == enumClass) {
return SEQUENCE_REPRESENTATION_NAME;
}
- throw new IllegalArgumentException("Enumeration mapping for enumeration class '" +
- enumClass.getSimpleName() + "' does not exist.");
+ throw new IllegalArgumentException(
+ "Enumeration mapping for enumeration class '" + enumClass.getSimpleName() + "' does not exist.");
}
// ======================================================================
@@ -111,128 +117,146 @@
// ======================================================================
/**
- * Converts given ODS enumeration value using given enumeration class to
- * the corresponding enumeration constant.
+ * Converts given ODS enumeration value using given enumeration class to the
+ * corresponding enumeration constant.
*
- * @param <E> The enumeration type.
- * @param enumClass The enumeration class.
- * @param value The ODS enumeration value.
+ * @param <E>
+ * The enumeration type.
+ * @param enumClass
+ * The enumeration class.
+ * @param value
+ * The ODS enumeration value.
* @return The corresponding enumeration constant is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
@SuppressWarnings("unchecked")
static <E extends Enum<?>> E fromODSEnum(Class<E> enumClass, int value) {
- if(enumClass == null) {
+ if (enumClass == null) {
throw new IllegalArgumentException("Enumeration class is not allowed to be null.");
- } else if(ScalarType.class == enumClass) {
+ } else if (ScalarType.class == enumClass) {
return (E) fromODSScalarType(value);
- } else if(VersionState.class == enumClass) {
+ } else if (VersionState.class == enumClass) {
return (E) fromODSEnumByOrdinal(VersionState.class, value);
- } else if(Interpolation.class == enumClass) {
+ } else if (Interpolation.class == enumClass) {
return (E) fromODSEnumByOrdinal(Interpolation.class, value);
- } else if(AxisType.class == enumClass) {
+ } else if (AxisType.class == enumClass) {
return (E) fromODSEnumByOrdinal(AxisType.class, value);
- } else if(TypeSpecification.class == enumClass) {
+ } else if (TypeSpecification.class == enumClass) {
return (E) fromODSEnumByOrdinal(TypeSpecification.class, value);
- } else if(SequenceRepresentation.class == enumClass) {
+ } else if (SequenceRepresentation.class == enumClass) {
return (E) fromODSSequenceRepresentation(value);
}
- throw new IllegalArgumentException("Enumeration mapping for type '" + enumClass.getSimpleName() + "' does not exist.");
+ throw new IllegalArgumentException(
+ "Enumeration mapping for type '" + enumClass.getSimpleName() + "' does not exist.");
}
/**
* Converts given ODS enumeration values using given enumeration class to
* the corresponding enumeration constants.
*
- * @param <E> The enumeration type.
- * @param enumClass The enumeration class.
- * @param values The ODS enumeration values.
+ * @param <E>
+ * The enumeration type.
+ * @param enumClass
+ * The enumeration class.
+ * @param values
+ * The ODS enumeration values.
* @return The corresponding enumeration constants are returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
@SuppressWarnings("unchecked")
static <E extends Enum<?>> E[] fromODSEnumSeq(Class<E> enumClass, int[] values) {
- if(enumClass == null) {
+ if (enumClass == null) {
throw new IllegalArgumentException("Enumeration class is not allowed to be null.");
- } else if(ScalarType.class == enumClass) {
+ } else if (ScalarType.class == enumClass) {
List<E> scalarTypes = new ArrayList<>(values.length);
- for(int value : values) {
+ for (int value : values) {
scalarTypes.add((E) fromODSScalarType(value));
}
return (E[]) scalarTypes.toArray(new ScalarType[values.length]);
- } else if(VersionState.class == enumClass) {
+ } else if (VersionState.class == enumClass) {
return (E[]) fromODSEnumSeqByOrdinal(VersionState.class, values);
- } else if(Interpolation.class == enumClass) {
+ } else if (Interpolation.class == enumClass) {
return (E[]) fromODSEnumSeqByOrdinal(Interpolation.class, values);
- } else if(AxisType.class == enumClass) {
+ } else if (AxisType.class == enumClass) {
return (E[]) fromODSEnumSeqByOrdinal(AxisType.class, values);
- } else if(TypeSpecification.class == enumClass) {
+ } else if (TypeSpecification.class == enumClass) {
return (E[]) fromODSEnumSeqByOrdinal(TypeSpecification.class, values);
- } else if(SequenceRepresentation.class == enumClass) {
+ } else if (SequenceRepresentation.class == enumClass) {
List<E> sequenceRepresentations = new ArrayList<>(values.length);
- for(int value : values) {
+ for (int value : values) {
sequenceRepresentations.add((E) fromODSSequenceRepresentation(value));
}
return (E[]) sequenceRepresentations.toArray(new SequenceRepresentation[values.length]);
}
- throw new IllegalArgumentException("Enumeration mapping for type '" + enumClass.getSimpleName() + "' does not exist.");
+ throw new IllegalArgumentException(
+ "Enumeration mapping for type '" + enumClass.getSimpleName() + "' does not exist.");
}
/**
* Converts given enumeration constant to the corresponding ODS enumeration
* value.
*
- * @param <E> The enumeration type.
- * @param constant The enumeration constant.
+ * @param <E>
+ * The enumeration type.
+ * @param constant
+ * The enumeration constant.
* @return The corresponding ODS enumeration value is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
static <E extends Enum<?>> int toODSEnum(E constant) {
- if(constant == null) {
+ if (constant == null) {
return 0;
- } else if(constant instanceof ScalarType) {
+ } else if (constant instanceof ScalarType) {
return toODSScalarType((ScalarType) constant);
- } else if(constant instanceof VersionState || constant instanceof Interpolation
- || constant instanceof AxisType || constant instanceof TypeSpecification) {
- //NOTE: Ordinal numbers map directly to the corresponding ODS enumeration constant value.
+ } else if (constant instanceof VersionState || constant instanceof Interpolation || constant instanceof AxisType
+ || constant instanceof TypeSpecification) {
+ // NOTE: Ordinal numbers map directly to the corresponding ODS
+ // enumeration constant value.
return ((Enum<?>) constant).ordinal();
- } else if(constant instanceof SequenceRepresentation) {
+ } else if (constant instanceof SequenceRepresentation) {
return toODSSequenceRepresentation((SequenceRepresentation) constant);
}
- throw new IllegalArgumentException("Enumeration mapping for type '"
- + constant.getClass().getSimpleName() + "' does not exist.");
+ throw new IllegalArgumentException(
+ "Enumeration mapping for type '" + constant.getClass().getSimpleName() + "' does not exist.");
}
/**
- * Converts given enumeration constants to the corresponding ODS
- * enumeration values.
+ * Converts given enumeration constants to the corresponding ODS enumeration
+ * values.
*
- * @param <E> The enumeration type.
- * @param constants The enumeration constants.
+ * @param <E>
+ * The enumeration type.
+ * @param constants
+ * The enumeration constants.
* @return The corresponding ODS enumeration values are returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
static <E extends Enum<?>> int[] toODSEnumSeq(E[] constants) {
- if(constants == null) {
+ if (constants == null) {
return new int[0];
}
int[] values = new int[constants.length];
- if(constants instanceof ScalarType[]) {
- for(int i = 0; i < values.length; i++) {
+ if (constants instanceof ScalarType[]) {
+ for (int i = 0; i < values.length; i++) {
values[i] = toODSScalarType((ScalarType) constants[i]);
}
- } else if(constants instanceof VersionState[] || constants instanceof Interpolation[]
+ } else if (constants instanceof VersionState[] || constants instanceof Interpolation[]
|| constants instanceof AxisType[] || constants instanceof TypeSpecification[]) {
- for(int i = 0; i < values.length; i++) {
- //NOTE: Ordinal numbers directly map to the corresponding ODS enumeration constant value.
+ for (int i = 0; i < values.length; i++) {
+ // NOTE: Ordinal numbers directly map to the corresponding ODS
+ // enumeration constant value.
values[i] = ((Enum<?>) constants[i]).ordinal();
}
- } else if(constants instanceof SequenceRepresentation[]) {
- for(int i = 0; i < values.length; i++) {
+ } else if (constants instanceof SequenceRepresentation[]) {
+ for (int i = 0; i < values.length; i++) {
values[i] = toODSSequenceRepresentation((SequenceRepresentation) constants[i]);
}
} else {
@@ -248,45 +272,47 @@
// ======================================================================
/**
- * Converts given ODS enumeration value to the corresponding {@link
- * ScalarType} constant.
+ * Converts given ODS enumeration value to the corresponding
+ * {@link ScalarType} constant.
*
- * @param value The ODS enumeration value.
+ * @param value
+ * The ODS enumeration value.
* @return The corresponding {@code ScalarType} constant is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
private static ScalarType fromODSScalarType(int value) {
- if(value == 0) {
+ if (value == 0) {
return ScalarType.UNKNOWN;
- } else if(value == 1) {
+ } else if (value == 1) {
return ScalarType.STRING;
- } else if(value == 2) {
+ } else if (value == 2) {
return ScalarType.SHORT;
- } else if(value == 3) {
+ } else if (value == 3) {
return ScalarType.FLOAT;
- } else if(value == 4) {
+ } else if (value == 4) {
return ScalarType.BOOLEAN;
- } else if(value == 5) {
+ } else if (value == 5) {
return ScalarType.BYTE;
- } else if(value == 6) {
+ } else if (value == 6) {
return ScalarType.INTEGER;
- } else if(value == 7) {
+ } else if (value == 7) {
return ScalarType.DOUBLE;
- } else if(value == 8) {
+ } else if (value == 8) {
return ScalarType.LONG;
- } else if(value == 10) {
+ } else if (value == 10) {
return ScalarType.DATE;
- } else if(value == 11) {
+ } else if (value == 11) {
return ScalarType.BYTE_STREAM;
- } else if(value == 12) {
+ } else if (value == 12) {
return ScalarType.BLOB;
- } else if(value == 13) {
+ } else if (value == 13) {
return ScalarType.FLOAT_COMPLEX;
- } else if(value == 14) {
+ } else if (value == 14) {
return ScalarType.DOUBLE_COMPLEX;
- } else if(value == 28) {
+ } else if (value == 28) {
return ScalarType.FILE_LINK;
- } else if(value == 30) {
+ } else if (value == 30) {
return ScalarType.ENUMERATION;
}
@@ -298,80 +324,84 @@
* Converts given {@link ScalarType} to the corresponding ODS enumeration
* value.
*
- * @param scalarType The {@code ScalarType}.
+ * @param scalarType
+ * The {@code ScalarType}.
* @return The corresponding ODS enumeration value is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
private static int toODSScalarType(ScalarType scalarType) {
- if(ScalarType.UNKNOWN == scalarType) {
+ if (ScalarType.UNKNOWN == scalarType) {
return 0;
- } else if(ScalarType.STRING == scalarType) {
+ } else if (ScalarType.STRING == scalarType) {
return 1;
- } else if(ScalarType.SHORT == scalarType) {
+ } else if (ScalarType.SHORT == scalarType) {
return 2;
- } else if(ScalarType.FLOAT == scalarType) {
+ } else if (ScalarType.FLOAT == scalarType) {
return 3;
- } else if(ScalarType.BOOLEAN == scalarType) {
+ } else if (ScalarType.BOOLEAN == scalarType) {
return 4;
- } else if(ScalarType.BYTE == scalarType) {
+ } else if (ScalarType.BYTE == scalarType) {
return 5;
- } else if(ScalarType.INTEGER == scalarType) {
+ } else if (ScalarType.INTEGER == scalarType) {
return 6;
- } else if(ScalarType.DOUBLE == scalarType) {
+ } else if (ScalarType.DOUBLE == scalarType) {
return 7;
- } else if(ScalarType.LONG == scalarType) {
+ } else if (ScalarType.LONG == scalarType) {
return 8;
- } else if(ScalarType.DATE == scalarType) {
+ } else if (ScalarType.DATE == scalarType) {
return 10;
- } else if(ScalarType.BYTE_STREAM == scalarType) {
+ } else if (ScalarType.BYTE_STREAM == scalarType) {
return 11;
- } else if(ScalarType.BLOB == scalarType) {
+ } else if (ScalarType.BLOB == scalarType) {
return 12;
- } else if(ScalarType.FLOAT_COMPLEX == scalarType) {
+ } else if (ScalarType.FLOAT_COMPLEX == scalarType) {
return 13;
- } else if(ScalarType.DOUBLE_COMPLEX == scalarType) {
+ } else if (ScalarType.DOUBLE_COMPLEX == scalarType) {
return 14;
- } else if(ScalarType.FILE_LINK == scalarType) {
+ } else if (ScalarType.FILE_LINK == scalarType) {
return 28;
- } else if(ScalarType.ENUMERATION == scalarType) {
+ } else if (ScalarType.ENUMERATION == scalarType) {
return 30;
}
- throw new IllegalArgumentException("Unable to map enumeration constant '" + scalarType
- + "' of type '" + ScalarType.class.getSimpleName() + "' to ODS enumeration value.");
+ throw new IllegalArgumentException("Unable to map enumeration constant '" + scalarType + "' of type '"
+ + ScalarType.class.getSimpleName() + "' to ODS enumeration value.");
}
/**
- * Converts given ODS enumeration value to the corresponding {@link
- * SequenceRepresentation} constant.
+ * Converts given ODS enumeration value to the corresponding
+ * {@link SequenceRepresentation} constant.
*
- * @param value The ODS enumeration value.
+ * @param value
+ * The ODS enumeration value.
* @return The corresponding {@code SequenceRepresentation} constant is
- * returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * returned.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
private static SequenceRepresentation fromODSSequenceRepresentation(int value) {
- if(value == 0) {
+ if (value == 0) {
return SequenceRepresentation.EXPLICIT;
- } else if(value == 1) {
+ } else if (value == 1) {
return SequenceRepresentation.IMPLICIT_CONSTANT;
- } else if(value == 2) {
+ } else if (value == 2) {
return SequenceRepresentation.IMPLICIT_LINEAR;
- } else if(value == 3) {
+ } else if (value == 3) {
return SequenceRepresentation.IMPLICIT_SAW;
- } else if(value == 4) {
+ } else if (value == 4) {
return SequenceRepresentation.RAW_LINEAR;
- } else if(value == 5) {
+ } else if (value == 5) {
return SequenceRepresentation.RAW_POLYNOMIAL;
- } else if(value == 7) {
+ } else if (value == 7) {
return SequenceRepresentation.EXPLICIT_EXTERNAL;
- } else if(value == 8) {
+ } else if (value == 8) {
return SequenceRepresentation.RAW_LINEAR_EXTERNAL;
- } else if(value == 9) {
+ } else if (value == 9) {
return SequenceRepresentation.RAW_POLYNOMIAL_EXTERNAL;
- } else if(value == 10) {
+ } else if (value == 10) {
return SequenceRepresentation.RAW_LINEAR_CALIBRATED;
- } else if(value == 11) {
+ } else if (value == 11) {
return SequenceRepresentation.RAW_LINEAR_CALIBRATED_EXTERNAL;
}
@@ -383,32 +413,34 @@
* Converts given {@link SequenceRepresentation} to the corresponding ODS
* enumeration value.
*
- * @param sequenceRepresentation The {@code SequenceRepresentation}.
+ * @param sequenceRepresentation
+ * The {@code SequenceRepresentation}.
* @return The corresponding ODS enumeration value is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
private static int toODSSequenceRepresentation(SequenceRepresentation sequenceRepresentation) {
- if(SequenceRepresentation.EXPLICIT == sequenceRepresentation) {
+ if (SequenceRepresentation.EXPLICIT == sequenceRepresentation) {
return 0;
- } else if(SequenceRepresentation.IMPLICIT_CONSTANT == sequenceRepresentation) {
+ } else if (SequenceRepresentation.IMPLICIT_CONSTANT == sequenceRepresentation) {
return 1;
- } else if(SequenceRepresentation.IMPLICIT_LINEAR == sequenceRepresentation) {
+ } else if (SequenceRepresentation.IMPLICIT_LINEAR == sequenceRepresentation) {
return 2;
- } else if(SequenceRepresentation.IMPLICIT_SAW == sequenceRepresentation) {
+ } else if (SequenceRepresentation.IMPLICIT_SAW == sequenceRepresentation) {
return 3;
- } else if(SequenceRepresentation.RAW_LINEAR == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_LINEAR == sequenceRepresentation) {
return 4;
- } else if(SequenceRepresentation.RAW_POLYNOMIAL == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_POLYNOMIAL == sequenceRepresentation) {
return 5;
- } else if(SequenceRepresentation.EXPLICIT_EXTERNAL == sequenceRepresentation) {
+ } else if (SequenceRepresentation.EXPLICIT_EXTERNAL == sequenceRepresentation) {
return 7;
- } else if(SequenceRepresentation.RAW_LINEAR_EXTERNAL == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_LINEAR_EXTERNAL == sequenceRepresentation) {
return 8;
- } else if(SequenceRepresentation.RAW_POLYNOMIAL_EXTERNAL == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_POLYNOMIAL_EXTERNAL == sequenceRepresentation) {
return 9;
- } else if(SequenceRepresentation.RAW_LINEAR_CALIBRATED == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_LINEAR_CALIBRATED == sequenceRepresentation) {
return 10;
- } else if(SequenceRepresentation.RAW_LINEAR_CALIBRATED_EXTERNAL == sequenceRepresentation) {
+ } else if (SequenceRepresentation.RAW_LINEAR_CALIBRATED_EXTERNAL == sequenceRepresentation) {
return 11;
}
@@ -421,20 +453,25 @@
* constant. The ODS enumeration value is used as the ordinal number of the
* requested enumeration constant.
*
- * @param <E> The enumeration type.
- * @param enumClass The enumeration class.
- * @param value The ODS enumeration value.
+ * @param <E>
+ * The enumeration type.
+ * @param enumClass
+ * The enumeration class.
+ * @param value
+ * The ODS enumeration value.
* @return The corresponding enumeration constant is returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
private static <E extends Enum<?>> E fromODSEnumByOrdinal(Class<E> enumClass, int value) {
E[] constants = enumClass.getEnumConstants();
- if(value < 0 || value > constants.length) {
+ if (value < 0 || value > constants.length) {
throw new IllegalArgumentException("Unable to map ODS enumeration vaue '" + value
+ "' to constant of type '" + enumClass.getSimpleName() + "'.");
}
- //NOTE: Ordinal numbers directly map to the corresponding ODS enumeration constant value.
+ // NOTE: Ordinal numbers directly map to the corresponding ODS
+ // enumeration constant value.
return constants[value];
}
@@ -443,24 +480,29 @@
* constants. The ODS enumeration values are used as the ordinal numbers of
* the requested enumeration constants.
*
- * @param <E> The enumeration type.
- * @param enumClass The enumeration class.
- * @param values The ODS enumeration values.
+ * @param <E>
+ * The enumeration type.
+ * @param enumClass
+ * The enumeration class.
+ * @param values
+ * The ODS enumeration values.
* @return The corresponding enumeration constants are returned.
- * @throws IllegalArgumentException Thrown if conversion not possible.
+ * @throws IllegalArgumentException
+ * Thrown if conversion not possible.
*/
@SuppressWarnings("unchecked")
private static <E extends Enum<?>> E[] fromODSEnumSeqByOrdinal(Class<E> enumClass, int[] values) {
List<E> enumValues = new ArrayList<>(values.length);
E[] constants = enumClass.getEnumConstants();
- for(int value : values) {
- if(value < 0 || value > constants.length) {
- throw new IllegalArgumentException("Unable to map ODS enumeration vaue '" + value + "' to constant of type '"
- + enumClass.getSimpleName() + "'.");
+ for (int value : values) {
+ if (value < 0 || value > constants.length) {
+ throw new IllegalArgumentException("Unable to map ODS enumeration vaue '" + value
+ + "' to constant of type '" + enumClass.getSimpleName() + "'.");
}
- //NOTE: Ordinal numbers directly map to the corresponding ODS enumeration constant value.
+ // NOTE: Ordinal numbers directly map to the corresponding ODS
+ // enumeration constant value.
enumValues.add(constants[value]);
}
diff --git a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSUtils.java b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSUtils.java
index 6ac8c6a..df5b335 100644
--- a/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSUtils.java
+++ b/src/main/java/org/eclipse/mdm/api/odsadapter/utils/ODSUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Gigatronik Ingolstadt GmbH
+ * Copyright (c) 2016 Gigatronik Ingolstadt GmbH and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -153,4 +153,7 @@
JOINS.addMappings(Join.OUTER, org.asam.ods.JoinType.JTOUTER);
}
+ public static boolean isValidID(String instanceID) {
+ return instanceID != null && !instanceID.isEmpty() && !"0".equals(instanceID);
+ }
}
diff --git a/src/test/java/org/eclipse/mdm/api/odsadapter/JoinTest.java b/src/test/java/org/eclipse/mdm/api/odsadapter/JoinTest.java
index 84c6edb..ad64fa6 100644
--- a/src/test/java/org/eclipse/mdm/api/odsadapter/JoinTest.java
+++ b/src/test/java/org/eclipse/mdm/api/odsadapter/JoinTest.java
@@ -33,6 +33,7 @@
import org.eclipse.mdm.api.dflt.model.EntityFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,6 +43,9 @@
* @since 1.0.0
* @author jst, Peak Solution GmbH
*/
+@Ignore
+// FIXME 10.7.2017: this test needs a running ODS Server, that is not suitable for continous build in Jenkins.
+// Comment this in for local tests only.
public class JoinTest {
private static final Logger LOGGER = LoggerFactory.getLogger(JoinTest.class);
@@ -59,16 +63,16 @@
String nameServicePort = System.getProperty("port");
String serviceName = System.getProperty("service");
- if(nameServiceHost == null || nameServiceHost.isEmpty()) {
+ if (nameServiceHost == null || nameServiceHost.isEmpty()) {
throw new IllegalArgumentException("name service host is unknown: define system property 'host'");
}
- nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
- if(nameServicePort == null || nameServicePort.isEmpty()) {
+ nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
+ if (nameServicePort == null || nameServicePort.isEmpty()) {
throw new IllegalArgumentException("name service port is unknown: define system property 'port'");
}
- if(serviceName == null || serviceName.isEmpty()) {
+ if (serviceName == null || serviceName.isEmpty()) {
throw new IllegalArgumentException("service name is unknown: define system property 'service'");
}
@@ -82,227 +86,205 @@
entityFactory = entityManager.getEntityFactory()
.orElseThrow(() -> new IllegalStateException("Entity manager factory not available."));
}
-
+
@AfterClass
public static void tearDownAfterClass() throws ConnectionException {
- if(entityManager != null) {
+ if (entityManager != null) {
entityManager.close();
}
}
-
@org.junit.Test
public void findTestFromTestStepId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(TestStep.class);
-
-
- List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, 37L));
-
+
+ List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, "37"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestFromMeasurementId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Measurement.class);
-
-
- List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, 65L));
-
+
+ List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, "65"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestFromChannelGroupId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(ChannelGroup.class);
-
-
- List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, 80L));
-
+
+ List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, "80"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestFromChannelId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Channel.class);
-
-
- List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, 302L));
-
+
+ List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, "302"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
-
-
+
@org.junit.Test
public void findTestStepFromTestId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Test.class);
-
-
- List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, 28L));
-
+
+ List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, "28"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestStepFromMeasurementId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Measurement.class);
-
-
- List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, 65L));
-
+
+ List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, "65"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestStepFromChannelGroupId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(ChannelGroup.class);
-
-
- List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, 80L));
-
+
+ List<Test> list = searchService.fetch(Test.class, Filter.idOnly(et, "80"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findTestStepFromChannelId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Channel.class);
-
-
- List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, 302L));
-
+
+ List<TestStep> list = searchService.fetch(TestStep.class, Filter.idOnly(et, "302"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
-
@org.junit.Test
public void findMeasurementFromTestId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Test.class);
-
-
- List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, 28L));
-
+
+ List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, "28"));
+
assertEquals(9, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findMeasurementFromTestStepId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(TestStep.class);
-
-
- List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, 37L));
-
+
+ List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, "37"));
+
assertEquals(9, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findMeasurementFromChannelGroupId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(ChannelGroup.class);
-
-
- List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, 80L));
-
+
+ List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, "80"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findMeasurementFromChannelId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Channel.class);
-
-
- List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, 302L));
-
+
+ List<Measurement> list = searchService.fetch(Measurement.class, Filter.idOnly(et, "302"));
+
assertEquals(1, list.size());
System.out.println(list.size());
}
-
-
@org.junit.Test
public void findChannelGroupFromTestId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Test.class);
-
-
- List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, 28L));
-
+
+ List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, "28"));
+
assertEquals(14, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findChannelGroupFromTestStepId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(TestStep.class);
-
-
- List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, 37L));
-
+
+ List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, "37"));
+
assertEquals(14, list.size());
System.out.println(list.size());
- }
-
+ }
+
@org.junit.Test
public void findChannelGroupFromMeasurementId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Measurement.class);
-
-
- List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, 65L));
-
+
+ List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, "65"));
+
assertEquals(2, list.size());
System.out.println(list.size());
}
@@ -313,71 +295,63 @@
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Channel.class);
-
-
- List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, 302L));
-
+
+ List<ChannelGroup> list = searchService.fetch(ChannelGroup.class, Filter.idOnly(et, "302"));
+
assertEquals(2, list.size());
System.out.println(list.size());
}
-
-
-
+
@org.junit.Test
public void findChannelFromTestId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
-
+
EntityType et = modelManager.getEntityType(Test.class);
-
-
- List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, 28L));
-
+
+ List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, "28"));
+
assertEquals(43, list.size());
System.out.println(list.size());
}
-
+
@org.junit.Test
public void findChannelFromTestStepId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(TestStep.class);
-
-
- List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, 37L));
-
+
+ List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, "37"));
+
assertEquals(43, list.size());
System.out.println(list.size());
- }
-
+ }
+
@org.junit.Test
public void findChannelFromMeasurementId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(Measurement.class);
-
-
- List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, 65L));
-
+
+ List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, "65"));
+
assertEquals(2, list.size());
System.out.println(list.size());
- }
-
+ }
+
@org.junit.Test
public void findChannelFromChannelGroupId() throws DataAccessException {
ModelManager modelManager = entityManager.getModelManager().get();
SearchService searchService = entityManager.getSearchService().get();
EntityType et = modelManager.getEntityType(ChannelGroup.class);
-
-
- List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, 80L));
-
+
+ List<Channel> list = searchService.fetch(Channel.class, Filter.idOnly(et, "80"));
+
assertEquals(2, list.size());
System.out.println(list.size());
- }
-
-
+ }
+
}
diff --git a/src/test/java/org/eclipse/mdm/api/odsadapter/ODSAdapterTest.java b/src/test/java/org/eclipse/mdm/api/odsadapter/ODSAdapterTest.java
index 8482b43..e04002e 100644
--- a/src/test/java/org/eclipse/mdm/api/odsadapter/ODSAdapterTest.java
+++ b/src/test/java/org/eclipse/mdm/api/odsadapter/ODSAdapterTest.java
@@ -51,18 +51,21 @@
import org.eclipse.mdm.api.dflt.model.TemplateTestStep;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Ignore
+// FIXME 10.7.2017: this test needs a running ODS Server, that is not suitable for continous build in Jenkins.
+// Comment this in for local tests only.
public class ODSAdapterTest {
/*
- * ATTENTION:
- * ==========
+ * ATTENTION: ==========
*
- * To run this test make sure the target service is running a
- * MDM default model and any database constraint which enforces
- * a relation of Test to a parent entity is deactivated!
+ * To run this test make sure the target service is running a MDM default
+ * model and any database constraint which enforces a relation of Test to a
+ * parent entity is deactivated!
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ODSAdapterTest.class);
@@ -81,16 +84,16 @@
String nameServicePort = System.getProperty("port");
String serviceName = System.getProperty("service");
- if(nameServiceHost == null || nameServiceHost.isEmpty()) {
+ if (nameServiceHost == null || nameServiceHost.isEmpty()) {
throw new IllegalArgumentException("name service host is unknown: define system property 'host'");
}
- nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
- if(nameServicePort == null || nameServicePort.isEmpty()) {
+ nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
+ if (nameServicePort == null || nameServicePort.isEmpty()) {
throw new IllegalArgumentException("name service port is unknown: define system property 'port'");
}
- if(serviceName == null || serviceName.isEmpty()) {
+ if (serviceName == null || serviceName.isEmpty()) {
throw new IllegalArgumentException("service name is unknown: define system property 'service'");
}
@@ -107,7 +110,7 @@
@AfterClass
public static void tearDownAfterClass() throws ConnectionException {
- if(entityManager != null) {
+ if (entityManager != null) {
entityManager.close();
}
}
@@ -122,7 +125,6 @@
Unit unit = entityFactory.createUnit("any_unit", physicalDimension);
Quantity quantity = entityFactory.createQuantity("any_quantity", unit);
-
Transaction transaction = entityManager.startTransaction();
try {
create(transaction, "catalog components", catalogComponents);
@@ -134,7 +136,7 @@
create(transaction, "quantity", Collections.singletonList(quantity));
transaction.commit();
- } catch(RuntimeException e) {
+ } catch (RuntimeException e) {
transaction.abort();
fail("Unable to create test data due to: " + e.getMessage());
}
@@ -142,14 +144,14 @@
List<Project> projects = Collections.emptyList();
try {
projects = createTestData(templateTest, quantity);
- } catch(DataAccessException | RuntimeException e) {
+ } catch (DataAccessException | RuntimeException e) {
e.printStackTrace();
}
transaction = entityManager.startTransaction();
try {
// delete in reverse order!
- if(!projects.isEmpty()) {
+ if (!projects.isEmpty()) {
delete(transaction, "projects and their children", projects);
}
@@ -162,12 +164,12 @@
delete(transaction, "catalog components", catalogComponents);
transaction.commit();
- } catch(RuntimeException e) {
+ } catch (RuntimeException e) {
transaction.abort();
fail("Unable to delete test data due to: " + e.getMessage());
}
- if(projects.isEmpty()) {
+ if (projects.isEmpty()) {
fail("Was unable to create test data.");
}
}
@@ -181,21 +183,22 @@
// create measurement test data
List<WriteRequest> writeRequests = new ArrayList<>();
- for(Test test : tests) {
- for(TestStep testStep : test.getCommissionedTestSteps()) {
+ for (Test test : tests) {
+ for (TestStep testStep : test.getCommissionedTestSteps()) {
Optional<TemplateTestStep> templateTestStep = TemplateTestStep.of(testStep);
ContextRoot[] contextRoots = new ContextRoot[0];
- if(templateTestStep.isPresent()) {
+ if (templateTestStep.isPresent()) {
contextRoots = templateTestStep.get().getTemplateRoots().stream()
.map(templateRoot -> entityFactory.createContextRoot(templateRoot))
.toArray(ContextRoot[]::new);
}
- for(int i = 1; i < 3; i++) {
- Measurement measurement = entityFactory.createMeasurement("measurement_" + i, testStep, contextRoots);
+ for (int i = 1; i < 3; i++) {
+ Measurement measurement = entityFactory.createMeasurement("measurement_" + i, testStep,
+ contextRoots);
// create channels
List<Channel> channels = new ArrayList<>();
- for(int j = 0; j < 9; j++) {
+ for (int j = 0; j < 9; j++) {
channels.add(entityFactory.createChannel("channel_ " + j, measurement, quantity));
}
@@ -214,7 +217,7 @@
transaction.writeMeasuredValues(writeRequests);
transaction.commit();
return Collections.singletonList(project);
- } catch(DataAccessException | RuntimeException e) {
+ } catch (DataAccessException | RuntimeException e) {
e.printStackTrace();
transaction.abort();
}
@@ -222,7 +225,8 @@
return Collections.emptyList();
}
- private List<WriteRequest> createMeasurementData(Measurement measurement, ChannelGroup channelGroup, List<Channel> channels) {
+ private List<WriteRequest> createMeasurementData(Measurement measurement, ChannelGroup channelGroup,
+ List<Channel> channels) {
// set length of the channel value sequence
List<WriteRequest> writeRequests = new ArrayList<>();
@@ -230,72 +234,56 @@
Collections.sort(channels, (c1, c2) -> c1.getName().compareTo(c2.getName()));
WriteRequestBuilder wrb = WriteRequest.create(channelGroup, channels.get(0), AxisType.X_AXIS);
- writeRequests.add(wrb
- .implicitLinear(ScalarType.FLOAT, 0, 1)
- .independent()
- .build());
+ writeRequests.add(wrb.implicitLinear(ScalarType.FLOAT, 0, 1).independent().build());
wrb = WriteRequest.create(channelGroup, channels.get(1), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .booleanValues(new boolean[] { true,true,false,true,true,false,true,false,false,false })
+ writeRequests.add(wrb.explicit()
+ .booleanValues(new boolean[] { true, true, false, true, true, false, true, false, false, false })
.build());
wrb = WriteRequest.create(channelGroup, channels.get(2), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .byteValues(new byte[] { 5,32,42,9,17,65,13,8,15,21 })
- .build());
+ writeRequests.add(wrb.explicit().byteValues(new byte[] { 5, 32, 42, 9, 17, 65, 13, 8, 15, 21 }).build());
wrb = WriteRequest.create(channelGroup, channels.get(3), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .integerValues(new int[] { 423,645,221,111,675,353,781,582,755,231 })
- .build());
+ writeRequests.add(
+ wrb.explicit().integerValues(new int[] { 423, 645, 221, 111, 675, 353, 781, 582, 755, 231 }).build());
wrb = WriteRequest.create(channelGroup, channels.get(4), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .stringValues(new String[] { "s1","s2","s3","s4","s5","s6","s7","s8","s9","s10" })
- .build());
+ writeRequests.add(wrb.explicit()
+ .stringValues(new String[] { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" }).build());
LocalDateTime now = LocalDateTime.now();
wrb = WriteRequest.create(channelGroup, channels.get(5), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .dateValues(new LocalDateTime[] { now,now.plusDays(1),now.plusDays(2),
- now.plusDays(3),now.plusDays(4),now.plusDays(5), now.plusDays(6),now.plusDays(7),
- now.plusDays(8),now.plusDays(9) })
- .build());
+ writeRequests
+ .add(wrb.explicit()
+ .dateValues(new LocalDateTime[] { now, now.plusDays(1), now.plusDays(2), now.plusDays(3),
+ now.plusDays(4), now.plusDays(5), now.plusDays(6), now.plusDays(7), now.plusDays(8),
+ now.plusDays(9) })
+ .build());
wrb = WriteRequest.create(channelGroup, channels.get(6), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .explicit()
- .byteStreamValues(new byte[][] {{1,2},{3,4,5},{6,7,8},{9,10},{11},{12,13,14},
- {15,16},{17,18,19,20},{21,22},{23} })
- .build());
+ writeRequests.add(wrb.explicit().byteStreamValues(new byte[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 9, 10 },
+ { 11 }, { 12, 13, 14 }, { 15, 16 }, { 17, 18, 19, 20 }, { 21, 22 }, { 23 } }).build());
wrb = WriteRequest.create(channelGroup, channels.get(7), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .implicitConstant(ScalarType.SHORT, Short.MAX_VALUE)
- .build());
+ writeRequests.add(wrb.implicitConstant(ScalarType.SHORT, Short.MAX_VALUE).build());
wrb = WriteRequest.create(channelGroup, channels.get(8), AxisType.Y_AXIS);
- writeRequests.add(wrb
- .implicitSaw(ScalarType.FLOAT, 0, 1, 4)
- .build());
+ writeRequests.add(wrb.implicitSaw(ScalarType.FLOAT, 0, 1, 4).build());
return writeRequests;
}
- private static void delete(Transaction transaction, String key, Collection<? extends Deletable> entities) throws DataAccessException {
+ private static void delete(Transaction transaction, String key, Collection<? extends Deletable> entities)
+ throws DataAccessException {
LOGGER.info(">>>>>>>>>>>>>>>>> deleting " + key + "...");
long start = System.currentTimeMillis();
transaction.delete(entities);
LOGGER.info(">>>>>>>>>>>>>>>>> " + key + " deleted in " + (System.currentTimeMillis() - start) + " ms");
}
- private static void create(Transaction transaction, String key, Collection<? extends Entity> entities) throws DataAccessException {
+ private static void create(Transaction transaction, String key, Collection<? extends Entity> entities)
+ throws DataAccessException {
LOGGER.info(">>>>>>>>>>>>>>>>> creating " + key + "...");
long start = System.currentTimeMillis();
transaction.create(entities);
@@ -303,7 +291,8 @@
}
private List<Test> createTests(int count, Pool pool, TemplateTest templateTest) {
- return IntStream.range(1, ++count).mapToObj(i -> entityFactory.createTest("simple_test_" + i, pool, templateTest))
+ return IntStream.range(1, ++count)
+ .mapToObj(i -> entityFactory.createTest("simple_test_" + i, pool, templateTest))
.collect(Collectors.toList());
}
@@ -331,15 +320,19 @@
}
private List<TemplateRoot> createTemplateRoots(List<CatalogComponent> catalogComponents) {
- Map<ContextType, List<CatalogComponent>> groups = catalogComponents.stream().collect(Collectors.groupingBy(CatalogComponent::getContextType));
+ Map<ContextType, List<CatalogComponent>> groups = catalogComponents.stream()
+ .collect(Collectors.groupingBy(CatalogComponent::getContextType));
List<TemplateRoot> templateRoots = new ArrayList<>();
groups.forEach((contextType, catalogComps) -> {
- TemplateRoot templateRoot = entityFactory.createTemplateRoot(contextType, "tpl_" + toLower(contextType.name()) + "_root");
+ TemplateRoot templateRoot = entityFactory.createTemplateRoot(contextType,
+ "tpl_" + toLower(contextType.name()) + "_root");
// create child template components for template root
catalogComps.forEach(catalogComp -> {
- TemplateComponent templateComponent = entityFactory.createTemplateComponent("tpl_" + catalogComp.getName() + "_parent", templateRoot, catalogComp);
- entityFactory.createTemplateComponent("tpl_" + catalogComp.getName() + "_child", templateComponent, catalogComp);
+ TemplateComponent templateComponent = entityFactory
+ .createTemplateComponent("tpl_" + catalogComp.getName() + "_parent", templateRoot, catalogComp);
+ entityFactory.createTemplateComponent("tpl_" + catalogComp.getName() + "_child", templateComponent,
+ catalogComp);
});
templateRoots.add(templateRoot);
@@ -357,7 +350,8 @@
}
private CatalogComponent createCatalogComponent(ContextType contextType) {
- CatalogComponent catalogComponent = entityFactory.createCatalogComponent(contextType, toLower(contextType.name()));
+ CatalogComponent catalogComponent = entityFactory.createCatalogComponent(contextType,
+ toLower(contextType.name()));
entityFactory.createCatalogAttribute("string", ValueType.STRING, catalogComponent);
entityFactory.createCatalogAttribute("date", ValueType.DATE, catalogComponent);
diff --git a/src/test/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationTest.java b/src/test/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationTest.java
index b322ad6..d84ab21 100644
--- a/src/test/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationTest.java
+++ b/src/test/java/org/eclipse/mdm/api/odsadapter/notification/peak/PeakNotificationTest.java
@@ -45,35 +45,38 @@
import org.eclipse.mdm.api.odsadapter.query.ODSModelManager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Test notification service.
+ * Test notification service.
*
- * Needs a running ODS and Notification Server.
- * Assumes an existing Test with name defined in {@link PeakNotificationTest#PARENT_TEST},
- * an UnitUnderTest with ID 11 and an UnitUnderTestPart with ID 34.
+ * Needs a running ODS and Notification Server. Assumes an existing Test with
+ * name defined in {@link PeakNotificationTest#PARENT_TEST}, an UnitUnderTest
+ * with ID 11 and an UnitUnderTestPart with ID 34.
*
* @author Matthias Koller, Peak Solution GmbH
*
*/
+@Ignore
+// FIXME 10.7.2017: this test needs a running ODS Server, that is not suitable for continous build in Jenkins.
+// Comment this in for local tests only.
public class PeakNotificationTest {
/*
- * ATTENTION:
- * ==========
+ * ATTENTION: ==========
*
- * To run this test make sure the target service is running a
- * MDM default model and any database constraint which enforces
- * a relation of Test to a parent entity is deactivated!
+ * To run this test make sure the target service is running a MDM default
+ * model and any database constraint which enforces a relation of Test to a
+ * parent entity is deactivated!
*/
-
+
private static final Logger LOGGER = LoggerFactory.getLogger(EventProcessor.class);
-
- // TODO name service: corbaloc::1.2@<SERVER_IP>:<SERVER_PORT>/NameService
+
+ // TODO name service: corbaloc::1.2@<SERVER_IP>:<SERVER_PORT>/NameService
private static final String NAME_SERVICE = "corbaloc::1.2@127.0.0.1:2809/NameService";
// TODO service name: <SERVICE_NAME>.ASAM-ODS
@@ -84,12 +87,11 @@
private static final String PARENT_TEST = "PBN_UNECE_R51_13022014_1349";
-
private static final String NOTIFICATION_URL = "http://localhost:8080/api";
private static final String NOTIFICATION_REGISTRATION_NAME = "mdm";
private static final String NOTIFICATION_USER = "sa";
private static final String NOTIFICATION_PASSWORD = "sa";
-
+
private static EntityManager entityManager;
private static NotificationManager notificationManager;
@@ -102,143 +104,131 @@
connectionParameters.put(PARAM_PASSWORD, PASSWORD);
entityManager = new ODSEntityManagerFactory().connect(connectionParameters);
-
+
Map<String, String> notificationParameters = new HashMap<>();
- notificationParameters.put(ODSNotificationManagerFactory.PARAM_SERVER_TYPE, ODSNotificationManagerFactory.SERVER_TYPE_PEAK);
+ notificationParameters.put(ODSNotificationManagerFactory.PARAM_SERVER_TYPE,
+ ODSNotificationManagerFactory.SERVER_TYPE_PEAK);
notificationParameters.put(ODSNotificationManagerFactory.PARAM_URL, NOTIFICATION_URL);
notificationParameters.put(ODSEntityManagerFactory.PARAM_USER, NOTIFICATION_USER);
notificationParameters.put(ODSEntityManagerFactory.PARAM_PASSWORD, NOTIFICATION_PASSWORD);
notificationParameters.put(ODSNotificationManagerFactory.PARAM_EVENT_MEDIATYPE, "application/json");
-
- notificationManager = new ODSNotificationManagerFactory().create((ODSEntityManager) entityManager, notificationParameters);
+
+ notificationManager = new ODSNotificationManagerFactory().create((ODSEntityManager) entityManager,
+ notificationParameters);
}
@AfterClass
public static void tearDownAfterClass() throws ConnectionException, NotificationException {
- if (entityManager != null)
- {
+ if (entityManager != null) {
entityManager.close();
}
-
- if (notificationManager != null)
- {
+
+ if (notificationManager != null) {
notificationManager.deregister(NOTIFICATION_REGISTRATION_NAME);
notificationManager.close(true);
}
}
-
+
@org.junit.Test
- public void testCreateTestStep() throws NotificationException, DataAccessException, InterruptedException
- {
+ public void testCreateTestStep() throws NotificationException, DataAccessException, InterruptedException {
String testStepName = USER + "_TestStep";
-
+
NotificationListener l = Mockito.mock(NotificationListener.class);
notificationManager.register(NOTIFICATION_REGISTRATION_NAME, new NotificationFilter(), l);
- try
- {
+ try {
createTestStep(PARENT_TEST, testStepName);
-
+
// make sure notification has some time to be pushed
Thread.sleep(1000L);
-
+
@SuppressWarnings({ "unchecked", "rawtypes" })
ArgumentCaptor<List<TestStep>> testStepCaptor = ArgumentCaptor.forClass((Class) List.class);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
-
+
verify(l, times(1)).instanceCreated(testStepCaptor.capture(), userCaptor.capture());
-
+
assertThat(testStepCaptor.getValue().size(), is(1));
assertThat(testStepCaptor.getValue().get(0).getName(), is(testStepName));
assertThat(userCaptor.getValue().getName(), is(USER));
- }
- finally
- {
+ } finally {
notificationManager.deregister(NOTIFICATION_REGISTRATION_NAME);
deleteTestStep(testStepName);
}
}
-
@org.junit.Test
- public void testModifyContextRoot() throws NotificationException, DataAccessException, InterruptedException, IOException
- {
+ public void testModifyContextRoot()
+ throws NotificationException, DataAccessException, InterruptedException, IOException {
NotificationListener l = Mockito.mock(NotificationListener.class);
-
+
notificationManager.register(NOTIFICATION_REGISTRATION_NAME, new NotificationFilter(), l);
-
- try
- {
+
+ try {
updateUUT(11, "application/x-asam.aounitundertest.unitundertest");
-
+
// make sure notification has some time to be pushed
Thread.sleep(1000L);
-
+
@SuppressWarnings({ "unchecked", "rawtypes" })
ArgumentCaptor<List<Entity>> entityCaptor = ArgumentCaptor.forClass((Class) List.class);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
-
+
verify(l, times(1)).instanceModified(entityCaptor.capture(), userCaptor.capture());
-
+
assertThat(entityCaptor.getValue().size(), is(1));
assertThat(entityCaptor.getValue().get(0).getName(), is("PBN_UNECE_R51_Left_AccV"));
assertThat(userCaptor.getValue().getName(), is(USER));
- }
- finally
- {
+ } finally {
notificationManager.deregister(NOTIFICATION_REGISTRATION_NAME);
}
}
-
+
@org.junit.Test
- public void testModifyContextComponent() throws NotificationException, DataAccessException, InterruptedException, IOException
- {
+ public void testModifyContextComponent()
+ throws NotificationException, DataAccessException, InterruptedException, IOException {
NotificationListener l = Mockito.mock(NotificationListener.class);
-
+
notificationManager.register(NOTIFICATION_REGISTRATION_NAME, new NotificationFilter(), l);
-
- try
- {
+
+ try {
updateUUTP(34, "test");
-
+
// make sure notification has some time to be pushed
Thread.sleep(1000L);
-
+
@SuppressWarnings({ "unchecked", "rawtypes" })
ArgumentCaptor<List<Entity>> entityCaptor = ArgumentCaptor.forClass((Class) List.class);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
-
+
verify(l, times(1)).instanceModified(entityCaptor.capture(), userCaptor.capture());
-
+
assertThat(entityCaptor.getValue().size(), is(1));
assertThat(entityCaptor.getValue().get(0).getName(), is("PBN_UNECE_R51_Left_SteadyV"));
assertThat(userCaptor.getValue().getName(), is(USER));
- }
- finally
- {
+ } finally {
notificationManager.deregister(NOTIFICATION_REGISTRATION_NAME);
}
}
-
+
private void createTestStep(String parentName, String name) throws DataAccessException {
Transaction transaction = entityManager.startTransaction();
-
+
List<Test> tests = entityManager.loadAll(Test.class, parentName);
-
+
assertThat("Parent test not found!", !tests.isEmpty());
-
+
Optional<EntityFactory> entityFactory = entityManager.getEntityFactory();
- if (!entityFactory.isPresent())
- {
+ if (!entityFactory.isPresent()) {
throw new IllegalStateException("Entity factory not present!");
}
-
+
TestStep testStep = entityFactory.get().createTestStep(name, tests.get(0));
testStep.setSortIndex(0);
-
+
transaction.create(Arrays.asList(testStep));
-
+
transaction.commit();
}
@@ -248,44 +238,39 @@
List<TestStep> testSteps = entityManager.loadAll(TestStep.class, name);
transaction.delete(testSteps);
-
+
transaction.commit();
}
-
+
private void updateUUT(int uutId, String newValue) throws DataAccessException {
-
+
AoSession session = null;
- try
- {
+ try {
session = ((ODSModelManager) entityManager.getModelManager().get()).getAoSession().createCoSession();
-
+
ApplicationElement aeUUT = session.getApplicationStructure().getElementsByBaseType("AoUnitUnderTest")[0];
-
+
final ApplElemAccess aea = session.getApplElemAccess();
-
+
TS_UnionSeq uId = new TS_UnionSeq();
- uId.longlongVal(new T_LONGLONG[] { new T_LONGLONG(0, uutId)});
-
+ uId.longlongVal(new T_LONGLONG[] { new T_LONGLONG(0, uutId) });
+
TS_UnionSeq uManufacturer = new TS_UnionSeq();
uManufacturer.stringVal(new String[] { newValue });
-
+
AIDNameValueSeqUnitId[] val = new AIDNameValueSeqUnitId[] {
- new AIDNameValueSeqUnitId(new AIDName(aeUUT.getId(), "Id"), new T_LONGLONG(), new TS_ValueSeq(uId, new short[] { (short) 15 })) ,
- new AIDNameValueSeqUnitId(new AIDName(aeUUT.getId(), "Mimetype"), new T_LONGLONG(), new TS_ValueSeq(uManufacturer, new short[] { (short) 15 }))
- };
+ new AIDNameValueSeqUnitId(new AIDName(aeUUT.getId(), "Id"), new T_LONGLONG(),
+ new TS_ValueSeq(uId, new short[] { (short) 15 })),
+ new AIDNameValueSeqUnitId(new AIDName(aeUUT.getId(), "Mimetype"), new T_LONGLONG(),
+ new TS_ValueSeq(uManufacturer, new short[] { (short) 15 })) };
session.startTransaction();
aea.updateInstances(val);
session.commitTransaction();
-
- }
- catch (AoException e)
- {
+
+ } catch (AoException e) {
throw new DataAccessException(e.reason, e);
- }
- finally
- {
- if (session != null)
- {
+ } finally {
+ if (session != null) {
try {
session.close();
} catch (AoException e) {
@@ -294,41 +279,36 @@
}
}
}
-
+
private void updateUUTP(int tyreId, String newValue) throws DataAccessException {
-
+
AoSession session = null;
- try
- {
+ try {
session = ((ODSModelManager) entityManager.getModelManager().get()).getAoSession().createCoSession();
-
+
ApplicationElement aeTyre = session.getApplicationStructure().getElementByName("tyre");
-
+
final ApplElemAccess aea = session.getApplElemAccess();
-
+
TS_UnionSeq uId = new TS_UnionSeq();
- uId.longlongVal(new T_LONGLONG[] { new T_LONGLONG(0, tyreId)});
-
+ uId.longlongVal(new T_LONGLONG[] { new T_LONGLONG(0, tyreId) });
+
TS_UnionSeq uManufacturer = new TS_UnionSeq();
uManufacturer.stringVal(new String[] { newValue });
-
+
AIDNameValueSeqUnitId[] val = new AIDNameValueSeqUnitId[] {
- new AIDNameValueSeqUnitId(new AIDName(aeTyre.getId(), "Id"), new T_LONGLONG(), new TS_ValueSeq(uId, new short[] { (short) 15 })) ,
- new AIDNameValueSeqUnitId(new AIDName(aeTyre.getId(), "manufacturer"), new T_LONGLONG(), new TS_ValueSeq(uManufacturer, new short[] { (short) 15 }))
- };
+ new AIDNameValueSeqUnitId(new AIDName(aeTyre.getId(), "Id"), new T_LONGLONG(),
+ new TS_ValueSeq(uId, new short[] { (short) 15 })),
+ new AIDNameValueSeqUnitId(new AIDName(aeTyre.getId(), "manufacturer"), new T_LONGLONG(),
+ new TS_ValueSeq(uManufacturer, new short[] { (short) 15 })) };
session.startTransaction();
aea.updateInstances(val);
session.commitTransaction();
-
- }
- catch (AoException e)
- {
+
+ } catch (AoException e) {
throw new DataAccessException(e.reason, e);
- }
- finally
- {
- if (session != null)
- {
+ } finally {
+ if (session != null) {
try {
session.close();
} catch (AoException e) {
diff --git a/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearchTest.java b/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearchTest.java
index 8ad954f..05070c5 100644
--- a/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearchTest.java
+++ b/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSFreeTextSearchTest.java
@@ -100,9 +100,9 @@
@Test
public void specialCharacters_correctlyEscaped() throws InterruptedException {
- createExampleIndex("Measurement", "mdm", "hallo\"!§");
+ createExampleIndex("Measurement", "mdm", "hallo\"!§");
- Map<Class<? extends Entity>, List<Entity>> search = fts.search("hallo\"!§");
+ Map<Class<? extends Entity>, List<Entity>> search = fts.search("hallo\"!§");
assertEquals(ts, search.get(Measurement.class).get(0));
}
@@ -123,16 +123,16 @@
assertEquals(2, search.get(org.eclipse.mdm.api.base.model.Test.class).size());
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void illegalLoadRequest_niceExceptionIsThrown() throws DataAccessException, InterruptedException {
loader = mock(EntityLoader.class);
when(loader.loadAll(any(Key.class), anyCollection())).thenThrow(new DataAccessException(""));
createExampleIndex("TestStep", "mdm2", "asdf");
ODSFreeTextSearch fts2 = new ODSFreeTextSearch(loader, "mdm2", HOST);
-
+
fts2.search("asdf");
}
-
+
private void createExampleIndex(String type, String name, String value) throws InterruptedException {
createExampleIndex(type, name, value, "0");
}
diff --git a/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchServiceTest.java b/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchServiceTest.java
index ae05c92..b6b848a 100644
--- a/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchServiceTest.java
+++ b/src/test/java/org/eclipse/mdm/api/odsadapter/search/ODSSearchServiceTest.java
@@ -26,20 +26,23 @@
import org.eclipse.mdm.api.odsadapter.ODSEntityManagerFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.ImmutableMap;
+@Ignore
+// FIXME 10.7.2017: this test needs a running ODS Server, that is not suitable for continous build in Jenkins.
+// Comment this in for local tests only.
public class ODSSearchServiceTest {
/*
- * ATTENTION:
- * ==========
+ * ATTENTION: ==========
*
- * To run this test make sure the target service is running a
- * MDM default model and any database constraint which enforces
- * a relation of Test to a parent entity is deactivated!
+ * To run this test make sure the target service is running a MDM default
+ * model and any database constraint which enforces a relation of Test to a
+ * parent entity is deactivated!
*/
private static final String NAME_SERVICE = "corbaloc::1.2@%s:%s/NameService";
@@ -49,23 +52,23 @@
private static EntityManager entityManager;
private static ModelManager modelManager;
-
+
@BeforeClass
public static void setUpBeforeClass() throws ConnectionException {
String nameServiceHost = System.getProperty("host");
String nameServicePort = System.getProperty("port");
String serviceName = System.getProperty("service");
- if(nameServiceHost == null || nameServiceHost.isEmpty()) {
+ if (nameServiceHost == null || nameServiceHost.isEmpty()) {
throw new IllegalArgumentException("name service host is unknown: define system property 'host'");
}
- nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
- if(nameServicePort == null || nameServicePort.isEmpty()) {
+ nameServicePort = nameServicePort == null || nameServicePort.isEmpty() ? String.valueOf(2809) : nameServicePort;
+ if (nameServicePort == null || nameServicePort.isEmpty()) {
throw new IllegalArgumentException("name service port is unknown: define system property 'port'");
}
- if(serviceName == null || serviceName.isEmpty()) {
+ if (serviceName == null || serviceName.isEmpty()) {
throw new IllegalArgumentException("service name is unknown: define system property 'service'");
}
@@ -76,79 +79,78 @@
connectionParameters.put(PARAM_PASSWORD, PASSWORD);
entityManager = new ODSEntityManagerFactory().connect(connectionParameters);
- modelManager = entityManager.getModelManager().orElseThrow(() -> new IllegalStateException("No ModelManager available!"));
+ modelManager = entityManager.getModelManager()
+ .orElseThrow(() -> new IllegalStateException("No ModelManager available!"));
}
@AfterClass
public static void tearDownAfterClass() throws ConnectionException {
- if(entityManager != null) {
+ if (entityManager != null) {
entityManager.close();
}
}
-
+
private Extractor<FilterItem, Tuple> filterExtractors = new Extractor<FilterItem, Tuple>() {
@Override
public Tuple extract(FilterItem f) {
- return tuple(
- f.isOperator() ? f.getOperator() : null,
- f.isCondition() ? f.getCondition().getAttribute().getName() : null,
- f.isCondition() ? f.getCondition().getOperation() : null,
- f.isCondition() ? f.getCondition().getValue().extract() : null);
+ return tuple(f.isOperator() ? f.getOperator() : null,
+ f.isCondition() ? f.getCondition().getAttribute().getName() : null,
+ f.isCondition() ? f.getCondition().getOperation() : null,
+ f.isCondition() ? f.getCondition().getValue().extract() : null);
}
};
-
- @Test
- public void testGetMergedFilter() throws Exception {
-
- ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().orElseThrow(() -> new IllegalStateException("No SearchService available!")));
-
- Mockito.doReturn(ImmutableMap.of(TestStep.class, Arrays.asList(10L))).when(service).fetchIds(Mockito.anyString());
-
- EntityType testStep = modelManager.getEntityType(TestStep.class);
-
- assertThat(service.getMergedFilter(Filter.idOnly(testStep, 11L), "query")).hasSize(7).extracting(filterExtractors)
- .containsExactly(
- tuple(Operator.OPEN, null, null, null),
- tuple(null, "Id", Operation.EQUAL, 11L),
- tuple(Operator.CLOSE, null, null, null),
- tuple(Operator.AND, null, null, null),
- tuple(Operator.OPEN, null, null, null),
- tuple(null, "Id", Operation.IN_SET, new long[] { 10L }),
- tuple(Operator.CLOSE, null, null, null)
- );
- }
-
- @Test
- public void testGetMergedFilterNoAttributeFilter() throws Exception {
- ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
-
- Mockito.doReturn(ImmutableMap.of(TestStep.class, Arrays.asList(10L))).when(service).fetchIds(Mockito.anyString());
-
- assertThat(service.getMergedFilter(Filter.and(), "query")).extracting(filterExtractors)
- .containsExactly(tuple(null, "Id", Operation.IN_SET, new long[] {10L}));
- }
-
- @Test
- public void testGetMergedFilterNoFreetextResult() throws Exception {
- ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
-
- Mockito.doReturn(Collections.emptyMap()).when(service).fetchIds(Mockito.anyString());
-
- EntityType testStep = modelManager.getEntityType(TestStep.class);
-
- assertThat(service.getMergedFilter(Filter.idOnly(testStep, 11L), "")).extracting(filterExtractors)
- .containsExactly(tuple(null, "Id", Operation.EQUAL, 11L));
- }
@Test
- public void testGetMergedFilterNoAttributeFilterAndNoFreetextResult() throws Exception {
- ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
-
- Mockito.doReturn(Collections.emptyMap()).when(service).fetchIds(Mockito.anyString());
-
- assertThat(service.getMergedFilter(Filter.and(), null)).isEmpty();
-
- assertThat(service.getMergedFilter(Filter.and(), "")).isEmpty();
- }
+ public void testGetMergedFilter() throws Exception {
+
+ ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService()
+ .orElseThrow(() -> new IllegalStateException("No SearchService available!")));
+
+ Mockito.doReturn(ImmutableMap.of(TestStep.class, Arrays.asList("10"))).when(service)
+ .fetchIds(Mockito.anyString());
+
+ EntityType testStep = modelManager.getEntityType(TestStep.class);
+
+ assertThat(service.getMergedFilter(Filter.idOnly(testStep, "11"), "query")).hasSize(7)
+ .extracting(filterExtractors).containsExactly(tuple(Operator.OPEN, null, null, null),
+ tuple(null, "Id", Operation.EQUAL, "10"), tuple(Operator.CLOSE, null, null, null),
+ tuple(Operator.AND, null, null, null), tuple(Operator.OPEN, null, null, null),
+ tuple(null, "Id", Operation.IN_SET, new String[] { "10" }),
+ tuple(Operator.CLOSE, null, null, null));
+ }
+
+ @Test
+ public void testGetMergedFilterNoAttributeFilter() throws Exception {
+ ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
+
+ Mockito.doReturn(ImmutableMap.of(TestStep.class, Arrays.asList("10"))).when(service)
+ .fetchIds(Mockito.anyString());
+
+ assertThat(service.getMergedFilter(Filter.and(), "query")).extracting(filterExtractors)
+ .containsExactly(tuple(null, "Id", Operation.IN_SET, new String[] { "10" }));
+ }
+
+ @Test
+ public void testGetMergedFilterNoFreetextResult() throws Exception {
+ ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
+
+ Mockito.doReturn(Collections.emptyMap()).when(service).fetchIds(Mockito.anyString());
+
+ EntityType testStep = modelManager.getEntityType(TestStep.class);
+
+ assertThat(service.getMergedFilter(Filter.idOnly(testStep, "11"), "")).extracting(filterExtractors)
+ .containsExactly(tuple(null, "Id", Operation.EQUAL, "11"));
+ }
+
+ @Test
+ public void testGetMergedFilterNoAttributeFilterAndNoFreetextResult() throws Exception {
+ ODSSearchService service = Mockito.spy((ODSSearchService) entityManager.getSearchService().get());
+
+ Mockito.doReturn(Collections.emptyMap()).when(service).fetchIds(Mockito.anyString());
+
+ assertThat(service.getMergedFilter(Filter.and(), null)).isEmpty();
+
+ assertThat(service.getMergedFilter(Filter.and(), "")).isEmpty();
+ }
}