, KapuaMessage, ?>> translatorToKapua = translatorHub.getTranslatorFor(deviceMessageType, kapuaMessageType);
+ KapuaMessage, ?> kapuaMessage = translatorToKapua.translate(deviceMessage);
+ if (StringUtils.isEmpty(kapuaMessage.getClientId())) {
+ logger.debug("Updating client id since the received value is null (new value {})", clientId);
+ kapuaMessage.setClientId(clientId);
+ }
+ return new CamelKapuaMessage<>(kapuaMessage, connectionId, connectorDescriptor);
+ }
}
diff --git a/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/ErrorMessageListener.java b/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/ErrorMessageListener.java
index ab6a09025b5..0b0b9fe52fe 100644
--- a/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/ErrorMessageListener.java
+++ b/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/ErrorMessageListener.java
@@ -12,10 +12,6 @@
*******************************************************************************/
package org.eclipse.kapua.service.camel.listener.error;
-import java.text.ParseException;
-import java.util.Base64;
-import java.util.Date;
-
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.spi.UriEndpoint;
@@ -26,6 +22,11 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
+import java.text.ParseException;
+import java.util.Base64;
+import java.util.Date;
+
@UriEndpoint(title = "error message processor", syntax = "bean:ecErrorMessageListener", scheme = "bean")
public class ErrorMessageListener {
@@ -40,7 +41,12 @@ public class ErrorMessageListener {
private static final String EMPTY_ENCODED_MESSAGE = "N/A";
private static final String EMPTY_FIELD = "N/A";
- private MetricsCamel metrics;
+ @Inject
+ public ErrorMessageListener(MetricsCamel metricsCamel) {
+ this.metrics = metricsCamel;
+ }
+
+ private final MetricsCamel metrics;
/**
* Process an error condition for an elaboration of a generic message
@@ -49,7 +55,6 @@ public class ErrorMessageListener {
* @param message
*/
public void processMessage(Exchange exchange, Object message) {
- metrics = MetricsCamel.getInstance();
logToFile(exchange, message);
}
@@ -70,7 +75,7 @@ private String getMessage(Exchange exchange) {
Long timestamp = message.getHeader(MessageConstants.HEADER_KAPUA_RECEIVED_TIMESTAMP, Long.class);
String encodedMsg = getMessageBody(message.getBody());
String messageLogged = String.format("%s %s %s",
- clientId!=null ? clientId : EMPTY_FIELD,
+ clientId != null ? clientId : EMPTY_FIELD,
getDate(timestamp),
encodedMsg);
if (logger.isDebugEnabled()) {
@@ -81,7 +86,7 @@ private String getMessage(Exchange exchange) {
private String getDate(Long timestamp) {
try {
- return timestamp!=null ? KapuaDateUtils.formatDate(new Date(timestamp)) : EMPTY_FIELD;
+ return timestamp != null ? KapuaDateUtils.formatDate(new Date(timestamp)) : EMPTY_FIELD;
} catch (ParseException e) {
return String.format(ERROR_DATE_MESSAGE_PATTERN, timestamp);
}
@@ -90,26 +95,23 @@ private String getDate(Long timestamp) {
private String getMessageBody(Object body) {
if (body instanceof CamelKapuaMessage>) {
return getBody(((CamelKapuaMessage>) body).getMessage());
- }
- else {
+ } else {
return getBody(body);
}
}
private String getBody(Object body) {
if (body instanceof byte[]) {
- return Base64.getEncoder().encodeToString((byte[])body);
- }
- else if (body instanceof String) {
+ return Base64.getEncoder().encodeToString((byte[]) body);
+ } else if (body instanceof String) {
return Base64.getEncoder().encodeToString(((String) body).getBytes());
- }
- else {
+ } else {
//something wrong happened! Anyway try to get the message to be stored
- logger.error("Wrong message type! Cannot convert message of type {} to byte[]", body!=null ? body.getClass() : "N/A");
+ logger.error("Wrong message type! Cannot convert message of type {} to byte[]", body != null ? body.getClass() : "N/A");
metrics.getUnknownBodyType().inc();
return EMPTY_ENCODED_MESSAGE;
}
- }
+ }
protected int getDelivery(Exchange exchange) {
return exchange.getIn().getHeader(JMS_EXCHANGE_REDELIVERY_COUNTER, 0, Integer.class);
diff --git a/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/FailureProcessor.java b/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/FailureProcessor.java
index 43bd97308e4..481b2848b97 100644
--- a/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/FailureProcessor.java
+++ b/service/camel/src/main/java/org/eclipse/kapua/service/camel/listener/error/FailureProcessor.java
@@ -19,20 +19,21 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
+
/**
* Processor called before sending the message to the dlq processor chain.
* So this is the last chance to modify the object or take actions before the message will be discarded.
- *
*/
public class FailureProcessor implements Processor {
private static final Logger logger = LoggerFactory.getLogger(FailureProcessor.class);
- //TODO inject!!!
- private MetricsCamel metrics;
+ private MetricsCamel metricsCamel;
- public FailureProcessor() {
- metrics = MetricsCamel.getInstance();
+ @Inject
+ public FailureProcessor(MetricsCamel metricsCamel) {
+ this.metricsCamel = metricsCamel;
}
@Override
@@ -41,10 +42,9 @@ public void process(Exchange exchange) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Detected unauthenticated error on message processing retry!");
}
- metrics.getUnauthenticatedError().inc();
- }
- else {
- metrics.getGenericError().inc();
+ metricsCamel.getUnauthenticatedError().inc();
+ } else {
+ metricsCamel.getGenericError().inc();
}
}
@@ -56,9 +56,8 @@ private boolean isUnauthenticatedException(Exchange exchange) {
private Exception getException(Exchange exchange) {
if (exchange.getException() != null) {
return exchange.getException();
- }
- else {
- return (Exception)exchange.getProperty(org.apache.camel.Exchange.EXCEPTION_CAUGHT);
+ } else {
+ return (Exception) exchange.getProperty(org.apache.camel.Exchange.EXCEPTION_CAUGHT);
}
}
}
diff --git a/service/camel/src/main/java/org/eclipse/kapua/service/camel/message/JmsUtil.java b/service/camel/src/main/java/org/eclipse/kapua/service/camel/message/JmsUtil.java
index 494003101b2..7bc7749060e 100644
--- a/service/camel/src/main/java/org/eclipse/kapua/service/camel/message/JmsUtil.java
+++ b/service/camel/src/main/java/org/eclipse/kapua/service/camel/message/JmsUtil.java
@@ -13,34 +13,21 @@
*******************************************************************************/
package org.eclipse.kapua.service.camel.message;
-import org.apache.commons.lang3.StringUtils;
-import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.message.KapuaMessage;
-import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.client.message.MessageConstants;
-import org.eclipse.kapua.service.client.message.MessageType;
-import org.eclipse.kapua.service.client.protocol.ProtocolDescriptor;
-import org.eclipse.kapua.service.device.call.message.DeviceMessage;
-import org.eclipse.kapua.translator.Translator;
-import org.eclipse.kapua.transport.message.jms.JmsMessage;
-import org.eclipse.kapua.transport.message.jms.JmsPayload;
-import org.eclipse.kapua.transport.message.jms.JmsTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.Topic;
-import java.util.Date;
-
/**
* Jms message utility class
*
* @since 1.0
*/
+//TODO: Convert this into an injectable collaborator
public class JmsUtil {
public static final Logger logger = LoggerFactory.getLogger(JmsUtil.class);
@@ -48,110 +35,6 @@ public class JmsUtil {
private JmsUtil() {
}
- /**
- * Convert a {@link BytesMessage} to {@link CamelKapuaMessage}
- *
- * @param jmsMessage
- * @throws JMSException
- * @throws KapuaException
- */
- public static CamelKapuaMessage> convertToKapuaMessage(ProtocolDescriptor connectorDescriptor, MessageType messageType, BytesMessage jmsMessage, KapuaId connectionId, String clientId)
- throws JMSException, KapuaException {
- String jmsTopic = jmsMessage.getStringProperty(MessageConstants.PROPERTY_ORIGINAL_TOPIC);
- Date queuedOn = new Date(jmsMessage.getLongProperty(MessageConstants.PROPERTY_ENQUEUED_TIMESTAMP));
- return convertToKapuaMessage(connectorDescriptor, connectorDescriptor.getDeviceClass(messageType), connectorDescriptor.getKapuaClass(messageType), jmsMessage, jmsTopic, queuedOn, connectionId,
- clientId);
- }
-
- /**
- * Convert a {@link BytesMessage} to {@link KapuaMessage}
- *
- * this code
- *
- *
- *
- * if (jmsMessage.getBodyLength() > 0) {
- * payload = new byte[(int) jmsMessage.getBodyLength()];
- * jmsMessage.readBytes(payload);
- * }
- *
- *
- *
- * with camel doesn't work.
- * The call getBodyLength returns the correct message size but the read call reads an empty array (-1 is returned).
- * The following code return the payload evaluated.
- * ((ActiveMQMessage)jmsMessage).getContent().data
- * so we modify the method assuming that camel converter called this utility method with a byte[] representing the jms body message.
- *
- * @param jmsMessage
- * @throws JMSException
- * @throws KapuaException
- * @see AbstractKapuaConverter
- */
-
- // TODO check the code with huge messages
- private static CamelKapuaMessage> convertToKapuaMessage(ProtocolDescriptor connectorDescriptor, Class extends DeviceMessage, ?>> deviceMessageType,
- Class extends KapuaMessage, ?>> kapuaMessageType, BytesMessage jmsMessage, String jmsTopic,
- Date queuedOn, KapuaId connectionId, String clientId)
- throws JMSException, KapuaException {
- byte[] payload = null;
- // TODO JMS message have no size limits!
- if (jmsMessage.getBodyLength() > 0) {
- payload = new byte[(int) jmsMessage.getBodyLength()];
- int readBytes = jmsMessage.readBytes(payload);
- logger.debug("Message conversion... {} bytes read!", readBytes);
- }
- KapuaMessage, ?> kapuaMessage = convertToKapuaMessage(deviceMessageType, kapuaMessageType, payload, jmsTopic, queuedOn, clientId);
- return new CamelKapuaMessage<>(kapuaMessage, connectionId, connectorDescriptor);
- }
-
- /**
- * Convert raw byte[] message to {@link CamelKapuaMessage}
- *
- * @param connectorDescriptor
- * @param messageType
- * @param messageBody
- * @param jmsTopic
- * @param queuedOn
- * @param connectionId
- * @return
- * @throws KapuaException
- */
- public static CamelKapuaMessage> convertToCamelKapuaMessage(ProtocolDescriptor connectorDescriptor, MessageType messageType, byte[] messageBody, String jmsTopic, Date queuedOn,
- KapuaId connectionId, String clientId)
- throws KapuaException {
- KapuaMessage, ?> kapuaMessage = convertToKapuaMessage(connectorDescriptor.getDeviceClass(messageType), connectorDescriptor.getKapuaClass(messageType), messageBody, jmsTopic, queuedOn, clientId);
- return new CamelKapuaMessage<>(kapuaMessage, connectionId, connectorDescriptor);
- }
-
- /**
- * Convert raw byte[] message to {@link KapuaMessage}
- *
- * @param deviceMessageType
- * @param kapuaMessageType
- * @param messageBody
- * @param jmsTopic
- * @param queuedOn
- * @return
- * @throws KapuaException
- */
- private static KapuaMessage, ?> convertToKapuaMessage(Class extends DeviceMessage, ?>> deviceMessageType, Class extends KapuaMessage, ?>> kapuaMessageType, byte[] messageBody,
- String jmsTopic, Date queuedOn, String clientId)
- throws KapuaException {
- // first step... from jms to device dependent protocol level (unknown)
- Translator> translatorFromJms = Translator.getTranslatorFor(JmsMessage.class, deviceMessageType);// birth ...
- DeviceMessage, ?> deviceMessage = translatorFromJms.translate(new JmsMessage(new JmsTopic(jmsTopic), queuedOn, new JmsPayload(messageBody)));
-
- // second step.... from device dependent protocol (unknown) to Kapua
- Translator, KapuaMessage, ?>> translatorToKapua = Translator.getTranslatorFor(deviceMessageType, kapuaMessageType);
- KapuaMessage, ?> message = translatorToKapua.translate(deviceMessage);
- if (StringUtils.isEmpty(message.getClientId())) {
- logger.debug("Updating client id since the received value is null (new value {})", clientId);
- message.setClientId(clientId);
- }
- return message;
- }
-
public static String getTopic(org.apache.camel.Message message) throws JMSException {
String topicOrig = message.getHeader(MessageConstants.PROPERTY_ORIGINAL_TOPIC, String.class);
if (topicOrig != null) {
@@ -160,11 +43,9 @@ public static String getTopic(org.apache.camel.Message message) throws JMSExcept
Destination destination = message.getHeader(MessageConstants.HEADER_CAMEL_JMS_HEADER_DESTINATION, Destination.class);
if (destination instanceof Queue) {
topicOrig = ((Queue) destination).getQueueName();
- }
- else if (destination instanceof Topic) {
+ } else if (destination instanceof Topic) {
topicOrig = ((Topic) destination).getTopicName();
- }
- else {
+ } else {
logger.warn("jmsMessage destination is null!", destination);
throw new JMSException(String.format("Unable to extract the destination. Wrong destination %s", destination));
}
diff --git a/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoader.java b/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoader.java
index 545a340b475..f12b9ae0469 100644
--- a/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoader.java
+++ b/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoader.java
@@ -23,25 +23,21 @@
/**
* Jaxb context loader
- *
*/
public class ServiceJAXBContextLoader {
protected static final Logger logger = LoggerFactory.getLogger(ServiceJAXBContextLoader.class);
- private static final String JAXB_CONTEXT_CLASS_NAME;
-
- static {
- ServiceSetting config = ServiceSetting.getInstance();
- JAXB_CONTEXT_CLASS_NAME = config.getString(ServiceSettingKey.JAXB_CONTEXT_CLASS_NAME);
- }
+ private final String jaxbContextClassName;
public ServiceJAXBContextLoader() throws KapuaException {
+ ServiceSetting config = ServiceSetting.getInstance();
+ jaxbContextClassName = config.getString(ServiceSettingKey.JAXB_CONTEXT_CLASS_NAME);
}
public void init() throws KapuaException {
logger.info(">>> Jaxb context loader... load context");
- JAXBContextProvider jaxbContextProvider = ClassUtil.newInstance(JAXB_CONTEXT_CLASS_NAME, null);
+ JAXBContextProvider jaxbContextProvider = ClassUtil.newInstance(jaxbContextClassName, null);
XmlUtil.setContextProvider(jaxbContextProvider);
logger.info(">>> Jaxb context loader... load context DONE");
}
diff --git a/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoaderProvider.java b/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoaderProvider.java
new file mode 100644
index 00000000000..8251fc120f2
--- /dev/null
+++ b/service/camel/src/main/java/org/eclipse/kapua/service/camel/xml/ServiceJAXBContextLoaderProvider.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.camel.xml;
+
+import org.eclipse.kapua.KapuaException;
+
+import javax.inject.Provider;
+
+public class ServiceJAXBContextLoaderProvider implements Provider {
+ @Override
+ public ServiceJAXBContextLoader get() {
+ try {
+ ServiceJAXBContextLoader serviceJAXBContextLoader = new ServiceJAXBContextLoader();
+ serviceJAXBContextLoader.init();
+ return serviceJAXBContextLoader;
+ } catch (KapuaException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/service/client/src/main/java/org/eclipse/kapua/service/client/DatabaseCheckUpdate.java b/service/client/src/main/java/org/eclipse/kapua/service/client/DatabaseCheckUpdate.java
deleted file mode 100644
index 17a6d747f2c..00000000000
--- a/service/client/src/main/java/org/eclipse/kapua/service/client/DatabaseCheckUpdate.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.client;
-
-import com.google.common.base.MoreObjects;
-import org.eclipse.kapua.commons.jpa.JdbcConnectionUrlResolvers;
-import org.eclipse.kapua.commons.liquibase.KapuaLiquibaseClient;
-import org.eclipse.kapua.commons.setting.system.SystemSetting;
-import org.eclipse.kapua.commons.setting.system.SystemSettingKey;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Call Liquibase database schema check and update (if enabled)
- */
-public class DatabaseCheckUpdate {
-
- private static final Logger logger = LoggerFactory.getLogger(DatabaseCheckUpdate.class);
-
- public DatabaseCheckUpdate() {
- logger.info("Kapua database schema check and update...");
- try {
- SystemSetting config = SystemSetting.getInstance();
- if (config.getBoolean(SystemSettingKey.DB_SCHEMA_UPDATE, false)) {
- logger.debug("Starting Liquibase embedded client.");
- String dbUsername = config.getString(SystemSettingKey.DB_USERNAME);
- String dbPassword = config.getString(SystemSettingKey.DB_PASSWORD);
- String schema = MoreObjects.firstNonNull(config.getString(SystemSettingKey.DB_SCHEMA_ENV), config.getString(SystemSettingKey.DB_SCHEMA));
-
- new KapuaLiquibaseClient(JdbcConnectionUrlResolvers.resolveJdbcUrl(), dbUsername, dbPassword, schema).update();
- logger.info("Kapua database schema check and update... DONE");
- } else {
- logger.info("Kapua database schema check and update... skipping (not enabled by configuration) DONE");
- }
- } catch (Exception e) {
- logger.error("Kapua database schema check and update... ERROR: {}", e.getMessage(), e);
- throw new SecurityException(e);
- }
- }
-
-}
diff --git a/service/commons/elasticsearch/client-api/pom.xml b/service/commons/elasticsearch/client-api/pom.xml
index 765adf4669a..1ba930dad8e 100644
--- a/service/commons/elasticsearch/client-api/pom.xml
+++ b/service/commons/elasticsearch/client-api/pom.xml
@@ -28,7 +28,10 @@
org.eclipse.kapua
kapua-commons
-
+
+ org.eclipse.kapua
+ kapua-service-storable-api
+
org.apache.httpcomponents
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchClientProvider.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchClientProvider.java
index 5676eff65cd..8d81de32439 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchClientProvider.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchClientProvider.java
@@ -23,7 +23,7 @@
* @param {@link ElasticsearchClient} type.
* @since 1.0.0
*/
-public interface ElasticsearchClientProvider extends AutoCloseable {
+public interface ElasticsearchClientProvider {
/**
* Initializes the {@link ElasticsearchClientProvider}.
@@ -43,7 +43,6 @@ public interface ElasticsearchClientProvider exte
* @throws ClientClosingException in case of error while closing the client.
* @since 1.0.0
*/
- @Override
void close() throws ClientClosingException;
/**
@@ -81,5 +80,5 @@ public interface ElasticsearchClientProvider exte
* @throws ClientUnavailableException if the client has not being initialized.
* @since 1.0.0
*/
- C getElasticsearchClient() throws ClientUnavailableException;
+ C getElasticsearchClient() throws ClientUnavailableException, ClientProviderInitException;
}
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java
new file mode 100644
index 00000000000..302892df84b
--- /dev/null
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java
@@ -0,0 +1,291 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.elasticsearch.client;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.eclipse.kapua.commons.cache.LocalCache;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.elasticsearch.client.model.BulkUpdateRequest;
+import org.eclipse.kapua.service.elasticsearch.client.model.BulkUpdateResponse;
+import org.eclipse.kapua.service.elasticsearch.client.model.IndexRequest;
+import org.eclipse.kapua.service.elasticsearch.client.model.IndexResponse;
+import org.eclipse.kapua.service.elasticsearch.client.model.Response;
+import org.eclipse.kapua.service.elasticsearch.client.model.ResultList;
+import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
+import org.eclipse.kapua.service.elasticsearch.client.model.UpdateRequest;
+import org.eclipse.kapua.service.elasticsearch.client.model.UpdateResponse;
+import org.eclipse.kapua.service.storable.StorableFactory;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.Storable;
+import org.eclipse.kapua.service.storable.model.StorableListResult;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.StorableQuery;
+import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public abstract class ElasticsearchRepository<
+ T extends Storable,
+ L extends StorableListResult,
+ Q extends StorableQuery> implements StorableRepository {
+ protected final ElasticsearchClientProvider elasticsearchClientProviderInstance;
+ protected final String type;
+ private final Class clazz;
+ private final StorableFactory storableFactory;
+ protected final StorablePredicateFactory storablePredicateFactory;
+ protected final Logger logger = LoggerFactory.getLogger(this.getClass());
+ protected final LocalCache indexUpserted;
+
+ protected abstract String indexResolver(KapuaId scopeId);
+
+ protected abstract JsonNode getIndexSchema() throws MappingException;
+
+ protected abstract ObjectNode getMappingSchema(String idxName) throws MappingException;
+
+ protected abstract StorableId idExtractor(T storable);
+
+ protected ElasticsearchRepository(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ String type,
+ Class clazz,
+ StorableFactory storableFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ LocalCache indexesCache) {
+ this.elasticsearchClientProviderInstance = elasticsearchClientProviderInstance;
+ this.type = type;
+ this.storableFactory = storableFactory;
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.clazz = clazz;
+ this.indexUpserted = indexesCache;
+ }
+
+ protected ElasticsearchRepository(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ String type,
+ Class clazz,
+ StorableFactory storableFactory,
+ StorablePredicateFactory storablePredicateFactory) {
+ this.elasticsearchClientProviderInstance = elasticsearchClientProviderInstance;
+ this.type = type;
+ this.storableFactory = storableFactory;
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.clazz = clazz;
+ this.indexUpserted = new LocalCache<>(0, null);
+ }
+
+ @Override
+ public T find(KapuaId scopeId, StorableId id) {
+ return doFind(scopeId, indexResolver(scopeId), id);
+ }
+
+ protected T doFind(KapuaId scopeId, String indexName, StorableId id) {
+ try {
+ final Q idsQuery = storableFactory.newQuery(scopeId);
+ idsQuery.setLimit(1);
+
+ final IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(type);
+ idsPredicate.addId(id);
+ idsQuery.setPredicate(idsPredicate);
+
+ synchIndex(indexName);
+ final T res;
+ res = (T) elasticsearchClientProviderInstance.getElasticsearchClient().find(getDescriptor(indexName), idsQuery, clazz);
+ return res;
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void synchIndex(String indexName) {
+ if (!indexUpserted.containsKey(indexName)) {
+ synchronized (clazz) {
+ doUpsertIndex(indexName);
+ indexUpserted.put(indexName, true);
+ }
+ }
+ }
+
+ @Override
+ public L query(Q query) {
+ try {
+ final String indexName = indexResolver(query.getScopeId());
+ synchIndex(indexName);
+ final ResultList partialResult = elasticsearchClientProviderInstance.getElasticsearchClient().query(getDescriptor(indexName), query, clazz);
+ final L res = storableFactory.newListResult();
+ res.addItems(partialResult.getResult());
+ res.setTotalCount(partialResult.getTotalCount());
+ setLimitExceed(query, partialResult.getTotalHitsExceedsCount(), res);
+ return res;
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void setLimitExceed(StorableQuery query, boolean hitsExceedsTotalCount, StorableListResult list) {
+ int offset = query.getOffset() != null ? query.getOffset() : 0;
+ if (query.getLimit() != null) {
+ if (hitsExceedsTotalCount || //pre-condition: there are more than 10k documents in ES && query limit is <= 10k
+ list.getTotalCount() > offset + query.getLimit()) {
+ list.setLimitExceeded(true);
+ }
+ }
+ }
+
+ @Override
+ public long count(Q query) {
+ try {
+ final String indexName = indexResolver(query.getScopeId());
+ synchIndex(indexName);
+
+ return elasticsearchClientProviderInstance.getElasticsearchClient().count(getDescriptor(indexName), query);
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void delete(KapuaId scopeId, StorableId id) {
+ final String indexName = indexResolver(scopeId);
+ doDelete(indexName, id);
+ }
+
+ protected void doDelete(String indexName, StorableId id) {
+ try {
+ synchIndex(indexName);
+
+ elasticsearchClientProviderInstance.getElasticsearchClient().delete(getDescriptor(indexName), id.toString());
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void delete(Q query) {
+ try {
+ elasticsearchClientProviderInstance.getElasticsearchClient().deleteByQuery(getDescriptor(indexResolver(query.getScopeId())), query);
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String upsert(String itemId, T item) {
+ try {
+ final String indexName = indexResolver(item.getScopeId());
+ synchIndex(indexName);
+
+ final UpdateRequest request = new UpdateRequest(itemId.toString(), getDescriptor(indexName), item);
+ final UpdateResponse upsertResponse;
+ upsertResponse = elasticsearchClientProviderInstance.getElasticsearchClient().upsert(request);
+ final String responseId = upsertResponse.getId();
+ logger.debug("Upsert successfully executed [{}.{}, {} - {}]", indexName, type, itemId, responseId);
+ return responseId;
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Set upsert(List items) {
+ try {
+ final List requests = items.stream()
+ .map(storableItem -> new UpdateRequest(
+ idExtractor(storableItem).toString(),
+ getDescriptor(indexResolver(storableItem.getScopeId())),
+ storableItem))
+ .collect(Collectors.toList());
+ requests.stream().map(r -> r.getStorable().getScopeId()).collect(Collectors.toSet())
+ .forEach(scopeId -> {
+ final String indexName = indexResolver(scopeId);
+ synchIndex(indexName);
+ });
+ final BulkUpdateRequest bulkUpdateRequest = new BulkUpdateRequest();
+ bulkUpdateRequest.setRequest(requests);
+ final BulkUpdateResponse updateResponse = elasticsearchClientProviderInstance
+ .getElasticsearchClient()
+ .upsert(bulkUpdateRequest);
+ return updateResponse.getResponse()
+ .stream()
+ .peek(response -> {
+ String index = response.getTypeDescriptor().getIndex();
+ String type = response.getTypeDescriptor().getType();
+ String id = response.getId();
+ logger.debug("Upsert successfully executed [{}.{}, {}]", index, type, id);
+ }).map(Response::getId)
+ .collect(Collectors.toSet());
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ protected void doUpsertIndex(String indexName) {
+ final ElasticsearchClient elasticsearchClient;
+ try {
+ elasticsearchClient = elasticsearchClientProviderInstance.getElasticsearchClient();
+ // Check existence of the kapua internal indexes
+ IndexResponse indexExistsResponse = elasticsearchClient.isIndexExists(new IndexRequest(indexName));
+ if (!indexExistsResponse.isIndexExists()) {
+ elasticsearchClient.createIndex(indexName, getMappingSchema(indexName));
+ logger.info("Index created: {}", indexExistsResponse);
+ elasticsearchClient.putMapping(getDescriptor(indexName), getIndexSchema());
+ }
+ } catch (ClientException | MappingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ public TypeDescriptor getDescriptor(String indexName) {
+ return new TypeDescriptor(indexName, type);
+ }
+
+ @Override
+ public void refreshAllIndexes() {
+ try {
+ this.indexUpserted.invalidateAll();
+ elasticsearchClientProviderInstance.getElasticsearchClient().refreshAllIndexes();
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void deleteAllIndexes() {
+ try {
+ this.indexUpserted.invalidateAll();
+ elasticsearchClientProviderInstance.getElasticsearchClient().deleteAllIndexes();
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void deleteIndexes(String indexExp) {
+ try {
+ this.indexUpserted.invalidateAll();
+ elasticsearchClientProviderInstance.getElasticsearchClient().deleteIndexes(indexExp);
+ } catch (ClientException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/configuration/ElasticsearchClientConfiguration.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/configuration/ElasticsearchClientConfiguration.java
index 7c38c94d91c..2bd6809fbbf 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/configuration/ElasticsearchClientConfiguration.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/configuration/ElasticsearchClientConfiguration.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.service.elasticsearch.client.configuration;
import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClient;
-import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
import java.util.ArrayList;
import java.util.List;
@@ -56,27 +55,6 @@ public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
- /**
- * Gets the {@link ElasticsearchClientProvider} implementing {@link Class#getName()}.
- *
- * @return The {@link ElasticsearchClientProvider} implementing {@link Class#getName()}.
- */
- public String getProviderClassName() {
- return providerClassName;
- }
-
- /**
- * Sets the {@link ElasticsearchClientProvider} implementing {@link Class#getName()}.
- *
- * @param providerClassName The {@link ElasticsearchClientProvider} implementing {@link Class#getName()}.
- * @return This {@link ElasticsearchClientConfiguration} to chain method invocation.
- * @since 1.3.0
- */
- public ElasticsearchClientConfiguration setProviderClassName(String providerClassName) {
- this.providerClassName = providerClassName;
- return this;
- }
-
/**
* Gets the Elasticsearch cluster name to use.
*
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/IndexResponse.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/IndexResponse.java
index c93f79ab9c9..b627354dfee 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/IndexResponse.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/IndexResponse.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.elasticsearch.client.model;
+import java.util.Arrays;
+
/**
* {@link IndexResponse} definition.
*
@@ -62,4 +64,11 @@ public String[] getIndexes() {
return indexes;
}
+ @Override
+ public String toString() {
+ return "IndexResponse{" +
+ "indexExists=" + indexExists +
+ ", indexes=" + Arrays.toString(indexes) +
+ '}';
+ }
}
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/InsertRequest.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/InsertRequest.java
index 0daefac0381..63d0197a55d 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/InsertRequest.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/InsertRequest.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.elasticsearch.client.model;
+import org.eclipse.kapua.service.storable.model.Storable;
+
/**
* Insert {@link Request} definition.
*
@@ -27,7 +29,7 @@ public class InsertRequest extends Request {
* @param storable The Object to insert.
* @since 1.0.0
*/
- public InsertRequest(String id, TypeDescriptor typeDescriptor, Object storable) {
+ public InsertRequest(String id, TypeDescriptor typeDescriptor, Storable storable) {
super(id, typeDescriptor, storable);
}
}
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/Request.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/Request.java
index 9e818da4ca8..cc6a2ac3904 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/Request.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/Request.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.elasticsearch.client.model;
+import org.eclipse.kapua.service.storable.model.Storable;
+
/**
* Base {@link Request} definition.
*
@@ -36,7 +38,7 @@ public abstract class Request {
/**
* The Object of the {@link Request}
*/
- private Object storable;
+ private Storable storable;
/**
* Constructor.
@@ -45,7 +47,7 @@ public abstract class Request {
* @param storable the objetc of the request
* @since 1.0.0
*/
- protected Request(String id, TypeDescriptor typeDescriptor, Object storable) {
+ protected Request(String id, TypeDescriptor typeDescriptor, Storable storable) {
setId(id);
setTypeDescriptor(typeDescriptor);
setStorable(storable);
@@ -97,7 +99,7 @@ public void setTypeDescriptor(TypeDescriptor typeDescriptor) {
* @return The object of the request.
* @since 1.0.0
*/
- public Object getStorable() {
+ public Storable getStorable() {
return storable;
}
@@ -107,7 +109,7 @@ public Object getStorable() {
* @param storable The object of the request.
* @since 1.0.0
*/
- public void setStorable(Object storable) {
+ public void setStorable(Storable storable) {
this.storable = storable;
}
diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/UpdateRequest.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/UpdateRequest.java
index 7eb86c40291..e31946ff01b 100644
--- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/UpdateRequest.java
+++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/model/UpdateRequest.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.elasticsearch.client.model;
+import org.eclipse.kapua.service.storable.model.Storable;
+
/**
* Update {@link Request} definition.
*
@@ -27,7 +29,7 @@ public class UpdateRequest extends Request {
* @param storable The Object to update.
* @since 1.0.0
*/
- public UpdateRequest(String id, TypeDescriptor typeDescriptor, Object storable) {
+ public UpdateRequest(String id, TypeDescriptor typeDescriptor, Storable storable) {
super(id, typeDescriptor, storable);
}
diff --git a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/MetricsEsClient.java b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/MetricsEsClient.java
index 1c5545d539b..9fe673e3a2a 100644
--- a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/MetricsEsClient.java
+++ b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/MetricsEsClient.java
@@ -12,13 +12,15 @@
*******************************************************************************/
package org.eclipse.kapua.service.elasticsearch.client.rest;
-import org.eclipse.kapua.commons.metric.CommonsMetric;
-import org.eclipse.kapua.commons.metric.MetricServiceFactory;
+import com.codahale.metrics.Counter;
import org.eclipse.kapua.commons.metric.MetricsLabel;
import org.eclipse.kapua.commons.metric.MetricsService;
-import com.codahale.metrics.Counter;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+@Singleton
public class MetricsEsClient {
public static final String REST_CLIENT = "rest_client";
@@ -35,25 +37,18 @@ public class MetricsEsClient {
private Counter timeoutRetry;
private Counter timeoutRetryLimitReached;
- private static MetricsEsClient instance;
-
- public synchronized static MetricsEsClient getInstance() {
- if (instance == null) {
- instance = new MetricsEsClient();
- }
- return instance;
- }
-
- private MetricsEsClient() {
- MetricsService metricsService = MetricServiceFactory.getInstance();
+ @Inject
+ private MetricsEsClient(MetricsService metricsService,
+ @Named("metricModuleName")
+ String metricModuleName) {
//timeout
- timeoutRetry = metricsService.getCounter(CommonsMetric.module, REST_CLIENT, TIMEOUT_RETRY);
- timeoutRetryLimitReached = metricsService.getCounter(CommonsMetric.module, REST_CLIENT, TIMEOUT_RETRY_LIMIT_REACHED);
- clientReconnectCall = metricsService.getCounter(CommonsMetric.module, REST_CLIENT, RECONNECT_CALL);
+ timeoutRetry = metricsService.getCounter(metricModuleName, REST_CLIENT, TIMEOUT_RETRY);
+ timeoutRetryLimitReached = metricsService.getCounter(metricModuleName, REST_CLIENT, TIMEOUT_RETRY_LIMIT_REACHED);
+ clientReconnectCall = metricsService.getCounter(metricModuleName, REST_CLIENT, RECONNECT_CALL);
//exception
- exception = metricsService.getCounter(CommonsMetric.module, REST_CLIENT, MetricsLabel.ERROR);
- runtimeException = metricsService.getCounter(CommonsMetric.module, REST_CLIENT, RUNTIME_ERROR);
+ exception = metricsService.getCounter(metricModuleName, REST_CLIENT, MetricsLabel.ERROR);
+ runtimeException = metricsService.getCounter(metricModuleName, REST_CLIENT, RUNTIME_ERROR);
}
public Counter getException() {
diff --git a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClient.java b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClient.java
index e6f256c35f3..951add4f56e 100644
--- a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClient.java
+++ b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClient.java
@@ -44,7 +44,6 @@
import org.eclipse.kapua.service.elasticsearch.client.model.UpdateResponse;
import org.eclipse.kapua.service.elasticsearch.client.rest.exception.RequestEntityWriteError;
import org.eclipse.kapua.service.elasticsearch.client.rest.exception.ResponseEntityReadError;
-
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
@@ -52,6 +51,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
@@ -78,14 +78,17 @@ public class RestElasticsearchClient extends AbstractElasticsearchClient getClient().performRequest(request), insertRequest.getTypeDescriptor().getIndex(),"INSERT");
+ Response insertResponse = restCallTimeoutHandler(() -> getClient().performRequest(request), insertRequest.getTypeDescriptor().getIndex(), "INSERT");
if (isRequestSuccessful(insertResponse)) {
JsonNode responseNode = readResponseAsJsonNode(insertResponse);
@@ -364,7 +367,7 @@ public IndexResponse findIndexes(IndexRequest indexRequest) throws ClientExcepti
LOG.debug("Find indexes - index prefix: '{}'", indexRequest.getIndex());
Request request = new Request(ElasticsearchKeywords.ACTION_GET, ElasticsearchResourcePaths.findIndex(indexRequest.getIndex()));
request.addParameter("pretty", "true");
- Response findIndexResponse = restCallTimeoutHandler(() -> getClient().performRequest(request), indexRequest.getIndex(),"INDEX EXIST");
+ Response findIndexResponse = restCallTimeoutHandler(() -> getClient().performRequest(request), indexRequest.getIndex(), "INDEX EXIST");
if (isRequestSuccessful(findIndexResponse)) {
try {
@@ -475,7 +478,7 @@ private Response restCallTimeoutHandler(Callable restAction, String in
return restAction.call();
} catch (RuntimeException e) {
if (e.getCause() instanceof TimeoutException) {
- MetricsEsClient.getInstance().getTimeoutRetry().inc();
+ metricsEsClient.getTimeoutRetry().inc();
if (retryCount < getClientConfiguration().getRequestConfiguration().getRequestRetryAttemptMax() - 1) {
try {
Thread.sleep((long) (getClientConfiguration().getRequestConfiguration().getRequestRetryAttemptWait() * (0.5 + RANDOM.nextFloat() / 2)));
@@ -495,7 +498,7 @@ private Response restCallTimeoutHandler(Callable restAction, String in
} catch (Exception e) {
throw new ClientInternalError(e, "Error in handling REST timeout handler");
}
- MetricsEsClient.getInstance().getTimeoutRetryLimitReached().inc();
+ metricsEsClient.getTimeoutRetryLimitReached().inc();
throw new ClientCommunicationException();
}
diff --git a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClientProvider.java b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClientProvider.java
index 373b3a8afe7..f6723b25a81 100644
--- a/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClientProvider.java
+++ b/service/commons/elasticsearch/client-rest/src/main/java/org/eclipse/kapua/service/elasticsearch/client/rest/RestElasticsearchClientProvider.java
@@ -14,6 +14,7 @@
package org.eclipse.kapua.service.elasticsearch.client.rest;
import com.google.common.base.Strings;
+import com.google.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
@@ -57,7 +58,6 @@
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
-import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
@@ -88,13 +88,18 @@ public class RestElasticsearchClientProvider implements ElasticsearchClientProvi
private ScheduledExecutorService reconnectExecutorTask;
private MetricsEsClient metrics;
+ private boolean initialized;
- public RestElasticsearchClientProvider() {
- metrics = MetricsEsClient.getInstance();
+ @Inject
+ public RestElasticsearchClientProvider(MetricsEsClient metricsEsClient) {
+ this.metrics = metricsEsClient;
}
@Override
public RestElasticsearchClientProvider init() throws ClientProviderInitException {
+ if (initialized) {
+ return this;
+ }
synchronized (RestElasticsearchClientProvider.class) {
if (elasticsearchClientConfiguration == null) {
throw new ClientProviderInitException("Client configuration not defined");
@@ -176,7 +181,7 @@ public RestElasticsearchClientProvider init() throws ClientProviderInitException
LOG.info(">>> Initializing Elasticsearch REST client... Connecting... Error: {}", e.getMessage(), e);
}
}, getClientReconnectConfiguration().getReconnectDelay(), getClientReconnectConfiguration().getReconnectDelay(), TimeUnit.MILLISECONDS);
-
+ initialized = true;
return this;
}
}
@@ -269,20 +274,41 @@ private RestClient initClient() throws ClientInitializationException {
boolean sslEnabled = clientConfiguration.getSslConfiguration().isEnabled();
LOG.info("ES Rest Client - SSL Layer: {}", (sslEnabled ? "Enabled" : "Disabled "));
- List hosts = new ArrayList<>();
+ List hosts;
try {
- InetAddressParser
+ hosts = InetAddressParser
.parseAddresses(clientConfiguration.getNodes())
.stream()
- .map(inetSocketAddress ->
- new HttpHost(
- inetSocketAddress.getAddress(),
- inetSocketAddress.getHostName(),
- inetSocketAddress.getPort(),
- (sslEnabled ? "https" : "http"))
+ .peek(inetSocketAddress -> LOG.info("Evaluating address: {}", inetSocketAddress))
+ .filter(inetSocketAddress -> {
+ if (inetSocketAddress == null) {
+ LOG.warn("Null Inet Socket Address! Skipping...");
+ return false;
+ }
+ return true;
+ }).filter(inetSocketAddress -> {
+ if (inetSocketAddress.getAddress() == null) {
+ LOG.warn("Invalid Inet Socket Address! Skipping...");
+ return false;
+ }
+ return true;
+ }).filter(inetSocketAddress -> {
+ if (inetSocketAddress.getHostName() == null) {
+ LOG.warn("Invalid Inet Socket hostname! Skipping...");
+ return false;
+ }
+ return true;
+ })
+ .map(inetSocketAddress -> {
+ LOG.info("Inet Socket Address: {}", inetSocketAddress);
+ return new HttpHost(
+ inetSocketAddress.getAddress(),
+ inetSocketAddress.getHostName(),
+ inetSocketAddress.getPort(),
+ (sslEnabled ? "https" : "http"));
+ }
)
- .collect(Collectors.toCollection(() -> hosts));
-
+ .collect(Collectors.toList());
} catch (Exception e) {
throw new ClientInitializationException(e, "Error while parsing node addresses!");
}
@@ -319,7 +345,7 @@ private RestClient initClient() throws ClientInitializationException {
RestClient restClient = restClientBuilder.build();
// Init Kapua Elasticsearch Client
- restElasticsearchClient = new RestElasticsearchClient();
+ restElasticsearchClient = new RestElasticsearchClient(metrics);
restElasticsearchClient
.withClientConfiguration(clientConfiguration)
.withModelContext(modelContext)
@@ -387,7 +413,8 @@ public ElasticsearchClientProvider withModelConverter(Q
}
@Override
- public RestElasticsearchClient getElasticsearchClient() throws ClientUnavailableException {
+ public RestElasticsearchClient getElasticsearchClient() throws ClientUnavailableException, ClientProviderInitException {
+ this.init();
if (restElasticsearchClient == null) {
throw new ClientUnavailableException("Client not initialized");
}
diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/id/StorableIdXmlAdapter.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/id/StorableIdXmlAdapter.java
index b4716101ac6..a912b184d72 100644
--- a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/id/StorableIdXmlAdapter.java
+++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/id/StorableIdXmlAdapter.java
@@ -25,8 +25,7 @@
*/
public class StorableIdXmlAdapter extends XmlAdapter {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
+ private final StorableIdFactory storableIdFactory = KapuaLocator.getInstance().getFactory(StorableIdFactory.class);
@Override
public String marshal(StorableId storableId) {
@@ -35,7 +34,7 @@ public String marshal(StorableId storableId) {
@Override
public StorableId unmarshal(String storableIdString) {
- return STORABLE_ID_FACTORY.newStorableId(storableIdString);
+ return storableIdFactory.newStorableId(storableIdString);
}
}
diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/repository/StorableRepository.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/repository/StorableRepository.java
new file mode 100644
index 00000000000..6df3f8b0b93
--- /dev/null
+++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/repository/StorableRepository.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.storable.repository;
+
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.storable.model.Storable;
+import org.eclipse.kapua.service.storable.model.StorableListResult;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.StorableQuery;
+
+import java.util.List;
+import java.util.Set;
+
+public interface StorableRepository<
+ T extends Storable,
+ L extends StorableListResult,
+ Q extends StorableQuery> {
+ String upsert(String itemId, T item);
+
+ Set upsert(List items);
+
+ T find(KapuaId scopeId, StorableId id);
+
+ L query(Q query);
+
+ long count(Q query);
+
+ void delete(KapuaId scopeId, StorableId id);
+
+ void delete(Q query);
+
+ void refreshAllIndexes();
+
+ void deleteAllIndexes();
+
+ void deleteIndexes(String indexExp);
+
+}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoRegistryService.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoRegistryService.java
index b43825dfe60..24c23b3289a 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoRegistryService.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoRegistryService.java
@@ -12,11 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.KapuaService;
import org.eclipse.kapua.service.datastore.model.ChannelInfo;
import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
import org.eclipse.kapua.service.storable.StorableService;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
/**
* {@link ChannelInfoRegistryService} definition.
@@ -26,4 +29,9 @@
* @since 1.0.0
*/
public interface ChannelInfoRegistryService extends KapuaService, StorableService {
+ void delete(KapuaId scopeId, StorableId id)
+ throws KapuaException;
+
+ void delete(ChannelInfoQuery query)
+ throws KapuaException;
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoRegistryService.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoRegistryService.java
index 581a01b47c3..478a0ea2136 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoRegistryService.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoRegistryService.java
@@ -12,11 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.KapuaService;
import org.eclipse.kapua.service.datastore.model.ClientInfo;
import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
import org.eclipse.kapua.service.storable.StorableService;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
/**
* {@link ClientInfoRegistryService} definition.
@@ -26,4 +29,9 @@
* @since 1.0.0
*/
public interface ClientInfoRegistryService extends KapuaService, StorableService {
+ void delete(ClientInfoQuery query)
+ throws KapuaException;
+
+ void delete(KapuaId scopeId, StorableId id)
+ throws KapuaException;
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoRegistryService.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoRegistryService.java
index 1612e896eef..87d3ab7ac47 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoRegistryService.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoRegistryService.java
@@ -12,11 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.KapuaService;
import org.eclipse.kapua.service.datastore.model.MetricInfo;
import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
import org.eclipse.kapua.service.storable.StorableService;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
/**
* {@link MetricInfoRegistryService} definition.
@@ -26,4 +29,9 @@
* @since 1.0.0
*/
public interface MetricInfoRegistryService extends KapuaService, StorableService {
+ void delete(MetricInfoQuery query)
+ throws KapuaException;
+
+ void delete(KapuaId scopeId, StorableId id)
+ throws KapuaException;
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java
index 745a25904c0..5882830e5b5 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java
@@ -27,8 +27,7 @@
@XmlRegistry
public class ChannelInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final ChannelInfoFactory CHANNEL_INFO_FACTORY = LOCATOR.getFactory(ChannelInfoFactory.class);
+ private final ChannelInfoFactory channelInfoFactory = KapuaLocator.getInstance().getFactory(ChannelInfoFactory.class);
/**
* Creates a {@link ChannelInfoListResult} instance
@@ -36,7 +35,7 @@ public class ChannelInfoXmlRegistry {
* @return
*/
public ChannelInfoListResult newListResult() {
- return CHANNEL_INFO_FACTORY.newListResult();
+ return channelInfoFactory.newListResult();
}
/**
@@ -45,6 +44,6 @@ public ChannelInfoListResult newListResult() {
* @return
*/
public ChannelInfoQuery newQuery() {
- return CHANNEL_INFO_FACTORY.newQuery(null);
+ return channelInfoFactory.newQuery(null);
}
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java
index 89c22577783..591a130db8b 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java
@@ -27,8 +27,7 @@
@XmlRegistry
public class ClientInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final ClientInfoFactory CLIENT_INFO_FACTORY = LOCATOR.getFactory(ClientInfoFactory.class);
+ private final ClientInfoFactory clientInfoFactory = KapuaLocator.getInstance().getFactory(ClientInfoFactory.class);
/**
* Creates a {@link ClientInfoListResult} instance
@@ -36,7 +35,7 @@ public class ClientInfoXmlRegistry {
* @return
*/
public ClientInfoListResult newListResult() {
- return CLIENT_INFO_FACTORY.newListResult();
+ return clientInfoFactory.newListResult();
}
/**
@@ -45,6 +44,6 @@ public ClientInfoListResult newListResult() {
* @return
*/
public ClientInfoQuery newQuery() {
- return CLIENT_INFO_FACTORY.newQuery(null);
+ return clientInfoFactory.newQuery(null);
}
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java
index 5f9076ad9b4..b687541185f 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java
@@ -27,8 +27,7 @@
@XmlRegistry
public class DatastoreMessageXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final MessageStoreFactory MESSAGE_STORE_FACTORY = LOCATOR.getFactory(MessageStoreFactory.class);
+ private final MessageStoreFactory messageStoreFactory = KapuaLocator.getInstance().getFactory(MessageStoreFactory.class);
/**
* Creates a {@link MessageListResult} instance
@@ -36,7 +35,7 @@ public class DatastoreMessageXmlRegistry {
* @return
*/
public MessageListResult newListResult() {
- return MESSAGE_STORE_FACTORY.newListResult();
+ return messageStoreFactory.newListResult();
}
/**
@@ -45,6 +44,6 @@ public MessageListResult newListResult() {
* @return
*/
public MessageQuery newQuery() {
- return MESSAGE_STORE_FACTORY.newQuery(null);
+ return messageStoreFactory.newQuery(null);
}
}
diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java
index e23a9f4770e..36ab6c9480a 100644
--- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java
+++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java
@@ -27,8 +27,7 @@
@XmlRegistry
public class MetricInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final MetricInfoFactory METRIC_INFO_FACTORY = LOCATOR.getFactory(MetricInfoFactory.class);
+ private final MetricInfoFactory metricInfoFactory = KapuaLocator.getInstance().getFactory(MetricInfoFactory.class);
/**
* Creates a {@link MetricInfoListResult} instance
@@ -36,7 +35,7 @@ public class MetricInfoXmlRegistry {
* @return
*/
public MetricInfoListResult newListResult() {
- return METRIC_INFO_FACTORY.newListResult();
+ return metricInfoFactory.newListResult();
}
/**
@@ -45,6 +44,6 @@ public MetricInfoListResult newListResult() {
* @return
*/
public MetricInfoQuery newQuery() {
- return METRIC_INFO_FACTORY.newQuery(null);
+ return metricInfoFactory.newQuery(null);
}
}
diff --git a/service/datastore/internal/pom.xml b/service/datastore/internal/pom.xml
index fbffb7c1d30..59e98f97bae 100644
--- a/service/datastore/internal/pom.xml
+++ b/service/datastore/internal/pom.xml
@@ -75,7 +75,10 @@
org.eclipse.kapua
kapua-locator-guice
- test
+
+
+ org.eclipse.kapua
+ kapua-service-elasticsearch-client-rest
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractDatastoreFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractDatastoreFacade.java
new file mode 100644
index 00000000000..35f294efb40
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractDatastoreFacade.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
+import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class AbstractDatastoreFacade {
+
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractDatastoreFacade.class);
+
+ protected final ConfigurationProvider configProvider;
+
+ public AbstractDatastoreFacade(ConfigurationProvider configProvider) {
+ this.configProvider = configProvider;
+ }
+
+ protected boolean isDatastoreServiceEnabled(KapuaId scopeId) throws ConfigurationException {
+ MessageStoreConfiguration messageStoreConfiguration = configProvider.getConfiguration(scopeId);
+ long ttl = messageStoreConfiguration.getDataTimeToLiveMilliseconds();
+
+ return messageStoreConfiguration.getDataStorageEnabled() && ttl != MessageStoreConfiguration.DISABLED;
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractRegistryFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractRegistryFacade.java
deleted file mode 100644
index 504d2a0b063..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/AbstractRegistryFacade.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal;
-
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.client.DatastoreClientFactory;
-import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
-import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration;
-import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClient;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientUnavailableException;
-import org.eclipse.kapua.service.storable.model.Storable;
-import org.eclipse.kapua.service.storable.model.StorableListResult;
-import org.eclipse.kapua.service.storable.model.query.StorableQuery;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractRegistryFacade {
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractRegistryFacade.class);
-
- private final ConfigurationProvider configProvider;
-
- public AbstractRegistryFacade(ConfigurationProvider configProvider) {
- this.configProvider = configProvider;
- }
-
- public ConfigurationProvider getConfigProvider() {
- return configProvider;
- }
-
- protected boolean isDatastoreServiceEnabled(KapuaId scopeId) throws ConfigurationException {
- MessageStoreConfiguration messageStoreConfiguration = configProvider.getConfiguration(scopeId);
- long ttl = messageStoreConfiguration.getDataTimeToLiveMilliseconds();
-
- return messageStoreConfiguration.getDataStorageEnabled() && ttl != MessageStoreConfiguration.DISABLED;
- }
-
- protected ElasticsearchClient> getElasticsearchClient() throws ClientUnavailableException {
- return DatastoreClientFactory.getElasticsearchClient();
- }
-
- protected void setLimitExceed(StorableQuery query, boolean hitsExceedsTotalCount, StorableListResult list) {
- int offset = query.getOffset() != null ? query.getOffset() : 0;
- if (query.getLimit() != null) {
- if (hitsExceedsTotalCount || //pre-condition: there are more than 10k documents in ES && query limit is <= 10k
- list.getTotalCount() > offset + query.getLimit()) {
- list.setLimitExceeded(true);
- }
- }
- }
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java
new file mode 100644
index 00000000000..b0a048f42ff
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.ChannelInfoFactory;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
+import org.eclipse.kapua.service.datastore.model.ChannelInfo;
+import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+
+import javax.inject.Inject;
+
+public class ChannelInfoElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements ChannelInfoRepository {
+
+ private final DatastoreUtils datastoreUtils;
+
+ @Inject
+ protected ChannelInfoElasticsearchRepository(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ ChannelInfoFactory channelInfoFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ DatastoreSettings datastoreSettings,
+ DatastoreUtils datastoreUtils,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(elasticsearchClientProviderInstance,
+ ChannelInfoSchema.CHANNEL_TYPE_NAME,
+ ChannelInfo.class,
+ channelInfoFactory,
+ storablePredicateFactory,
+ datastoreCacheManager.getChannelsCache(),
+ datastoreSettings);
+ this.datastoreUtils = datastoreUtils;
+ }
+
+ @Override
+ protected StorableId idExtractor(ChannelInfo storable) {
+ return storable.getId();
+ }
+
+ @Override
+ protected String indexResolver(KapuaId scopeId) {
+ return datastoreUtils.getChannelIndexName(scopeId);
+ }
+
+ @Override
+ protected JsonNode getIndexSchema() throws MappingException {
+ return ChannelInfoSchema.getChannelTypeSchema();
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacade.java
index c464931d899..86af3ab6006 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacade.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacade.java
@@ -13,244 +13,25 @@
package org.eclipse.kapua.service.datastore.internal;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField;
-import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoRegistryMediator;
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
-import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoListResultImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.internal.schema.SchemaUtil;
import org.eclipse.kapua.service.datastore.model.ChannelInfo;
import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.model.ResultList;
-import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateResponse;
import org.eclipse.kapua.service.storable.exception.MappingException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
-import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
-import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
-import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/**
- * Channel information registry facade
- *
- * @since 1.0.0
- */
-public class ChannelInfoRegistryFacade extends AbstractRegistryFacade {
-
- private static final Logger LOG = LoggerFactory.getLogger(ChannelInfoRegistryFacade.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
- private final ChannelInfoRegistryMediator mediator;
- private final Object metadataUpdateSync = new Object();
-
- private static final String QUERY = "query";
- private static final String QUERY_SCOPE_ID = "query.scopeId";
-
- /**
- * Constructs the channel info registry facade
- *
- * @param configProvider
- * @param mediator
- * @since 1.0.0
- */
- public ChannelInfoRegistryFacade(ConfigurationProvider configProvider, ChannelInfoRegistryMediator mediator) {
- super(configProvider);
-
- this.mediator = mediator;
- }
-
- /**
- * Update the channel information after a message store operation
- *
- * @param channelInfo
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public StorableId upstore(ChannelInfo channelInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
- ArgumentValidator.notNull(channelInfo, "channelInfo");
- ArgumentValidator.notNull(channelInfo.getScopeId(), "channelInfo.scopeId");
- ArgumentValidator.notNull(channelInfo.getName(), "channelInfo.name");
- ArgumentValidator.notNull(channelInfo.getFirstMessageId(), "channelInfo.messageId");
- ArgumentValidator.notNull(channelInfo.getFirstMessageOn(), "channelInfo.messageTimestamp");
-
- String channelInfoId = ChannelInfoField.getOrDeriveId(channelInfo.getId(), channelInfo);
- StorableId storableId = STORABLE_ID_FACTORY.newStorableId(channelInfoId);
-
- UpdateResponse response;
- // Store channel. Look up channel in the cache, and cache it if it doesn't exist
- if (!DatastoreCacheManager.getInstance().getChannelsCache().get(channelInfoId)) {
- // The code is safe even without the synchronized block
- // Synchronize in order to let the first thread complete its
- // update then the others of the same type will find the cache
- // updated and skip the update.
- synchronized (metadataUpdateSync) {
- if (!DatastoreCacheManager.getInstance().getChannelsCache().get(channelInfoId)) {
- ChannelInfo storedField = find(channelInfo.getScopeId(), storableId);
- if (storedField == null) {
- Metadata metadata = mediator.getMetadata(channelInfo.getScopeId(), channelInfo.getFirstMessageOn().getTime());
- String registryIndexName = metadata.getChannelRegistryIndexName();
-
- UpdateRequest request = new UpdateRequest(channelInfo.getId().toString(), new TypeDescriptor(metadata.getChannelRegistryIndexName(), ChannelInfoSchema.CHANNEL_TYPE_NAME), channelInfo);
- response = getElasticsearchClient().upsert(request);
-
- LOG.debug("Upsert on channel successfully executed [{}.{}, {} - {}]", registryIndexName, ChannelInfoSchema.CHANNEL_TYPE_NAME, channelInfoId, response.getId());
- }
- // Update cache if channel update is completed successfully
- DatastoreCacheManager.getInstance().getChannelsCache().put(channelInfoId, true);
- }
- }
- }
- return storableId;
- }
-
- /**
- * Delete channel information by identifier.
- *
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the channel info registry entry by id without checking the consistency of the others registries or the message store.
- *
- * @param scopeId
- * @param id
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- if (!isDatastoreServiceEnabled(scopeId)) {
- LOG.debug("Storage not enabled for account {}, return", scopeId);
- return;
- }
-
- String indexName = SchemaUtil.getChannelIndexName(scopeId);
- ChannelInfo channelInfo = find(scopeId, id);
- if (channelInfo != null) {
- mediator.onBeforeChannelInfoDelete(channelInfo);
-
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- getElasticsearchClient().delete(typeDescriptor, id.toString());
- }
- }
-
- /**
- * Find channel information by identifier
- *
- * @param scopeId
- * @param id
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public ChannelInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- ChannelInfoQueryImpl idsQuery = new ChannelInfoQueryImpl(scopeId);
- idsQuery.setLimit(1);
-
- IdsPredicate idsPredicate = STORABLE_PREDICATE_FACTORY.newIdsPredicate(ChannelInfoSchema.CHANNEL_TYPE_NAME);
- idsPredicate.addId(id);
- idsQuery.setPredicate(idsPredicate);
-
- ChannelInfoListResult result = query(idsQuery);
- return result.getFirstItem();
- }
-
- /**
- * Find channels informations matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public ChannelInfoListResult query(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return new ChannelInfoListResultImpl();
- }
-
- String indexName = SchemaUtil.getChannelIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- ResultList rl = getElasticsearchClient().query(typeDescriptor, query, ChannelInfo.class);
- ChannelInfoListResult result = new ChannelInfoListResultImpl(rl);
- setLimitExceed(query, rl.getTotalHitsExceedsCount(), result);
- return result;
- }
-
- /**
- * Get channels informations count matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public long count(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return 0;
- }
-
- String indexName = SchemaUtil.getChannelIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- return getElasticsearchClient().count(typeDescriptor, query);
- }
+public interface ChannelInfoRegistryFacade {
+ StorableId upstore(ChannelInfo channelInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException;
- /**
- * Delete channels informations count matching the given query.
- *
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the channel info registry entries that matching the query without checking the consistency of the others registries or the message store.
- *
- * @param query
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- void delete(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
- return;
- }
+ void delete(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- String indexName = SchemaUtil.getChannelIndexName(query.getScopeId());
- ChannelInfoListResult channels = query(query);
+ ChannelInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- for (ChannelInfo channelInfo : channels.getItems()) {
- mediator.onBeforeChannelInfoDelete(channelInfo);
- }
+ ChannelInfoListResult query(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeDescriptor, query);
- }
+ long count(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java
new file mode 100644
index 00000000000..a181ede2bf3
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java
@@ -0,0 +1,236 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.KapuaIllegalArgumentException;
+import org.eclipse.kapua.commons.util.ArgumentValidator;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField;
+import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
+import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoListResultImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl;
+import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema;
+import org.eclipse.kapua.service.datastore.model.ChannelInfo;
+import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
+import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+
+/**
+ * Channel information registry facade
+ *
+ * @since 1.0.0
+ */
+public class ChannelInfoRegistryFacadeImpl extends AbstractDatastoreFacade implements ChannelInfoRegistryFacade {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ChannelInfoRegistryFacadeImpl.class);
+
+ private final StorableIdFactory storableIdFactory;
+ private final StorablePredicateFactory storablePredicateFactory;
+ private final ChannelInfoRepository repository;
+ private final DatastoreCacheManager datastoreCacheManager;
+ private final Object metadataUpdateSync = new Object();
+
+ private static final String QUERY = "query";
+ private static final String QUERY_SCOPE_ID = "query.scopeId";
+
+ /**
+ * Constructs the channel info registry facade
+ *
+ * @param configProvider
+ * @since 1.0.0
+ */
+ @Inject
+ public ChannelInfoRegistryFacadeImpl(
+ ConfigurationProvider configProvider,
+ StorableIdFactory storableIdFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ ChannelInfoRepository channelInfoRepository,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(configProvider);
+ this.storableIdFactory = storableIdFactory;
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.repository = channelInfoRepository;
+ this.datastoreCacheManager = datastoreCacheManager;
+ }
+
+ /**
+ * Update the channel information after a message store operation
+ *
+ * @param channelInfo
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public StorableId upstore(ChannelInfo channelInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
+ ArgumentValidator.notNull(channelInfo, "channelInfo");
+ ArgumentValidator.notNull(channelInfo.getScopeId(), "channelInfo.scopeId");
+ ArgumentValidator.notNull(channelInfo.getName(), "channelInfo.name");
+ ArgumentValidator.notNull(channelInfo.getFirstMessageId(), "channelInfo.messageId");
+ ArgumentValidator.notNull(channelInfo.getFirstMessageOn(), "channelInfo.messageTimestamp");
+
+ String channelInfoId = ChannelInfoField.getOrDeriveId(channelInfo.getId(), channelInfo);
+ StorableId storableId = storableIdFactory.newStorableId(channelInfoId);
+
+ // Store channel. Look up channel in the cache, and cache it if it doesn't exist
+ if (!datastoreCacheManager.getChannelsCache().get(channelInfoId)) {
+ // The code is safe even without the synchronized block
+ // Synchronize in order to let the first thread complete its
+ // update then the others of the same type will find the cache
+ // updated and skip the update.
+ synchronized (metadataUpdateSync) {
+ if (!datastoreCacheManager.getChannelsCache().get(channelInfoId)) {
+ ChannelInfo storedField = doFind(channelInfo.getScopeId(), storableId);
+ if (storedField == null) {
+ repository.upsert(channelInfoId, channelInfo);
+ }
+ // Update cache if channel update is completed successfully
+ datastoreCacheManager.getChannelsCache().put(channelInfoId, true);
+ }
+ }
+ }
+ return storableId;
+ }
+
+ /**
+ * Delete channel information by identifier.
+ *
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the channel info registry entry by id without checking the consistency of the others registries or the message store.
+ *
+ * @param scopeId
+ * @param id
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(scopeId, "scopeId");
+ ArgumentValidator.notNull(id, "id");
+
+ if (!isDatastoreServiceEnabled(scopeId)) {
+ LOG.debug("Storage not enabled for account {}, return", scopeId);
+ return;
+ }
+
+ ChannelInfo channelInfo = doFind(scopeId, id);
+ if (channelInfo != null) {
+ repository.delete(scopeId, id);
+ }
+ }
+
+ /**
+ * Find channel information by identifier
+ *
+ * @param scopeId
+ * @param id
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public ChannelInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ return doFind(scopeId, id);
+ }
+
+ private ChannelInfo doFind(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ChannelInfoQueryImpl idsQuery = new ChannelInfoQueryImpl(scopeId);
+ idsQuery.setLimit(1);
+
+ IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(ChannelInfoSchema.CHANNEL_TYPE_NAME);
+ idsPredicate.addId(id);
+ idsQuery.setPredicate(idsPredicate);
+
+ ChannelInfoListResult result = query(idsQuery);
+ return result.getFirstItem();
+ }
+
+ /**
+ * Find channels informations matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public ChannelInfoListResult query(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return new ChannelInfoListResultImpl();
+ }
+
+ return repository.query(query);
+ }
+
+ /**
+ * Get channels informations count matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public long count(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return 0;
+ }
+
+ return repository.count(query);
+ }
+
+ /**
+ * Delete channels informations count matching the given query.
+ *
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the channel info registry entries that matching the query without checking the consistency of the others registries or the message store.
+ *
+ * @param query
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(ChannelInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
+ return;
+ }
+ repository.delete(query);
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java
index 2193fd98e5a..be6175784f0 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException;
import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.account.AccountService;
@@ -25,9 +24,7 @@
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService;
-import org.eclipse.kapua.service.datastore.MessageStoreService;
import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreMediator;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageField;
import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl;
import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema;
@@ -35,6 +32,7 @@
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
import org.eclipse.kapua.service.datastore.model.ChannelInfo;
import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
import org.eclipse.kapua.service.datastore.model.MessageListResult;
import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
@@ -48,10 +46,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.Optional;
/**
* Channel info registry implementation
@@ -63,14 +63,13 @@ public class ChannelInfoRegistryServiceImpl implements ChannelInfoRegistryServic
private static final Logger LOG = LoggerFactory.getLogger(ChannelInfoRegistryServiceImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DatastorePredicateFactory DATASTORE_PREDICATE_FACTORY = LOCATOR.getFactory(DatastorePredicateFactory.class);
-
+ private final DatastorePredicateFactory datastorePredicateFactory;
private final AccountService accountService;
private final AuthorizationService authorizationService;
private final PermissionFactory permissionFactory;
private final ChannelInfoRegistryFacade channelInfoRegistryFacade;
- private final MessageStoreService messageStoreService;
+ private final MessageRepository messageRepository;
+ private final DatastoreSettings datastoreSettings;
private static final String QUERY = "query";
private static final String QUERY_SCOPE_ID = "query.scopeId";
@@ -80,17 +79,22 @@ public class ChannelInfoRegistryServiceImpl implements ChannelInfoRegistryServic
*
* @since 1.0.0
*/
- public ChannelInfoRegistryServiceImpl() {
- KapuaLocator locator = KapuaLocator.getInstance();
- accountService = locator.getService(AccountService.class);
- authorizationService = locator.getService(AuthorizationService.class);
- permissionFactory = locator.getFactory(PermissionFactory.class);
- messageStoreService = locator.getService(MessageStoreService.class);
-
- MessageStoreService messageStoreService = KapuaLocator.getInstance().getService(MessageStoreService.class);
- ConfigurationProviderImpl configurationProvider = new ConfigurationProviderImpl(messageStoreService, accountService);
- channelInfoRegistryFacade = new ChannelInfoRegistryFacade(configurationProvider, DatastoreMediator.getInstance());
- DatastoreMediator.getInstance().setChannelInfoStoreFacade(channelInfoRegistryFacade);
+ @Inject
+ public ChannelInfoRegistryServiceImpl(
+ DatastorePredicateFactory datastorePredicateFactory,
+ AccountService accountService,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ MessageRepository messageStoreService,
+ ChannelInfoRegistryFacade channelInfoRegistryFacade,
+ DatastoreSettings datastoreSettings) {
+ this.datastorePredicateFactory = datastorePredicateFactory;
+ this.accountService = accountService;
+ this.authorizationService = authorizationService;
+ this.permissionFactory = permissionFactory;
+ this.messageRepository = messageStoreService;
+ this.channelInfoRegistryFacade = channelInfoRegistryFacade;
+ this.datastoreSettings = datastoreSettings;
}
@Override
@@ -164,7 +168,8 @@ public long count(ChannelInfoQuery query)
}
}
- void delete(KapuaId scopeId, StorableId id)
+ @Override
+ public void delete(KapuaId scopeId, StorableId id)
throws KapuaException {
if (!isServiceEnabled(scopeId)) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -181,7 +186,8 @@ void delete(KapuaId scopeId, StorableId id)
}
}
- void delete(ChannelInfoQuery query)
+ @Override
+ public void delete(ChannelInfoQuery query)
throws KapuaException {
if (!isServiceEnabled(query.getScopeId())) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -224,24 +230,25 @@ private void updateLastPublishedFields(ChannelInfo channelInfo) throws KapuaExce
messageQuery.setOffset(0);
messageQuery.setSortFields(sort);
- RangePredicate messageIdPredicate = DATASTORE_PREDICATE_FACTORY.newRangePredicate(ChannelInfoField.TIMESTAMP, channelInfo.getFirstMessageOn(), null);
- TermPredicate clientIdPredicate = DATASTORE_PREDICATE_FACTORY.newTermPredicate(MessageField.CLIENT_ID, channelInfo.getClientId());
- TermPredicate channelPredicate = DATASTORE_PREDICATE_FACTORY.newTermPredicate(MessageField.CHANNEL, channelInfo.getName());
+ RangePredicate messageIdPredicate = datastorePredicateFactory.newRangePredicate(ChannelInfoField.TIMESTAMP, channelInfo.getFirstMessageOn(), null);
+ TermPredicate clientIdPredicate = datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, channelInfo.getClientId());
+ TermPredicate channelPredicate = datastorePredicateFactory.newTermPredicate(MessageField.CHANNEL, channelInfo.getName());
- AndPredicate andPredicate = DATASTORE_PREDICATE_FACTORY.newAndPredicate();
+ AndPredicate andPredicate = datastorePredicateFactory.newAndPredicate();
andPredicate.getPredicates().add(messageIdPredicate);
andPredicate.getPredicates().add(clientIdPredicate);
andPredicate.getPredicates().add(channelPredicate);
messageQuery.setPredicate(andPredicate);
- MessageListResult messageList = messageStoreService.query(messageQuery);
+ MessageListResult messageList = messageRepository.query(messageQuery);
+ final List messages = Optional.ofNullable(messageList).map(ml -> ml.getItems()).orElse(new ArrayList<>());
StorableId lastPublishedMessageId = null;
Date lastPublishedMessageTimestamp = null;
- if (messageList.getSize() == 1) {
- lastPublishedMessageId = messageList.getFirstItem().getDatastoreId();
- lastPublishedMessageTimestamp = messageList.getFirstItem().getTimestamp();
- } else if (messageList.isEmpty()) {
+ if (messages.size() == 1) {
+ lastPublishedMessageId = messages.get(0).getDatastoreId();
+ lastPublishedMessageTimestamp = messages.get(0).getTimestamp();
+ } else if (messages.isEmpty()) {
// this condition could happens due to the ttl of the messages (so if it happens, it does not necessarily mean there has been an error!)
LOG.warn("Cannot find last timestamp for the specified client id '{}' - account '{}'", channelInfo.getScopeId(), channelInfo.getClientId());
} else {
@@ -256,7 +263,7 @@ private void updateLastPublishedFields(ChannelInfo channelInfo) throws KapuaExce
@Override
public boolean isServiceEnabled(KapuaId scopeId) {
- return !DatastoreSettings.getInstance().getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
+ return !datastoreSettings.getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactory.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRepository.java
similarity index 53%
rename from service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactory.java
rename to service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRepository.java
index 9e69d070ddc..ff9ed4d8445 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactory.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRepository.java
@@ -10,20 +10,12 @@
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
-package org.eclipse.kapua.service.authorization.access.shiro;
+package org.eclipse.kapua.service.datastore.internal;
-import org.eclipse.kapua.commons.jpa.AbstractEntityCacheFactory;
+import org.eclipse.kapua.service.datastore.model.ChannelInfo;
+import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
-/**
- * Cache factory for the {@link AccessRoleServiceImpl}
- */
-public class AccessRoleCacheFactory extends AbstractEntityCacheFactory {
-
- public AccessRoleCacheFactory() {
- super("AccessRoleId");
- }
-
- protected static AccessRoleCacheFactory getInstance() {
- return new AccessRoleCacheFactory();
- }
+public interface ChannelInfoRepository extends StorableRepository {
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java
new file mode 100644
index 00000000000..97d815b0739
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.ClientInfoFactory;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
+import org.eclipse.kapua.service.datastore.model.ClientInfo;
+import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+
+import javax.inject.Inject;
+
+public class ClientInfoElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements ClientInfoRepository {
+
+ private final DatastoreUtils datastoreUtils;
+
+ @Inject
+ protected ClientInfoElasticsearchRepository(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ ClientInfoFactory clientInfoFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ DatastoreSettings datastoreSettings,
+ DatastoreUtils datastoreUtils,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(elasticsearchClientProviderInstance,
+ ClientInfoSchema.CLIENT_TYPE_NAME,
+ ClientInfo.class,
+ clientInfoFactory,
+ storablePredicateFactory,
+ datastoreCacheManager.getClientsCache(),
+ datastoreSettings);
+ this.datastoreUtils = datastoreUtils;
+ }
+
+ @Override
+ protected String indexResolver(KapuaId scopeId) {
+ return datastoreUtils.getClientIndexName(scopeId);
+ }
+
+ @Override
+ protected JsonNode getIndexSchema() throws MappingException {
+ return ClientInfoSchema.getClientTypeSchema();
+ }
+
+ @Override
+ protected StorableId idExtractor(ClientInfo storable) {
+ return storable.getId();
+ }
+
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacade.java
index 82197ce6410..802e9fc5942 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacade.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacade.java
@@ -13,232 +13,25 @@
package org.eclipse.kapua.service.datastore.internal;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField;
-import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoRegistryMediator;
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
-import org.eclipse.kapua.service.datastore.internal.model.ClientInfoListResultImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.internal.schema.SchemaUtil;
import org.eclipse.kapua.service.datastore.model.ClientInfo;
import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.model.ResultList;
-import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateResponse;
import org.eclipse.kapua.service.storable.exception.MappingException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
-import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
-import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
-import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/**
- * Client information registry facade
- *
- * @since 1.0.0
- */
-public class ClientInfoRegistryFacade extends AbstractRegistryFacade {
-
- private static final Logger LOG = LoggerFactory.getLogger(ClientInfoRegistryFacade.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
- private final ClientInfoRegistryMediator mediator;
- private final Object metadataUpdateSync = new Object();
-
- private static final String QUERY = "query";
- private static final String QUERY_SCOPE_ID = "query.scopeId";
-
- /**
- * Constructs the client info registry facade
- *
- * @param configProvider
- * @param mediator
- * @since 1.0.0
- */
- public ClientInfoRegistryFacade(ConfigurationProvider configProvider, ClientInfoRegistryMediator mediator) {
- super(configProvider);
-
- this.mediator = mediator;
- }
-
- /**
- * Update the client information after a message store operation
- *
- * @param clientInfo
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- * @since 1.0.0
- */
- public StorableId upstore(ClientInfo clientInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
- ArgumentValidator.notNull(clientInfo, "clientInfo");
- ArgumentValidator.notNull(clientInfo.getScopeId(), "clientInfo.scopeId");
- ArgumentValidator.notNull(clientInfo.getFirstMessageId(), "clientInfo.firstPublishedMessageId");
- ArgumentValidator.notNull(clientInfo.getFirstMessageOn(), "clientInfo.firstPublishedMessageTimestamp");
-
- String clientInfoId = ClientInfoField.getOrDeriveId(clientInfo.getId(), clientInfo);
- StorableId storableId = STORABLE_ID_FACTORY.newStorableId(clientInfoId);
-
- UpdateResponse response = null;
- // Store channel. Look up channel in the cache, and cache it if it doesn't exist
- if (!DatastoreCacheManager.getInstance().getClientsCache().get(clientInfo.getClientId())) {
- // The code is safe even without the synchronized block
- // Synchronize in order to let the first thread complete its update
- // then the others of the same type will find the cache updated and
- // skip the update.
- synchronized (metadataUpdateSync) {
- if (!DatastoreCacheManager.getInstance().getClientsCache().get(clientInfo.getClientId())) {
- // fix #REPLACE_ISSUE_NUMBER
- ClientInfo storedField = find(clientInfo.getScopeId(), storableId);
- if (storedField == null) {
- Metadata metadata = mediator.getMetadata(clientInfo.getScopeId(), clientInfo.getFirstMessageOn().getTime());
- String kapuaIndexName = metadata.getClientRegistryIndexName();
-
- UpdateRequest request = new UpdateRequest(clientInfo.getId().toString(), new TypeDescriptor(kapuaIndexName, ClientInfoSchema.CLIENT_TYPE_NAME), clientInfo);
- response = getElasticsearchClient().upsert(request);
-
- LOG.debug("Upsert on asset successfully executed [{}.{}, {} - {}]", kapuaIndexName, ClientInfoSchema.CLIENT_TYPE_NAME, response.getId(), response.getId());
- }
- // Update cache if client update is completed successfully
- DatastoreCacheManager.getInstance().getClientsCache().put(clientInfo.getClientId(), true);
- }
- }
- }
- return storableId;
- }
-
- /**
- * Delete client information by identifier.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the client info registry entry by id without checking the consistency of the others registries or the message store.
- *
- * @param scopeId
- * @param id
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- if (!isDatastoreServiceEnabled(scopeId)) {
- LOG.debug("Storage not enabled for account {}, return", scopeId);
- return;
- }
-
- String indexName = SchemaUtil.getClientIndexName(scopeId);
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- getElasticsearchClient().delete(typeDescriptor, id.toString());
- }
-
- /**
- * Find client information by identifier
- *
- * @param scopeId
- * @param id
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public ClientInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- ClientInfoQueryImpl idsQuery = new ClientInfoQueryImpl(scopeId);
- idsQuery.setLimit(1);
-
- IdsPredicate idsPredicate = STORABLE_PREDICATE_FACTORY.newIdsPredicate(ClientInfoSchema.CLIENT_TYPE_NAME);
- idsPredicate.addId(id);
- idsQuery.setPredicate(idsPredicate);
-
- ClientInfoListResult result = query(idsQuery);
- return result.getFirstItem();
- }
-
- /**
- * Find clients informations matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public ClientInfoListResult query(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return new ClientInfoListResultImpl();
- }
-
- String indexName = SchemaUtil.getClientIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- ResultList rl = getElasticsearchClient().query(typeDescriptor, query, ClientInfo.class);
- ClientInfoListResult result = new ClientInfoListResultImpl(rl);
- setLimitExceed(query, rl.getTotalHitsExceedsCount(), result);
- return result;
- }
-
- /**
- * Get clients informations count matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public long count(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+public interface ClientInfoRegistryFacade {
+ StorableId upstore(ClientInfo clientInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return 0;
- }
+ void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- String dataIndexName = SchemaUtil.getClientIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(dataIndexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- return getElasticsearchClient().count(typeDescriptor, query);
- }
+ ClientInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- /**
- * Delete clients informations count matching the given query.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the client info registry entries that matching the query without checking the consistency of the others registries or the message store.
- *
- * @param query
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ ClientInfoListResult query(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
- return;
- }
+ long count(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- String indexName = SchemaUtil.getClientIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeDescriptor, query);
- }
+ void delete(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java
new file mode 100644
index 00000000000..85952aaf074
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java
@@ -0,0 +1,218 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.KapuaIllegalArgumentException;
+import org.eclipse.kapua.commons.util.ArgumentValidator;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField;
+import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
+import org.eclipse.kapua.service.datastore.internal.model.ClientInfoListResultImpl;
+import org.eclipse.kapua.service.datastore.model.ClientInfo;
+import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+
+/**
+ * Client information registry facade
+ *
+ * @since 1.0.0
+ */
+public class ClientInfoRegistryFacadeImpl extends AbstractDatastoreFacade implements ClientInfoRegistryFacade {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ClientInfoRegistryFacadeImpl.class);
+
+ private final StorableIdFactory storableIdFactory;
+ private final StorablePredicateFactory storablePredicateFactory;
+ private final ClientInfoRepository repository;
+ private final DatastoreCacheManager datastoreCacheManager;
+ private final Object metadataUpdateSync = new Object();
+
+ private static final String QUERY = "query";
+ private static final String QUERY_SCOPE_ID = "query.scopeId";
+
+ /**
+ * Constructs the client info registry facade
+ *
+ * @param configProvider
+ * @since 1.0.0
+ */
+ @Inject
+ public ClientInfoRegistryFacadeImpl(
+ ConfigurationProvider configProvider,
+ StorableIdFactory storableIdFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ ClientInfoRepository clientInfoRepository,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(configProvider);
+ this.storableIdFactory = storableIdFactory;
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.repository = clientInfoRepository;
+ this.datastoreCacheManager = datastoreCacheManager;
+ }
+
+ /**
+ * Update the client information after a message store operation
+ *
+ * @param clientInfo
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ * @since 1.0.0
+ */
+ @Override
+ public StorableId upstore(ClientInfo clientInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
+ ArgumentValidator.notNull(clientInfo, "clientInfo");
+ ArgumentValidator.notNull(clientInfo.getScopeId(), "clientInfo.scopeId");
+ ArgumentValidator.notNull(clientInfo.getFirstMessageId(), "clientInfo.firstPublishedMessageId");
+ ArgumentValidator.notNull(clientInfo.getFirstMessageOn(), "clientInfo.firstPublishedMessageTimestamp");
+
+ String clientInfoId = ClientInfoField.getOrDeriveId(clientInfo.getId(), clientInfo);
+ StorableId storableId = storableIdFactory.newStorableId(clientInfoId);
+
+ // Store channel. Look up channel in the cache, and cache it if it doesn't exist
+ if (!datastoreCacheManager.getClientsCache().get(clientInfo.getClientId())) {
+ // The code is safe even without the synchronized block
+ // Synchronize in order to let the first thread complete its update
+ // then the others of the same type will find the cache updated and
+ // skip the update.
+ synchronized (metadataUpdateSync) {
+ if (!datastoreCacheManager.getClientsCache().get(clientInfo.getClientId())) {
+ // fix #REPLACE_ISSUE_NUMBER
+ ClientInfo storedField = repository.find(clientInfo.getScopeId(), storableId);
+ if (storedField == null) {
+ repository.upsert(clientInfoId, clientInfo);
+ }
+ // Update cache if client update is completed successfully
+ datastoreCacheManager.getClientsCache().put(clientInfo.getClientId(), true);
+ }
+ }
+ }
+ return storableId;
+ }
+
+ /**
+ * Delete client information by identifier.
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the client info registry entry by id without checking the consistency of the others registries or the message store.
+ *
+ * @param scopeId
+ * @param id
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(scopeId, "scopeId");
+ ArgumentValidator.notNull(id, "id");
+
+ if (!isDatastoreServiceEnabled(scopeId)) {
+ LOG.debug("Storage not enabled for account {}, return", scopeId);
+ return;
+ }
+
+ repository.delete(scopeId, id);
+ }
+
+ /**
+ * Find client information by identifier
+ *
+ * @param scopeId
+ * @param id
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public ClientInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ return repository.find(scopeId, id);
+ }
+
+ /**
+ * Find clients informations matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public ClientInfoListResult query(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return new ClientInfoListResultImpl();
+ }
+
+ return repository.query(query);
+ }
+
+ /**
+ * Get clients informations count matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public long count(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return 0;
+ }
+
+ return repository.count(query);
+ }
+
+ /**
+ * Delete clients informations count matching the given query.
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the client info registry entries that matching the query without checking the consistency of the others registries or the message store.
+ *
+ * @param query
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(ClientInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
+ return;
+ }
+
+ repository.delete(query);
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java
index 7f08c41be57..1300cf74ca6 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException;
import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.account.AccountService;
@@ -25,9 +24,7 @@
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.datastore.ClientInfoRegistryService;
-import org.eclipse.kapua.service.datastore.MessageStoreService;
import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreMediator;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageField;
import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl;
import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema;
@@ -35,11 +32,11 @@
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
import org.eclipse.kapua.service.datastore.model.ClientInfo;
import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
import org.eclipse.kapua.service.datastore.model.MessageListResult;
import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientInitializationException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
import org.eclipse.kapua.service.storable.model.query.SortField;
import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle;
@@ -50,10 +47,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.Optional;
/**
* Client information registry implementation.
@@ -65,37 +64,39 @@ public class ClientInfoRegistryServiceImpl implements ClientInfoRegistryService
private static final Logger LOG = LoggerFactory.getLogger(ClientInfoRegistryServiceImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
-
+ private final StorablePredicateFactory storablePredicateFactory;
private final AccountService accountService;
private final AuthorizationService authorizationService;
private final PermissionFactory permissionFactory;
private final ClientInfoRegistryFacade clientInfoRegistryFacade;
- private final MessageStoreService messageStoreService;
private final DatastorePredicateFactory datastorePredicateFactory;
+ private final MessageRepository messageRepository;
+ private final DatastoreSettings datastoreSettings;
private static final String QUERY = "query";
private static final String QUERY_SCOPE_ID = "query.scopeId";
/**
* Default constructor
- *
- * @throws ClientInitializationException
*/
- public ClientInfoRegistryServiceImpl() throws ClientInitializationException {
- KapuaLocator locator = KapuaLocator.getInstance();
- accountService = locator.getService(AccountService.class);
- authorizationService = locator.getService(AuthorizationService.class);
- permissionFactory = locator.getFactory(PermissionFactory.class);
- messageStoreService = locator.getService(MessageStoreService.class);
- datastorePredicateFactory = KapuaLocator.getInstance().getFactory(DatastorePredicateFactory.class);
-
- MessageStoreService messageStoreService = KapuaLocator.getInstance().getService(MessageStoreService.class);
- ConfigurationProviderImpl configurationProvider = new ConfigurationProviderImpl(messageStoreService, accountService);
- clientInfoRegistryFacade = new ClientInfoRegistryFacade(configurationProvider, DatastoreMediator.getInstance());
- DatastoreMediator.getInstance().setClientInfoStoreFacade(clientInfoRegistryFacade);
+ @Inject
+ public ClientInfoRegistryServiceImpl(
+ StorablePredicateFactory storablePredicateFactory,
+ AccountService accountService,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ DatastorePredicateFactory datastorePredicateFactory,
+ ClientInfoRegistryFacade clientInfoRegistryFacade,
+ MessageRepository messageRepository,
+ DatastoreSettings datastoreSettings) {
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.accountService = accountService;
+ this.authorizationService = authorizationService;
+ this.permissionFactory = permissionFactory;
+ this.datastorePredicateFactory = datastorePredicateFactory;
+ this.clientInfoRegistryFacade = clientInfoRegistryFacade;
+ this.messageRepository = messageRepository;
+ this.datastoreSettings = datastoreSettings;
}
@Override
@@ -168,7 +169,8 @@ public long count(ClientInfoQuery query)
}
}
- void delete(ClientInfoQuery query)
+ @Override
+ public void delete(ClientInfoQuery query)
throws KapuaException {
if (!isServiceEnabled(query.getScopeId())) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -185,7 +187,8 @@ void delete(ClientInfoQuery query)
}
}
- void delete(KapuaId scopeId, StorableId id)
+ @Override
+ public void delete(KapuaId scopeId, StorableId id)
throws KapuaException {
if (!isServiceEnabled(scopeId)) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -226,22 +229,23 @@ private void updateLastPublishedFields(ClientInfo clientInfo) throws KapuaExcept
messageQuery.setOffset(0);
messageQuery.setSortFields(sort);
- RangePredicate messageIdPredicate = STORABLE_PREDICATE_FACTORY.newRangePredicate(ClientInfoField.TIMESTAMP, clientInfo.getFirstMessageOn(), null);
+ RangePredicate messageIdPredicate = storablePredicateFactory.newRangePredicate(ClientInfoField.TIMESTAMP, clientInfo.getFirstMessageOn(), null);
TermPredicate clientIdPredicate = datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, clientInfo.getClientId());
- AndPredicate andPredicate = STORABLE_PREDICATE_FACTORY.newAndPredicate();
+ AndPredicate andPredicate = storablePredicateFactory.newAndPredicate();
andPredicate.getPredicates().add(messageIdPredicate);
andPredicate.getPredicates().add(clientIdPredicate);
messageQuery.setPredicate(andPredicate);
- MessageListResult messageList = messageStoreService.query(messageQuery);
+ MessageListResult messageList = messageRepository.query(messageQuery);
+ final List messages = Optional.ofNullable(messageList).map(ml -> ml.getItems()).orElse(new ArrayList<>());
StorableId lastPublishedMessageId = null;
Date lastPublishedMessageTimestamp = null;
- if (messageList.getSize() == 1) {
- lastPublishedMessageId = messageList.getFirstItem().getDatastoreId();
- lastPublishedMessageTimestamp = messageList.getFirstItem().getTimestamp();
- } else if (messageList.isEmpty()) {
+ if (messages.size() == 1) {
+ lastPublishedMessageId = messages.get(0).getDatastoreId();
+ lastPublishedMessageTimestamp = messages.get(0).getTimestamp();
+ } else if (messages.isEmpty()) {
// this condition could happens due to the ttl of the messages (so if it happens, it does not necessarily mean there has been an error!)
LOG.warn("Cannot find last timestamp for the specified client id '{}' - account '{}'", clientInfo.getScopeId(), clientInfo.getClientId());
} else {
@@ -255,7 +259,7 @@ private void updateLastPublishedFields(ClientInfo clientInfo) throws KapuaExcept
@Override
public boolean isServiceEnabled(KapuaId scopeId) {
- return !DatastoreSettings.getInstance().getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
+ return !datastoreSettings.getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
}
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRepository.java
new file mode 100644
index 00000000000..03581286525
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRepository.java
@@ -0,0 +1,21 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.service.datastore.model.ClientInfo;
+import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
+
+public interface ClientInfoRepository extends StorableRepository {
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ConfigurationProviderImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ConfigurationProviderImpl.java
index d358b0cf684..f87dc7439fc 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ConfigurationProviderImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ConfigurationProviderImpl.java
@@ -13,14 +13,15 @@
package org.eclipse.kapua.service.datastore.internal;
import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.account.AccountService;
-import org.eclipse.kapua.service.config.KapuaConfigurableService;
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageInfo;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration;
+import org.eclipse.kapua.storage.TxManager;
/**
* Datastore configuration provider implementation.
@@ -29,19 +30,22 @@
*/
public class ConfigurationProviderImpl implements ConfigurationProvider {
+ private final TxManager txManager;
private AccountService accountService;
- private KapuaConfigurableService configurableService;
+ private ServiceConfigurationManager serviceConfigurationManager;
/**
* Construct the configuration provider with the provided parameters
*
- * @param configurableService
+ * @param serviceConfigurationManager
* @param accountService
*/
- public ConfigurationProviderImpl(KapuaConfigurableService configurableService,
- AccountService accountService) {
+ public ConfigurationProviderImpl(TxManager txManager,
+ ServiceConfigurationManager serviceConfigurationManager,
+ AccountService accountService) {
+ this.txManager = txManager;
this.accountService = accountService;
- this.configurableService = configurableService;
+ this.serviceConfigurationManager = serviceConfigurationManager;
}
@Override
@@ -49,7 +53,7 @@ public MessageStoreConfiguration getConfiguration(KapuaId scopeId)
throws ConfigurationException {
MessageStoreConfiguration messageStoreConfiguration = null;
try {
- messageStoreConfiguration = new MessageStoreConfiguration(configurableService.getConfigValues(scopeId));
+ messageStoreConfiguration = new MessageStoreConfiguration(txManager.execute(tx -> serviceConfigurationManager.getConfigValues(tx, scopeId, true)));
} catch (KapuaException e) {
throw new ConfigurationException("Cannot load configuration parameters", e);
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreCacheManager.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreCacheManager.java
index 853cc2b8bc9..35705bcbafa 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreCacheManager.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreCacheManager.java
@@ -12,11 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal;
+import com.google.inject.Inject;
import org.eclipse.kapua.commons.cache.LocalCache;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
+import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
+import java.util.Map;
+
/**
* Datastore cache manager.
* It keeps informations about channels, metrics and clients to speed up the store operation and avoid time consuming unnecessary operations.
@@ -25,18 +28,16 @@
*/
public class DatastoreCacheManager {
- private static final DatastoreCacheManager INSTANCE = new DatastoreCacheManager();
-
- private final LocalCache schemaCache;
+ private final LocalCache> schemaCache;
private final LocalCache channelsCache;
private final LocalCache metricsCache;
private final LocalCache clientsCache;
- private DatastoreCacheManager() {
- DatastoreSettings config = DatastoreSettings.getInstance();
- int expireAfter = config.getInt(DatastoreSettingsKey.CONFIG_CACHE_LOCAL_EXPIRE_AFTER);
- int sizeMax = config.getInt(DatastoreSettingsKey.CONFIG_CACHE_LOCAL_SIZE_MAXIMUM);
- int sizeMaxMetadata = config.getInt(DatastoreSettingsKey.CONFIG_CACHE_METADATA_LOCAL_SIZE_MAXIMUM);
+ @Inject
+ public DatastoreCacheManager(DatastoreSettings datastoreSettings) {
+ int expireAfter = datastoreSettings.getInt(DatastoreSettingsKey.CONFIG_CACHE_LOCAL_EXPIRE_AFTER);
+ int sizeMax = datastoreSettings.getInt(DatastoreSettingsKey.CONFIG_CACHE_LOCAL_SIZE_MAXIMUM);
+ int sizeMaxMetadata = datastoreSettings.getInt(DatastoreSettingsKey.CONFIG_CACHE_METADATA_LOCAL_SIZE_MAXIMUM);
// TODO set expiration to happen frequently because the reset cache method will not get
// called from service clients any more
@@ -46,16 +47,6 @@ private DatastoreCacheManager() {
schemaCache = new LocalCache<>(sizeMaxMetadata, null);
}
- /**
- * Get the cache manager instance
- *
- * @return
- * @since 1.0.0
- */
- public static DatastoreCacheManager getInstance() {
- return INSTANCE;
- }
-
/**
* Get the channels informations cache
*
@@ -92,7 +83,7 @@ public LocalCache getClientsCache() {
* @return
* @since 1.0.0
*/
- public LocalCache getMetadataCache() {
+ public LocalCache> getMetadataCache() {
return schemaCache;
}
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java
new file mode 100644
index 00000000000..b10dfd97a8c
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java
@@ -0,0 +1,88 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.eclipse.kapua.commons.cache.LocalCache;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchRepository;
+import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
+import org.eclipse.kapua.service.storable.StorableFactory;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.Storable;
+import org.eclipse.kapua.service.storable.model.StorableListResult;
+import org.eclipse.kapua.service.storable.model.query.StorableQuery;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
+import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
+
+public abstract class DatastoreElasticSearchRepositoryBase<
+ T extends Storable,
+ L extends StorableListResult,
+ Q extends StorableQuery>
+ extends ElasticsearchRepository
+ implements StorableRepository {
+
+ protected final DatastoreSettings datastoreSettings;
+
+ protected DatastoreElasticSearchRepositoryBase(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ String type,
+ Class clazz,
+ StorableFactory storableFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ LocalCache indexesCache,
+ DatastoreSettings datastoreSettings) {
+ super(elasticsearchClientProviderInstance, type, clazz, storableFactory, storablePredicateFactory,
+ indexesCache);
+ this.datastoreSettings = datastoreSettings;
+ }
+
+ protected DatastoreElasticSearchRepositoryBase(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ String type,
+ Class clazz,
+ StorableFactory storableFactory,
+ StorablePredicateFactory storablePredicateFactory, DatastoreSettings datastoreSettings) {
+ super(elasticsearchClientProviderInstance, type, clazz, storableFactory, storablePredicateFactory);
+ this.datastoreSettings = datastoreSettings;
+ }
+
+ /**
+ * @param idxName
+ * @return
+ * @throws org.eclipse.kapua.service.storable.exception.MappingException
+ * @since 1.0.0
+ */
+ @Override
+ protected ObjectNode getMappingSchema(String idxName) throws MappingException {
+ String idxRefreshInterval = String.format("%ss", datastoreSettings.getLong(DatastoreSettingsKey.INDEX_REFRESH_INTERVAL));
+ Integer idxShardNumber = datastoreSettings.getInt(DatastoreSettingsKey.INDEX_SHARD_NUMBER, 1);
+ Integer idxReplicaNumber = datastoreSettings.getInt(DatastoreSettingsKey.INDEX_REPLICA_NUMBER, 0);
+
+ ObjectNode rootNode = MappingUtils.newObjectNode();
+ ObjectNode settingsNode = MappingUtils.newObjectNode();
+ ObjectNode refreshIntervalNode = MappingUtils.newObjectNode(new KeyValueEntry[]{
+ new KeyValueEntry(SchemaKeys.KEY_REFRESH_INTERVAL, idxRefreshInterval),
+ new KeyValueEntry(SchemaKeys.KEY_SHARD_NUMBER, idxShardNumber),
+ new KeyValueEntry(SchemaKeys.KEY_REPLICA_NUMBER, idxReplicaNumber)});
+ settingsNode.set(SchemaKeys.KEY_INDEX, refreshIntervalNode);
+ rootNode.set(SchemaKeys.KEY_SETTINGS, settingsNode);
+ logger.info("Creating index for '{}' - refresh: '{}' - shards: '{}' replicas: '{}': ", idxName, idxRefreshInterval, idxShardNumber, idxReplicaNumber);
+ return rootNode;
+ }
+
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java
index 8787ef3db84..4c248f45e67 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.RootUserTester;
import org.eclipse.kapua.commons.configuration.ServiceConfigImplJpaRepository;
@@ -22,6 +21,7 @@
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManagerCachingWrapper;
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManagerImpl;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
@@ -40,8 +40,17 @@
import org.eclipse.kapua.service.datastore.MessageStoreService;
import org.eclipse.kapua.service.datastore.MetricInfoFactory;
import org.eclipse.kapua.service.datastore.MetricInfoRegistryService;
+import org.eclipse.kapua.service.datastore.internal.client.DatastoreElasticsearchClientConfiguration;
+import org.eclipse.kapua.service.datastore.internal.converter.ModelContextImpl;
+import org.eclipse.kapua.service.datastore.internal.converter.QueryConverterImpl;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.elasticsearch.client.configuration.ElasticsearchClientConfiguration;
+import org.eclipse.kapua.service.elasticsearch.client.rest.MetricsEsClient;
+import org.eclipse.kapua.service.elasticsearch.client.rest.RestElasticsearchClientProvider;
+import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
import org.eclipse.kapua.storage.TxContext;
import javax.inject.Named;
@@ -50,13 +59,28 @@
public class DatastoreModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(ChannelInfoFactory.class).to(ChannelInfoFactoryImpl.class);
- bind(ChannelInfoRegistryService.class).to(ChannelInfoRegistryServiceImpl.class);
- bind(ClientInfoFactory.class).to(ClientInfoFactoryImpl.class);
- bind(ClientInfoRegistryService.class).to(ClientInfoRegistryServiceImpl.class);
- bind(MessageStoreFactory.class).to(MessageStoreFactoryImpl.class);
- bind(MetricInfoFactory.class).to(MetricInfoFactoryImpl.class);
- bind(MetricInfoRegistryService.class).to(MetricInfoRegistryServiceImpl.class);
+ bind(DatastoreSettings.class).in(Singleton.class);
+ bind(ClientInfoFactory.class).to(ClientInfoFactoryImpl.class).in(Singleton.class);
+ bind(ClientInfoRepository.class).to(ClientInfoElasticsearchRepository.class).in(Singleton.class);
+ bind(ClientInfoRegistryFacade.class).to(ClientInfoRegistryFacadeImpl.class).in(Singleton.class);
+ bind(ClientInfoRegistryService.class).to(ClientInfoRegistryServiceImpl.class).in(Singleton.class);
+
+ bind(MetricInfoFactory.class).to(MetricInfoFactoryImpl.class).in(Singleton.class);
+ bind(MetricInfoRepository.class).to(MetricInfoRepositoryImpl.class).in(Singleton.class);
+ bind(MetricInfoRegistryFacade.class).to(MetricInfoRegistryFacadeImpl.class).in(Singleton.class);
+ bind(MetricInfoRegistryService.class).to(MetricInfoRegistryServiceImpl.class).in(Singleton.class);
+
+ bind(ChannelInfoFactory.class).to(ChannelInfoFactoryImpl.class).in(Singleton.class);
+ bind(ChannelInfoRepository.class).to(ChannelInfoElasticsearchRepository.class).in(Singleton.class);
+ bind(ChannelInfoRegistryFacade.class).to(ChannelInfoRegistryFacadeImpl.class).in(Singleton.class);
+ bind(ChannelInfoRegistryService.class).to(ChannelInfoRegistryServiceImpl.class).in(Singleton.class);
+
+ bind(MessageStoreFactory.class).to(MessageStoreFactoryImpl.class).in(Singleton.class);
+ bind(MessageRepository.class).to(MessageElasticsearchRepository.class).in(Singleton.class);
+ bind(MessageStoreFacade.class).to(MessageStoreFacadeImpl.class).in(Singleton.class);
+ bind(MetricsDatastore.class).in(Singleton.class);
+ bind(DatastoreUtils.class).in(Singleton.class);
+ bind(DatastoreCacheManager.class).in(Singleton.class);
}
@ProvidesIntoSet
@@ -64,20 +88,45 @@ public Domain dataStoreDomain() {
return new DomainEntry(Domains.DATASTORE, "org.eclipse.kapua.service.datastore.DatastoreService", false, Actions.read, Actions.delete, Actions.write);
}
+ @Provides
+ @Singleton
+ ElasticsearchClientProvider elasticsearchClientProvider(MetricsEsClient metricsEsClient, StorableIdFactory storableIdFactory, DatastoreUtils datastoreUtils) {
+ ElasticsearchClientConfiguration esClientConfiguration = DatastoreElasticsearchClientConfiguration.getInstance();
+ return new RestElasticsearchClientProvider(metricsEsClient)
+ .withClientConfiguration(esClientConfiguration)
+ .withModelContext(new ModelContextImpl(storableIdFactory, datastoreUtils))
+ .withModelConverter(new QueryConverterImpl());
+ }
+
+ @Provides
+ @Singleton
+ ConfigurationProvider configurationProvider(
+ @Named("MessageStoreServiceConfigurationManager") ServiceConfigurationManager serviceConfigurationManager,
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ AccountService accountService
+ ) {
+ final ConfigurationProviderImpl configurationProvider = new ConfigurationProviderImpl(jpaTxManagerFactory.create("kapua-datastore"), serviceConfigurationManager, accountService);
+ return configurationProvider;
+ }
+
@Provides
@Singleton
MessageStoreService messageStoreService(
PermissionFactory permissionFactory,
AuthorizationService authorizationService,
- AccountService accountService,
@Named("MessageStoreServiceConfigurationManager") ServiceConfigurationManager serviceConfigurationManager,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ MessageStoreFacade messageStoreFacade,
+ MetricsDatastore metricsDatastore,
+ DatastoreSettings datastoreSettings) {
return new MessageStoreServiceImpl(
jpaTxManagerFactory.create("kapua-datastore"),
permissionFactory,
authorizationService,
- accountService,
- serviceConfigurationManager);
+ serviceConfigurationManager,
+ messageStoreFacade,
+ metricsDatastore,
+ datastoreSettings);
}
@Provides
@@ -85,20 +134,22 @@ MessageStoreService messageStoreService(
@Named("MessageStoreServiceConfigurationManager")
ServiceConfigurationManager messageStoreServiceConfigurationManager(
RootUserTester rootUserTester,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ DatastoreSettings datastoreSettings,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(new ServiceConfigurationManagerImpl(
MessageStoreService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester
) {
@Override
public boolean isServiceEnabled(TxContext txContext, KapuaId scopeId) {
- return !DatastoreSettings.getInstance().getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
+ return !datastoreSettings.getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
}
});
}
-}
+}
\ No newline at end of file
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java
new file mode 100644
index 00000000000..dd3cbb25763
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java
@@ -0,0 +1,220 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.commons.cache.LocalCache;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.MessageStoreFactory;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
+import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
+import org.eclipse.kapua.service.datastore.model.MessageListResult;
+import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.elasticsearch.client.exception.DatamodelMappingException;
+import org.eclipse.kapua.service.elasticsearch.client.model.InsertRequest;
+import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
+import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
+
+import javax.inject.Inject;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class MessageElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements MessageRepository {
+ private final DatastoreUtils datastoreUtils;
+ private final LocalCache> metricsByIndex;
+
+ @Inject
+ public MessageElasticsearchRepository(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ MessageStoreFactory messageStoreFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ DatastoreSettings datastoreSettings,
+ DatastoreUtils datastoreUtils,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(elasticsearchClientProviderInstance,
+ MessageSchema.MESSAGE_TYPE_NAME,
+ DatastoreMessage.class,
+ messageStoreFactory,
+ storablePredicateFactory,
+ datastoreSettings);
+ this.datastoreUtils = datastoreUtils;
+ metricsByIndex = datastoreCacheManager.getMetadataCache();
+ }
+
+ @Override
+ protected JsonNode getIndexSchema() {
+ try {
+ return MessageSchema.getMessageTypeSchema();
+ } catch (MappingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ protected StorableId idExtractor(DatastoreMessage storable) {
+ return storable.getDatastoreId();
+ }
+
+ @Override
+ protected String indexResolver(KapuaId scopeId) {
+ return datastoreUtils.getDataIndexName(scopeId);
+ }
+
+ protected String indexResolver(KapuaId scopeId, Long time) {
+ final String indexingWindowOption = datastoreSettings.getString(DatastoreSettingsKey.INDEXING_WINDOW_OPTION, DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK);
+ return datastoreUtils.getDataIndexName(scopeId, time, indexingWindowOption);
+ }
+
+ @Override
+ public DatastoreMessage find(KapuaId scopeId, StorableId storableId, long time) {
+ return this.doFind(scopeId, indexResolver(scopeId, time), storableId);
+ }
+
+ /**
+ * Store a message
+ *
+ * @throws ClientException
+ */
+ @Override
+ public String store(DatastoreMessage messageToStore, Map metrics) throws ClientException {
+ final Long messageTime = Optional.ofNullable(messageToStore.getTimestamp())
+ .map(date -> date.getTime())
+ .orElse(null);
+
+ final String indexName = indexResolver(messageToStore.getScopeId(), messageTime);
+
+ if (!metricsByIndex.containsKey(indexName)) {
+ synchronized (DatastoreMessage.class) {
+ doUpsertIndex(indexName);
+ doUpsertMappings(indexName, metrics);
+ metricsByIndex.put(indexName, metrics);
+ }
+ } else {
+ final Map newMetrics = getMessageMappingDiffs(metricsByIndex.get(indexName), metrics);
+ synchronized (DatastoreMessage.class) {
+ doUpsertMappings(indexName, metrics);
+ metricsByIndex.get(indexName).putAll(newMetrics);
+ }
+ }
+ final TypeDescriptor typeDescriptor = getDescriptor(indexName);
+ final InsertRequest insertRequest = new InsertRequest(idExtractor(messageToStore).toString(), typeDescriptor, messageToStore);
+ return elasticsearchClientProviderInstance.getElasticsearchClient().insert(insertRequest).getId();
+ }
+
+ private Map getMessageMappingDiffs(Map currentMetrics, Map newMetrics) {
+ final Map newEntries = newMetrics.entrySet()
+ .stream()
+ .filter(kv -> !currentMetrics.containsKey(kv.getKey()))
+ .collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));
+ return newEntries;
+ }
+
+ private void doUpsertMappings(String index, Map esMetrics) {
+ try {
+ if (esMetrics.isEmpty()) {
+ return;
+ }
+ final ObjectNode metricsMapping = getNewMessageMappingsBuilder(esMetrics);
+ logger.trace("Sending dynamic message mappings: {}", metricsMapping);
+ elasticsearchClientProviderInstance.getElasticsearchClient().putMapping(getDescriptor(index), metricsMapping);
+ } catch (ClientException | MappingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void delete(KapuaId scopeId, StorableId id, long time) {
+ super.doDelete(indexResolver(scopeId, time), id);
+ }
+
+ /**
+ * @param esMetrics
+ * @return
+ * @throws DatamodelMappingException
+ * @throws KapuaException
+ * @since 1.0.0
+ */
+ private ObjectNode getNewMessageMappingsBuilder(Map esMetrics) throws MappingException {
+ if (esMetrics == null || esMetrics.isEmpty()) {
+ return null;
+ }
+ // metrics mapping container (to be added to message mapping)
+ ObjectNode typeNode = MappingUtils.newObjectNode(); // root
+ ObjectNode typePropertiesNode = MappingUtils.newObjectNode(); // properties
+ ObjectNode metricsNode = MappingUtils.newObjectNode(); // metrics
+ ObjectNode metricsPropertiesNode = MappingUtils.newObjectNode(); // properties (metric properties)
+ typeNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, typePropertiesNode);
+ typePropertiesNode.set(SchemaKeys.FIELD_NAME_METRICS, metricsNode);
+ metricsNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricsPropertiesNode);
+
+ // metrics mapping
+ ObjectNode metricMapping;
+ for (Map.Entry esMetric : esMetrics.entrySet()) {
+ Metric metric = esMetric.getValue();
+ metricMapping = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, SchemaKeys.VALUE_TRUE)});
+
+ ObjectNode metricMappingPropertiesNode = MappingUtils.newObjectNode(); // properties (inside metric name)
+ ObjectNode valueMappingNode;
+
+ switch (metric.getType()) {
+ case SchemaKeys.TYPE_STRING:
+ valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
+ break;
+ case SchemaKeys.TYPE_DATE:
+ valueMappingNode = MappingUtils.newObjectNode(
+ new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
+ break;
+ default:
+ valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, metric.getType())});
+ break;
+ }
+
+ metricMappingPropertiesNode.set(datastoreUtils.getClientMetricFromAcronym(metric.getType()), valueMappingNode);
+ metricMapping.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricMappingPropertiesNode);
+ metricsPropertiesNode.set(metric.getName(), metricMapping);
+ }
+ return typeNode;
+ }
+
+ @Override
+ public void refreshAllIndexes() {
+ super.refreshAllIndexes();
+ this.metricsByIndex.invalidateAll();
+ }
+
+ @Override
+ public void deleteAllIndexes() {
+ super.deleteAllIndexes();
+ this.metricsByIndex.invalidateAll();
+ }
+
+ @Override
+ public void deleteIndexes(String indexExp) {
+ super.deleteIndexes(indexExp);
+ this.metricsByIndex.invalidateAll();
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageRepository.java
new file mode 100644
index 00000000000..dc3f4248360
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageRepository.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
+import org.eclipse.kapua.service.datastore.model.MessageListResult;
+import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
+
+import java.util.Map;
+
+public interface MessageRepository extends StorableRepository {
+
+ String store(DatastoreMessage messageToStore, Map metrics) throws ClientException;
+
+ void delete(KapuaId scopeId, StorableId id, long time);
+
+ DatastoreMessage find(KapuaId scopeId, StorableId storableId, long time);
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacade.java
index 3e0a04a14cc..889cf8d8519 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacade.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacade.java
@@ -12,538 +12,60 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal;
-import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.commons.cache.LocalCache;
-import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.commons.util.KapuaDateUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaMessage;
-import org.eclipse.kapua.message.device.data.KapuaDataChannel;
-import org.eclipse.kapua.message.internal.device.data.KapuaDataChannelImpl;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.exception.DatastoreDisabledException;
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreChannel;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
-import org.eclipse.kapua.service.datastore.internal.mediator.MessageField;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageInfo;
-import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration;
-import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreMediator;
-import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
-import org.eclipse.kapua.service.datastore.internal.model.DataIndexBy;
-import org.eclipse.kapua.service.datastore.internal.model.DatastoreMessageImpl;
-import org.eclipse.kapua.service.datastore.internal.model.MessageListResultImpl;
-import org.eclipse.kapua.service.datastore.internal.model.MessageUniquenessCheck;
-import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl;
-import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.SchemaUtil;
-import org.eclipse.kapua.service.datastore.model.ChannelInfo;
-import org.eclipse.kapua.service.datastore.model.ClientInfo;
import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
import org.eclipse.kapua.service.datastore.model.MessageListResult;
-import org.eclipse.kapua.service.datastore.model.MetricInfo;
import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.exception.QueryMappingException;
-import org.eclipse.kapua.service.elasticsearch.client.model.InsertRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.InsertResponse;
-import org.eclipse.kapua.service.elasticsearch.client.model.ResultList;
-import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
import org.eclipse.kapua.service.storable.exception.MappingException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
-import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
-import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle;
-import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
-import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Message store facade
- *
- * @since 1.0.0
- */
-public final class MessageStoreFacade extends AbstractRegistryFacade {
-
- private static final Logger LOG = LoggerFactory.getLogger(MessageStoreFacade.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
- private final MessageStoreMediator mediator;
-
- private static final String QUERY = "query";
- private static final String QUERY_SCOPE_ID = "query.scopeId";
- private static final String SCOPE_ID = "scopeId";
-
- private MetricsDatastore metrics;
-
- /**
- * Constructs the message store facade
- *
- * @param confProvider
- * @param mediator
- * @since 1.0.0
- */
- public MessageStoreFacade(ConfigurationProvider confProvider, MessageStoreMediator mediator) {
- super(confProvider);
- this.mediator = mediator;
- metrics = MetricsDatastore.getInstance();
- }
-
- /**
- * Store a message
- *
- * @param message
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public StorableId store(KapuaMessage, ?> message, String messageId, boolean newInsert)
+public interface MessageStoreFacade {
+ StorableId store(KapuaMessage, ?> message, String messageId, boolean newInsert)
throws KapuaIllegalArgumentException,
DatastoreDisabledException,
ConfigurationException,
- ClientException, MappingException {
- ArgumentValidator.notNull(message, "message");
- ArgumentValidator.notNull(message.getScopeId(), SCOPE_ID);
- ArgumentValidator.notNull(message.getReceivedOn(), "receivedOn");
- ArgumentValidator.notNull(messageId, "messageId");
-
- // Define data TTL
- if (!isDatastoreServiceEnabled(message.getScopeId())) {
- throw new DatastoreDisabledException(message.getScopeId());
- }
-
- Date capturedOn = message.getCapturedOn();
- // Overwrite timestamp if necessary
- // Use the account service plan to determine whether we will give
- // precede to the device time
- MessageStoreConfiguration accountServicePlan = getConfigProvider().getConfiguration(message.getScopeId());
- long indexedOn = KapuaDateUtils.getKapuaSysDate().toEpochMilli();
- if (DataIndexBy.DEVICE_TIMESTAMP.equals(accountServicePlan.getDataIndexBy())) {
- if (capturedOn != null) {
- indexedOn = capturedOn.getTime();
- } else {
- LOG.debug("The account is set to use, as date indexing, the device timestamp but the device timestamp is null! Current system date will be used to indexing the message by date!");
- }
- }
- // Extract schema metadata
- Metadata schemaMetadata = mediator.getMetadata(message.getScopeId(), indexedOn);
-
- Date indexedOnDate = new Date(indexedOn);
- String indexName = schemaMetadata.getDataIndexName();
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MessageSchema.MESSAGE_TYPE_NAME);
-
- if (!newInsert && !MessageUniquenessCheck.NONE.equals(accountServicePlan.getMessageUniquenessCheck())) {
- DatastoreMessage datastoreMessage = MessageUniquenessCheck.FULL.equals(accountServicePlan.getMessageUniquenessCheck()) ?
- find(message.getScopeId(), STORABLE_ID_FACTORY.newStorableId(messageId), StorableFetchStyle.SOURCE_SELECT) :
- find(message.getScopeId(), indexName, STORABLE_ID_FACTORY.newStorableId(messageId), StorableFetchStyle.SOURCE_SELECT);
- if (datastoreMessage != null) {
- LOG.debug("Message with datatstore id '{}' already found", messageId);
- metrics.getAlreadyInTheDatastore().inc();
- return STORABLE_ID_FACTORY.newStorableId(messageId);
- }
- }
-
- // Save message (the big one)
- DatastoreMessage messageToStore = convertTo(message, messageId);
- messageToStore.setTimestamp(indexedOnDate);
- InsertRequest insertRequest = new InsertRequest(messageToStore.getDatastoreId().toString(), typeDescriptor, messageToStore);
- // Possibly update the schema with new metric mappings
- Map metrics = new HashMap<>();
- if (message.getPayload() != null && message.getPayload().getMetrics() != null && !message.getPayload().getMetrics().isEmpty()) {
-
- Map messageMetrics = message.getPayload().getMetrics();
- for (Map.Entry messageMetric : messageMetrics.entrySet()) {
- String metricName = DatastoreUtils.normalizeMetricName(messageMetric.getKey());
- String clientMetricType = DatastoreUtils.getClientMetricFromType(messageMetric.getValue().getClass());
- Metric metric = new Metric(metricName, clientMetricType);
-
- // each metric is potentially a dynamic field so report it a new mapping
- String mappedName = DatastoreUtils.getMetricValueQualifier(metricName, clientMetricType);
- metrics.put(mappedName, metric);
- }
- }
- try {
- mediator.onUpdatedMappings(message.getScopeId(), indexedOn, metrics);
- } catch (KapuaException e) {
- LOG.warn("Update mappings error", e);
- }
+ ClientException, MappingException;
- InsertResponse insertResponse = getElasticsearchClient().insert(insertRequest);
- messageToStore.setDatastoreId(STORABLE_ID_FACTORY.newStorableId(insertResponse.getId()));
-
- MessageInfo messageInfo = getConfigProvider().getInfo(message.getScopeId());
- mediator.onAfterMessageStore(messageInfo, messageToStore);
-
- return STORABLE_ID_FACTORY.newStorableId(insertResponse.getId());
- }
-
- /**
- * Delete message by identifier.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the message by id without checking the consistency of the registries.
- *
- * @param scopeId
- * @param id
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(KapuaId scopeId, StorableId id)
+ void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage message)
throws KapuaIllegalArgumentException,
ConfigurationException,
- ClientException {
- ArgumentValidator.notNull(scopeId, SCOPE_ID);
- ArgumentValidator.notNull(id, "id");
-
- if (!isDatastoreServiceEnabled(scopeId)) {
- LOG.debug("Storage not enabled for account {}, return", scopeId);
- return;
- }
-
- // get the index by finding the object by id
- DatastoreMessage messageToBeDeleted = find(scopeId, id, StorableFetchStyle.FIELDS);
- if (messageToBeDeleted != null) {
- Metadata schemaMetadata = null;
- try {
- schemaMetadata = mediator.getMetadata(scopeId, messageToBeDeleted.getTimestamp().getTime());
- } catch (KapuaException e) {
- LOG.warn("Retrieving metadata error", e);
- }
- String indexName = schemaMetadata.getDataIndexName();
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MessageSchema.MESSAGE_TYPE_NAME);
- getElasticsearchClient().delete(typeDescriptor, id.toString());
- } else {
- LOG.warn("Cannot find the message to be deleted. scopeId: '{}' - id: '{}'", scopeId, id);
- }
- // otherwise no message to be deleted found
- }
-
- /**
- * Find message by identifier
- *
- * @param scopeId
- * @param id
- * @param fetchStyle
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws QueryMappingException
- * @throws ClientException
- */
- public DatastoreMessage find(KapuaId scopeId, StorableId id, StorableFetchStyle fetchStyle) throws KapuaIllegalArgumentException, ClientException {
- ArgumentValidator.notNull(scopeId, SCOPE_ID);
- return find(scopeId, SchemaUtil.getDataIndexName(scopeId), id, fetchStyle);
- }
-
- /**
- * Find message by identifier
- *
- * @param scopeId
- * @param id
- * @param fetchStyle
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws QueryMappingException
- * @throws ClientException
- */
- public DatastoreMessage find(KapuaId scopeId, String indexName, StorableId id, StorableFetchStyle fetchStyle)
- throws KapuaIllegalArgumentException, ClientException {
-
- ArgumentValidator.notNull(scopeId, SCOPE_ID);
- ArgumentValidator.notNull(id, "id");
- ArgumentValidator.notNull(fetchStyle, "fetchStyle");
+ MappingException,
+ ClientException;
- MessageQueryImpl idsQuery = new MessageQueryImpl(scopeId);
- idsQuery.setLimit(1);
+ DatastoreMessage convertTo(KapuaMessage, ?> message, String messageId);
- IdsPredicate idsPredicate = STORABLE_PREDICATE_FACTORY.newIdsPredicate(MessageSchema.MESSAGE_TYPE_NAME);
- idsPredicate.addId(id);
- idsQuery.setPredicate(idsPredicate);
-
-// String indexName = SchemaUtil.getDataIndexName(scopeId);
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MessageSchema.MESSAGE_TYPE_NAME);
- return getElasticsearchClient().find(typeDescriptor, idsQuery, DatastoreMessage.class);
- }
-
- /**
- * Find messages matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws QueryMappingException
- * @throws ClientException
- */
- public MessageListResult query(MessageQuery query)
+ void delete(KapuaId scopeId, StorableId id)
throws KapuaIllegalArgumentException,
ConfigurationException,
- ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ ClientException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return new MessageListResultImpl();
- }
+ DatastoreMessage find(KapuaId scopeId, StorableId id)
+ throws KapuaIllegalArgumentException, ClientException;
- String dataIndexName = SchemaUtil.getDataIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(dataIndexName, MessageSchema.MESSAGE_TYPE_NAME);
- ResultList rl = getElasticsearchClient().query(typeDescriptor, query, DatastoreMessage.class);
- MessageListResult result = new MessageListResultImpl(rl);
- setLimitExceed(query, rl.getTotalHitsExceedsCount(), result);
- return result;
- }
-
- /**
- * Get messages count matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public long count(MessageQuery query)
+ MessageListResult query(MessageQuery query)
throws KapuaIllegalArgumentException,
ConfigurationException,
- ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
- return 0;
- }
+ ClientException;
- String indexName = SchemaUtil.getDataIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MessageSchema.MESSAGE_TYPE_NAME);
- return getElasticsearchClient().count(typeDescriptor, query);
- }
-
- /**
- * Delete messages count matching the given query.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the messages that matching the query without checking the consistency of the registries.
- *
- * @param query
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(MessageQuery query)
+ long count(MessageQuery query)
throws KapuaIllegalArgumentException,
ConfigurationException,
- ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
- return;
- }
-
- String indexName = SchemaUtil.getDataIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MessageSchema.MESSAGE_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeDescriptor, query);
- }
+ ClientException;
- // TODO cache will not be reset from the client code it should be automatically reset
- // after some time.
- private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, String clientId) throws Exception {
-
- boolean isAnyClientId;
- boolean isClientToDelete = false;
- String semTopic;
-
- if (channel != null) {
-
- // determine if we should delete an client if topic = account/clientId/#
- isAnyClientId = isAnyClientId(channel);
- semTopic = channel;
-
- if (semTopic.isEmpty() && !isAnyClientId) {
- isClientToDelete = true;
- }
- } else {
- isClientToDelete = true;
- }
-
- // Find all topics
- String dataIndexName = SchemaUtil.getDataIndexName(scopeId);
-
- int pageSize = 1000;
- int offset = 0;
- long totalHits = 1;
-
- MetricInfoQueryImpl metricQuery = new MetricInfoQueryImpl(scopeId);
- metricQuery.setLimit(pageSize + 1);
- metricQuery.setOffset(offset);
-
- ChannelMatchPredicateImpl channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
- metricQuery.setPredicate(channelPredicate);
-
- // Remove metrics
- while (totalHits > 0) {
- TypeDescriptor typeDescriptor = new TypeDescriptor(dataIndexName, MetricInfoSchema.METRIC_TYPE_NAME);
- ResultList metrics = getElasticsearchClient().query(typeDescriptor, metricQuery, MetricInfo.class);
-
- totalHits = metrics.getTotalCount();
- LocalCache metricsCache = DatastoreCacheManager.getInstance().getMetricsCache();
- long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
-
- for (int i = 0; i < toBeProcessed; i++) {
- String id = metrics.getResult().get(i).getId().toString();
- if (metricsCache.get(id)) {
- metricsCache.remove(id);
- }
- }
-
- if (totalHits > pageSize) {
- offset += pageSize + 1;
- }
- }
- LOG.debug("Removed cached channel metrics for: {}", channel);
- TypeDescriptor typeMetricDescriptor = new TypeDescriptor(dataIndexName, MetricInfoSchema.METRIC_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeMetricDescriptor, metricQuery);
- LOG.debug("Removed channel metrics for: {}", channel);
- ChannelInfoQueryImpl channelQuery = new ChannelInfoQueryImpl(scopeId);
- channelQuery.setLimit(pageSize + 1);
- channelQuery.setOffset(offset);
-
- channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
- channelQuery.setPredicate(channelPredicate);
-
- // Remove channel
- offset = 0;
- totalHits = 1;
- while (totalHits > 0) {
- TypeDescriptor typeDescriptor = new TypeDescriptor(dataIndexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- ResultList channels = getElasticsearchClient().query(typeDescriptor, channelQuery, ChannelInfo.class);
-
- totalHits = channels.getTotalCount();
- LocalCache channelsCache = DatastoreCacheManager.getInstance().getChannelsCache();
- long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
-
- for (int i = 0; i < toBeProcessed; i++) {
- String id = channels.getResult().get(0).getId().toString();
- if (channelsCache.get(id)) {
- channelsCache.remove(id);
- }
- }
- if (totalHits > pageSize) {
- offset += pageSize + 1;
- }
- }
-
- LOG.debug("Removed cached channels for: {}", channel);
- TypeDescriptor typeChannelDescriptor = new TypeDescriptor(dataIndexName, ChannelInfoSchema.CHANNEL_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeChannelDescriptor, channelQuery);
-
- LOG.debug("Removed channels for: {}", channel);
- // Remove client
- if (isClientToDelete) {
- ClientInfoQueryImpl clientInfoQuery = new ClientInfoQueryImpl(scopeId);
- clientInfoQuery.setLimit(pageSize + 1);
- clientInfoQuery.setOffset(offset);
-
- channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
- clientInfoQuery.setPredicate(channelPredicate);
- offset = 0;
- totalHits = 1;
- while (totalHits > 0) {
- TypeDescriptor typeDescriptor = new TypeDescriptor(dataIndexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- ResultList clients = getElasticsearchClient().query(typeDescriptor, clientInfoQuery, ClientInfo.class);
-
- totalHits = clients.getTotalCount();
- LocalCache clientsCache = DatastoreCacheManager.getInstance().getClientsCache();
- long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
-
- for (int i = 0; i < toBeProcessed; i++) {
- String id = clients.getResult().get(i).getId().toString();
- if (clientsCache.get(id)) {
- clientsCache.remove(id);
- }
- }
- if (totalHits > pageSize) {
- offset += pageSize + 1;
- }
- }
-
- LOG.debug("Removed cached clients for: {}", channel);
- TypeDescriptor typeClientDescriptor = new TypeDescriptor(dataIndexName, ClientInfoSchema.CLIENT_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeClientDescriptor, clientInfoQuery);
-
- LOG.debug("Removed clients for: {}", channel);
- }
- }
-
- // Utility methods
-
- /**
- * Check if the channel admit any client identifier (so if the channel has a specific wildcard in the second topic level).
- * In the MQTT word this method return true if the topic starts with 'account/+/'.
- *
- * @param clientId
- * @return
- * @since 1.0.0
- */
- private boolean isAnyClientId(String clientId) {
- return DatastoreChannel.SINGLE_LEVEL_WCARD.equals(clientId);
- }
-
- /**
- * This constructor should be used for wrapping Kapua message into datastore message for insert purpose
- *
- * @param message
- */
- private DatastoreMessage convertTo(KapuaMessage, ?> message, String messageId) {
- KapuaDataChannel datastoreChannel = new KapuaDataChannelImpl();
- datastoreChannel.setSemanticParts(message.getChannel().getSemanticParts());
-
- DatastoreMessage datastoreMessage = new DatastoreMessageImpl();
- datastoreMessage.setCapturedOn(message.getCapturedOn());
- datastoreMessage.setChannel(datastoreChannel);
- datastoreMessage.setClientId(message.getClientId());
- datastoreMessage.setDeviceId(message.getDeviceId());
- datastoreMessage.setId(message.getId());
- datastoreMessage.setPayload(message.getPayload());
- datastoreMessage.setPosition(message.getPosition());
- datastoreMessage.setReceivedOn(message.getReceivedOn());
- datastoreMessage.setScopeId(message.getScopeId());
- datastoreMessage.setSentOn(message.getSentOn());
-
- // generate uuid
- datastoreMessage.setId(message.getId());
- datastoreMessage.setDatastoreId(STORABLE_ID_FACTORY.newStorableId(messageId));
- return datastoreMessage;
- }
+ void delete(MessageQuery query)
+ throws KapuaIllegalArgumentException,
+ ConfigurationException,
+ ClientException;
- public void refreshAllIndexes() throws ClientException {
- getElasticsearchClient().refreshAllIndexes();
- }
+ void refreshAllIndexes() throws ClientException;
- public void deleteAllIndexes() throws ClientException {
- getElasticsearchClient().deleteAllIndexes();
- }
+ void deleteAllIndexes() throws ClientException;
- public void deleteIndexes(String indexExp) throws ClientException {
- getElasticsearchClient().deleteIndexes(indexExp);
- }
+ void deleteIndexes(String indexExp) throws ClientException;
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java
new file mode 100644
index 00000000000..e125bad715a
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java
@@ -0,0 +1,523 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.KapuaIllegalArgumentException;
+import org.eclipse.kapua.commons.cache.LocalCache;
+import org.eclipse.kapua.commons.util.ArgumentValidator;
+import org.eclipse.kapua.commons.util.KapuaDateUtils;
+import org.eclipse.kapua.message.KapuaMessage;
+import org.eclipse.kapua.message.KapuaPayload;
+import org.eclipse.kapua.message.device.data.KapuaDataChannel;
+import org.eclipse.kapua.message.internal.device.data.KapuaDataChannelImpl;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.exception.DatastoreDisabledException;
+import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField;
+import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField;
+import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreChannel;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.mediator.MessageField;
+import org.eclipse.kapua.service.datastore.internal.mediator.MessageInfo;
+import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration;
+import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
+import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField;
+import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoImpl;
+import org.eclipse.kapua.service.datastore.internal.model.ClientInfoImpl;
+import org.eclipse.kapua.service.datastore.internal.model.DataIndexBy;
+import org.eclipse.kapua.service.datastore.internal.model.DatastoreMessageImpl;
+import org.eclipse.kapua.service.datastore.internal.model.MessageListResultImpl;
+import org.eclipse.kapua.service.datastore.internal.model.MessageUniquenessCheck;
+import org.eclipse.kapua.service.datastore.internal.model.MetricInfoImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl;
+import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult;
+import org.eclipse.kapua.service.datastore.model.ClientInfoListResult;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
+import org.eclipse.kapua.service.datastore.model.MessageListResult;
+import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.elasticsearch.client.exception.QueryMappingException;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Message store facade
+ *
+ * @since 1.0.0
+ */
+public final class MessageStoreFacadeImpl extends AbstractDatastoreFacade implements MessageStoreFacade {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MessageStoreFacadeImpl.class);
+
+ private final StorableIdFactory storableIdFactory;
+ private final ClientInfoRegistryFacade clientInfoRegistryFacade;
+ private final ChannelInfoRegistryFacade channelInfoStoreFacade;
+ private final MetricInfoRegistryFacade metricInfoStoreFacade;
+ private final MessageRepository messageRepository;
+ private final MetricInfoRepository metricInfoRepository;
+ private final ChannelInfoRepository channelInfoRepository;
+ private final ClientInfoRepository clientInfoRepository;
+ private final MetricsDatastore metrics;
+ private final DatastoreUtils datastoreUtils;
+ private final DatastoreCacheManager datastoreCacheManager;
+
+ private static final String QUERY = "query";
+ private static final String QUERY_SCOPE_ID = "query.scopeId";
+ private static final String SCOPE_ID = "scopeId";
+
+ @Inject
+ public MessageStoreFacadeImpl(
+ ConfigurationProvider configProvider,
+ StorableIdFactory storableIdFactory,
+ ClientInfoRegistryFacade clientInfoRegistryFacade,
+ ChannelInfoRegistryFacade channelInfoStoreFacade,
+ MetricInfoRegistryFacade metricInfoStoreFacade,
+ MessageRepository messageRepository,
+ MetricInfoRepository metricInfoRepository,
+ ChannelInfoRepository channelInfoRepository,
+ ClientInfoRepository clientInfoRepository,
+ MetricsDatastore metricsDatastore,
+ DatastoreUtils datastoreUtils,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(configProvider);
+ this.storableIdFactory = storableIdFactory;
+ this.clientInfoRegistryFacade = clientInfoRegistryFacade;
+ this.channelInfoStoreFacade = channelInfoStoreFacade;
+ this.metricInfoStoreFacade = metricInfoStoreFacade;
+ this.messageRepository = messageRepository;
+ this.metricInfoRepository = metricInfoRepository;
+ this.channelInfoRepository = channelInfoRepository;
+ this.clientInfoRepository = clientInfoRepository;
+ this.metrics = metricsDatastore;
+ this.datastoreUtils = datastoreUtils;
+ this.datastoreCacheManager = datastoreCacheManager;
+ }
+
+ /**
+ * Store a message
+ *
+ * @param message
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public StorableId store(KapuaMessage, ?> message, String messageId, boolean newInsert) throws KapuaIllegalArgumentException, DatastoreDisabledException, ConfigurationException, ClientException, MappingException {
+ ArgumentValidator.notNull(message, "message");
+ ArgumentValidator.notNull(message.getScopeId(), SCOPE_ID);
+ ArgumentValidator.notNull(message.getReceivedOn(), "receivedOn");
+ ArgumentValidator.notNull(messageId, "messageId");
+
+ // Define data TTL
+ if (!isDatastoreServiceEnabled(message.getScopeId())) {
+ throw new DatastoreDisabledException(message.getScopeId());
+ }
+
+ Date capturedOn = message.getCapturedOn();
+ // Overwrite timestamp if necessary
+ // Use the account service plan to determine whether we will give
+ // precede to the device time
+ MessageStoreConfiguration accountServicePlan = configProvider.getConfiguration(message.getScopeId());
+ long indexedOn = KapuaDateUtils.getKapuaSysDate().toEpochMilli();
+ if (DataIndexBy.DEVICE_TIMESTAMP.equals(accountServicePlan.getDataIndexBy())) {
+ if (capturedOn != null) {
+ indexedOn = capturedOn.getTime();
+ } else {
+ LOG.debug("The account is set to use, as date indexing, the device timestamp but the device timestamp is null! Current system date will be used to indexing the message by date!");
+ }
+ }
+ // Extract schema metadata
+ Date indexedOnDate = new Date(indexedOn);
+
+ if (!newInsert && !MessageUniquenessCheck.NONE.equals(accountServicePlan.getMessageUniquenessCheck())) {
+ DatastoreMessage datastoreMessage = MessageUniquenessCheck.FULL.equals(accountServicePlan.getMessageUniquenessCheck()) ?
+ messageRepository.find(message.getScopeId(), storableIdFactory.newStorableId(messageId)) :
+ messageRepository.find(message.getScopeId(), storableIdFactory.newStorableId(messageId), message.getCapturedOn().getTime());
+ if (datastoreMessage != null) {
+ LOG.debug("Message with datastore id '{}' already found", messageId);
+ metrics.getAlreadyInTheDatastore().inc();
+ return storableIdFactory.newStorableId(messageId);
+ }
+ }
+
+ // Save message (the big one)
+ final DatastoreMessage messageToStore = convertTo(message, messageId);
+ messageToStore.setTimestamp(indexedOnDate);
+ // Possibly update the schema with new metric mappings
+ Map metrics = new HashMap<>();
+ if (message.getPayload() != null && message.getPayload().getMetrics() != null && !message.getPayload().getMetrics().isEmpty()) {
+ Map messageMetrics = message.getPayload().getMetrics();
+ for (Map.Entry messageMetric : messageMetrics.entrySet()) {
+ String metricName = datastoreUtils.normalizeMetricName(messageMetric.getKey());
+ String clientMetricType = datastoreUtils.getClientMetricFromType(messageMetric.getValue().getClass());
+ Metric metric = new Metric(metricName, clientMetricType);
+
+ // each metric is potentially a dynamic field so report it a new mapping
+ String mappedName = datastoreUtils.getMetricValueQualifier(metricName, clientMetricType);
+ metrics.put(mappedName, metric);
+ }
+ }
+
+ final String storedId = messageRepository.store(messageToStore, metrics);
+ messageToStore.setDatastoreId(storableIdFactory.newStorableId(storedId));
+
+ MessageInfo messageInfo = configProvider.getInfo(message.getScopeId());
+ this.onAfterMessageStore(messageInfo, messageToStore);
+
+ return storableIdFactory.newStorableId(storedId);
+ }
+
+ /**
+ * This constructor should be used for wrapping Kapua message into datastore message for insert purpose
+ *
+ * @param message
+ */
+ @Override
+ public DatastoreMessage convertTo(KapuaMessage, ?> message, String messageId) {
+ KapuaDataChannel datastoreChannel = new KapuaDataChannelImpl();
+ datastoreChannel.setSemanticParts(message.getChannel().getSemanticParts());
+
+ DatastoreMessage datastoreMessage = new DatastoreMessageImpl();
+ datastoreMessage.setCapturedOn(message.getCapturedOn());
+ datastoreMessage.setChannel(datastoreChannel);
+ datastoreMessage.setClientId(message.getClientId());
+ datastoreMessage.setDeviceId(message.getDeviceId());
+ datastoreMessage.setId(message.getId());
+ datastoreMessage.setPayload(message.getPayload());
+ datastoreMessage.setPosition(message.getPosition());
+ datastoreMessage.setReceivedOn(message.getReceivedOn());
+ datastoreMessage.setScopeId(message.getScopeId());
+ datastoreMessage.setSentOn(message.getSentOn());
+
+ // generate uuid
+ datastoreMessage.setId(message.getId());
+ datastoreMessage.setDatastoreId(storableIdFactory.newStorableId(messageId));
+ return datastoreMessage;
+ }
+
+ /**
+ * Delete message by identifier.
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the message by id without checking the consistency of the registries.
+ *
+ * @param id
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(scopeId, SCOPE_ID);
+ ArgumentValidator.notNull(id, "id");
+
+ if (!isDatastoreServiceEnabled(scopeId)) {
+ LOG.debug("Storage not enabled for account {}, return", scopeId);
+ return;
+ }
+
+ // get the index by finding the object by id
+ DatastoreMessage messageToBeDeleted = messageRepository.find(scopeId, id);
+ if (messageToBeDeleted != null) {
+ messageRepository.delete(scopeId, id, messageToBeDeleted.getTimestamp().getTime());
+ } else {
+ LOG.warn("Cannot find the message to be deleted. scopeId: '{}' - id: '{}'", scopeId, id);
+ }
+ // otherwise no message to be deleted found
+ }
+
+ @Override
+ public void delete(MessageQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, skipping delete", query.getScopeId());
+ return;
+ }
+
+ messageRepository.delete(query);
+ }
+
+ @Override
+ public DatastoreMessage find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ClientException {
+ ArgumentValidator.notNull(scopeId, SCOPE_ID);
+ ArgumentValidator.notNull(id, "id");
+ return messageRepository.find(scopeId, id);
+ }
+
+ @Override
+ public long count(MessageQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return 0;
+ }
+ return messageRepository.count(query);
+ }
+
+
+ @Override
+ public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage message)
+ throws KapuaIllegalArgumentException,
+ ConfigurationException,
+ MappingException,
+ ClientException {
+
+ // convert semantic channel to String
+ final String semanticChannel = Optional.ofNullable(message.getChannel()).map(c -> c.toString()).orElse("");
+
+ ClientInfoImpl clientInfo = new ClientInfoImpl(message.getScopeId());
+ clientInfo.setClientId(message.getClientId());
+ clientInfo.setId(storableIdFactory.newStorableId(ClientInfoField.getOrDeriveId(null, message.getScopeId(), message.getClientId())));
+ clientInfo.setFirstMessageId(message.getDatastoreId());
+ clientInfo.setFirstMessageOn(message.getTimestamp());
+ clientInfoRegistryFacade.upstore(clientInfo);
+
+ ChannelInfoImpl channelInfo = new ChannelInfoImpl(message.getScopeId());
+ channelInfo.setClientId(message.getClientId());
+ channelInfo.setName(semanticChannel);
+ channelInfo.setFirstMessageId(message.getDatastoreId());
+ channelInfo.setFirstMessageOn(message.getTimestamp());
+ channelInfo.setId(storableIdFactory.newStorableId(ChannelInfoField.getOrDeriveId(null, channelInfo)));
+ channelInfoStoreFacade.upstore(channelInfo);
+
+ KapuaPayload payload = message.getPayload();
+ if (payload == null) {
+ return;
+ }
+
+ Map metrics = payload.getMetrics();
+ if (metrics == null) {
+ return;
+ }
+
+ int i = 0;
+ MetricInfoImpl[] messageMetrics = new MetricInfoImpl[metrics.size()];
+ for (Map.Entry entry : metrics.entrySet()) {
+ MetricInfoImpl metricInfo = new MetricInfoImpl(message.getScopeId());
+ metricInfo.setClientId(message.getClientId());
+ metricInfo.setChannel(semanticChannel);
+ metricInfo.setName(entry.getKey());
+ metricInfo.setMetricType(entry.getValue().getClass());
+ metricInfo.setId(storableIdFactory.newStorableId(MetricInfoField.getOrDeriveId(null, metricInfo)));
+ metricInfo.setFirstMessageId(message.getDatastoreId());
+ metricInfo.setFirstMessageOn(message.getTimestamp());
+ messageMetrics[i++] = metricInfo;
+ }
+
+ metricInfoStoreFacade.upstore(messageMetrics);
+ }
+
+ /**
+ * Find messages matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws QueryMappingException
+ * @throws ClientException
+ */
+ @Override
+ public MessageListResult query(MessageQuery query)
+ throws KapuaIllegalArgumentException,
+ ConfigurationException,
+ ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ if (!this.isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId());
+ return new MessageListResultImpl();
+ }
+
+ return messageRepository.query(query);
+ }
+
+
+ // TODO cache will not be reset from the client code it should be automatically reset
+ // after some time.
+ private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, String clientId) throws Exception {
+
+ boolean isAnyClientId;
+ boolean isClientToDelete = false;
+ String semTopic;
+
+ if (channel != null) {
+
+ // determine if we should delete an client if topic = account/clientId/#
+ isAnyClientId = isAnyClientId(channel);
+ semTopic = channel;
+
+ if (semTopic.isEmpty() && !isAnyClientId) {
+ isClientToDelete = true;
+ }
+ } else {
+ isClientToDelete = true;
+ }
+
+ // Find all topics
+ int pageSize = 1000;
+ int offset = 0;
+ long totalHits = 1;
+
+ MetricInfoQueryImpl metricQuery = new MetricInfoQueryImpl(scopeId);
+ metricQuery.setLimit(pageSize + 1);
+ metricQuery.setOffset(offset);
+
+ ChannelMatchPredicateImpl channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
+ metricQuery.setPredicate(channelPredicate);
+
+ // Remove metrics
+ while (totalHits > 0) {
+ MetricInfoListResult metrics = metricInfoRepository.query(metricQuery);
+
+ totalHits = metrics.getTotalCount();
+ LocalCache metricsCache = datastoreCacheManager.getMetricsCache();
+ long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
+
+ for (int i = 0; i < toBeProcessed; i++) {
+ String id = metrics.getItem(i).getId().toString();
+ if (metricsCache.get(id)) {
+ metricsCache.remove(id);
+ }
+ }
+
+ if (totalHits > pageSize) {
+ offset += pageSize + 1;
+ }
+ }
+ LOG.debug("Removed cached channel metrics for: {}", channel);
+ metricInfoRepository.delete(metricQuery);
+ LOG.debug("Removed channel metrics for: {}", channel);
+ ChannelInfoQueryImpl channelQuery = new ChannelInfoQueryImpl(scopeId);
+ channelQuery.setLimit(pageSize + 1);
+ channelQuery.setOffset(offset);
+
+ channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
+ channelQuery.setPredicate(channelPredicate);
+
+ // Remove channel
+ offset = 0;
+ totalHits = 1;
+ while (totalHits > 0) {
+ final ChannelInfoListResult channels = channelInfoRepository.query(channelQuery);
+
+ totalHits = channels.getTotalCount();
+ LocalCache channelsCache = datastoreCacheManager.getChannelsCache();
+ long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
+
+ for (int i = 0; i < toBeProcessed; i++) {
+ String id = channels.getFirstItem().getId().toString();
+ if (channelsCache.get(id)) {
+ channelsCache.remove(id);
+ }
+ }
+ if (totalHits > pageSize) {
+ offset += pageSize + 1;
+ }
+ }
+
+ LOG.debug("Removed cached channels for: {}", channel);
+ channelInfoRepository.delete(channelQuery);
+
+ LOG.debug("Removed channels for: {}", channel);
+ // Remove client
+ if (isClientToDelete) {
+ ClientInfoQueryImpl clientInfoQuery = new ClientInfoQueryImpl(scopeId);
+ clientInfoQuery.setLimit(pageSize + 1);
+ clientInfoQuery.setOffset(offset);
+
+ channelPredicate = new ChannelMatchPredicateImpl(MessageField.CHANNEL, channel);
+ clientInfoQuery.setPredicate(channelPredicate);
+ offset = 0;
+ totalHits = 1;
+ while (totalHits > 0) {
+ ClientInfoListResult clients = clientInfoRepository.query(clientInfoQuery);
+ totalHits = clients.getTotalCount();
+ LocalCache clientsCache = datastoreCacheManager.getClientsCache();
+ long toBeProcessed = totalHits > pageSize ? pageSize : totalHits;
+
+ for (int i = 0; i < toBeProcessed; i++) {
+ String id = clients.getItem(i).getId().toString();
+ if (clientsCache.get(id)) {
+ clientsCache.remove(id);
+ }
+ }
+ if (totalHits > pageSize) {
+ offset += pageSize + 1;
+ }
+ }
+
+ LOG.debug("Removed cached clients for: {}", channel);
+ clientInfoRepository.delete(clientInfoQuery);
+
+ LOG.debug("Removed clients for: {}", channel);
+ }
+ }
+
+ // Utility methods
+
+ /**
+ * Check if the channel admit any client identifier (so if the channel has a specific wildcard in the second topic level).
+ * In the MQTT word this method return true if the topic starts with 'account/+/'.
+ *
+ * @param clientId
+ * @return
+ * @since 1.0.0
+ */
+ private boolean isAnyClientId(String clientId) {
+ return DatastoreChannel.SINGLE_LEVEL_WCARD.equals(clientId);
+ }
+
+
+ @Override
+ public void refreshAllIndexes() throws ClientException {
+ messageRepository.refreshAllIndexes();
+ clientInfoRepository.refreshAllIndexes();
+ channelInfoRepository.refreshAllIndexes();
+ metricInfoRepository.refreshAllIndexes();
+ }
+
+ @Override
+ public void deleteAllIndexes() throws ClientException {
+ messageRepository.deleteAllIndexes();
+ clientInfoRepository.deleteAllIndexes();
+ channelInfoRepository.deleteAllIndexes();
+ metricInfoRepository.deleteAllIndexes();
+ }
+
+
+ @Override
+ public void deleteIndexes(String indexExp) throws ClientException {
+ messageRepository.deleteIndexes(indexExp);
+ clientInfoRepository.deleteIndexes(indexExp);
+ channelInfoRepository.deleteIndexes(indexExp);
+ metricInfoRepository.deleteIndexes(indexExp);
+ }
+
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java
index e6f4a7d5ce4..b1ebf819b61 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java
@@ -31,7 +31,6 @@
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreCommunicationException;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreException;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreMediator;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
@@ -46,6 +45,7 @@
import javax.inject.Inject;
import javax.inject.Singleton;
+import java.util.Optional;
import java.util.UUID;
/**
@@ -58,14 +58,13 @@ public class MessageStoreServiceImpl extends KapuaConfigurableServiceBase implem
private static final Logger logger = LoggerFactory.getLogger(MessageStoreServiceImpl.class);
- //TODO inject!!!
private MetricsDatastore metrics;
protected AccountService accountService;
protected AuthorizationService authorizationService;
protected PermissionFactory permissionFactory;
- protected static final Integer MAX_ENTRIES_ON_DELETE = DatastoreSettings.getInstance().getInt(DatastoreSettingsKey.CONFIG_MAX_ENTRIES_ON_DELETE);
- protected static final Integer MAX_LIMIT_VALUE = DatastoreSettings.getInstance().getInt(DatastoreSettingsKey.MAX_LIMIT_VALUE);
+ protected final Integer maxLimitValue;
+ protected final Integer maxEntriesOnDelete;
protected final MessageStoreFacade messageStoreFacade;
@Inject
@@ -73,16 +72,18 @@ public MessageStoreServiceImpl(
TxManager txManager,
PermissionFactory permissionFactory,
AuthorizationService authorizationService,
- AccountService accountService,
- ServiceConfigurationManager serviceConfigurationManager
+ ServiceConfigurationManager serviceConfigurationManager,
+ MessageStoreFacade messageStoreFacade,
+ MetricsDatastore metricsDatastore,
+ DatastoreSettings datastoreSettings
) {
super(txManager, serviceConfigurationManager, Domains.DATASTORE, authorizationService, permissionFactory);
this.permissionFactory = permissionFactory;
this.authorizationService = authorizationService;
- final ConfigurationProviderImpl configurationProvider = new ConfigurationProviderImpl(this, accountService);
- metrics = MetricsDatastore.getInstance();
- messageStoreFacade = new MessageStoreFacade(configurationProvider, DatastoreMediator.getInstance());
- DatastoreMediator.getInstance().setMessageStoreFacade(messageStoreFacade);
+ this.metrics = metricsDatastore;
+ this.messageStoreFacade = messageStoreFacade;
+ maxLimitValue = datastoreSettings.getInt(DatastoreSettingsKey.MAX_LIMIT_VALUE);
+ maxEntriesOnDelete = datastoreSettings.getInt(DatastoreSettingsKey.CONFIG_MAX_ENTRIES_ON_DELETE);
}
@Override
@@ -95,15 +96,19 @@ public StorableId store(KapuaMessage, ?> message)
metrics.getMessage().inc();
return messageStoreFacade.store(message, datastoreId, true);
} catch (ConfigurationException e) {
+ logger.error("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ", e);
metrics.getConfigurationError().inc();
throw e;
} catch (KapuaIllegalArgumentException e) {
+ logger.error("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ", e);
metrics.getValidationError().inc();
throw e;
} catch (ClientCommunicationException e) {
+ logger.error("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ", e);
metrics.getCommunicationError().inc();
throw new DatastoreCommunicationException(datastoreId, e);
} catch (Exception e) {
+ logger.error("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ", e);
metrics.getGenericError().inc();
logException(e);
throw new DatastoreException(KapuaErrorCodes.INTERNAL_ERROR, e, e.getMessage());
@@ -148,7 +153,7 @@ public DatastoreMessage find(KapuaId scopeId, StorableId id) throws KapuaExcepti
public DatastoreMessage find(KapuaId scopeId, StorableId id, StorableFetchStyle fetchStyle) throws KapuaException {
checkDataAccess(scopeId, Actions.read);
try {
- return messageStoreFacade.find(scopeId, id, fetchStyle);
+ return messageStoreFacade.find(scopeId, id);
} catch (Exception e) {
logException(e);
throw new DatastoreException(KapuaErrorCodes.INTERNAL_ERROR, e, e.getMessage());
@@ -160,7 +165,7 @@ public MessageListResult query(MessageQuery query)
throws KapuaException {
checkDataAccess(query.getScopeId(), Actions.read);
if (query.getLimit() != null) {
- ArgumentValidator.numRange(query.getLimit(), 0, MAX_LIMIT_VALUE, "limit");
+ ArgumentValidator.numRange(query.getLimit(), 0, maxLimitValue, "limit");
}
try {
return messageStoreFacade.query(query);
@@ -169,7 +174,7 @@ public MessageListResult query(MessageQuery query)
throw new DatastoreException(
KapuaErrorCodes.INTERNAL_ERROR,
e,
- e.getCause().getMessage() != null ? e.getCause().getMessage() : e.getMessage()
+ Optional.ofNullable(e.getCause()).flatMap(c -> Optional.ofNullable(c.getMessage())).orElse(e.getMessage())
);
}
}
@@ -201,7 +206,7 @@ public void delete(KapuaId scopeId, StorableId id)
@Override
public void delete(MessageQuery query)
throws KapuaException {
- ArgumentValidator.numRange(query.getLimit(), 0, MAX_ENTRIES_ON_DELETE, "limit");
+ ArgumentValidator.numRange(query.getLimit(), 0, maxEntriesOnDelete, "limit");
checkDataAccess(query.getScopeId(), Actions.delete);
try {
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacade.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacade.java
index aaa0007f9eb..fc7d0962e77 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacade.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacade.java
@@ -13,301 +13,32 @@
package org.eclipse.kapua.service.datastore.internal;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
-import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField;
-import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoRegistryMediator;
-import org.eclipse.kapua.service.datastore.internal.model.MetricInfoListResultImpl;
-import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema;
-import org.eclipse.kapua.service.datastore.internal.schema.SchemaUtil;
import org.eclipse.kapua.service.datastore.model.MetricInfo;
import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.model.BulkUpdateRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.BulkUpdateResponse;
-import org.eclipse.kapua.service.elasticsearch.client.model.ResultList;
-import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.UpdateResponse;
import org.eclipse.kapua.service.storable.exception.MappingException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
-import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
-import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
-import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/**
- * Metric information registry facade
- *
- * @since 1.0.0
- */
-public class MetricInfoRegistryFacade extends AbstractRegistryFacade {
-
- private static final Logger LOG = LoggerFactory.getLogger(MetricInfoRegistryFacade.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
- private final MetricInfoRegistryMediator mediator;
-
- private static final String QUERY = "query";
- private static final String QUERY_SCOPE_ID = "query.scopeId";
- private static final String STORAGE_NOT_ENABLED = "Storage not enabled for account {}, returning empty result";
-
- /**
- * Constructs the metric info registry facade
- *
- * @param configProvider
- * @param mediator
- * @since 1.0.0
- */
- public MetricInfoRegistryFacade(ConfigurationProvider configProvider, MetricInfoRegistryMediator mediator) {
- super(configProvider);
-
- this.mediator = mediator;
- }
-
- /**
- * Update the metric information after a message store operation (for a single metric)
- *
- * @param metricInfo
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public StorableId upstore(MetricInfo metricInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
- ArgumentValidator.notNull(metricInfo, "metricInfo");
- ArgumentValidator.notNull(metricInfo.getScopeId(), "metricInfo.scopeId");
- ArgumentValidator.notNull(metricInfo.getFirstMessageId(), "metricInfoCreator.firstPublishedMessageId");
- ArgumentValidator.notNull(metricInfo.getFirstMessageOn(), "metricInfoCreator.firstPublishedMessageTimestamp");
+public interface MetricInfoRegistryFacade {
+ StorableId upstore(MetricInfo metricInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException;
- String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo);
- StorableId storableId = STORABLE_ID_FACTORY.newStorableId(metricInfoId);
-
- UpdateResponse response;
- // Store channel. Look up channel in the cache, and cache it if it doesn't exist
- if (!DatastoreCacheManager.getInstance().getMetricsCache().get(metricInfoId)) {
- // fix #REPLACE_ISSUE_NUMBER
- MetricInfo storedField = find(metricInfo.getScopeId(), storableId);
- if (storedField == null) {
- Metadata metadata = mediator.getMetadata(metricInfo.getScopeId(), metricInfo.getFirstMessageOn().getTime());
-
- String kapuaIndexName = metadata.getMetricRegistryIndexName();
-
- UpdateRequest request = new UpdateRequest(metricInfo.getId().toString(), new TypeDescriptor(metadata.getMetricRegistryIndexName(), MetricInfoSchema.METRIC_TYPE_NAME), metricInfo);
- response = getElasticsearchClient().upsert(request);
-
- LOG.debug("Upsert on metric successfully executed [{}.{}, {} - {}]", kapuaIndexName, MetricInfoSchema.METRIC_TYPE_NAME, metricInfoId, response.getId());
- }
- // Update cache if metric update is completed successfully
- DatastoreCacheManager.getInstance().getMetricsCache().put(metricInfoId, true);
- }
- return storableId;
- }
-
- /**
- * Update the metrics informations after a message store operation (for few metrics)
- *
- * @param metricInfos
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public BulkUpdateResponse upstore(MetricInfo[] metricInfos)
+ void upstore(MetricInfo[] metricInfos)
throws KapuaIllegalArgumentException,
ConfigurationException,
ClientException,
- MappingException {
- ArgumentValidator.notNull(metricInfos, "metricInfos");
-
- BulkUpdateRequest bulkRequest = new BulkUpdateRequest();
- boolean performUpdate = false;
- // Create a bulk request
- for (MetricInfo metricInfo : metricInfos) {
- String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo);
- // fix #REPLACE_ISSUE_NUMBER
- if (!DatastoreCacheManager.getInstance().getMetricsCache().get(metricInfoId)) {
- StorableId storableId = STORABLE_ID_FACTORY.newStorableId(metricInfoId);
- MetricInfo storedField = find(metricInfo.getScopeId(), storableId);
- if (storedField != null) {
- DatastoreCacheManager.getInstance().getMetricsCache().put(metricInfoId, true);
- continue;
- }
- performUpdate = true;
- Metadata metadata = mediator.getMetadata(metricInfo.getScopeId(), metricInfo.getFirstMessageOn().getTime());
-
- bulkRequest.add(
- new UpdateRequest(
- metricInfo.getId().toString(),
- new TypeDescriptor(metadata.getMetricRegistryIndexName(),
- MetricInfoSchema.METRIC_TYPE_NAME),
- metricInfo)
- );
- }
- }
-
- BulkUpdateResponse upsertResponse = null;
- if (performUpdate) {
- // execute the upstore
- try {
- upsertResponse = getElasticsearchClient().upsert(bulkRequest);
- } catch (ClientException e) {
- LOG.trace("Upsert failed {}", e.getMessage());
- throw e;
- }
-
- if (upsertResponse != null) {
- if (upsertResponse.getResponse().isEmpty()) {
- return upsertResponse;
- }
-
- for (UpdateResponse response : upsertResponse.getResponse()) {
- String index = response.getTypeDescriptor().getIndex();
- String type = response.getTypeDescriptor().getType();
- String id = response.getId();
- LOG.debug("Upsert on channel metric successfully executed [{}.{}, {}]", index, type, id);
-
- if (id == null || DatastoreCacheManager.getInstance().getMetricsCache().get(id)) {
- continue;
- }
-
- // Update cache if channel metric update is completed successfully
- DatastoreCacheManager.getInstance().getMetricsCache().put(id, true);
- }
- }
- }
- return upsertResponse;
- }
-
- /**
- * Delete metric information by identifier.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the metric info registry entry by id without checking the consistency of the others registries or the message store.
- *
- * @param scopeId
- * @param id
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- if (!isDatastoreServiceEnabled(scopeId)) {
- LOG.debug("Storage not enabled for account {}, return", scopeId);
- return;
- }
-
- String indexName = SchemaUtil.getMetricIndexName(scopeId);
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MetricInfoSchema.METRIC_TYPE_NAME);
- getElasticsearchClient().delete(typeDescriptor, id.toString());
- }
-
- /**
- * Find metric information by identifier
- *
- * @param scopeId
- * @param id
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public MetricInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(scopeId, "scopeId");
- ArgumentValidator.notNull(id, "id");
-
- MetricInfoQueryImpl idsQuery = new MetricInfoQueryImpl(scopeId);
- idsQuery.setLimit(1);
-
- IdsPredicate idsPredicate = STORABLE_PREDICATE_FACTORY.newIdsPredicate(MetricInfoSchema.METRIC_TYPE_NAME);
- idsPredicate.addId(id);
- idsQuery.setPredicate(idsPredicate);
-
- MetricInfoListResult result = query(idsQuery);
- return result.getFirstItem();
- }
-
- /**
- * Find metrics informations matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public MetricInfoListResult query(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
-
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
- return new MetricInfoListResultImpl();
- }
-
- String indexNme = SchemaUtil.getMetricIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexNme, MetricInfoSchema.METRIC_TYPE_NAME);
- ResultList rl = getElasticsearchClient().query(typeDescriptor, query, MetricInfo.class);
- MetricInfoListResult result = new MetricInfoListResultImpl(rl);
- setLimitExceed(query, rl.getTotalHitsExceedsCount(), result);
- return result;
- }
+ MappingException;
- /**
- * Get metrics informations count matching the given query
- *
- * @param query
- * @return
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public long count(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
- return 0;
- }
+ MetricInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- String indexName = SchemaUtil.getMetricIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MetricInfoSchema.METRIC_TYPE_NAME);
- return getElasticsearchClient().count(typeDescriptor, query);
- }
+ MetricInfoListResult query(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- /**
- * Delete metrics informations count matching the given query.
- * Be careful using this function since it doesn't guarantee the datastore consistency.
- * It just deletes the metric info registry entries that matching the query without checking the consistency of the others registries or the message store.
- *
- * @param query
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- public void delete(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
- ArgumentValidator.notNull(query, QUERY);
- ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+ long count(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- if (!isDatastoreServiceEnabled(query.getScopeId())) {
- LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
- return;
- }
+ void delete(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException;
- String indexName = SchemaUtil.getMetricIndexName(query.getScopeId());
- TypeDescriptor typeDescriptor = new TypeDescriptor(indexName, MetricInfoSchema.METRIC_TYPE_NAME);
- getElasticsearchClient().deleteByQuery(typeDescriptor, query);
- }
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java
new file mode 100644
index 00000000000..b2a8a1f49d9
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java
@@ -0,0 +1,278 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import org.eclipse.kapua.KapuaIllegalArgumentException;
+import org.eclipse.kapua.commons.util.ArgumentValidator;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException;
+import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField;
+import org.eclipse.kapua.service.datastore.internal.model.MetricInfoListResultImpl;
+import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl;
+import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema;
+import org.eclipse.kapua.service.datastore.model.MetricInfo;
+import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
+import org.eclipse.kapua.service.storable.model.query.predicate.IdsPredicate;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Metric information registry facade
+ *
+ * @since 1.0.0
+ */
+public class MetricInfoRegistryFacadeImpl extends AbstractDatastoreFacade implements MetricInfoRegistryFacade {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MetricInfoRegistryFacadeImpl.class);
+
+ private final StorableIdFactory storableIdFactory;
+ private final StorablePredicateFactory storablePredicateFactory;
+ private final MetricInfoRepository repository;
+ private final DatastoreCacheManager datastoreCacheManager;
+
+ private static final String QUERY = "query";
+ private static final String QUERY_SCOPE_ID = "query.scopeId";
+ private static final String STORAGE_NOT_ENABLED = "Storage not enabled for account {}, returning empty result";
+
+ /**
+ * Constructs the metric info registry facade
+ *
+ * @param configProvider
+ * @param metricInfoRepository
+ * @since 1.0.0
+ */
+ @Inject
+ public MetricInfoRegistryFacadeImpl(ConfigurationProvider configProvider,
+ StorableIdFactory storableIdFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ MetricInfoRepository metricInfoRepository,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(configProvider);
+ this.storableIdFactory = storableIdFactory;
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.repository = metricInfoRepository;
+ this.datastoreCacheManager = datastoreCacheManager;
+ }
+
+ /**
+ * Update the metric information after a message store operation (for a single metric)
+ *
+ * @param metricInfo
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public StorableId upstore(MetricInfo metricInfo) throws KapuaIllegalArgumentException, ConfigurationException, ClientException, MappingException {
+ ArgumentValidator.notNull(metricInfo, "metricInfo");
+ ArgumentValidator.notNull(metricInfo.getScopeId(), "metricInfo.scopeId");
+ ArgumentValidator.notNull(metricInfo.getFirstMessageId(), "metricInfoCreator.firstPublishedMessageId");
+ ArgumentValidator.notNull(metricInfo.getFirstMessageOn(), "metricInfoCreator.firstPublishedMessageTimestamp");
+
+ String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo);
+ StorableId storableId = storableIdFactory.newStorableId(metricInfoId);
+
+ // Store channel. Look up channel in the cache, and cache it if it doesn't exist
+ if (!datastoreCacheManager.getMetricsCache().get(metricInfoId)) {
+ // fix #REPLACE_ISSUE_NUMBER
+ MetricInfo storedField = doFind(metricInfo.getScopeId(), storableId);
+ if (storedField == null) {
+ repository.upsert(metricInfoId, metricInfo);
+ }
+ // Update cache if metric update is completed successfully
+ datastoreCacheManager.getMetricsCache().put(metricInfoId, true);
+ }
+ return storableId;
+ }
+
+ /**
+ * Update the metrics informations after a message store operation (for few metrics)
+ *
+ * @param metricInfos
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void upstore(MetricInfo[] metricInfos)
+ throws KapuaIllegalArgumentException,
+ ConfigurationException,
+ ClientException,
+ MappingException {
+ ArgumentValidator.notNull(metricInfos, "metricInfos");
+
+ // Create a bulk request
+ final List toUpsert = new ArrayList<>();
+ for (MetricInfo metricInfo : metricInfos) {
+ String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo);
+ // fix #REPLACE_ISSUE_NUMBER
+ if (!datastoreCacheManager.getMetricsCache().get(metricInfoId)) {
+ StorableId storableId = storableIdFactory.newStorableId(metricInfoId);
+ MetricInfo storedField = doFind(metricInfo.getScopeId(), storableId);
+ if (storedField != null) {
+ datastoreCacheManager.getMetricsCache().put(metricInfoId, true);
+ continue;
+ }
+ toUpsert.add(metricInfo);
+ }
+ }
+
+ final Set changedIds;
+ if (!toUpsert.isEmpty()) {
+ // execute the upstore
+ changedIds = repository.upsert(toUpsert);
+ if (changedIds != null) {
+ for (String changedId : changedIds) {
+ if (changedId == null || datastoreCacheManager.getMetricsCache().get(changedId)) {
+ continue;
+ }
+
+ // Update cache if channel metric update is completed successfully
+ datastoreCacheManager.getMetricsCache().put(changedId, true);
+ }
+ }
+ }
+ }
+
+ /**
+ * Delete metric information by identifier.
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the metric info registry entry by id without checking the consistency of the others registries or the message store.
+ *
+ * @param scopeId
+ * @param id
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(scopeId, "scopeId");
+ ArgumentValidator.notNull(id, "id");
+
+ if (!isDatastoreServiceEnabled(scopeId)) {
+ LOG.debug("Storage not enabled for account {}, return", scopeId);
+ return;
+ }
+
+ repository.delete(scopeId, id);
+ }
+
+ /**
+ * Find metric information by identifier
+ *
+ * @param scopeId
+ * @param id
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public MetricInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(scopeId, "scopeId");
+ ArgumentValidator.notNull(id, "id");
+ return doFind(scopeId, id);
+ }
+
+ private MetricInfo doFind(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ MetricInfoQueryImpl idsQuery = new MetricInfoQueryImpl(scopeId);
+ idsQuery.setLimit(1);
+
+ IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(MetricInfoSchema.METRIC_TYPE_NAME);
+ idsPredicate.addId(id);
+ idsQuery.setPredicate(idsPredicate);
+
+ MetricInfoListResult result = query(idsQuery);
+ return result.getFirstItem();
+ }
+
+ /**
+ * Find metrics informations matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public MetricInfoListResult query(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
+ return new MetricInfoListResultImpl();
+ }
+
+ return repository.query(query);
+ }
+
+ /**
+ * Get metrics informations count matching the given query
+ *
+ * @param query
+ * @return
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public long count(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
+ return 0;
+ }
+
+ return repository.count(query);
+ }
+
+ /**
+ * Delete metrics informations count matching the given query.
+ * Be careful using this function since it doesn't guarantee the datastore consistency.
+ * It just deletes the metric info registry entries that matching the query without checking the consistency of the others registries or the message store.
+ *
+ * @param query
+ * @throws KapuaIllegalArgumentException
+ * @throws ConfigurationException
+ * @throws ClientException
+ */
+ @Override
+ public void delete(MetricInfoQuery query) throws KapuaIllegalArgumentException, ConfigurationException, ClientException {
+ ArgumentValidator.notNull(query, QUERY);
+ ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID);
+
+ if (!isDatastoreServiceEnabled(query.getScopeId())) {
+ LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId());
+ return;
+ }
+
+ repository.delete(query);
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java
index 48375cb95f8..41827bdf095 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java
@@ -17,29 +17,25 @@
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException;
import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
-import org.eclipse.kapua.service.datastore.MessageStoreService;
import org.eclipse.kapua.service.datastore.MetricInfoRegistryService;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreMediator;
import org.eclipse.kapua.service.datastore.internal.mediator.MessageField;
import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField;
import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl;
import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
+import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
import org.eclipse.kapua.service.datastore.model.MessageListResult;
import org.eclipse.kapua.service.datastore.model.MetricInfo;
import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
import org.eclipse.kapua.service.datastore.model.query.MessageQuery;
import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientInitializationException;
import org.eclipse.kapua.service.storable.model.id.StorableId;
import org.eclipse.kapua.service.storable.model.query.SortField;
import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle;
@@ -51,10 +47,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.Optional;
/**
* Metric information registry implementation.
@@ -66,37 +64,33 @@ public class MetricInfoRegistryServiceImpl implements MetricInfoRegistryService
private static final Logger LOG = LoggerFactory.getLogger(MetricInfoRegistryServiceImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorablePredicateFactory STORABLE_PREDICATE_FACTORY = LOCATOR.getFactory(StorablePredicateFactory.class);
-
-
- private final AccountService accountService;
+ private final StorablePredicateFactory storablePredicateFactory;
private final AuthorizationService authorizationService;
private final PermissionFactory permissionFactory;
private final MetricInfoRegistryFacade metricInfoRegistryFacade;
- private final MessageStoreService messageStoreService;
private final DatastorePredicateFactory datastorePredicateFactory;
+ private final MessageRepository messageRepository;
+ private final DatastoreSettings datastoreSettings;
private static final String QUERY = "query";
private static final String QUERY_SCOPE_ID = "query.scopeId";
- /**
- * Default constructor
- *
- * @throws ClientInitializationException
- */
- public MetricInfoRegistryServiceImpl() throws ClientInitializationException {
- KapuaLocator locator = KapuaLocator.getInstance();
- accountService = locator.getService(AccountService.class);
- authorizationService = locator.getService(AuthorizationService.class);
- permissionFactory = locator.getFactory(PermissionFactory.class);
- messageStoreService = locator.getService(MessageStoreService.class);
- datastorePredicateFactory = KapuaLocator.getInstance().getFactory(DatastorePredicateFactory.class);
-
- MessageStoreService messageStoreService = KapuaLocator.getInstance().getService(MessageStoreService.class);
- ConfigurationProviderImpl configurationProvider = new ConfigurationProviderImpl(messageStoreService, accountService);
- metricInfoRegistryFacade = new MetricInfoRegistryFacade(configurationProvider, DatastoreMediator.getInstance());
- DatastoreMediator.getInstance().setMetricInfoStoreFacade(metricInfoRegistryFacade);
+ @Inject
+ public MetricInfoRegistryServiceImpl(
+ StorablePredicateFactory storablePredicateFactory,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ DatastorePredicateFactory datastorePredicateFactory,
+ MetricInfoRegistryFacade metricInfoRegistryFacade,
+ MessageRepository messageRepository,
+ DatastoreSettings datastoreSettings) {
+ this.storablePredicateFactory = storablePredicateFactory;
+ this.authorizationService = authorizationService;
+ this.permissionFactory = permissionFactory;
+ this.datastorePredicateFactory = datastorePredicateFactory;
+ this.metricInfoRegistryFacade = metricInfoRegistryFacade;
+ this.messageRepository = messageRepository;
+ this.datastoreSettings = datastoreSettings;
}
@Override
@@ -170,7 +164,8 @@ public long count(MetricInfoQuery query)
}
}
- void delete(MetricInfoQuery query)
+ @Override
+ public void delete(MetricInfoQuery query)
throws KapuaException {
if (!isServiceEnabled(query.getScopeId())) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -187,7 +182,8 @@ void delete(MetricInfoQuery query)
}
}
- void delete(KapuaId scopeId, StorableId id)
+ @Override
+ public void delete(KapuaId scopeId, StorableId id)
throws KapuaException {
if (!isServiceEnabled(scopeId)) {
throw new KapuaServiceDisabledException(this.getClass().getName());
@@ -227,24 +223,25 @@ private void updateLastPublishedFields(MetricInfo metricInfo) throws KapuaExcept
messageQuery.setOffset(0);
messageQuery.setSortFields(sort);
- RangePredicate messageIdPredicate = STORABLE_PREDICATE_FACTORY.newRangePredicate(MetricInfoField.TIMESTAMP, metricInfo.getFirstMessageOn(), null);
+ RangePredicate messageIdPredicate = storablePredicateFactory.newRangePredicate(MetricInfoField.TIMESTAMP, metricInfo.getFirstMessageOn(), null);
TermPredicate clientIdPredicate = datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, metricInfo.getClientId());
- ExistsPredicate metricPredicate = STORABLE_PREDICATE_FACTORY.newExistsPredicate(MessageField.METRICS.field(), metricInfo.getName());
+ ExistsPredicate metricPredicate = storablePredicateFactory.newExistsPredicate(MessageField.METRICS.field(), metricInfo.getName());
- AndPredicate andPredicate = STORABLE_PREDICATE_FACTORY.newAndPredicate();
+ AndPredicate andPredicate = storablePredicateFactory.newAndPredicate();
andPredicate.getPredicates().add(messageIdPredicate);
andPredicate.getPredicates().add(clientIdPredicate);
andPredicate.getPredicates().add(metricPredicate);
messageQuery.setPredicate(andPredicate);
- MessageListResult messageList = messageStoreService.query(messageQuery);
+ MessageListResult messageList = messageRepository.query(messageQuery);
StorableId lastPublishedMessageId = null;
Date lastPublishedMessageTimestamp = null;
- if (messageList.getSize() == 1) {
- lastPublishedMessageId = messageList.getFirstItem().getDatastoreId();
- lastPublishedMessageTimestamp = messageList.getFirstItem().getTimestamp();
- } else if (messageList.isEmpty()) {
+ final List messages = Optional.ofNullable(messageList).map(ml -> ml.getItems()).orElse(new ArrayList<>());
+ if (messages.size() == 1) {
+ lastPublishedMessageId = messages.get(0).getDatastoreId();
+ lastPublishedMessageTimestamp = messages.get(0).getTimestamp();
+ } else if (messages.isEmpty()) {
// this condition could happens due to the ttl of the messages (so if it happens, it does not necessarily mean there has been an error!)
LOG.warn("Cannot find last timestamp for the specified client id '{}' - account '{}'", metricInfo.getClientId(), metricInfo.getScopeId());
} else {
@@ -259,7 +256,7 @@ private void updateLastPublishedFields(MetricInfo metricInfo) throws KapuaExcept
@Override
public boolean isServiceEnabled(KapuaId scopeId) {
- return !DatastoreSettings.getInstance().getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
+ return !datastoreSettings.getBoolean(DatastoreSettingsKey.DISABLE_DATASTORE, false);
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCacheFactory.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepository.java
similarity index 54%
rename from service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCacheFactory.java
rename to service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepository.java
index 3da39e83190..4cbcbd3d563 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCacheFactory.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepository.java
@@ -10,17 +10,13 @@
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
-package org.eclipse.kapua.service.authorization.role.shiro;
+package org.eclipse.kapua.service.datastore.internal;
-import org.eclipse.kapua.commons.jpa.AbstractEntityCacheFactory;
+import org.eclipse.kapua.service.datastore.model.MetricInfo;
+import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
+import org.eclipse.kapua.service.storable.repository.StorableRepository;
-/**
- * Cache factory for the {@link RolePermissionServiceImpl}
- */
-public class RolePermissionCacheFactory extends AbstractEntityCacheFactory {
-
- public RolePermissionCacheFactory() {
- super("RolePermissionId");
- }
+public interface MetricInfoRepository extends StorableRepository {
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java
new file mode 100644
index 00000000000..9f8cce0fbc0
--- /dev/null
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.datastore.internal;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.service.datastore.MetricInfoFactory;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
+import org.eclipse.kapua.service.datastore.model.MetricInfo;
+import org.eclipse.kapua.service.datastore.model.MetricInfoListResult;
+import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery;
+import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
+import org.eclipse.kapua.service.storable.exception.MappingException;
+import org.eclipse.kapua.service.storable.model.id.StorableId;
+import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory;
+
+import javax.inject.Inject;
+
+public class MetricInfoRepositoryImpl extends DatastoreElasticSearchRepositoryBase implements MetricInfoRepository {
+
+ private final DatastoreUtils datastoreUtils;
+
+ @Inject
+ protected MetricInfoRepositoryImpl(
+ ElasticsearchClientProvider elasticsearchClientProviderInstance,
+ MetricInfoFactory metricInfoFactory,
+ StorablePredicateFactory storablePredicateFactory,
+ DatastoreSettings datastoreSettings,
+ DatastoreUtils datastoreUtils,
+ DatastoreCacheManager datastoreCacheManager) {
+ super(elasticsearchClientProviderInstance,
+ MetricInfoSchema.METRIC_TYPE_NAME,
+ MetricInfo.class,
+ metricInfoFactory,
+ storablePredicateFactory,
+ datastoreCacheManager.getMetricsCache(),
+ datastoreSettings);
+ this.datastoreUtils = datastoreUtils;
+ }
+
+ @Override
+ protected JsonNode getIndexSchema() throws MappingException {
+ return MetricInfoSchema.getMetricTypeSchema();
+ }
+
+ @Override
+ protected String indexResolver(KapuaId scopeId) {
+ return datastoreUtils.getMetricIndexName(scopeId);
+ }
+
+ @Override
+ protected StorableId idExtractor(MetricInfo storable) {
+ return storable.getId();
+ }
+}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricsDatastore.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricsDatastore.java
index 09e6f5e39be..7cb3939c106 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricsDatastore.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricsDatastore.java
@@ -12,13 +12,15 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal;
-import org.eclipse.kapua.commons.metric.MetricServiceFactory;
+import com.codahale.metrics.Counter;
+import com.codahale.metrics.Timer;
import org.eclipse.kapua.commons.metric.MetricsLabel;
import org.eclipse.kapua.commons.metric.MetricsService;
-import com.codahale.metrics.Counter;
-import com.codahale.metrics.Timer;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+@Singleton
public class MetricsDatastore {
private static final String CONSUMER_TELEMETRY = "consumer_telemetry";
@@ -40,17 +42,8 @@ public class MetricsDatastore {
private final Counter processedConfigurationError;
private final Counter processedGenericError;
- private static MetricsDatastore instance;
-
- public synchronized static MetricsDatastore getInstance() {
- if (instance == null) {
- instance = new MetricsDatastore();
- }
- return instance;
- }
-
- private MetricsDatastore() {
- MetricsService metricsService = MetricServiceFactory.getInstance();
+ @Inject
+ public MetricsDatastore(MetricsService metricsService) {
alreadyInTheDatastore = metricsService.getCounter(CONSUMER_TELEMETRY, STORE, DUPLICATED_STORE);
// data message
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreClientFactory.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreClientFactory.java
deleted file mode 100644
index 2897210f272..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreClientFactory.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.client;
-
-import org.eclipse.kapua.service.datastore.exception.DatastoreInternalError;
-import org.eclipse.kapua.service.datastore.internal.converter.ModelContextImpl;
-import org.eclipse.kapua.service.datastore.internal.converter.QueryConverterImpl;
-import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClient;
-import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider;
-import org.eclipse.kapua.service.elasticsearch.client.configuration.ElasticsearchClientConfiguration;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientUnavailableException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.Constructor;
-
-/**
- * Manages the {@link ElasticsearchClientProvider} as a singleton for the message store.
- *
- * @since 1.0.0
- */
-public class DatastoreClientFactory {
-
- private static final Logger LOG = LoggerFactory.getLogger(DatastoreClientFactory.class);
-
- private static ElasticsearchClientProvider> elasticsearchClientProviderInstance;
-
- private DatastoreClientFactory() {
- }
-
- /**
- * Gets the {@link ElasticsearchClientProvider} instance.
- *
- * The implementation is specified by {@link DatastoreElasticsearchClientConfiguration#getProviderClassName()}.
- *
- * @return An Elasticsearch client.
- */
- public static ElasticsearchClientProvider> getInstance() {
- if (elasticsearchClientProviderInstance == null) {
- synchronized (DatastoreClientFactory.class) {
- if (elasticsearchClientProviderInstance == null) {
-
- ElasticsearchClientProvider> elasticsearchClientProvider;
- try {
- ElasticsearchClientConfiguration esClientConfiguration = DatastoreElasticsearchClientConfiguration.getInstance();
-
- Class> providerClass = (Class>) Class.forName(esClientConfiguration.getProviderClassName());
- Constructor> constructor = providerClass.getConstructor();
- elasticsearchClientProvider = (ElasticsearchClientProvider>) constructor.newInstance();
-
- elasticsearchClientProvider
- .withClientConfiguration(esClientConfiguration)
- .withModelContext(new ModelContextImpl())
- .withModelConverter(new QueryConverterImpl())
- .init();
- } catch (Exception e) {
- throw new DatastoreInternalError(e, "Cannot instantiate Elasticsearch Client");
- }
-
- elasticsearchClientProviderInstance = elasticsearchClientProvider;
- }
- }
- }
-
- return elasticsearchClientProviderInstance;
- }
-
- /**
- * Gets the {@link ElasticsearchClient} instance.
- *
- * @return The {@link ElasticsearchClient} instance.
- * @throws ClientUnavailableException see {@link ElasticsearchClientProvider#getElasticsearchClient()}
- * @since 1.3.0
- */
- public static ElasticsearchClient> getElasticsearchClient() throws ClientUnavailableException {
- return getInstance().getElasticsearchClient();
- }
-
- /**
- * Closes the {@link ElasticsearchClientProvider} instance.
- *
- * @since 1.0.0
- */
- public static void close() {
- if (elasticsearchClientProviderInstance != null) {
- synchronized (DatastoreClientFactory.class) {
- if (elasticsearchClientProviderInstance != null) {
- try {
- elasticsearchClientProviderInstance.close();
- } catch (Exception e) {
- LOG.error("Unable to close ElasticsearchClientProvider instance.", e);
- } finally {
- elasticsearchClientProviderInstance = null;
- }
- }
- }
- }
- }
-
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreElasticsearchClientConfiguration.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreElasticsearchClientConfiguration.java
index 6e725e24c6b..e62ea8c7dfa 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreElasticsearchClientConfiguration.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/client/DatastoreElasticsearchClientConfiguration.java
@@ -24,27 +24,26 @@ public class DatastoreElasticsearchClientConfiguration extends ElasticsearchClie
private static final Logger LOG = LoggerFactory.getLogger(DatastoreElasticsearchClientConfiguration.class);
- private static final DatastoreElasticsearchClientSettings ELASTICSEARCH_CLIENT_SETTINGS = DatastoreElasticsearchClientSettings.getInstance();
+ private final DatastoreElasticsearchClientSettings elasticsearchClientSettings = DatastoreElasticsearchClientSettings.getInstance();
public DatastoreElasticsearchClientConfiguration() {
- setProviderClassName(ELASTICSEARCH_CLIENT_SETTINGS.getString(DatastoreElasticsearchClientSettingsKey.PROVIDER));
- setModuleName(ELASTICSEARCH_CLIENT_SETTINGS.getString(DatastoreElasticsearchClientSettingsKey.MODULE));
+ setModuleName(elasticsearchClientSettings.getString(DatastoreElasticsearchClientSettingsKey.MODULE));
- setClusterName(ELASTICSEARCH_CLIENT_SETTINGS.getString(DatastoreElasticsearchClientSettingsKey.CLUSTER));
+ setClusterName(elasticsearchClientSettings.getString(DatastoreElasticsearchClientSettingsKey.CLUSTER));
- List nodesSplitted = ELASTICSEARCH_CLIENT_SETTINGS.getList(String.class, DatastoreElasticsearchClientSettingsKey.NODES);
+ List nodesSplitted = elasticsearchClientSettings.getList(String.class, DatastoreElasticsearchClientSettingsKey.NODES);
for (String node : nodesSplitted) {
String[] nodeSplitted = node.split(":");
addNode(nodeSplitted[0], nodeSplitted.length == 2 ? Integer.parseInt(nodeSplitted[1]) : 9200);
}
- setUsername(ELASTICSEARCH_CLIENT_SETTINGS.getString(DatastoreElasticsearchClientSettingsKey.USERNAME));
- setPassword(ELASTICSEARCH_CLIENT_SETTINGS.getString(DatastoreElasticsearchClientSettingsKey.PASSWORD));
- getRequestConfiguration().setQueryTimeout(ELASTICSEARCH_CLIENT_SETTINGS.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_QUERY_TIMEOUT));
- getRequestConfiguration().setScrollTimeout(ELASTICSEARCH_CLIENT_SETTINGS.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_SCROLL_TIMEOUT));
- getRequestConfiguration().setRequestRetryAttemptMax(ELASTICSEARCH_CLIENT_SETTINGS.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_RETRY_MAX));
- getRequestConfiguration().setRequestRetryAttemptWait(ELASTICSEARCH_CLIENT_SETTINGS.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_RETRY_WAIT));
- getSslConfiguration().setEnabled(ELASTICSEARCH_CLIENT_SETTINGS.getBoolean(DatastoreElasticsearchClientSettingsKey.SSL_ENABLED));
+ setUsername(elasticsearchClientSettings.getString(DatastoreElasticsearchClientSettingsKey.USERNAME));
+ setPassword(elasticsearchClientSettings.getString(DatastoreElasticsearchClientSettingsKey.PASSWORD));
+ getRequestConfiguration().setQueryTimeout(elasticsearchClientSettings.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_QUERY_TIMEOUT));
+ getRequestConfiguration().setScrollTimeout(elasticsearchClientSettings.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_SCROLL_TIMEOUT));
+ getRequestConfiguration().setRequestRetryAttemptMax(elasticsearchClientSettings.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_RETRY_MAX));
+ getRequestConfiguration().setRequestRetryAttemptWait(elasticsearchClientSettings.getInt(DatastoreElasticsearchClientSettingsKey.REQUEST_RETRY_WAIT));
+ getSslConfiguration().setEnabled(elasticsearchClientSettings.getBoolean(DatastoreElasticsearchClientSettingsKey.SSL_ENABLED));
getReconnectConfiguration().setReconnectDelay(30000);
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java
index 8580a231987..31d89b93067 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java
@@ -15,7 +15,6 @@
import com.fasterxml.jackson.core.Base64Variants;
import org.eclipse.kapua.commons.model.id.KapuaEid;
import org.eclipse.kapua.commons.util.KapuaDateUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaPayload;
import org.eclipse.kapua.message.KapuaPosition;
import org.eclipse.kapua.message.internal.KapuaPositionImpl;
@@ -43,6 +42,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.Date;
@@ -60,12 +60,17 @@ public class ModelContextImpl implements ModelContext {
private static final Logger logger = LoggerFactory.getLogger(ModelContextImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
-
+ private final StorableIdFactory storableIdFactory;
+ private final DatastoreUtils datastoreUtils;
private static final String UNSUPPORTED_OBJECT_TYPE_ERROR_MSG = "The conversion of object [%s] is not supported!";
private static final String MARSHAL_INVALID_PARAMETERS_ERROR_MSG = "Object and/or object type cannot be null!";
+ @Inject
+ public ModelContextImpl(StorableIdFactory storableIdFactory, DatastoreUtils datastoreUtils) {
+ this.storableIdFactory = storableIdFactory;
+ this.datastoreUtils = datastoreUtils;
+ }
+
@Override
public String getIdKeyName() {
return "datastore_id";
@@ -132,7 +137,7 @@ private DatastoreMessage unmarshalDatastoreMessage(Map messageMa
StorableFetchStyle fetchStyle = getStorableFetchStyle(messageMap);
DatastoreMessageImpl message = new DatastoreMessageImpl();
String id = (String) messageMap.get(getIdKeyName());
- message.setDatastoreId(STORABLE_ID_FACTORY.newStorableId(id));
+ message.setDatastoreId(storableIdFactory.newStorableId(id));
String messageId = (String) messageMap.get(MessageSchema.MESSAGE_ID);
if (messageId != null) {
message.setId(UUID.fromString(messageId));
@@ -149,7 +154,7 @@ private DatastoreMessage unmarshalDatastoreMessage(Map messageMa
message.setDeviceId(deviceId);
String clientId = (String) messageMap.get(MessageSchema.MESSAGE_CLIENT_ID);
message.setClientId(clientId);
- message.setDatastoreId(STORABLE_ID_FACTORY.newStorableId(id));
+ message.setDatastoreId(storableIdFactory.newStorableId(id));
KapuaDataChannelImpl dataChannel = new KapuaDataChannelImpl();
message.setChannel(dataChannel);
@@ -226,7 +231,7 @@ private DatastoreMessage unmarshalDatastoreMessage(Map messageMa
// since elasticsearch doesn't return always the same type of the saved field
// (usually due to some promotion of the field type)
// we need to check the metric type returned by elasticsearch and, if needed, convert to the proper type
- payloadMetrics.put(DatastoreUtils.restoreMetricName(metricsName), DatastoreUtils.convertToCorrectType(valueTypes[0], value));
+ payloadMetrics.put(datastoreUtils.restoreMetricName(metricsName), datastoreUtils.convertToCorrectType(valueTypes[0], value));
}
}
payload.setMetrics(payloadMetrics);
@@ -255,17 +260,17 @@ private MetricInfo unmarshalMetricInfo(Map metricInfoMap) throws
String lastMsgId = (String) metricMap.get(MetricInfoSchema.METRIC_MTR_MSG_ID);
String clientId = (String) metricInfoMap.get(MetricInfoSchema.METRIC_CLIENT_ID);
String channel = (String) metricInfoMap.get(MetricInfoSchema.METRIC_CHANNEL);
- String metricName = DatastoreUtils.restoreMetricName(name);
+ String metricName = datastoreUtils.restoreMetricName(name);
Date timestamp = KapuaDateUtils.parseDate(lastMsgTimestamp);
MetricInfo metricInfo = new MetricInfoImpl(scopeId);
- metricInfo.setId(STORABLE_ID_FACTORY.newStorableId(id));
+ metricInfo.setId(storableIdFactory.newStorableId(id));
metricInfo.setClientId(clientId);
metricInfo.setChannel(channel);
- metricInfo.setFirstMessageId(STORABLE_ID_FACTORY.newStorableId(lastMsgId));
+ metricInfo.setFirstMessageId(storableIdFactory.newStorableId(lastMsgId));
metricInfo.setName(metricName);
metricInfo.setFirstMessageOn(timestamp);
- metricInfo.setMetricType(DatastoreUtils.convertToKapuaType(type));
+ metricInfo.setMetricType(datastoreUtils.convertToKapuaType(type));
return metricInfo;
}
@@ -275,10 +280,10 @@ private ChannelInfo unmarshalChannelInfo(Map channelInfoMap) thr
String id = (String) channelInfoMap.get(getIdKeyName());
ChannelInfo channelInfo = new ChannelInfoImpl(scopeId);
- channelInfo.setId(STORABLE_ID_FACTORY.newStorableId(id));
+ channelInfo.setId(storableIdFactory.newStorableId(id));
channelInfo.setClientId((String) channelInfoMap.get(ChannelInfoSchema.CHANNEL_CLIENT_ID));
channelInfo.setName((String) channelInfoMap.get(ChannelInfoSchema.CHANNEL_NAME));
- channelInfo.setFirstMessageId(STORABLE_ID_FACTORY.newStorableId((String) channelInfoMap.get(ChannelInfoSchema.CHANNEL_MESSAGE_ID)));
+ channelInfo.setFirstMessageId(storableIdFactory.newStorableId((String) channelInfoMap.get(ChannelInfoSchema.CHANNEL_MESSAGE_ID)));
channelInfo.setFirstMessageOn(KapuaDateUtils.parseDate((String) channelInfoMap.get(ChannelInfoSchema.CHANNEL_TIMESTAMP)));
return channelInfo;
@@ -289,9 +294,9 @@ private ClientInfo unmarshalClientInfo(Map clientInfoMap) throws
String id = (String) clientInfoMap.get(getIdKeyName());
ClientInfo clientInfo = new ClientInfoImpl(scopeId);
- clientInfo.setId(STORABLE_ID_FACTORY.newStorableId(id));
+ clientInfo.setId(storableIdFactory.newStorableId(id));
clientInfo.setClientId((String) clientInfoMap.get(ClientInfoSchema.CLIENT_ID));
- clientInfo.setFirstMessageId(STORABLE_ID_FACTORY.newStorableId((String) clientInfoMap.get(ClientInfoSchema.CLIENT_MESSAGE_ID)));
+ clientInfo.setFirstMessageId(storableIdFactory.newStorableId((String) clientInfoMap.get(ClientInfoSchema.CLIENT_MESSAGE_ID)));
clientInfo.setFirstMessageOn(KapuaDateUtils.parseDate((String) clientInfoMap.get(ClientInfoSchema.CLIENT_TIMESTAMP)));
return clientInfo;
@@ -356,11 +361,11 @@ private Map marshalDatastoreMessage(DatastoreMessage message) th
for (String kapuaMetricName : metricNames) {
Object metricValue = kapuaMetrics.get(kapuaMetricName);
// Sanitize field names: '.' is not allowed
- String metricName = DatastoreUtils.normalizeMetricName(kapuaMetricName);
- String clientMetricType = DatastoreUtils.getClientMetricFromType(metricValue.getClass());
- String clientMetricTypeAcronym = DatastoreUtils.getClientMetricFromAcronym(clientMetricType);
+ String metricName = datastoreUtils.normalizeMetricName(kapuaMetricName);
+ String clientMetricType = datastoreUtils.getClientMetricFromType(metricValue.getClass());
+ String clientMetricTypeAcronym = datastoreUtils.getClientMetricFromAcronym(clientMetricType);
Map field = new HashMap<>();
- if (DatastoreUtils.isDateMetric(clientMetricTypeAcronym) && metricValue instanceof Date) {
+ if (datastoreUtils.isDateMetric(clientMetricTypeAcronym) && metricValue instanceof Date) {
field.put(clientMetricTypeAcronym, KapuaDateUtils.formatDate((Date) metricValue));
} else {
field.put(clientMetricTypeAcronym, metricValue);
@@ -402,7 +407,7 @@ private Map marshalMetricInfo(MetricInfo metricInfo) throws Pars
Map unmarshalledMetricValue = new HashMap<>();
unmarshalledMetricValue.put(MetricInfoSchema.METRIC_MTR_NAME, metricInfo.getName());
- unmarshalledMetricValue.put(MetricInfoSchema.METRIC_MTR_TYPE, DatastoreUtils.convertToClientMetricType(metricInfo.getMetricType()));
+ unmarshalledMetricValue.put(MetricInfoSchema.METRIC_MTR_TYPE, datastoreUtils.convertToClientMetricType(metricInfo.getMetricType()));
unmarshalledMetricValue.put(MetricInfoSchema.METRIC_MTR_TIMESTAMP, KapuaDateUtils.formatDate(metricInfo.getFirstMessageOn()));
unmarshalledMetricValue.put(MetricInfoSchema.METRIC_MTR_MSG_ID, metricInfo.getFirstMessageId().toString());
unmarshalledMetricInfo.put(MetricInfoSchema.METRIC_MTR, unmarshalledMetricValue);
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java
index 3a1127d45c0..8094e3b0c8f 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.mediator;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema;
import org.eclipse.kapua.service.datastore.model.ChannelInfo;
@@ -83,7 +84,8 @@ public String field() {
*/
private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel) {
if (id == null) {
- return DatastoreUtils.getHashCode(scopeId.toCompactId(), clientId, channel);
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
+ return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId, channel);
} else {
return id.toString();
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoRegistryMediator.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoRegistryMediator.java
deleted file mode 100644
index 1ad6efb0939..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoRegistryMediator.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.mediator;
-
-import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.model.ChannelInfo;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.exception.QueryMappingException;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-
-/**
- * Channel information registry mediator definition
- *
- * @since 1.0.0
- */
-public interface ChannelInfoRegistryMediator {
-
- /**
- * Get the channel info metadata
- *
- * @param scopeId
- * @param indexedOn
- * @return
- * @throws ClientException
- */
- Metadata getMetadata(KapuaId scopeId, long indexedOn)
- throws ClientException, MappingException;
-
- /**
- * On before channel info delete event handler
- *
- * @param channelInfo
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws QueryMappingException
- * @throws ClientException
- */
- void onBeforeChannelInfoDelete(ChannelInfo channelInfo)
- throws KapuaIllegalArgumentException,
- ConfigurationException,
- QueryMappingException,
- ClientException;
-
- /**
- * On after channel info delete event handler
- *
- * @param channelInfo
- */
- void onAfterChannelInfoDelete(ChannelInfo channelInfo);
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java
index ee2a9b61483..78eddc75dd6 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.mediator;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema;
import org.eclipse.kapua.service.datastore.model.ClientInfo;
@@ -75,7 +76,8 @@ public String field() {
*/
public static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId) {
if (id == null) {
- return DatastoreUtils.getHashCode(scopeId.toCompactId(), clientId);
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
+ return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId);
} else {
return id.toString();
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoRegistryMediator.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoRegistryMediator.java
deleted file mode 100644
index 56124befe9d..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoRegistryMediator.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.mediator;
-
-import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.model.ClientInfo;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-
-/**
- * Client information registry mediator definition
- *
- * @since 1.0
- */
-public interface ClientInfoRegistryMediator {
-
- /**
- * Get the client info metadata
- *
- * @param scopeId
- * @param indexedOn
- * @return
- * @throws ClientException
- */
- Metadata getMetadata(KapuaId scopeId, long indexedOn) throws ClientException, MappingException;
-
- /**
- * On after client info delete event handler
- *
- * @param scopeId
- * @param clientInfo
- * @throws KapuaIllegalArgumentException
- * @throws ConfigurationException
- * @throws ClientException
- */
- void onAfterClientInfoDelete(KapuaId scopeId, ClientInfo clientInfo)
- throws KapuaIllegalArgumentException,
- ConfigurationException,
- ClientException;
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreMediator.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreMediator.java
deleted file mode 100644
index 7086da8f1f8..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreMediator.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- * Red Hat Inc
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.mediator;
-
-import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.message.KapuaPayload;
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService;
-import org.eclipse.kapua.service.datastore.ClientInfoRegistryService;
-import org.eclipse.kapua.service.datastore.MetricInfoRegistryService;
-import org.eclipse.kapua.service.datastore.internal.ChannelInfoRegistryFacade;
-import org.eclipse.kapua.service.datastore.internal.ClientInfoRegistryFacade;
-import org.eclipse.kapua.service.datastore.internal.DatastoreCacheManager;
-import org.eclipse.kapua.service.datastore.internal.MessageStoreFacade;
-import org.eclipse.kapua.service.datastore.internal.MetricInfoRegistryFacade;
-import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoImpl;
-import org.eclipse.kapua.service.datastore.internal.model.ClientInfoImpl;
-import org.eclipse.kapua.service.datastore.internal.model.MetricInfoImpl;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.internal.schema.Schema;
-import org.eclipse.kapua.service.datastore.model.ChannelInfo;
-import org.eclipse.kapua.service.datastore.model.ClientInfo;
-import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
-import org.eclipse.kapua.service.datastore.model.MetricInfo;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-import org.eclipse.kapua.service.storable.model.id.StorableIdFactory;
-
-import java.util.Map;
-
-/**
- * Datastore mediator definition
- *
- * @since 1.0.0
- */
-public class DatastoreMediator implements MessageStoreMediator,
- ClientInfoRegistryMediator,
- ChannelInfoRegistryMediator,
- MetricInfoRegistryMediator {
-
- private static final DatastoreMediator INSTANCE;
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final StorableIdFactory STORABLE_ID_FACTORY = LOCATOR.getFactory(StorableIdFactory.class);
-
- private final Schema esSchema;
-
- private MessageStoreFacade messageStoreFacade;
- private ClientInfoRegistryFacade clientInfoRegistryFacade;
- private ChannelInfoRegistryFacade channelInfoStoreFacade;
- private MetricInfoRegistryFacade metricInfoStoreFacade;
-
- static {
- INSTANCE = new DatastoreMediator();
-
- // Be sure the data registry services are instantiated
- KapuaLocator.getInstance().getService(ClientInfoRegistryService.class);
- KapuaLocator.getInstance().getService(ChannelInfoRegistryService.class);
- KapuaLocator.getInstance().getService(MetricInfoRegistryService.class);
- }
-
- private DatastoreMediator() {
- esSchema = new Schema();
- }
-
- /**
- * Gets the {@link DatastoreMediator} instance.
- *
- * @return The {@link DatastoreMediator} instance.
- * @since 1.0.0
- */
- public static DatastoreMediator getInstance() {
- return INSTANCE;
- }
-
- /**
- * Sets the {@link MessageStoreFacade}.
- *
- * @param messageStoreFacade The {@link MessageStoreFacade}.
- * @since 1.0.0
- */
- public void setMessageStoreFacade(MessageStoreFacade messageStoreFacade) {
- this.messageStoreFacade = messageStoreFacade;
- }
-
- /**
- * Sets the {@link ClientInfoRegistryFacade}.
- *
- * @param clientInfoRegistryFacade The {@link ClientInfoRegistryFacade}.
- * @since 1.0.0
- */
- public void setClientInfoStoreFacade(ClientInfoRegistryFacade clientInfoRegistryFacade) {
- this.clientInfoRegistryFacade = clientInfoRegistryFacade;
- }
-
- /**
- * Sets the {@link ChannelInfoRegistryFacade}.
- *
- * @param channelInfoStoreFacade The {@link ChannelInfoRegistryFacade}.
- * @since 1.0.0
- */
- public void setChannelInfoStoreFacade(ChannelInfoRegistryFacade channelInfoStoreFacade) {
- this.channelInfoStoreFacade = channelInfoStoreFacade;
- }
-
- /**
- * Sets the {@link MetricInfoRegistryFacade}.
- *
- * @param metricInfoStoreFacade The {@link MetricInfoRegistryFacade}.
- * @since 1.0.0
- */
- public void setMetricInfoStoreFacade(MetricInfoRegistryFacade metricInfoStoreFacade) {
- this.metricInfoStoreFacade = metricInfoStoreFacade;
- }
- // Message Store Mediator methods
-
- @Override
- public Metadata getMetadata(KapuaId scopeId, long indexedOn) throws ClientException, MappingException {
- return esSchema.synch(scopeId, indexedOn);
- }
-
- @Override
- public void onUpdatedMappings(KapuaId scopeId, long indexedOn, Map metrics) throws ClientException, MappingException {
- esSchema.updateMessageMappings(scopeId, indexedOn, metrics);
- }
-
- @Override
- public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage message)
- throws KapuaIllegalArgumentException,
- ConfigurationException,
- MappingException,
- ClientException {
-
- // convert semantic channel to String
- String semanticChannel = message.getChannel() != null ? message.getChannel().toString() : "";
-
- ClientInfoImpl clientInfo = new ClientInfoImpl(message.getScopeId());
- clientInfo.setClientId(message.getClientId());
- clientInfo.setId(STORABLE_ID_FACTORY.newStorableId(ClientInfoField.getOrDeriveId(null, message.getScopeId(), message.getClientId())));
- clientInfo.setFirstMessageId(message.getDatastoreId());
- clientInfo.setFirstMessageOn(message.getTimestamp());
- clientInfoRegistryFacade.upstore(clientInfo);
-
- ChannelInfoImpl channelInfo = new ChannelInfoImpl(message.getScopeId());
- channelInfo.setClientId(message.getClientId());
- channelInfo.setName(semanticChannel);
- channelInfo.setFirstMessageId(message.getDatastoreId());
- channelInfo.setFirstMessageOn(message.getTimestamp());
- channelInfo.setId(STORABLE_ID_FACTORY.newStorableId(ChannelInfoField.getOrDeriveId(null, channelInfo)));
- channelInfoStoreFacade.upstore(channelInfo);
-
- KapuaPayload payload = message.getPayload();
- if (payload == null) {
- return;
- }
-
- Map metrics = payload.getMetrics();
- if (metrics == null) {
- return;
- }
-
- int i = 0;
- MetricInfoImpl[] messageMetrics = new MetricInfoImpl[metrics.size()];
- for (Map.Entry entry : metrics.entrySet()) {
- MetricInfoImpl metricInfo = new MetricInfoImpl(message.getScopeId());
- metricInfo.setClientId(message.getClientId());
- metricInfo.setChannel(semanticChannel);
- metricInfo.setName(entry.getKey());
- metricInfo.setMetricType(entry.getValue().getClass());
- metricInfo.setId(STORABLE_ID_FACTORY.newStorableId(MetricInfoField.getOrDeriveId(null, metricInfo)));
- metricInfo.setFirstMessageId(message.getDatastoreId());
- metricInfo.setFirstMessageOn(message.getTimestamp());
- messageMetrics[i++] = metricInfo;
- }
-
- metricInfoStoreFacade.upstore(messageMetrics);
- }
-
- /*
- *
- * ClientInfo Store Mediator methods
- */
- @Override
- public void onAfterClientInfoDelete(KapuaId scopeId, ClientInfo clientInfo) {
- // nothing to do at the present
- // the datastore coherence will be guarantee by a periodic task that will scan the datastore looking for a no more referenced info registry record
- // otherwise the computational cost for each delete operation will be too high
- }
-
- /*
- * ChannelInfo Store Mediator methods
- */
- @Override
- public void onBeforeChannelInfoDelete(ChannelInfo channelInfo) {
- // nothing to do at the present
- // the datastore coherence will be guarantee by a periodic task that will scan the datastore looking for a no more referenced info registry record
- // otherwise the computational cost for each delete operation will be too high
- }
-
- @Override
- public void onAfterChannelInfoDelete(ChannelInfo channelInfo) {
- // nothing to do at the present
- // the datastore coherence will be guarantee by a periodic task that will scan the datastore looking for a no more referenced info registry record
- // otherwise the computational cost for each delete operation will be too high
- }
-
- /*
- *
- * MetricInfo Store Mediator methods
- */
- @Override
- public void onAfterMetricInfoDelete(KapuaId scopeId, MetricInfo metricInfo) {
- // nothing to do at the present
- // the datastore coherence will be guarantee by a periodic task that will scan the datastore looking for a no more referenced info registry record
- // otherwise the computational cost for each delete operation will be too high
- }
-
- public void refreshAllIndexes() throws ClientException {
- messageStoreFacade.refreshAllIndexes();
- }
-
- public void deleteAllIndexes() throws ClientException {
- messageStoreFacade.deleteAllIndexes();
- clearCache();
- }
-
- public void deleteIndexes(String indexExp) throws ClientException {
- messageStoreFacade.deleteIndexes(indexExp);
- clearCache();
- }
-
- public void clearCache() {
- DatastoreCacheManager.getInstance().getChannelsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getClientsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getMetricsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getMetadataCache().invalidateAll();
- }
-
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreUtils.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreUtils.java
index 42d8bed54dd..f029eff9b7b 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreUtils.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/DatastoreUtils.java
@@ -16,7 +16,6 @@
import com.google.common.hash.Hashing;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.kapua.KapuaErrorCodes;
-import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.util.KapuaDateUtils;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
@@ -24,6 +23,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
@@ -51,10 +51,40 @@
public class DatastoreUtils {
private static final Logger LOG = LoggerFactory.getLogger(DatastoreUtils.class);
-
- private enum IndexType { CHANNEL, CLIENT, METRIC }
-
- private DatastoreUtils() {
+ private final DatastoreSettings datastoreSettings;
+
+ private enum IndexType {CHANNEL, CLIENT, METRIC}
+
+ @Inject
+ public DatastoreUtils(DatastoreSettings datastoreSettings) {
+ this.datastoreSettings = datastoreSettings;
+ dataIndexFormatterWeek = new DateTimeFormatterBuilder()
+ .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
+ .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
+ .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
+ .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
+ .appendPattern("YYYY-ww")
+ .toFormatter(KapuaDateUtils.getLocale())
+ .withLocale(KapuaDateUtils.getLocale())
+ .withResolverStyle(ResolverStyle.STRICT)
+ .withZone(KapuaDateUtils.getTimeZone());
+ dataIndexFormatterDay = new DateTimeFormatterBuilder()
+ .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
+ .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
+ .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
+ .appendPattern("YYYY-ww-ee")
+ .toFormatter(KapuaDateUtils.getLocale())
+ .withLocale(KapuaDateUtils.getLocale())
+ .withResolverStyle(ResolverStyle.STRICT)
+ .withZone(KapuaDateUtils.getTimeZone());
+ dataIndexFormatterHour = new DateTimeFormatterBuilder()
+ .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
+ .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
+ .appendPattern("YYYY-ww-ee-HH")
+ .toFormatter(KapuaDateUtils.getLocale())
+ .withLocale(KapuaDateUtils.getLocale())
+ .withResolverStyle(ResolverStyle.STRICT)
+ .withZone(KapuaDateUtils.getTimeZone());
}
private static final char SPECIAL_DOT = '.';
@@ -92,33 +122,9 @@ private DatastoreUtils() {
public static final String DATASTORE_DATE_FORMAT = "8" + KapuaDateUtils.ISO_DATE_PATTERN; // example 2017-01-24T11:22:10.999Z
- private static final DateTimeFormatter DATA_INDEX_FORMATTER_WEEK = new DateTimeFormatterBuilder()
- .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
- .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
- .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
- .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
- .appendPattern("YYYY-ww")
- .toFormatter(KapuaDateUtils.getLocale())
- .withLocale(KapuaDateUtils.getLocale())
- .withResolverStyle(ResolverStyle.STRICT)
- .withZone(KapuaDateUtils.getTimeZone());
- private static final DateTimeFormatter DATA_INDEX_FORMATTER_DAY = new DateTimeFormatterBuilder()
- .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
- .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
- .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
- .appendPattern("YYYY-ww-ee")
- .toFormatter(KapuaDateUtils.getLocale())
- .withLocale(KapuaDateUtils.getLocale())
- .withResolverStyle(ResolverStyle.STRICT)
- .withZone(KapuaDateUtils.getTimeZone());
- private static final DateTimeFormatter DATA_INDEX_FORMATTER_HOUR = new DateTimeFormatterBuilder()
- .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
- .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
- .appendPattern("YYYY-ww-ee-HH")
- .toFormatter(KapuaDateUtils.getLocale())
- .withLocale(KapuaDateUtils.getLocale())
- .withResolverStyle(ResolverStyle.STRICT)
- .withZone(KapuaDateUtils.getTimeZone());
+ private final DateTimeFormatter dataIndexFormatterWeek;
+ private final DateTimeFormatter dataIndexFormatterDay;
+ private final DateTimeFormatter dataIndexFormatterHour;
/**
* Return the hash code for the provided components (typically components are a sequence of account - client id - channel ...)
@@ -126,7 +132,7 @@ private DatastoreUtils() {
* @param components
* @return
*/
- public static String getHashCode(String... components) {
+ public String getHashCode(String... components) {
String concatString = "";
for (String str : components) {
concatString = concatString.concat(str);
@@ -141,15 +147,15 @@ public static String getHashCode(String... components) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(hashCode);
}
- private static String normalizeIndexName(String name) {
+ private String normalizeIndexName(String name) {
String normName = null;
try {
- DatastoreUtils.checkIdxAliasName(name);
+ checkIdxAliasName(name);
normName = name;
} catch (IllegalArgumentException exc) {
LOG.trace(exc.getMessage(), exc);
normName = name.toLowerCase().replace(ILLEGAL_CHARS, "_");
- DatastoreUtils.checkIdxAliasName(normName);
+ checkIdxAliasName(normName);
}
return normName;
}
@@ -162,7 +168,7 @@ private static String normalizeIndexName(String name) {
* @return The normalized metric name
* @since 1.0.0
*/
- public static String normalizeMetricName(String name) {
+ public String normalizeMetricName(String name) {
String newName = name;
if (newName.contains(".")) {
newName = newName.replace(String.valueOf(SPECIAL_DOLLAR), SPECIAL_DOLLAR_ESC);
@@ -179,7 +185,7 @@ public static String normalizeMetricName(String name) {
* @return The restored metric name
* @since 1.0.0
*/
- public static String restoreMetricName(String normalizedName) {
+ public String restoreMetricName(String normalizedName) {
String oldName = normalizedName;
oldName = oldName.replace(SPECIAL_DOT_ESC, String.valueOf(SPECIAL_DOT));
oldName = oldName.replace(SPECIAL_DOLLAR_ESC, String.valueOf(SPECIAL_DOLLAR));
@@ -192,7 +198,7 @@ public static String restoreMetricName(String normalizedName) {
* @param fullName
* @return
*/
- public static String[] getMetricParts(String fullName) {
+ public String[] getMetricParts(String fullName) {
return fullName == null ? null : fullName.split(Pattern.quote("."));
}
@@ -203,7 +209,7 @@ public static String[] getMetricParts(String fullName) {
* @param alias
* @since 1.0.0
*/
- public static void checkIdxAliasName(String alias) {
+ public void checkIdxAliasName(String alias) {
if (alias == null || alias.isEmpty()) {
throw new IllegalArgumentException(String.format("Alias name cannot be %s", alias == null ? "null" : "empty"));
}
@@ -226,8 +232,8 @@ public static void checkIdxAliasName(String alias) {
* @param index
* @since 1.0.0
*/
- public static void checkIdxName(String index) {
- DatastoreUtils.checkIdxAliasName(index);
+ public void checkIdxName(String index) {
+ checkIdxAliasName(index);
}
/**
@@ -237,7 +243,7 @@ public static void checkIdxName(String index) {
* @return The normalized index alias
* @since 1.0.0
*/
- public static String normalizeIndexAliasName(String alias) {
+ public String normalizeIndexAliasName(String alias) {
String aliasName = normalizeIndexName(alias);
aliasName = aliasName.replace("-", "_");
return aliasName;
@@ -249,13 +255,13 @@ public static String normalizeIndexAliasName(String alias) {
* @param scopeId
* @return
*/
- public static String getDataIndexName(KapuaId scopeId) {
+ public String getDataIndexName(KapuaId scopeId) {
final StringBuilder sb = new StringBuilder();
- final String prefix = DatastoreSettings.getInstance().getString(DatastoreSettingsKey.INDEX_PREFIX);
+ final String prefix = datastoreSettings.getString(DatastoreSettingsKey.INDEX_PREFIX);
if (StringUtils.isNotEmpty(prefix)) {
sb.append(prefix).append("-");
}
- String indexName = DatastoreUtils.normalizedIndexName(scopeId.toStringId());
+ String indexName = normalizedIndexName(scopeId.toStringId());
sb.append(indexName).append("-").append("data-message").append("-*");
return sb.toString();
}
@@ -267,40 +273,40 @@ public static String getDataIndexName(KapuaId scopeId) {
* @param timestamp
* @return
*/
- public static String getDataIndexName(KapuaId scopeId, long timestamp, String indexingWindowOption) throws KapuaException {
+ public String getDataIndexName(KapuaId scopeId, long timestamp, String indexingWindowOption) {
final StringBuilder sb = new StringBuilder();
- final String prefix = DatastoreSettings.getInstance().getString(DatastoreSettingsKey.INDEX_PREFIX);
+ final String prefix = datastoreSettings.getString(DatastoreSettingsKey.INDEX_PREFIX);
if (StringUtils.isNotEmpty(prefix)) {
sb.append(prefix).append("-");
}
- final String actualName = DatastoreUtils.normalizedIndexName(scopeId.toStringId());
+ final String actualName = normalizedIndexName(scopeId.toStringId());
sb.append(actualName).append('-').append("data-message").append('-');
DateTimeFormatter formatter;
switch (indexingWindowOption) {
default:
case INDEXING_WINDOW_OPTION_WEEK:
- formatter = DATA_INDEX_FORMATTER_WEEK;
+ formatter = dataIndexFormatterWeek;
break;
case INDEXING_WINDOW_OPTION_DAY:
- formatter = DATA_INDEX_FORMATTER_DAY;
+ formatter = dataIndexFormatterDay;
break;
case INDEXING_WINDOW_OPTION_HOUR:
- formatter = DATA_INDEX_FORMATTER_HOUR;
+ formatter = dataIndexFormatterHour;
break;
}
formatter.formatTo(Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.UTC), sb);
return sb.toString();
}
- public static String getChannelIndexName(KapuaId scopeId) {
+ public String getChannelIndexName(KapuaId scopeId) {
return getRegistryIndexName(scopeId, IndexType.CHANNEL);
}
- public static String getClientIndexName(KapuaId scopeId) {
+ public String getClientIndexName(KapuaId scopeId) {
return getRegistryIndexName(scopeId, IndexType.CLIENT);
}
- public static String getMetricIndexName(KapuaId scopeId) {
+ public String getMetricIndexName(KapuaId scopeId) {
return getRegistryIndexName(scopeId, IndexType.METRIC);
}
@@ -311,13 +317,13 @@ public static String getMetricIndexName(KapuaId scopeId) {
* @return The Kapua index name
* @since 1.0.0
*/
- private static String getRegistryIndexName(KapuaId scopeId, IndexType indexType) {
+ private String getRegistryIndexName(KapuaId scopeId, IndexType indexType) {
final StringBuilder sb = new StringBuilder();
- final String prefix = DatastoreSettings.getInstance().getString(DatastoreSettingsKey.INDEX_PREFIX);
+ final String prefix = datastoreSettings.getString(DatastoreSettingsKey.INDEX_PREFIX);
if (StringUtils.isNotEmpty(prefix)) {
sb.append(prefix).append("-");
}
- String indexName = DatastoreUtils.normalizedIndexName(scopeId.toStringId());
+ String indexName = normalizedIndexName(scopeId.toStringId());
sb.append(indexName);
sb.append("-data-").append(indexType.name().toLowerCase());
return sb.toString();
@@ -329,7 +335,7 @@ private static String getRegistryIndexName(KapuaId scopeId, IndexType indexType)
* @param index
* @return
*/
- public static String normalizedIndexName(String index) {
+ public String normalizedIndexName(String index) {
return normalizeIndexName(index);
}
@@ -344,7 +350,7 @@ public static String normalizedIndexName(String index) {
* @return The list of the data indexes between start and end
* @throws DatastoreException
*/
- public static String[] convertToDataIndexes(@NotNull String[] indexes, Instant windowStart, Instant windowEnd) throws DatastoreException {
+ public String[] convertToDataIndexes(@NotNull String[] indexes, Instant windowStart, Instant windowEnd) throws DatastoreException {
if (windowStart == null && windowEnd == null) {
return indexes;
}
@@ -363,19 +369,19 @@ public static String[] convertToDataIndexes(@NotNull String[] indexes, Instant w
case 2:
default:
// YYYY-ww
- formatter = DATA_INDEX_FORMATTER_WEEK;
+ formatter = dataIndexFormatterWeek;
indexUnit = ChronoUnit.DAYS;
indexWidth = 7;
break;
case 3:
// YYYY-ww-ee
- formatter = DATA_INDEX_FORMATTER_DAY;
+ formatter = dataIndexFormatterDay;
indexUnit = ChronoUnit.DAYS;
indexWidth = 1;
break;
case 4:
// YYYY-ww-ee-HH
- formatter = DATA_INDEX_FORMATTER_HOUR;
+ formatter = dataIndexFormatterHour;
indexUnit = ChronoUnit.HOURS;
indexWidth = 1;
break;
@@ -405,15 +411,15 @@ public static String[] convertToDataIndexes(@NotNull String[] indexes, Instant w
return result.toArray(new String[0]);
}
- private static boolean isIndexFullyAfterInstant(@NotNull Instant indexStart, @NotNull Instant indexEnd, @NotNull Instant checkpoint) {
+ private boolean isIndexFullyAfterInstant(@NotNull Instant indexStart, @NotNull Instant indexEnd, @NotNull Instant checkpoint) {
return !indexStart.isBefore(checkpoint) && !indexEnd.isBefore(checkpoint);
}
- private static boolean isIndexFullyBeforeInstant(@NotNull Instant indexStart, @NotNull Instant indexEnd, @NotNull Instant checkpoint) {
+ private boolean isIndexFullyBeforeInstant(@NotNull Instant indexStart, @NotNull Instant indexEnd, @NotNull Instant checkpoint) {
return !indexStart.isAfter(checkpoint) && !indexEnd.isAfter(checkpoint);
}
- private static String stripPrefixAndAccount(@NotNull String index) {
+ private String stripPrefixAndAccount(@NotNull String index) {
return StringUtils.substringAfter(index, "-data-message-");
}
@@ -425,8 +431,8 @@ private static String stripPrefixAndAccount(@NotNull String index) {
* @param type
* @return
*/
- public static String getMetricValueQualifier(String name, String type) {
- String shortType = DatastoreUtils.getClientMetricFromAcronym(type);
+ public String getMetricValueQualifier(String name, String type) {
+ String shortType = getClientMetricFromAcronym(type);
return String.format("%s.%s", name, shortType);
}
@@ -437,7 +443,7 @@ public static String getMetricValueQualifier(String name, String type) {
* @return The client metric type
* @since 1.0.0
*/
- public static String getClientMetricFromType(Class> clazz) {
+ public String getClientMetricFromType(Class> clazz) {
if (clazz == null) {
throw new NullPointerException("Metric value must not be null");
}
@@ -471,7 +477,7 @@ public static String getClientMetricFromType(Class> clazz) {
* @return The client metric type acronym
* @since 1.0.0
*/
- public static String getClientMetricFromAcronym(String acronym) {
+ public String getClientMetricFromAcronym(String acronym) {
if (CLIENT_METRIC_TYPE_STRING.equals(acronym)) {
return CLIENT_METRIC_TYPE_STRING_ACRONYM;
}
@@ -505,7 +511,7 @@ public static String getClientMetricFromAcronym(String acronym) {
* @param acronym
* @return
*/
- public static boolean isDateMetric(String acronym) {
+ public boolean isDateMetric(String acronym) {
return CLIENT_METRIC_TYPE_DATE_ACRONYM.equals(acronym);
}
@@ -516,7 +522,7 @@ public static boolean isDateMetric(String acronym) {
* @return The metric value type converted to string
* @since 1.0.0
*/
- public static String convertToClientMetricType(Class aClass) {
+ public String convertToClientMetricType(Class aClass) {
if (aClass == String.class) {
return CLIENT_METRIC_TYPE_STRING;
}
@@ -551,7 +557,7 @@ public static String convertToClientMetricType(Class aClass) {
* @return The concrete metric value type
* @since 1.0.0
*/
- public static Class> convertToKapuaType(String clientType) {
+ public Class> convertToKapuaType(String clientType) {
Class> clazz;
if (CLIENT_METRIC_TYPE_STRING.equals(clientType)) {
clazz = String.class;
@@ -583,7 +589,7 @@ public static Class> convertToKapuaType(String clientType) {
* @return The concrete metric value type
* @since 1.0.0
*/
- public static Object convertToCorrectType(String acronymType, Object value) {
+ public Object convertToCorrectType(String acronymType, Object value) {
Object convertedValue = null;
if (CLIENT_METRIC_TYPE_DOUBLE_ACRONYM.equals(acronymType)) {
if (value instanceof Number) {
@@ -638,7 +644,7 @@ public static Object convertToCorrectType(String acronymType, Object value) {
return convertedValue;
}
- private static String getValueClass(Object value) {
+ private String getValueClass(Object value) {
return value != null ? value.getClass().toString() : "null";
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageStoreMediator.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageStoreMediator.java
deleted file mode 100644
index 75aac26e242..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageStoreMediator.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.mediator;
-
-import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.model.DatastoreMessage;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-
-import java.util.Map;
-
-/**
- * Message mediator definition
- */
-public interface MessageStoreMediator {
-
- /**
- * Get the message metadata
- *
- * @param scopeId
- * @param indexedOn
- * @return
- * @throws ClientException
- */
- Metadata getMetadata(KapuaId scopeId, long indexedOn) throws ClientException, MappingException;
-
- /**
- * On after message mappings event handler
- *
- * @param scopeId
- * @param indexedOn
- * @param metrics
- * @throws ClientException
- */
- void onUpdatedMappings(KapuaId scopeId, long indexedOn, Map metrics) throws ClientException, MappingException;
-
- /**
- * On after message store event handler
- *
- * @param messageInfo
- * @param message
- * @throws ClientException
- */
- void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage message)
- throws KapuaIllegalArgumentException, ConfigurationException, MappingException, ClientException;
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java
index ecd97346e53..64d32ad493d 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.mediator;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema;
import org.eclipse.kapua.service.datastore.model.MetricInfo;
@@ -107,9 +108,11 @@ public String field() {
*/
private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String metricName, Class> metricType) {
if (id == null) {
- String metricMappedName = DatastoreUtils.getMetricValueQualifier(metricName, DatastoreUtils.convertToClientMetricType(metricType));
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
+ final DatastoreUtils datastoreUtils = KapuaLocator.getInstance().getComponent(DatastoreUtils.class);
+ String metricMappedName = datastoreUtils.getMetricValueQualifier(metricName, datastoreUtils.convertToClientMetricType(metricType));
- return DatastoreUtils.getHashCode(scopeId.toCompactId(), clientId, channel, metricMappedName);
+ return datastoreUtils.getHashCode(scopeId.toCompactId(), clientId, channel, metricMappedName);
} else {
return id.toString();
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoRegistryMediator.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoRegistryMediator.java
deleted file mode 100644
index fcb0ddf70fc..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoRegistryMediator.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.mediator;
-
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.schema.Metadata;
-import org.eclipse.kapua.service.datastore.model.MetricInfo;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-
-/**
- * Metric information registry mediator definition
- *
- * @since 1.0
- */
-public interface MetricInfoRegistryMediator {
-
- /**
- * Get the metric info metadata
- *
- * @param scopeId
- * @param indexedOn
- * @return
- * @throws ClientException
- */
- Metadata getMetadata(KapuaId scopeId, long indexedOn)
- throws ClientException, MappingException;
-
- /**
- * On after metric info delete event handler
- *
- * @param scopeId
- * @param metricInfo
- * @throws ClientException
- */
- void onAfterMetricInfoDelete(KapuaId scopeId, MetricInfo metricInfo) throws ClientException;
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/DatastorePredicateFactoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/DatastorePredicateFactoryImpl.java
index 9d931110bd9..7fbb1aef7be 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/DatastorePredicateFactoryImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/DatastorePredicateFactoryImpl.java
@@ -12,12 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.model.query.predicate;
+import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate;
import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory;
import org.eclipse.kapua.service.datastore.model.query.predicate.MetricExistsPredicate;
import org.eclipse.kapua.service.datastore.model.query.predicate.MetricPredicate;
import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactoryImpl;
+import javax.inject.Inject;
import javax.inject.Singleton;
/**
@@ -28,6 +30,13 @@
@Singleton
public class DatastorePredicateFactoryImpl extends StorablePredicateFactoryImpl implements DatastorePredicateFactory {
+ private final DatastoreUtils datastoreUtils;
+
+ @Inject
+ public DatastorePredicateFactoryImpl(DatastoreUtils datastoreUtils) {
+ this.datastoreUtils = datastoreUtils;
+ }
+
@Override
public ChannelMatchPredicate newChannelMatchPredicate(String expression) {
return new ChannelMatchPredicateImpl(expression);
@@ -35,11 +44,11 @@ public ChannelMatchPredicate newChannelMatchPredicate(String expression) {
@Override
public > MetricPredicate newMetricPredicate(String field, Class type, V minValue, V maxValue) {
- return new MetricPredicateImpl(field, type, minValue, maxValue);
+ return new MetricPredicateImpl(field, type, minValue, maxValue, datastoreUtils);
}
@Override
public > MetricExistsPredicate newMetricExistsPredicate(String metricName, Class type) {
- return new MetricExistsPredicateImpl(metricName, type);
+ return new MetricExistsPredicateImpl(metricName, type, datastoreUtils);
}
}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java
index cb7506d91a3..494688afb7f 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java
@@ -29,10 +29,12 @@
*/
public class MetricExistsPredicateImpl extends ExistsPredicateImpl implements MetricExistsPredicate {
+ private final DatastoreUtils datastoreUtils;
private Class> type;
- public > MetricExistsPredicateImpl(String fieldName, Class type) {
+ public > MetricExistsPredicateImpl(String fieldName, Class type, DatastoreUtils datastoreUtils) {
super(fieldName);
+ this.datastoreUtils = datastoreUtils;
setType(type);
}
@@ -67,11 +69,11 @@ public ObjectNode toSerializedMap() throws MappingException {
fieldNameSb.append(MessageField.METRICS.field())
.append(".")
- .append(DatastoreUtils.normalizeMetricName(getName()));
+ .append(datastoreUtils.normalizeMetricName(getName()));
if (getType() != null) {
fieldNameSb.append(".")
- .append(DatastoreUtils.getClientMetricFromAcronym(type.getSimpleName().toLowerCase()));
+ .append(datastoreUtils.getClientMetricFromAcronym(type.getSimpleName().toLowerCase()));
}
ObjectNode termNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(PredicateConstants.FIELD_KEY, fieldNameSb.toString())});
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java
index 505ec1b2b1f..2583029fa81 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java
@@ -28,11 +28,13 @@
*/
public class MetricPredicateImpl extends RangePredicateImpl implements MetricPredicate {
+ private final DatastoreUtils datastoreUtils;
private String name;
private Class> type;
- public > MetricPredicateImpl(String metricName, Class type, V minValue, V maxValue) {
+ public > MetricPredicateImpl(String metricName, Class type, V minValue, V maxValue, DatastoreUtils datastoreUtils) {
super(MessageField.METRICS, minValue, maxValue);
+ this.datastoreUtils = datastoreUtils;
setName(metricName);
setType(type);
@@ -86,9 +88,9 @@ public ObjectNode toSerializedMap() throws MappingException {
termNode.set(
getField().field()
.concat(".")
- .concat(DatastoreUtils.normalizeMetricName(getName()))
+ .concat(datastoreUtils.normalizeMetricName(getName()))
.concat(".")
- .concat(DatastoreUtils.getClientMetricFromAcronym(getType().getSimpleName().toLowerCase())),
+ .concat(datastoreUtils.getClientMetricFromAcronym(getType().getSimpleName().toLowerCase())),
valuesNode);
ObjectNode rootNode = MappingUtils.newObjectNode();
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java
index daa3491bc04..c046ee7cd5a 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.schema;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.datastore.model.ChannelInfo;
import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
@@ -19,9 +21,6 @@
import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
/**
* {@link ChannelInfo} schema definition.
*
@@ -75,33 +74,32 @@ private ChannelInfoSchema() {
/**
* Create and return the Json representation of the channel info schema
*
- * @param sourceEnable
* @return
* @throws MappingException
* @since 1.0.0
*/
- public static JsonNode getChannelTypeSchema(boolean sourceEnable) throws MappingException {
+ public static JsonNode getChannelTypeSchema() throws MappingException {
ObjectNode channelNode = MappingUtils.newObjectNode();
{
- ObjectNode sourceChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_ENABLED, sourceEnable) });
+ ObjectNode sourceChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)});
channelNode.set(SchemaKeys.KEY_SOURCE, sourceChannel);
ObjectNode propertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode channelScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode channelScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CHANNEL_SCOPE_ID, channelScopeId);
- ObjectNode channelClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode channelClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CHANNEL_CLIENT_ID, channelClientId);
- ObjectNode channelName = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode channelName = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CHANNEL_NAME, channelName);
- ObjectNode channelTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode channelTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(CHANNEL_TIMESTAMP, channelTimestamp);
- ObjectNode channelMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode channelMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CHANNEL_MESSAGE_ID, channelMessageId);
}
channelNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode);
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java
index 57509eb313d..90cbb8427f0 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.schema;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.datastore.model.ClientInfo;
import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
@@ -19,9 +21,6 @@
import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
/**
* {@link ClientInfo} schema definition.
*
@@ -73,30 +72,29 @@ private ClientInfoSchema() {
/**
* Create and return the Json representation of the client info schema
*
- * @param sourceEnable
* @return
* @throws MappingException
* @since 1.0.0
*/
- public static JsonNode getClientTypeSchema(boolean sourceEnable) throws MappingException {
+ public static JsonNode getClientTypeSchema() throws MappingException {
ObjectNode clientNode = MappingUtils.newObjectNode();
{
- ObjectNode sourceClient = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_ENABLED, sourceEnable) });
+ ObjectNode sourceClient = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)});
clientNode.set(SchemaKeys.KEY_SOURCE, sourceClient);
ObjectNode propertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode clientId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode clientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CLIENT_ID, clientId);
- ObjectNode clientTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode clientTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(CLIENT_TIMESTAMP, clientTimestamp);
- ObjectNode clientScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode clientScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CLIENT_SCOPE_ID, clientScopeId);
- ObjectNode clientMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode clientMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(CLIENT_MESSAGE_ID, clientMessageId);
}
clientNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode);
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java
index 19ac0c1d8ba..251922a4e34 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.schema;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.kapua.message.Message;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
@@ -19,9 +21,6 @@
import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
/**
* {@link Message} schema definition.
*
@@ -270,77 +269,76 @@ private MessageSchema() {
/**
* Create and return the Json representation of the message schema
*
- * @param sourceEnable
* @return
* @throws MappingException
* @since 1.0.0
*/
- public static JsonNode getMesageTypeSchema(boolean sourceEnable) throws MappingException {
+ public static JsonNode getMessageTypeSchema() throws MappingException {
ObjectNode messageNode = MappingUtils.newObjectNode();
{
- ObjectNode sourceMessage = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_ENABLED, sourceEnable) });
+ ObjectNode sourceMessage = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)});
messageNode.set(SchemaKeys.KEY_SOURCE, sourceMessage);
ObjectNode propertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode messageId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode messageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(MESSAGE_ID, messageId);
- ObjectNode messageTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode messageTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(MESSAGE_TIMESTAMP, messageTimestamp);
- ObjectNode messageReceivedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode messageReceivedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(MESSAGE_RECEIVED_ON, messageReceivedOn);
- ObjectNode messageIp = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_IP) });
+ ObjectNode messageIp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_IP)});
propertiesNode.set(MESSAGE_IP_ADDRESS, messageIp);
- ObjectNode messageScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode messageScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(MESSAGE_SCOPE_ID, messageScopeId);
- ObjectNode messageDeviceId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode messageDeviceId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(MESSAGE_DEVICE_ID, messageDeviceId);
- ObjectNode messageClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode messageClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(MESSAGE_CLIENT_ID, messageClientId);
- ObjectNode messageChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode messageChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(MESSAGE_CHANNEL, messageChannel);
- ObjectNode messageCapturedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode messageCapturedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(MESSAGE_CAPTURED_ON, messageCapturedOn);
- ObjectNode messageSentOn = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode messageSentOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
propertiesNode.set(MESSAGE_SENT_ON, messageSentOn);
ObjectNode positionNode = MappingUtils.newObjectNode(
- new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
- new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false) });
+ new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
+ new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false)});
ObjectNode positionPropertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode messagePositionPropLocation = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_GEO_POINT) });
+ ObjectNode messagePositionPropLocation = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_GEO_POINT)});
positionPropertiesNode.set(MESSAGE_POS_LOCATION, messagePositionPropLocation);
- ObjectNode messagePositionPropAlt = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) });
+ ObjectNode messagePositionPropAlt = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)});
positionPropertiesNode.set(MESSAGE_POS_ALT, messagePositionPropAlt);
- ObjectNode messagePositionPropPrec = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) });
+ ObjectNode messagePositionPropPrec = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)});
positionPropertiesNode.set(MESSAGE_POS_PRECISION, messagePositionPropPrec);
- ObjectNode messagePositionPropHead = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) });
+ ObjectNode messagePositionPropHead = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)});
positionPropertiesNode.set(MESSAGE_POS_HEADING, messagePositionPropHead);
- ObjectNode messagePositionPropSpeed = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) });
+ ObjectNode messagePositionPropSpeed = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)});
positionPropertiesNode.set(MESSAGE_POS_SPEED, messagePositionPropSpeed);
- ObjectNode messagePositionPropTime = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode messagePositionPropTime = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
positionPropertiesNode.set(MESSAGE_POS_TIMESTAMP, messagePositionPropTime);
- ObjectNode messagePositionPropSat = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER) });
+ ObjectNode messagePositionPropSat = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER)});
positionPropertiesNode.set(MESSAGE_POS_SATELLITES, messagePositionPropSat);
- ObjectNode messagePositionPropStat = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER) });
+ ObjectNode messagePositionPropStat = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER)});
positionPropertiesNode.set(MESSAGE_POS_STATUS, messagePositionPropStat);
}
positionNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, positionPropertiesNode);
@@ -350,11 +348,11 @@ public static JsonNode getMesageTypeSchema(boolean sourceEnable) throws MappingE
messageNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode);
ObjectNode messageMetrics = MappingUtils.newObjectNode(
- new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
- new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, true) });
+ new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
+ new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, true)});
propertiesNode.set(MESSAGE_METRICS, messageMetrics);
- ObjectNode messageBody = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_BINARY), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_FALSE) });
+ ObjectNode messageBody = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_BINARY), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_FALSE)});
propertiesNode.set(MESSAGE_BODY, messageBody);
}
return messageNode;
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Metadata.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Metadata.java
deleted file mode 100644
index 66ebcf3b370..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Metadata.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.schema;
-
-import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Metadata object
- *
- * @since 1.0.0
- */
-public class Metadata {
-
- // Info fields does not change within the same account name
- private final String dataIndexName;
- private final String channelRegistryIndexName;
- private final String clientRegistryIndexName;
- private final String metricRegistryIndexName;
-
- // Custom mappings can only increase within the same account
- // No removal of existing cached mappings or changes in the
- // existing mappings.
- private final Map messageMappingsCache;
-
- /**
- * Get the mappings cache
- *
- * @return
- * @since 1.0.0
- */
- public Map getMessageMappingsCache() {
- return messageMappingsCache;
- }
-
- /**
- * Constructor.
- *
- * @since 1.0.0
- */
- public Metadata(String dataIndexName, String channelRegistryIndexName, String clientRegistryIndexName, String metricRegistryIndexName) {
- this.messageMappingsCache = new HashMap<>(100);
- this.dataIndexName = dataIndexName;
- this.channelRegistryIndexName = channelRegistryIndexName;
- this.clientRegistryIndexName = clientRegistryIndexName;
- this.metricRegistryIndexName = metricRegistryIndexName;
- }
-
- /**
- * Get the Elasticsearch data index name
- *
- * @return
- * @since 1.0.0
- */
- public String getDataIndexName() {
- return dataIndexName;
- }
-
- /**
- * Get the Kapua channel index name
- *
- * @return
- * @since 1.4.0
- */
- public String getChannelRegistryIndexName() {
- return channelRegistryIndexName;
- }
-
- /**
- * Get the Kapua client index name
- *
- * @return
- * @since 1.4.0
- */
- public String getClientRegistryIndexName() {
- return clientRegistryIndexName;
- }
-
- /**
- * Get the Kapua metric index name
- *
- * @return
- * @since 1.4.0
- */
- public String getMetricRegistryIndexName() {
- return metricRegistryIndexName;
- }
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java
index 626b190e100..cc0933583e1 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.schema;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
import org.eclipse.kapua.service.datastore.model.MetricInfo;
import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
@@ -19,9 +21,6 @@
import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
/**
* {@link MetricInfo} schema definition.
*
@@ -143,47 +142,46 @@ private MetricInfoSchema() {
/**
* Create and return the Json representation of the metric info schema
*
- * @param sourceEnable
* @return
* @throws MappingException
* @since 1.0.0
*/
- public static JsonNode getMetricTypeSchema(boolean sourceEnable) throws MappingException {
+ public static JsonNode getMetricTypeSchema() throws MappingException {
ObjectNode metricNode = MappingUtils.newObjectNode();
- ObjectNode sourceMetric = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_ENABLED, sourceEnable) });
+ ObjectNode sourceMetric = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)});
metricNode.set(SchemaKeys.KEY_SOURCE, sourceMetric);
ObjectNode propertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode metricAccount = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricAccount = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(METRIC_SCOPE_ID, metricAccount);
- ObjectNode metricClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(METRIC_CLIENT_ID, metricClientId);
- ObjectNode metricChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
propertiesNode.set(METRIC_CHANNEL, metricChannel);
ObjectNode metricMtrNode = MappingUtils.newObjectNode(
- new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
- new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false) });
+ new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true),
+ new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false)});
ObjectNode metricMtrPropertiesNode = MappingUtils.newObjectNode();
{
- ObjectNode metricMtrNameNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricMtrNameNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
metricMtrPropertiesNode.set(METRIC_MTR_NAME, metricMtrNameNode);
- ObjectNode metricMtrTypeNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricMtrTypeNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
metricMtrPropertiesNode.set(METRIC_MTR_TYPE, metricMtrTypeNode);
- ObjectNode metricMtrValueNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricMtrValueNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
metricMtrPropertiesNode.set(METRIC_MTR_VALUE, metricMtrValueNode);
- ObjectNode metricMtrTimestampNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) });
+ ObjectNode metricMtrTimestampNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
metricMtrPropertiesNode.set(METRIC_MTR_TIMESTAMP, metricMtrTimestampNode);
- ObjectNode metricMtrMsgIdNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) });
+ ObjectNode metricMtrMsgIdNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
metricMtrPropertiesNode.set(METRIC_MTR_MSG_ID, metricMtrMsgIdNode);
}
metricMtrNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricMtrPropertiesNode);
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Schema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Schema.java
deleted file mode 100644
index 697ba3ffc62..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/Schema.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.schema;
-
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.DatastoreCacheManager;
-import org.eclipse.kapua.service.datastore.internal.client.DatastoreClientFactory;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
-import org.eclipse.kapua.service.datastore.internal.mediator.Metric;
-import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
-import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey;
-import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClient;
-import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientErrorCodes;
-import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException;
-import org.eclipse.kapua.service.elasticsearch.client.exception.DatamodelMappingException;
-import org.eclipse.kapua.service.elasticsearch.client.model.IndexRequest;
-import org.eclipse.kapua.service.elasticsearch.client.model.IndexResponse;
-import org.eclipse.kapua.service.elasticsearch.client.model.TypeDescriptor;
-import org.eclipse.kapua.service.storable.exception.MappingException;
-import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry;
-import org.eclipse.kapua.service.storable.model.utils.MappingUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * Datastore schema creation/update
- *
- * @since 1.0.0
- */
-public class Schema {
-
- private static final Logger LOG = LoggerFactory.getLogger(Schema.class);
-
- /**
- * Synchronize metadata
- *
- * @param scopeId
- * @param time
- * @return
- * @throws ClientException
- * @since 1.0.0
- */
- public Metadata synch(KapuaId scopeId, long time) throws ClientException, MappingException {
- String dataIndexName;
- try {
- String indexingWindowOption = DatastoreSettings.getInstance().getString(DatastoreSettingsKey.INDEXING_WINDOW_OPTION, DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK);
- dataIndexName = DatastoreUtils.getDataIndexName(scopeId, time, indexingWindowOption);
- } catch (KapuaException kaex) {
- throw new ClientException(ClientErrorCodes.INTERNAL_ERROR, kaex, "Error while generating index name");
- }
-
- Metadata currentMetadata = DatastoreCacheManager.getInstance().getMetadataCache().get(dataIndexName);
- if (currentMetadata != null) {
- return currentMetadata;
- }
-
- LOG.debug("Before entering updating metadata");
- synchronized (Schema.class) {
- LOG.debug("Entered updating metadata");
- ElasticsearchClient> elasticsearchClient = DatastoreClientFactory.getInstance().getElasticsearchClient();
- // Check existence of the data index
- IndexResponse dataIndexExistsResponse = elasticsearchClient.isIndexExists(new IndexRequest(dataIndexName));
- if (!dataIndexExistsResponse.isIndexExists()) {
- elasticsearchClient.createIndex(dataIndexName, getMappingSchema(dataIndexName));
- LOG.info("Data index created: {}", dataIndexName);
- }
-
- boolean enableSourceField = true;
-
- elasticsearchClient.putMapping(new TypeDescriptor(dataIndexName, MessageSchema.MESSAGE_TYPE_NAME), MessageSchema.getMesageTypeSchema(enableSourceField));
-
- // Check existence of the kapua internal indexes
- String channelRegistryIndexName = DatastoreUtils.getChannelIndexName(scopeId);
- IndexResponse channelRegistryIndexExistsResponse = elasticsearchClient.isIndexExists(new IndexRequest(channelRegistryIndexName));
- if (!channelRegistryIndexExistsResponse.isIndexExists()) {
- elasticsearchClient.createIndex(channelRegistryIndexName, getMappingSchema(channelRegistryIndexName));
- LOG.info("Channel Metadata index created: {}", channelRegistryIndexExistsResponse);
-
- elasticsearchClient.putMapping(new TypeDescriptor(channelRegistryIndexName, ChannelInfoSchema.CHANNEL_TYPE_NAME), ChannelInfoSchema.getChannelTypeSchema(enableSourceField));
- }
-
- String clientRegistryIndexName = DatastoreUtils.getClientIndexName(scopeId);
- IndexResponse clientRegistryIndexExistsResponse = elasticsearchClient.isIndexExists(new IndexRequest(clientRegistryIndexName));
- if (!clientRegistryIndexExistsResponse.isIndexExists()) {
- elasticsearchClient.createIndex(clientRegistryIndexName, getMappingSchema(clientRegistryIndexName));
- LOG.info("Client Metadata index created: {}", clientRegistryIndexExistsResponse);
-
- elasticsearchClient.putMapping(new TypeDescriptor(clientRegistryIndexName, ClientInfoSchema.CLIENT_TYPE_NAME), ClientInfoSchema.getClientTypeSchema(enableSourceField));
- }
-
- String metricRegistryIndexName = DatastoreUtils.getMetricIndexName(scopeId);
- IndexResponse metricRegistryIndexExistsResponse = elasticsearchClient.isIndexExists(new IndexRequest(metricRegistryIndexName));
- if (!metricRegistryIndexExistsResponse.isIndexExists()) {
- elasticsearchClient.createIndex(metricRegistryIndexName, getMappingSchema(metricRegistryIndexName));
- LOG.info("Metric Metadata index created: {}", metricRegistryIndexExistsResponse);
-
- elasticsearchClient.putMapping(new TypeDescriptor(metricRegistryIndexName, MetricInfoSchema.METRIC_TYPE_NAME), MetricInfoSchema.getMetricTypeSchema(enableSourceField));
- }
-
- currentMetadata = new Metadata(dataIndexName, channelRegistryIndexName, clientRegistryIndexName, metricRegistryIndexName);
- LOG.debug("Leaving updating metadata");
- }
-
- // Current metadata can only increase the custom mappings
- // other fields does not change within the same account id
- // and custom mappings are not and must not be exposed to
- // outside this class to preserve thread safetyness
- DatastoreCacheManager.getInstance().getMetadataCache().put(dataIndexName, currentMetadata);
-
- return currentMetadata;
- }
-
- /**
- * Update metric mappings
- *
- * @param scopeId
- * @param time
- * @param metrics
- * @throws ClientException
- * @since 1.0.0
- */
- public void updateMessageMappings(KapuaId scopeId, long time, Map metrics)
- throws ClientException, MappingException {
- if (metrics == null || metrics.size() == 0) {
- return;
- }
- String newIndex;
- try {
- String indexingWindowOption = DatastoreSettings.getInstance().getString(DatastoreSettingsKey.INDEXING_WINDOW_OPTION, DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK);
- newIndex = DatastoreUtils.getDataIndexName(scopeId, time, indexingWindowOption);
- } catch (KapuaException kaex) {
- throw new ClientException(ClientErrorCodes.INTERNAL_ERROR, kaex, "Error while generating index name");
- }
- Metadata currentMetadata = DatastoreCacheManager.getInstance().getMetadataCache().get(newIndex);
-
- ObjectNode metricsMapping = null;
- Map diffs = null;
-
- synchronized (Schema.class) {
- // Update mappings only if a metric is new (not in cache)
- diffs = getMessageMappingDiffs(currentMetadata, metrics);
- if (diffs == null || diffs.isEmpty()) {
- return;
- }
- metricsMapping = getNewMessageMappingsBuilder(diffs);
- }
-
- LOG.trace("Sending dynamic message mappings: {}", metricsMapping);
- DatastoreClientFactory.getInstance().getElasticsearchClient().putMapping(new TypeDescriptor(currentMetadata.getDataIndexName(), MessageSchema.MESSAGE_TYPE_NAME), metricsMapping);
- }
-
- /**
- * @param esMetrics
- * @return
- * @throws DatamodelMappingException
- * @throws KapuaException
- * @since 1.0.0
- */
- private ObjectNode getNewMessageMappingsBuilder(Map esMetrics) throws MappingException {
- if (esMetrics == null) {
- return null;
- }
- // metrics mapping container (to be added to message mapping)
- ObjectNode typeNode = MappingUtils.newObjectNode(); // root
- ObjectNode typePropertiesNode = MappingUtils.newObjectNode(); // properties
- ObjectNode metricsNode = MappingUtils.newObjectNode(); // metrics
- ObjectNode metricsPropertiesNode = MappingUtils.newObjectNode(); // properties (metric properties)
- typeNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, typePropertiesNode);
- typePropertiesNode.set(SchemaKeys.FIELD_NAME_METRICS, metricsNode);
- metricsNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricsPropertiesNode);
-
- // metrics mapping
- ObjectNode metricMapping;
- for (Entry esMetric : esMetrics.entrySet()) {
- Metric metric = esMetric.getValue();
- metricMapping = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, SchemaKeys.VALUE_TRUE)});
-
- ObjectNode metricMappingPropertiesNode = MappingUtils.newObjectNode(); // properties (inside metric name)
- ObjectNode valueMappingNode;
-
- switch (metric.getType()) {
- case SchemaKeys.TYPE_STRING:
- valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)});
- break;
- case SchemaKeys.TYPE_DATE:
- valueMappingNode = MappingUtils.newObjectNode(
- new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)});
- break;
- default:
- valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, metric.getType())});
- break;
- }
-
- metricMappingPropertiesNode.set(DatastoreUtils.getClientMetricFromAcronym(metric.getType()), valueMappingNode);
- metricMapping.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricMappingPropertiesNode);
- metricsPropertiesNode.set(metric.getName(), metricMapping);
- }
- return typeNode;
- }
-
- /**
- * @param currentMetadata
- * @param esMetrics
- * @return
- * @since 1.0.0
- */
- private Map getMessageMappingDiffs(Metadata currentMetadata, Map esMetrics) {
- if (esMetrics == null || esMetrics.isEmpty()) {
- return null;
- }
-
- Map diffs = null;
- for (Entry esMetric : esMetrics.entrySet()) {
- if (!currentMetadata.getMessageMappingsCache().containsKey(esMetric.getKey())) {
- if (diffs == null) {
- diffs = new HashMap<>(100);
- }
- currentMetadata.getMessageMappingsCache().put(esMetric.getKey(), esMetric.getValue());
- diffs.put(esMetric.getKey(), esMetric.getValue());
- }
- }
-
- return diffs;
- }
-
- /**
- * @param idxName
- * @return
- * @throws MappingException
- * @since 1.0.0
- */
- private ObjectNode getMappingSchema(String idxName) throws MappingException {
- String idxRefreshInterval = String.format("%ss", DatastoreSettings.getInstance().getLong(DatastoreSettingsKey.INDEX_REFRESH_INTERVAL));
- Integer idxShardNumber = DatastoreSettings.getInstance().getInt(DatastoreSettingsKey.INDEX_SHARD_NUMBER, 1);
- Integer idxReplicaNumber = DatastoreSettings.getInstance().getInt(DatastoreSettingsKey.INDEX_REPLICA_NUMBER, 0);
-
- ObjectNode rootNode = MappingUtils.newObjectNode();
- ObjectNode settingsNode = MappingUtils.newObjectNode();
- ObjectNode refreshIntervalNode = MappingUtils.newObjectNode(new KeyValueEntry[]{
- new KeyValueEntry(SchemaKeys.KEY_REFRESH_INTERVAL, idxRefreshInterval),
- new KeyValueEntry(SchemaKeys.KEY_SHARD_NUMBER, idxShardNumber),
- new KeyValueEntry(SchemaKeys.KEY_REPLICA_NUMBER, idxReplicaNumber)});
- settingsNode.set(SchemaKeys.KEY_INDEX, refreshIntervalNode);
- rootNode.set(SchemaKeys.KEY_SETTINGS, settingsNode);
- LOG.info("Creating index for '{}' - refresh: '{}' - shards: '{}' replicas: '{}': ", idxName, idxRefreshInterval, idxShardNumber, idxReplicaNumber);
- return rootNode;
- }
-
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/SchemaUtil.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/SchemaUtil.java
deleted file mode 100644
index a8730b34bf0..00000000000
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/SchemaUtil.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.datastore.internal.schema;
-
-import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Schema utility class
- *
- * @since 1.0.0
- */
-public class SchemaUtil {
-
-
- /**
- * @since 1.0.0
- */
- private SchemaUtil() {
- }
-
- /**
- * Return a map of map. The contained map has, as entries, the couples subKeys-values.
- * NOTE! No arrays subKeys-values coherence will be done (length or null check)!
- *
- * @param key
- * @param subKeys
- * @param values
- * @return
- * @since 1.0.0
- */
- public static Map getMapOfMap(String key, String[] subKeys, String[] values) {
- Map mapChildren = new HashMap<>();
- for (int i = 0; i < subKeys.length; i++) {
- mapChildren.put(subKeys[i], values[i]);
- }
- Map map = new HashMap<>();
- map.put(key, mapChildren);
- return map;
- }
-
- /**
- * Get the Elasticsearch data index name
- *
- * @param scopeId
- * @return
- * @since 1.0.0
- */
- public static String getDataIndexName(KapuaId scopeId) {
- return DatastoreUtils.getDataIndexName(scopeId);
- }
-
- /**
- * Get the Kapua data index name
- *
- * @param scopeId
- * @return
- * @since 1.0.0
- */
- public static String getChannelIndexName(KapuaId scopeId) {
- return DatastoreUtils.getChannelIndexName(scopeId);
- }
-
- /**
- * Get the Kapua data index name
- *
- * @param scopeId
- * @return
- */
- public static String getClientIndexName(KapuaId scopeId) {
- return DatastoreUtils.getClientIndexName(scopeId);
- }
-
- /**
- * Get the Kapua data index name
- *
- * @param scopeId
- * @return
- */
- public static String getMetricIndexName(KapuaId scopeId) {
- return DatastoreUtils.getMetricIndexName(scopeId);
- }
-
-}
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettings.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettings.java
index 54471d370c1..99feee507e0 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettings.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettings.java
@@ -19,6 +19,7 @@
*
* @since 1.3.0
*/
+//TODO: FIXME: singletons should not be handled manually, we have DI for that
public class DatastoreElasticsearchClientSettings extends AbstractKapuaSetting {
/**
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettingsKey.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettingsKey.java
index a332e8ad958..0a6e511984f 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettingsKey.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreElasticsearchClientSettingsKey.java
@@ -21,12 +21,6 @@
*/
public enum DatastoreElasticsearchClientSettingsKey implements SettingKey {
- /**
- * {@link org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider} implementation class.
- *
- * @since 1.3.0
- */
- PROVIDER("datastore.elasticsearch.provider"),
/**
* The name of the module which is managing the {@link org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClient}.
*
diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreSettings.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreSettings.java
index bd8a5094e06..d61fb49f627 100644
--- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreSettings.java
+++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/setting/DatastoreSettings.java
@@ -14,6 +14,8 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Datastore {@link AbstractKapuaSetting}.
*
@@ -28,29 +30,14 @@ public class DatastoreSettings extends AbstractKapuaSetting entry) {
private StorableIdFactory storableIdFactory;
private ChannelInfoRegistryService channelInfoRegistryService;
- private ChannelInfoRegistryServiceProxy channelInfoRegistryServiceProxy;
-
private MetricInfoRegistryService metricInfoRegistryService;
- private MetricInfoRegistryServiceProxy metricInfoRegistryServiceProxy;
-
private ClientInfoRegistryService clientInfoRegistryService;
- private ClientInfoRegistryServiceProxy clientInfoRegistryServiceProxy;
private MessageStoreService messageStoreService;
private KapuaMessageFactory messageFactory;
private KapuaDataMessageFactory dataMessageFactory;
+ private MessageStoreFacade messageStoreFacade;
private SimulatedDevice currentDevice;
private Session session;
@@ -302,20 +296,18 @@ public void setServices() throws Exception {
messageFactory = locator.getFactory(KapuaMessageFactory.class);
storableIdFactory = locator.getFactory(StorableIdFactory.class);
channelInfoRegistryService = locator.getService(ChannelInfoRegistryService.class);
- elasticsearchClient = DatastoreClientFactory.getInstance().getElasticsearchClient();
+ elasticsearchClient = locator.getComponent(ElasticsearchClientProvider.class).getElasticsearchClient();
channelInfoFactory = locator.getFactory(ChannelInfoFactory.class);
clientInfoFactory = locator.getFactory(ClientInfoFactory.class);
messageStoreFactory = locator.getFactory(MessageStoreFactory.class);
metricInfoFactory = locator.getFactory(MetricInfoFactory.class);
datastorePredicateFactory = locator.getFactory(DatastorePredicateFactory.class);
- channelInfoRegistryServiceProxy = new ChannelInfoRegistryServiceProxy();
metricInfoRegistryService = locator.getService(MetricInfoRegistryService.class);
- metricInfoRegistryServiceProxy = new MetricInfoRegistryServiceProxy();
clientInfoRegistryService = locator.getService(ClientInfoRegistryService.class);
- clientInfoRegistryServiceProxy = new ClientInfoRegistryServiceProxy();
messageFactory = locator.getFactory(KapuaMessageFactory.class);
dataMessageFactory = locator.getFactory(KapuaDataMessageFactory.class);
-
+ messageStoreFacade = locator.getComponent(MessageStoreFacade.class);
+ datastoreCacheManager = locator.getComponent(DatastoreCacheManager.class);
}
// *************************************
@@ -340,26 +332,29 @@ public void afterScenario() {
@Given("I delete indexes {string}")
public void deleteIndexes(String indexExp) throws Exception {
- DatastoreMediator.getInstance().deleteIndexes(indexExp);
- DatastoreMediator.getInstance().refreshAllIndexes();
+ messageStoreFacade.deleteIndexes(indexExp);
}
@Given("I delete all indices")
public void deleteIndices() throws Exception {
- DatastoreMediator.getInstance().deleteAllIndexes();
+ messageStoreFacade.refreshAllIndexes();
+ messageStoreFacade.deleteAllIndexes();
}
@When("I refresh all indices")
public void refreshIndeces() throws Throwable {
- DatastoreMediator.getInstance().refreshAllIndexes();
+ messageStoreFacade.refreshAllIndexes();
+ datastoreCacheManager.getMetricsCache().invalidateAll();
+ datastoreCacheManager.getChannelsCache().invalidateAll();
+ datastoreCacheManager.getClientsCache().invalidateAll();
}
@When("I clear all the database caches")
public void clearDatabaseCaches() {
- DatastoreCacheManager.getInstance().getChannelsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getClientsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getMetricsCache().invalidateAll();
- DatastoreCacheManager.getInstance().getMetadataCache().invalidateAll();
+ datastoreCacheManager.getChannelsCache().invalidateAll();
+ datastoreCacheManager.getClientsCache().invalidateAll();
+ datastoreCacheManager.getMetricsCache().invalidateAll();
+ datastoreCacheManager.getMetadataCache().invalidateAll();
}
@Given("I have a mock data application named {string}")
@@ -383,35 +378,32 @@ public void publishMetric(String topic, List metrics) {
@Then("I expect the number of messages for this device to be {long}")
public void expectNumberOfMessages(long numberOfMessages) throws Exception {
- final MessageStoreService service = KapuaLocator.getInstance().getService(MessageStoreService.class);
session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> {
MessageQuery query = messageStoreFactory.newQuery(account.getId());
query.setPredicate(datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, currentDevice.getClientId()));
query.setAskTotalCount(true);
query.setLimit((int) numberOfMessages);
- MessageListResult result = service.query(query);
+ MessageListResult result = messageStoreService.query(query);
Assert.assertEquals(numberOfMessages, result.getSize());
Assert.assertEquals(Long.valueOf(numberOfMessages), result.getTotalCount());
- Assert.assertEquals(numberOfMessages, service.count(query));
+ Assert.assertEquals(numberOfMessages, messageStoreService.count(query));
}));
}
@Then("I delete the messages for this device")
public void deleteMessages() throws Exception {
- final MessageStoreService service = KapuaLocator.getInstance().getService(MessageStoreService.class);
session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> {
MessageQuery query = messageStoreFactory.newQuery(account.getId());
query.setPredicate(datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, currentDevice.getClientId()));
query.setAskTotalCount(true);
query.setLimit(100);
- service.delete(query);
+ messageStoreService.delete(query);
}));
}
@Then("I expect the latest captured message on channel {string} to have the metrics")
public void testMessageData(String topic, List expectedMetrics) throws Exception {
- final MessageStoreService service = KapuaLocator.getInstance().getService(MessageStoreService.class);
session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> {
MessageQuery query = messageStoreFactory.newQuery(account.getId());
AndPredicate and = datastorePredicateFactory.newAndPredicate();
@@ -419,7 +411,7 @@ public void testMessageData(String topic, List expectedMetrics) thr
and.getPredicates().add(datastorePredicateFactory.newTermPredicate(MessageField.CHANNEL, topic));
query.setPredicate(and);
query.setSortFields(Arrays.asList(SortField.descending(MessageField.CAPTURED_ON.field())));
- MessageListResult result = service.query(query);
+ MessageListResult result = messageStoreService.query(query);
Assert.assertEquals(1, result.getSize());
DatastoreMessage message = result.getFirstItem();
Assert.assertEquals(currentDevice.getClientId(), message.getClientId());
@@ -443,11 +435,7 @@ public void checkCurrentDateIndexName(String name) throws Exception {
String indexName = "";
primeException();
- try {
- indexName = DatastoreUtils.getDataIndexName(SYS_SCOPE_ID, instant.toEpochMilli(), window);
- } catch (KapuaException ex) {
- verifyException(ex);
- }
+ indexName = KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getDataIndexName(SYS_SCOPE_ID, instant.toEpochMilli(), window);
Assert.assertEquals(name, indexName);
}
@@ -961,7 +949,7 @@ public void deleteAllChannelsFromList(String lstKey) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
ChannelInfoListResult tmpList = (ChannelInfoListResult) stepData.get(lstKey);
for (ChannelInfo tmpItem : tmpList.getItems()) {
- channelInfoRegistryServiceProxy.delete(account.getId(), tmpItem.getId());
+ channelInfoRegistryService.delete(account.getId(), tmpItem.getId());
}
}
@@ -969,7 +957,7 @@ public void deleteAllChannelsFromList(String lstKey) throws KapuaException {
public void deleteChannelWithId(String idKey) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
StorableId tmpId = (StorableId) stepData.get(idKey);
- channelInfoRegistryServiceProxy.delete(account.getId(), tmpId);
+ channelInfoRegistryService.delete(account.getId(), tmpId);
}
@When("I query for the current account metrics (again )and store (it/them) as {string}")
@@ -1125,7 +1113,7 @@ public void deleteAllMetricsFromList(String lstKey) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
MetricInfoListResult tmpList = (MetricInfoListResult) stepData.get(lstKey);
for (MetricInfo tmpItem : tmpList.getItems()) {
- metricInfoRegistryServiceProxy.delete(account.getId(), tmpItem.getId());
+ metricInfoRegistryService.delete(account.getId(), tmpItem.getId());
}
}
@@ -1220,7 +1208,7 @@ public void deleteAllClientsFromList(String lstKey) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
ClientInfoListResult tmpList = (ClientInfoListResult) stepData.get(lstKey);
for (ClientInfo tmpItem : tmpList.getItems()) {
- clientInfoRegistryServiceProxy.delete(account.getId(), tmpItem.getId());
+ clientInfoRegistryService.delete(account.getId(), tmpItem.getId());
}
}
@@ -1228,7 +1216,7 @@ public void deleteAllClientsFromList(String lstKey) throws KapuaException {
public void deleteClientFromList(int index, String lstKey) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
ClientInfoListResult tmpList = (ClientInfoListResult) stepData.get(lstKey);
- clientInfoRegistryServiceProxy.delete(account.getId(), tmpList.getItem(index).getId());
+ clientInfoRegistryService.delete(account.getId(), tmpList.getItem(index).getId());
}
@When("I search for data message with id {string}")
@@ -1443,13 +1431,13 @@ public void queryForChannelInfo() throws KapuaException {
@When("I delete the channel info data based on the last query")
public void deleteChannelInfoByQuery() throws KapuaException {
ChannelInfoQuery tmpQuery = (ChannelInfoQuery) stepData.get(CHANNEL_INFO_QUERY);
- channelInfoRegistryServiceProxy.delete(tmpQuery);
+ channelInfoRegistryService.delete(tmpQuery);
}
@When("I delete the the channel info data with the ID {string} from the current account")
public void deleteChannelInfoWithId(String id) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
- channelInfoRegistryServiceProxy.delete(account.getId(), storableIdFactory.newStorableId(id));
+ channelInfoRegistryService.delete(account.getId(), storableIdFactory.newStorableId(id));
}
@Then("I get empty channel info list result")
@@ -1495,13 +1483,13 @@ public void getEmptyMetricInfoListResult() {
@When("I delete the metric info data based on the last query")
public void deleteMetricsInfoByQuery() throws KapuaException {
MetricInfoQuery tmpQuery = (MetricInfoQuery) stepData.get(METRIC_INFO_QUERY);
- metricInfoRegistryServiceProxy.delete(tmpQuery);
+ metricInfoRegistryService.delete(tmpQuery);
}
@When("I delete the the metric info data with the ID {string} from the current account")
public void deleteMetricsInfoWithId(String id) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
- metricInfoRegistryServiceProxy.delete(account.getId(), storableIdFactory.newStorableId(id));
+ metricInfoRegistryService.delete(account.getId(), storableIdFactory.newStorableId(id));
}
@When("I count for metric info")
@@ -1540,13 +1528,13 @@ public void getEmptyClientInfoListResult() {
@When("I delete the client info data based on the last query")
public void deleteClientInfoByQuery() throws KapuaException {
ClientInfoQuery tmpQuery = (ClientInfoQuery) stepData.get(CLIENT_INFO_QUERY);
- clientInfoRegistryServiceProxy.delete(tmpQuery);
+ clientInfoRegistryService.delete(tmpQuery);
}
@When("I delete the the client info data with the ID {string} from the current account")
public void deleteClientInfoWithId(String id) throws KapuaException {
Account account = (Account) stepData.get(LAST_ACCOUNT);
- clientInfoRegistryServiceProxy.delete(account.getId(), storableIdFactory.newStorableId(id));
+ clientInfoRegistryService.delete(account.getId(), storableIdFactory.newStorableId(id));
}
@When("I count for client info")
@@ -1594,7 +1582,7 @@ public void configureDatastoreService(String enabled, int dataTTL, int rxByteLim
public void deleteIndexesBetweenDates(String fromDate, String toDate) throws Exception {
primeException();
try {
- String[] indexes = DatastoreUtils.convertToDataIndexes(getDataIndexesByAccount(getCurrentScopeId()), KapuaDateUtils.parseDate(fromDate).toInstant(),
+ String[] indexes = KapuaLocator.getInstance().getComponent(DatastoreUtils.class).convertToDataIndexes(getDataIndexesByAccount(getCurrentScopeId()), KapuaDateUtils.parseDate(fromDate).toInstant(),
KapuaDateUtils.parseDate(toDate).toInstant());
elasticsearchClient.deleteIndexes(indexes);
} catch (Exception ex) {
diff --git a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/DatastoreUtilsIndexCalculatorTest.java b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/DatastoreUtilsIndexCalculatorTest.java
index b9d0023fea4..7338e97f441 100644
--- a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/DatastoreUtilsIndexCalculatorTest.java
+++ b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/DatastoreUtilsIndexCalculatorTest.java
@@ -20,6 +20,7 @@
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreException;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -42,6 +43,7 @@ public class DatastoreUtilsIndexCalculatorTest {
private static final Logger LOG = LoggerFactory.getLogger(DatastoreUtilsIndexCalculatorTest.class);
private final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm Z");
+ private DatastoreUtils datastoreUtils = new DatastoreUtils(new DatastoreSettings());
@BeforeClass
public static void setUpBeforeClass() {
@@ -105,38 +107,38 @@ public void testIndex() throws KapuaException, ParseException {
@Test
public void dataIndexNameByScopeId() {
- Assert.assertEquals("1-data-message-*", DatastoreUtils.getDataIndexName(KapuaId.ONE));
+ Assert.assertEquals("1-data-message-*", datastoreUtils.getDataIndexName(KapuaId.ONE));
}
@Test
public void dataIndexNameByScopeIdAndTimestamp() throws KapuaException, ParseException {
// Index by Week
- String weekIndexName = DatastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK);
+ String weekIndexName = datastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), datastoreUtils.INDEXING_WINDOW_OPTION_WEEK);
Assert.assertEquals("1-data-message-2017-01", weekIndexName);
// Index by Day
- String dayIndexName = DatastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), DatastoreUtils.INDEXING_WINDOW_OPTION_DAY);
+ String dayIndexName = datastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), datastoreUtils.INDEXING_WINDOW_OPTION_DAY);
Assert.assertEquals("1-data-message-2017-01-02", dayIndexName);
// Index by Hour
- String hourIndexName = DatastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), DatastoreUtils.INDEXING_WINDOW_OPTION_HOUR);
+ String hourIndexName = datastoreUtils.getDataIndexName(KapuaId.ONE, sdf.parse("02/01/2017 13:12 +0100").getTime(), datastoreUtils.INDEXING_WINDOW_OPTION_HOUR);
Assert.assertEquals("1-data-message-2017-01-02-12", hourIndexName); // Index Hour is UTC!
}
@Test
public void channelIndexNameByScopeId() {
- Assert.assertEquals("1-data-channel", DatastoreUtils.getChannelIndexName(KapuaId.ONE));
+ Assert.assertEquals("1-data-channel", datastoreUtils.getChannelIndexName(KapuaId.ONE));
}
@Test
public void clientIndexNameByScopeId() {
- Assert.assertEquals("1-data-client", DatastoreUtils.getClientIndexName(KapuaId.ONE));
+ Assert.assertEquals("1-data-client", datastoreUtils.getClientIndexName(KapuaId.ONE));
}
@Test
public void metricIndexNameByScopeId() {
- Assert.assertEquals("1-data-metric", DatastoreUtils.getMetricIndexName(KapuaId.ONE));
+ Assert.assertEquals("1-data-metric", datastoreUtils.getMetricIndexName(KapuaId.ONE));
}
private void performTest(Date startDate, Date endDate, String[] expectedIndexes) throws DatastoreException {
@@ -157,7 +159,7 @@ private void performTest(Date startDate, Date endDate, String[] expectedIndexes)
calEndDate != null ? calEndDate.get(Calendar.WEEK_OF_YEAR) : "Infinity",
calEndDate != null ? calEndDate.get(Calendar.DAY_OF_WEEK) : "Infinity");
- String[] index = DatastoreUtils.convertToDataIndexes(getDataIndexesByAccount(KapuaEid.ONE), startDate != null ? startDate.toInstant() : null, endDate != null ? endDate.toInstant() : null);
+ String[] index = datastoreUtils.convertToDataIndexes(getDataIndexesByAccount(KapuaEid.ONE), startDate != null ? startDate.toInstant() : null, endDate != null ? endDate.toInstant() : null);
compareResult(expectedIndexes, index);
}
@@ -179,7 +181,7 @@ private void performNullIndexTest(Date startDate, Date endDate) throws Datastore
calEndDate != null ? calEndDate.get(Calendar.WEEK_OF_YEAR) : "Infinity",
calEndDate != null ? calEndDate.get(Calendar.DAY_OF_WEEK) : "Infinity");
- String[] index = DatastoreUtils.convertToDataIndexes(new String[]{null, null}, startDate != null ? startDate.toInstant() : null, endDate != null ? endDate.toInstant() : null);
+ String[] index = datastoreUtils.convertToDataIndexes(new String[]{null, null}, startDate != null ? startDate.toInstant() : null, endDate != null ? endDate.toInstant() : null);
compareResult(null, index);
}
diff --git a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsConvertDateTest.java b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsConvertDateTest.java
index 7ec5e7e2bbd..040b44f1de5 100644
--- a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsConvertDateTest.java
+++ b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsConvertDateTest.java
@@ -15,6 +15,7 @@
import org.assertj.core.api.Assertions;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@@ -25,26 +26,27 @@
@Category(JUnitTests.class)
public class DatastoreUtilsConvertDateTest {
+ private DatastoreUtils datastoreUtils = new DatastoreUtils(new DatastoreSettings());
@Test(expected = java.lang.IllegalArgumentException.class)
public void convertNullString() {
- DatastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, null);
+ datastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, null);
}
@Test
public void convertValidString() {
- Assertions.assertThat(DatastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "2017-01-02T12:34:56.123Z"))
+ Assertions.assertThat(datastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "2017-01-02T12:34:56.123Z"))
.isInstanceOf(Date.class)
.isEqualTo(Date.from(ZonedDateTime.of(2017, 1, 2, 12, 34, 56, 123_000_000, ZoneOffset.UTC).toInstant()));
}
@Test(expected = java.time.format.DateTimeParseException.class)
public void convertWrongString() {
- DatastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "01-02-2017T12:34:56.123Z");
+ datastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "01-02-2017T12:34:56.123Z");
}
@Test(expected = java.time.format.DateTimeParseException.class)
public void convertEmptyString() {
- DatastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "");
+ datastoreUtils.convertToCorrectType(DatastoreUtils.CLIENT_METRIC_TYPE_DATE_ACRONYM, "");
}
}
diff --git a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsIndexNameTest.java b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsIndexNameTest.java
index fc4eca65cc1..fa2034a38b2 100644
--- a/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsIndexNameTest.java
+++ b/service/datastore/test/src/test/java/org/eclipse/kapua/service/datastore/test/junit/utils/DatastoreUtilsIndexNameTest.java
@@ -12,12 +12,12 @@
*******************************************************************************/
package org.eclipse.kapua.service.datastore.test.junit.utils;
-import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.model.id.KapuaEid;
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils;
+import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings;
import org.eclipse.kapua.service.datastore.test.junit.DatastoreJAXBContextProvider;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -40,37 +40,31 @@ public static void setUpBeforeClass() {
XmlUtil.setContextProvider(new DatastoreJAXBContextProvider());
}
+ private DatastoreUtils datastoreUtils = new DatastoreUtils(new DatastoreSettings());
+
@Test
public void test1() {
final Instant instant = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant();
- try {
- // Index by Week
- Assert.assertEquals("1-data-message-2017-01", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK));
+ // Index by Week
+ Assert.assertEquals("1-data-message-2017-01", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_WEEK));
- // Index by Day
- Assert.assertEquals("1-data-message-2017-01-01", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_DAY));
+ // Index by Day
+ Assert.assertEquals("1-data-message-2017-01-01", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_DAY));
- // Index by Hour
- Assert.assertEquals("1-data-message-2017-01-01-00", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_HOUR));
- } catch (KapuaException kaex) {
- Assert.fail("Error while generating index name");
- }
+ // Index by Hour
+ Assert.assertEquals("1-data-message-2017-01-01-00", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_HOUR));
}
@Test
public void test2() {
final Instant instant = ZonedDateTime.of(2017, 1, 8, 0, 0, 0, 0, ZoneOffset.UTC).toInstant();
- try {
- // Index by Week
- Assert.assertEquals("1-data-message-2017-02", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_WEEK));
+ // Index by Week
+ Assert.assertEquals("1-data-message-2017-02", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_WEEK));
- // Index by Day
- Assert.assertEquals("1-data-message-2017-02-01", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_DAY));
+ // Index by Day
+ Assert.assertEquals("1-data-message-2017-02-01", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_DAY));
- // Index by Hour
- Assert.assertEquals("1-data-message-2017-02-01-00", DatastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), DatastoreUtils.INDEXING_WINDOW_OPTION_HOUR));
- } catch (KapuaException kaex) {
- Assert.fail("Error while generating index name");
- }
+ // Index by Hour
+ Assert.assertEquals("1-data-message-2017-02-01-00", datastoreUtils.getDataIndexName(ONE, instant.toEpochMilli(), datastoreUtils.INDEXING_WINDOW_OPTION_HOUR));
}
}
diff --git a/service/datastore/test/src/test/resources/kapua-datastore-rest-client-setting.properties b/service/datastore/test/src/test/resources/kapua-datastore-rest-client-setting.properties
index 324bb022e52..ae9a8f3440f 100644
--- a/service/datastore/test/src/test/resources/kapua-datastore-rest-client-setting.properties
+++ b/service/datastore/test/src/test/resources/kapua-datastore-rest-client-setting.properties
@@ -11,29 +11,22 @@
# Eurotech - initial API and implementation
#
###############################################################################
-
#
# Provider
-#datastore.elasticsearch.provider=org.eclipse.kapua.service.elasticsearch.client.transport.TransportElasticsearchClientProvider
-datastore.elasticsearch.provider=org.eclipse.kapua.service.elasticsearch.client.rest.RestElasticsearchClientProvider
datastore.elasticsearch.module=datastore-elasticsearch-client
-
#
# Connection
datastore.elasticsearch.cluster=kapua-datastore
datastore.elasticsearch.nodes=127.0.0.1:9200
datastore.elasticsearch.username=
datastore.elasticsearch.password=
-
datastore.elasticsearch.client.reconnection_wait_between_exec=15000
-
#
# Requests
datastore.elasticsearch.request.query.timeout=15000
datastore.elasticsearch.request.scroll.timeout=60000
datastore.elasticsearch.request.retry.max=3
datastore.elasticsearch.request.retry.wait=2500
-
#
# SSL
datastore.elasticsearch.ssl.enabled=false
diff --git a/service/datastore/test/src/test/resources/kapua-datastore-transport-client-setting.properties b/service/datastore/test/src/test/resources/kapua-datastore-transport-client-setting.properties
index 945a72cda12..64554e8cb25 100644
--- a/service/datastore/test/src/test/resources/kapua-datastore-transport-client-setting.properties
+++ b/service/datastore/test/src/test/resources/kapua-datastore-transport-client-setting.properties
@@ -11,29 +11,22 @@
# Eurotech - initial API and implementation
#
###############################################################################
-
#
# Provider
-datastore.elasticsearch.provider=org.eclipse.kapua.service.elasticsearch.client.transport.TransportElasticsearchClientProvider
-#datastore.elasticsearch.provider=org.eclipse.kapua.service.elasticsearch.client.rest.RestElasticsearchClientProvider
datastore.elasticsearch.module=datastore-elasticsearch-client
-
#
# Connection
datastore.elasticsearch.cluster=kapua-datastore
datastore.elasticsearch.nodes=localhost:9300
datastore.elasticsearch.username=
datastore.elasticsearch.password=
-
datastore.elasticsearch.client.reconnection_wait_between_exec=15000
-
#
# Requests
datastore.elasticsearch.request.query.timeout=15000
datastore.elasticsearch.request.scroll.timeout=60000
datastore.elasticsearch.request.retry.max=3
datastore.elasticsearch.request.retry.wait=2500
-
#
# SSL
datastore.elasticsearch.ssl.enabled=false
diff --git a/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/request/xml/RequestMessageXmlRegistry.java b/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/request/xml/RequestMessageXmlRegistry.java
index 58b6ddbce27..da3fe17f48b 100644
--- a/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/request/xml/RequestMessageXmlRegistry.java
+++ b/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/request/xml/RequestMessageXmlRegistry.java
@@ -24,18 +24,17 @@
@XmlRegistry
public class RequestMessageXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final KapuaRequestMessageFactory KAPUA_REQUEST_MESSAGE_FACTORY = LOCATOR.getFactory(KapuaRequestMessageFactory.class);
+ private final KapuaRequestMessageFactory kapuaRequestMessageFactory = KapuaLocator.getInstance().getFactory(KapuaRequestMessageFactory.class);
public KapuaRequestMessage, ?> newRequestMessage() {
- return KAPUA_REQUEST_MESSAGE_FACTORY.newRequestMessage();
+ return kapuaRequestMessageFactory.newRequestMessage();
}
public KapuaRequestChannel newRequestChannel() {
- return KAPUA_REQUEST_MESSAGE_FACTORY.newRequestChannel();
+ return kapuaRequestMessageFactory.newRequestChannel();
}
public KapuaRequestPayload newRequestPayload() {
- return KAPUA_REQUEST_MESSAGE_FACTORY.newRequestPayload();
+ return kapuaRequestMessageFactory.newRequestPayload();
}
}
diff --git a/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/xml/KapuaAppPropertiesXmlAdapter.java b/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/xml/KapuaAppPropertiesXmlAdapter.java
index 98a04b277d9..633dae09e19 100644
--- a/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/xml/KapuaAppPropertiesXmlAdapter.java
+++ b/service/device/api/src/main/java/org/eclipse/kapua/service/device/management/message/xml/KapuaAppPropertiesXmlAdapter.java
@@ -25,8 +25,7 @@
*/
public class KapuaAppPropertiesXmlAdapter extends XmlAdapter {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final KapuaRequestMessageFactory REQUEST_MESSAGE_FACTORY = LOCATOR.getFactory(KapuaRequestMessageFactory.class);
+ private final KapuaRequestMessageFactory kapuaRequestMessageFactory = KapuaLocator.getInstance().getFactory(KapuaRequestMessageFactory.class);
@Override
public String marshal(KapuaAppProperties kapuaAppProperties) throws Exception {
@@ -35,6 +34,6 @@ public String marshal(KapuaAppProperties kapuaAppProperties) throws Exception {
@Override
public KapuaAppProperties unmarshal(String string) throws Exception {
- return REQUEST_MESSAGE_FACTORY.newAppProperties(string);
+ return kapuaRequestMessageFactory.newAppProperties(string);
}
}
diff --git a/service/device/call/kura/pom.xml b/service/device/call/kura/pom.xml
index e15b7f3500d..8e6def2ff79 100644
--- a/service/device/call/kura/pom.xml
+++ b/service/device/call/kura/pom.xml
@@ -54,7 +54,10 @@
org.eclipse.kapua
kapua-message-internal
-
+
+ org.eclipse.kapua
+ kapua-transport-mqtt
+
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/DeviceCallKuraModule.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/DeviceCallKuraModule.java
index cd3275fb381..1f52e7b78e7 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/DeviceCallKuraModule.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/DeviceCallKuraModule.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.service.device.call.DeviceCallFactory;
import org.eclipse.kapua.service.device.call.DeviceMessageFactory;
+import org.eclipse.kapua.service.device.call.message.kura.setting.DeviceCallSettings;
+
+import javax.inject.Singleton;
public class DeviceCallKuraModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(DeviceCallFactory.class).to(KuraDeviceCallFactoryImpl.class);
- bind(DeviceMessageFactory.class).to(KuraMessageFactoryImpl.class);
+ bind(DeviceCallFactory.class).to(KuraDeviceCallFactoryImpl.class).in(Singleton.class);
+ bind(DeviceMessageFactory.class).to(KuraMessageFactoryImpl.class).in(Singleton.class);
+ bind(DeviceCallSettings.class).in(Singleton.class);
}
}
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallFactoryImpl.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallFactoryImpl.java
index 4f18f9b9aea..27d3327f651 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallFactoryImpl.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallFactoryImpl.java
@@ -12,8 +12,13 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.call.kura;
+import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.device.call.DeviceCallFactory;
+import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
+import org.eclipse.kapua.translator.TranslatorHub;
+import org.eclipse.kapua.transport.TransportClientFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
/**
@@ -23,8 +28,23 @@
*/
@Singleton
public class KuraDeviceCallFactoryImpl implements DeviceCallFactory {
+ private final AccountService accountService;
+ private final DeviceRegistryService deviceRegistryService;
+ private final TransportClientFactory transportClientFactory;
+ private final TranslatorHub translatorHub;
+
+ @Inject
+ public KuraDeviceCallFactoryImpl(AccountService accountService,
+ DeviceRegistryService deviceRegistryService,
+ TransportClientFactory transportClientFactory, TranslatorHub translatorHub) {
+ this.accountService = accountService;
+ this.deviceRegistryService = deviceRegistryService;
+ this.transportClientFactory = transportClientFactory;
+ this.translatorHub = translatorHub;
+ }
+
@Override
public KuraDeviceCallImpl newDeviceCall() {
- return new KuraDeviceCallImpl();
+ return new KuraDeviceCallImpl(accountService, deviceRegistryService, transportClientFactory, translatorHub);
}
}
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallImpl.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallImpl.java
index 7b3ea10c071..9438085914f 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallImpl.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/KuraDeviceCallImpl.java
@@ -19,7 +19,6 @@
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.util.RandomUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.Message;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.account.AccountService;
@@ -36,6 +35,7 @@
import org.eclipse.kapua.service.device.registry.Device;
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.TranslatorHub;
import org.eclipse.kapua.translator.exception.TranslatorNotFoundException;
import org.eclipse.kapua.transport.TransportClientFactory;
import org.eclipse.kapua.transport.TransportFacade;
@@ -44,6 +44,7 @@
import org.eclipse.kapua.transport.exception.TransportTimeoutException;
import org.eclipse.kapua.transport.message.TransportMessage;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
@@ -58,14 +59,21 @@
public class KuraDeviceCallImpl implements DeviceCall {
private static final Random RANDOM = RandomUtils.getInstance();
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
-
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
-
- private static final TransportClientFactory TRANSPORT_CLIENT_FACTORY = LOCATOR.getFactory(TransportClientFactory.class);
+ protected final AccountService accountService;
+ protected final DeviceRegistryService deviceRegistryService;
+ protected final TransportClientFactory transportClientFactory;
+ protected final TranslatorHub translatorHub;
+
+ @Inject
+ public KuraDeviceCallImpl(
+ AccountService accountService,
+ DeviceRegistryService deviceRegistryService,
+ TransportClientFactory transportClientFactory, TranslatorHub translatorHub) {
+ this.accountService = accountService;
+ this.deviceRegistryService = deviceRegistryService;
+ this.transportClientFactory = transportClientFactory;
+ this.translatorHub = translatorHub;
+ }
@Override
public KuraResponseMessage create(@NotNull KuraRequestMessage requestMessage, @Nullable Long timeout)
@@ -192,13 +200,13 @@ protected KuraResponseMessage sendInternal(@NotNull KuraRequestMessage requestMe
String serverIp = null;
try {
serverIp = KapuaSecurityUtils.doPrivileged(() -> {
- Account account = ACCOUNT_SERVICE.findByName(kuraRequestMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraRequestMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraRequestMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraRequestMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraRequestMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.TYPE, kuraRequestMessage.getChannel().getClientId());
}
@@ -212,8 +220,7 @@ protected KuraResponseMessage sendInternal(@NotNull KuraRequestMessage requestMe
Map configParameters = new HashMap<>(1);
configParameters.put("serverAddress", serverIp);
-
- return TRANSPORT_CLIENT_FACTORY.getFacade(configParameters);
+ return transportClientFactory.getFacade(configParameters);
} catch (TransportException tce) {
throw tce;
} catch (Exception e) {
@@ -235,7 +242,7 @@ protected KuraResponseMessage sendInternal(@NotNull KuraRequestMessage requestMe
protected , T extends Message, ?>> Translator getTranslator(Class from, Class to) throws KuraDeviceCallException {
Translator translator;
try {
- translator = Translator.getTranslatorFor(from, to);
+ translator = translatorHub.getTranslatorFor(from, to);
} catch (TranslatorNotFoundException e) {
throw new KuraDeviceCallException(KuraDeviceCallErrorCodes.CALL_ERROR, e, from, to);
}
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapted.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapted.java
index af278116317..4792fa2ed4a 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapted.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapted.java
@@ -20,7 +20,6 @@
* A container for XmlConfigPropertyAdapted organized into an array.
*
* @since 1.0
- *
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class KuraXmlConfigPropertiesAdapted {
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapter.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapter.java
index 99ac6a4b5af..57658fb5be3 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapter.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/KuraXmlConfigPropertiesAdapter.java
@@ -12,14 +12,24 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.call.kura.model.configuration.xml;
+import org.eclipse.kapua.commons.configuration.metatype.PasswordPropertyAdapter;
import org.eclipse.kapua.commons.crypto.CryptoUtil;
-import org.eclipse.kapua.service.device.call.kura.model.configuration.KuraPassword;
+import org.eclipse.kapua.locator.KapuaLocator;
+import org.eclipse.kapua.model.xml.adapters.BooleanPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.BytePropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.CharPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.DoublePropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.FloatPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.IntegerPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.LongPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.ShortPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.StringPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.XmlPropertiesAdapter;
+import org.eclipse.kapua.model.xml.adapters.XmlPropertyAdapter;
import org.eclipse.kapua.service.device.call.kura.model.configuration.xml.XmlConfigPropertyAdapted.ConfigPropertyType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
-import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
/**
@@ -29,317 +39,33 @@
*/
public class KuraXmlConfigPropertiesAdapter extends XmlAdapter> {
- @Override
- public KuraXmlConfigPropertiesAdapted marshal(Map props) throws Exception {
- List adaptedValues = new ArrayList<>();
- if (props != null) {
- props.forEach((name, value) -> {
-
- XmlConfigPropertyAdapted adaptedValue = new XmlConfigPropertyAdapted();
- adaptedValue.setName(name);
-
- if (value instanceof String) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.stringType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Long) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.longType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Double) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.doubleType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Float) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.floatType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Integer) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.integerType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Byte) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.byteType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Character) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.charType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Boolean) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.booleanType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Short) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.shortType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof KuraPassword) {
- adaptedValue.setArray(false);
- adaptedValue.setEncrypted(true);
- adaptedValue.setType(ConfigPropertyType.passwordType);
- adaptedValue.setValues(new String[]{CryptoUtil.encodeBase64(value.toString())});
- } else if (value instanceof String[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.stringType);
- adaptedValue.setValues((String[]) value);
- } else if (value instanceof Long[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.longType);
- Long[] nativeValues = (Long[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Double[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.doubleType);
- Double[] nativeValues = (Double[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Float[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.floatType);
- Float[] nativeValues = (Float[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Integer[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.integerType);
- Integer[] nativeValues = (Integer[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Byte[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.byteType);
- Byte[] nativeValues = (Byte[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Character[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.charType);
- Character[] nativeValues = (Character[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Boolean[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.booleanType);
- Boolean[] nativeValues = (Boolean[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Short[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.shortType);
- Short[] nativeValues = (Short[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof KuraPassword[]) {
- adaptedValue.setArray(true);
- adaptedValue.setEncrypted(true);
- adaptedValue.setType(ConfigPropertyType.passwordType);
- KuraPassword[] nativeValues = (KuraPassword[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = CryptoUtil.encodeBase64(nativeValues[i].toString());
- }
- }
- adaptedValue.setValues(stringValues);
- }
-
- adaptedValues.add(adaptedValue);
- });
+ private XmlPropertiesAdapter adapter = new XmlPropertiesAdapter<>(XmlConfigPropertyAdapted.class, () -> new XmlConfigPropertyAdapted(), new HashMap() {
+ {
+ put(ConfigPropertyType.stringType, new StringPropertyAdapter());
+ put(ConfigPropertyType.longType, new LongPropertyAdapter());
+ put(ConfigPropertyType.doubleType, new DoublePropertyAdapter());
+ put(ConfigPropertyType.floatType, new FloatPropertyAdapter());
+ put(ConfigPropertyType.integerType, new IntegerPropertyAdapter());
+ put(ConfigPropertyType.byteType, new BytePropertyAdapter());
+ put(ConfigPropertyType.charType, new CharPropertyAdapter());
+ put(ConfigPropertyType.booleanType, new BooleanPropertyAdapter());
+ put(ConfigPropertyType.shortType, new ShortPropertyAdapter());
+ put(ConfigPropertyType.passwordType, new PasswordPropertyAdapter(KapuaLocator.getInstance().getComponent(CryptoUtil.class)));
}
+ });
- KuraXmlConfigPropertiesAdapted result = new KuraXmlConfigPropertiesAdapted();
- result.setProperties(adaptedValues.toArray(new XmlConfigPropertyAdapted[]{}));
- return result;
+ public KuraXmlConfigPropertiesAdapter() {
}
@Override
- public Map unmarshal(KuraXmlConfigPropertiesAdapted adaptedPropsAdapted) {
- XmlConfigPropertyAdapted[] adaptedProps = adaptedPropsAdapted.getProperties();
- if (adaptedProps == null) {
- return new HashMap<>();
- }
+ public Map unmarshal(KuraXmlConfigPropertiesAdapted v) throws Exception {
+ return adapter.unmarshal(v.getProperties());
+ }
- Map properties = new HashMap<>();
- for (XmlConfigPropertyAdapted adaptedProp : adaptedProps) {
- String propName = adaptedProp.getName();
- ConfigPropertyType type = adaptedProp.getType();
- if (type != null) {
- Object propValue = null;
- if (!adaptedProp.getArray()) {
- switch (adaptedProp.getType()) {
- case stringType:
- propValue = adaptedProp.getValues()[0];
- break;
- case longType:
- propValue = Long.parseLong(adaptedProp.getValues()[0]);
- break;
- case doubleType:
- propValue = Double.parseDouble(adaptedProp.getValues()[0]);
- break;
- case floatType:
- propValue = Float.parseFloat(adaptedProp.getValues()[0]);
- break;
- case integerType:
- propValue = Integer.parseInt(adaptedProp.getValues()[0]);
- break;
- case byteType:
- propValue = Byte.parseByte(adaptedProp.getValues()[0]);
- break;
- case charType:
- String s = adaptedProp.getValues()[0];
- propValue = s.charAt(0);
- break;
- case booleanType:
- propValue = Boolean.parseBoolean(adaptedProp.getValues()[0]);
- break;
- case shortType:
- propValue = Short.parseShort(adaptedProp.getValues()[0]);
- break;
- case passwordType:
- propValue = adaptedProp.getValues()[0];
- propValue =
- adaptedProp.isEncrypted() ?
- new KuraPassword(CryptoUtil.decodeBase64((String) propValue)) :
- new KuraPassword((String) propValue);
- break;
- }
- } else {
- switch (adaptedProp.getType()) {
- case stringType:
- propValue = adaptedProp.getValues();
- break;
- case longType:
- Long[] longValues = new Long[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- longValues[i] = Long.parseLong(adaptedProp.getValues()[i]);
- }
- }
- propValue = longValues;
- break;
- case doubleType:
- Double[] doubleValues = new Double[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- doubleValues[i] = Double.parseDouble(adaptedProp.getValues()[i]);
- }
- }
- propValue = doubleValues;
- break;
- case floatType:
- Float[] floatValues = new Float[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- floatValues[i] = Float.parseFloat(adaptedProp.getValues()[i]);
- }
- }
- propValue = floatValues;
- break;
- case integerType:
- Integer[] intValues = new Integer[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- intValues[i] = Integer.parseInt(adaptedProp.getValues()[i]);
- }
- }
- propValue = intValues;
- break;
- case byteType:
- Byte[] byteValues = new Byte[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- byteValues[i] = Byte.parseByte(adaptedProp.getValues()[i]);
- }
- }
- propValue = byteValues;
- break;
- case charType:
- Character[] charValues = new Character[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- String s = adaptedProp.getValues()[i];
- charValues[i] = s.charAt(0);
- }
- }
- propValue = charValues;
- break;
- case booleanType:
- Boolean[] booleanValues = new Boolean[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- booleanValues[i] = Boolean.parseBoolean(adaptedProp.getValues()[i]);
- }
- }
- propValue = booleanValues;
- break;
- case shortType:
- Short[] shortValues = new Short[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- shortValues[i] = Short.parseShort(adaptedProp.getValues()[i]);
- }
- }
- propValue = shortValues;
- break;
- case passwordType:
- KuraPassword[] pwdValues = new KuraPassword[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- pwdValues[i] =
- adaptedProp.isEncrypted() ?
- new KuraPassword(CryptoUtil.decodeBase64(adaptedProp.getValues()[i])) :
- new KuraPassword(adaptedProp.getValues()[i]);
- }
- }
- propValue = pwdValues;
- break;
- }
- }
- properties.put(propName, propValue);
- }
- }
- return properties;
+ @Override
+ public KuraXmlConfigPropertiesAdapted marshal(Map v) throws Exception {
+ final KuraXmlConfigPropertiesAdapted res = new KuraXmlConfigPropertiesAdapted();
+ res.setProperties(adapter.marshal(v));
+ return res;
}
}
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/XmlConfigPropertyAdapted.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/XmlConfigPropertyAdapted.java
index d34f1b9d6d7..6d444ccd252 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/XmlConfigPropertyAdapted.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/kura/model/configuration/xml/XmlConfigPropertyAdapted.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.call.kura.model.configuration.xml;
+import org.eclipse.kapua.model.xml.XmlPropertyAdapted;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@@ -26,10 +28,9 @@
* encrypted.
*
* @since 1.0
- *
*/
@XmlAccessorType(XmlAccessType.FIELD)
-public class XmlConfigPropertyAdapted {
+public class XmlConfigPropertyAdapted implements XmlPropertyAdapted {
@XmlEnum
public enum ConfigPropertyType {
@@ -46,6 +47,20 @@ public enum ConfigPropertyType {
passwordType
}
+ public XmlConfigPropertyAdapted() {
+ }
+
+ public XmlConfigPropertyAdapted(String name,
+ ConfigPropertyType type,
+ String... values) {
+ super();
+ this.name = name;
+ this.type = type;
+ this.encrypted = false;
+ this.array = values != null && values.length > 1;
+ this.values = values;
+ }
+
/**
* The name of the property.
*/
@@ -76,115 +91,42 @@ public enum ConfigPropertyType {
@XmlElement(name = "value")
private String[] values;
- /**
- * Constructor
- */
- public XmlConfigPropertyAdapted() {
- }
-
- /**
- * Constructor
- *
- * @param name
- * @param type
- * @param values
- */
- public XmlConfigPropertyAdapted(String name,
- ConfigPropertyType type,
- String[] values) {
- super();
-
- this.type = type;
- this.values = values;
- this.encrypted = false;
- }
-
- /**
- * Get the property name
- *
- * @return
- */
public String getName() {
return name;
}
- /**
- * Set the property name
- *
- * @param name
- */
public void setName(String name) {
this.name = name;
}
- /**
- * Get the is array flag property
- *
- * @return
- */
public boolean getArray() {
return array;
}
- /**
- * Set the is array flag property
- *
- * @param array
- */
public void setArray(boolean array) {
this.array = array;
}
- /**
- * Get the property type
- *
- * @return
- */
public ConfigPropertyType getType() {
return type;
}
- /**
- * Set the property type
- *
- * @param type
- */
public void setType(ConfigPropertyType type) {
this.type = type;
}
- /**
- * Get the is encrypted flag property
- *
- * @return
- */
public boolean isEncrypted() {
return encrypted;
}
- /**
- * Set the is encrypted flag property
- *
- * @param encrypted
- */
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
- /**
- * Get property values
- *
- * @return
- */
public String[] getValues() {
return values;
}
- /**
- * Set property values
- *
- * @param values
- */
public void setValues(String[] values) {
this.values = values;
}
diff --git a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/message/kura/setting/DeviceCallSettings.java b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/message/kura/setting/DeviceCallSettings.java
index 41a26e9a85c..8cc63773544 100644
--- a/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/message/kura/setting/DeviceCallSettings.java
+++ b/service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/message/kura/setting/DeviceCallSettings.java
@@ -14,6 +14,8 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* {@link DeviceCallSettings} for {@code kapua-device-call-kura} module.
*
@@ -29,29 +31,13 @@ public class DeviceCallSettings extends AbstractKapuaSetting requestMessage, KapuaResponseMessage, ?> responseMessage) throws KapuaException {
DeviceEventCreator deviceEventCreator =
- DEVICE_EVENT_FACTORY.newCreator(
+ deviceEventFactory.newCreator(
scopeId,
deviceId,
responseMessage != null ? responseMessage.getReceivedOn() : requestMessage.getSentOn(),
@@ -112,7 +105,7 @@ protected void createDeviceEvent(KapuaId scopeId, KapuaId deviceId, KapuaRequest
deviceEventCreator.setResponseCode(responseMessage != null ? responseMessage.getResponseCode() : KapuaResponseCode.SENT);
deviceEventCreator.setEventMessage(responseMessage != null ? responseMessage.getPayload().toDisplayString() : requestMessage.getPayload().toDisplayString());
- KapuaSecurityUtils.doPrivileged(() -> DEVICE_EVENT_SERVICE.create(deviceEventCreator));
+ KapuaSecurityUtils.doPrivileged(() -> kapuaLocatorService.create(deviceEventCreator));
}
/**
@@ -131,7 +124,7 @@ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws Kapua
//
// Check Device existence
- Device device = DEVICE_REGISTRY_SERVICE.find(scopeId, deviceId);
+ Device device = deviceRegistryService.find(scopeId, deviceId);
if (device == null) {
throw new KapuaEntityNotFoundException(Device.TYPE, deviceId);
@@ -149,7 +142,7 @@ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws Kapua
protected KapuaId createManagementOperation(KapuaId scopeId, KapuaId deviceId, KapuaId operationId, KapuaRequestMessage, ?> requestMessage) throws KapuaException {
- DeviceManagementOperationCreator deviceManagementOperationCreator = DEVICE_MANAGEMENT_OPERATION_FACTORY.newCreator(scopeId);
+ DeviceManagementOperationCreator deviceManagementOperationCreator = deviceManagementOperationFactory.newCreator(scopeId);
deviceManagementOperationCreator.setDeviceId(deviceId);
deviceManagementOperationCreator.setOperationId(operationId);
deviceManagementOperationCreator.setStartedOn(new Date());
@@ -159,7 +152,7 @@ protected KapuaId createManagementOperation(KapuaId scopeId, KapuaId deviceId, K
deviceManagementOperationCreator.setStatus(NotifyStatus.RUNNING);
deviceManagementOperationCreator.setInputProperties(extractInputProperties(requestMessage));
- DeviceManagementOperation deviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.create(deviceManagementOperationCreator));
+ DeviceManagementOperation deviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> deviceManagementOperationRegistryService.create(deviceManagementOperationCreator));
return deviceManagementOperation.getId();
}
@@ -169,7 +162,7 @@ protected void closeManagementOperation(KapuaId scopeId, KapuaId deviceId, Kapua
}
protected void closeManagementOperation(KapuaId scopeId, KapuaId deviceId, KapuaId operationId, KapuaResponseMessage, ?> responseMessageMessage) throws KapuaException {
- DeviceManagementOperation deviceManagementOperation = DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.findByOperationId(scopeId, operationId);
+ DeviceManagementOperation deviceManagementOperation = deviceManagementOperationRegistryService.findByOperationId(scopeId, operationId);
if (deviceManagementOperation == null) {
throw new KapuaEntityNotFoundException(DeviceManagementOperation.TYPE, operationId);
@@ -183,7 +176,7 @@ protected void closeManagementOperation(KapuaId scopeId, KapuaId deviceId, Kapua
deviceManagementOperation.setEndedOn(new Date());
}
- KapuaSecurityUtils.doPrivileged(() -> DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.update(deviceManagementOperation));
+ KapuaSecurityUtils.doPrivileged(() -> deviceManagementOperationRegistryService.update(deviceManagementOperation));
}
@@ -271,7 +264,7 @@ private List extractInputProperties(KapuaRequ
properties.forEach((k, v) -> {
if (v != null) {
inputProperties.add(
- DEVICE_MANAGEMENT_OPERATION_FACTORY.newStepProperty(
+ deviceManagementOperationFactory.newStepProperty(
k,
ObjectTypeConverter.toString(v.getClass()),
ObjectValueConverter.toString(v))
diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/DeviceCommonsModule.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/DeviceCommonsModule.java
index ba6fe6661d6..aee51be71dc 100644
--- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/DeviceCommonsModule.java
+++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/DeviceCommonsModule.java
@@ -14,11 +14,15 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.service.device.management.commons.message.KapuaRequestMessageFactoryImpl;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.message.request.KapuaRequestMessageFactory;
+import javax.inject.Singleton;
+
public class DeviceCommonsModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(KapuaRequestMessageFactory.class).to(KapuaRequestMessageFactoryImpl.class);
+ bind(KapuaRequestMessageFactory.class).to(KapuaRequestMessageFactoryImpl.class).in(Singleton.class);
+ bind(DeviceManagementSetting.class).in(Singleton.class);
}
}
diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallBuilder.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallBuilder.java
index 2802ab80a33..a025ef8a57e 100644
--- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallBuilder.java
+++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallBuilder.java
@@ -39,6 +39,7 @@
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus;
import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.TranslatorHub;
import org.eclipse.kapua.transport.exception.TransportException;
import java.util.Date;
@@ -63,13 +64,13 @@
*/
public class DeviceCallBuilder, RS extends KapuaResponseMessage> {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceCallFactory deviceCallFactory = KapuaLocator.getInstance().getFactory(DeviceCallFactory.class);
- private static final DeviceCallFactory DEVICE_CALL_FACTORY = LOCATOR.getFactory(DeviceCallFactory.class);
+ private final DeviceRegistryService deviceRegistryService = KapuaLocator.getInstance().getService(DeviceRegistryService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ private final TranslatorHub translatorHub = KapuaLocator.getInstance().getComponent(TranslatorHub.class);
- private static final Long DEFAULT_TIMEOUT = DeviceManagementSetting.getInstance().getLong(DeviceManagementSettingKey.REQUEST_TIMEOUT);
+ private final Long defaultTimeout = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getLong(DeviceManagementSettingKey.REQUEST_TIMEOUT);
private RQ requestMessage;
private Long timeout;
@@ -115,13 +116,13 @@ public DeviceCallBuilder withTimeout(Long timeout) {
}
/**
- * Configures the timeout of the MQTT request-reply and sets the {@link #DEFAULT_TIMEOUT} if provided timeout is {@code null}.
+ * Configures the timeout of the MQTT request-reply or sets the default timeout (see {@link DeviceManagementSettingKey#REQUEST_TIMEOUT}) in case the provided timeout is {@code null}.
*
* @return The {@link DeviceCallBuilder} itself.
* @since 1.4.0
*/
public DeviceCallBuilder withTimeoutOrDefault(Long timeout) {
- this.timeout = timeout != null ? timeout : DEFAULT_TIMEOUT;
+ this.timeout = timeout != null ? timeout : defaultTimeout;
return this;
}
@@ -143,8 +144,8 @@ public RS send() throws KapuaEntityNotFoundException, KapuaIllegalArgumentExcept
try {
requestMessage.setSentOn(new Date());
- DeviceCall, DeviceResponseMessage, ?>> deviceCall = DEVICE_CALL_FACTORY.newDeviceCall();
- Translator> tKapuaToClient = Translator.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
+ DeviceCall, DeviceResponseMessage, ?>> deviceCall = deviceCallFactory.newDeviceCall();
+ Translator> tKapuaToClient = translatorHub.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
DeviceRequestMessage, ?> deviceRequestMessage = tKapuaToClient.translate(requestMessage);
// Send the request
DeviceResponseMessage, ?> responseMessage;
@@ -182,7 +183,7 @@ public RS send() throws KapuaEntityNotFoundException, KapuaIllegalArgumentExcept
throw new DeviceManagementRequestBadMethodException(requestMessage.getChannel().getMethod());
}
// Translate the response from Device to Kapua
- Translator, RS> tClientToKapua = Translator.getTranslatorFor(deviceCall.getBaseMessageClass(), requestMessage.getResponseClass());
+ Translator, RS> tClientToKapua = translatorHub.getTranslatorFor(deviceCall.getBaseMessageClass(), requestMessage.getResponseClass());
return tClientToKapua.translate(responseMessage);
} catch (DeviceCallTimeoutException dcte) {
throw new DeviceManagementTimeoutException(dcte, timeout);
@@ -209,8 +210,8 @@ public void sendAndForget() throws KapuaEntityNotFoundException, KapuaIllegalArg
try {
requestMessage.setSentOn(new Date());
- DeviceCall, DeviceResponseMessage, ?>> deviceCall = DEVICE_CALL_FACTORY.newDeviceCall();
- Translator> tKapuaToClient = Translator.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
+ DeviceCall, DeviceResponseMessage, ?>> deviceCall = deviceCallFactory.newDeviceCall();
+ Translator> tKapuaToClient = translatorHub.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
DeviceRequestMessage, ?> deviceRequestMessage = tKapuaToClient.translate(requestMessage);
// Send the request
switch (requestMessage.getChannel().getMethod()) {
@@ -264,7 +265,7 @@ private void deviceCallPreChecks() throws DeviceManagementSendException, KapuaEn
// Check Device existence
Device device;
try {
- device = DEVICE_REGISTRY_SERVICE.find(requestMessage.getScopeId(), requestMessage.getDeviceId());
+ device = deviceRegistryService.find(requestMessage.getScopeId(), requestMessage.getDeviceId());
} catch (KapuaException e) {
throw new DeviceManagementSendException(e, requestMessage);
}
diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallExecutor.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallExecutor.java
index 737fb8cb2c9..7aded1c1c8b 100644
--- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallExecutor.java
+++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/call/DeviceCallExecutor.java
@@ -37,6 +37,7 @@
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus;
import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.TranslatorHub;
import org.eclipse.kapua.transport.exception.TransportException;
import javax.validation.constraints.NotNull;
@@ -57,13 +58,13 @@
@Deprecated
public class DeviceCallExecutor, RS extends KapuaResponseMessage> {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceCallFactory deviceCallFactory = KapuaLocator.getInstance().getFactory(DeviceCallFactory.class);
- private static final DeviceCallFactory DEVICE_CALL_FACTORY = LOCATOR.getFactory(DeviceCallFactory.class);
+ private final DeviceRegistryService deviceRegistryService = KapuaLocator.getInstance().getService(DeviceRegistryService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ private final TranslatorHub translatorHub = KapuaLocator.getInstance().getComponent(TranslatorHub.class);
- private static final Long DEFAULT_TIMEOUT = DeviceManagementSetting.getInstance().getLong(DeviceManagementSettingKey.REQUEST_TIMEOUT);
+ private final Long defaultTimeout = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getLong(DeviceManagementSettingKey.REQUEST_TIMEOUT);
private final RQ requestMessage;
private final Long timeout;
@@ -89,7 +90,7 @@ public DeviceCallExecutor(@NotNull RQ requestMessage) {
*/
public DeviceCallExecutor(@NotNull RQ requestMessage, @Nullable Long timeout) {
this.requestMessage = requestMessage;
- this.timeout = timeout != null ? timeout : DEFAULT_TIMEOUT;
+ this.timeout = timeout != null ? timeout : defaultTimeout;
}
/**
@@ -106,7 +107,7 @@ public RS send() throws KapuaEntityNotFoundException, DeviceNotConnectedExceptio
// Check Device existence
Device device;
try {
- device = DEVICE_REGISTRY_SERVICE.find(requestMessage.getScopeId(), requestMessage.getDeviceId());
+ device = deviceRegistryService.find(requestMessage.getScopeId(), requestMessage.getDeviceId());
} catch (KapuaException e) {
throw new DeviceManagementSendException(e, requestMessage);
}
@@ -125,8 +126,8 @@ public RS send() throws KapuaEntityNotFoundException, DeviceNotConnectedExceptio
try {
requestMessage.setSentOn(new Date());
- DeviceCall, DeviceResponseMessage, ?>> deviceCall = DEVICE_CALL_FACTORY.newDeviceCall();
- Translator> tKapuaToClient = Translator.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
+ DeviceCall, DeviceResponseMessage, ?>> deviceCall = deviceCallFactory.newDeviceCall();
+ Translator> tKapuaToClient = translatorHub.getTranslatorFor(requestMessage.getRequestClass(), deviceCall.getBaseMessageClass());
DeviceRequestMessage, ?> deviceRequestMessage = tKapuaToClient.translate(requestMessage);
// Send the request
DeviceResponseMessage, ?> responseMessage = null;
@@ -158,7 +159,7 @@ public RS send() throws KapuaEntityNotFoundException, DeviceNotConnectedExceptio
throw new DeviceManagementRequestBadMethodException(requestMessage.getChannel().getMethod());
}
// Translate the response from Device to Kapua
- Translator, RS> tClientToKapua = Translator.getTranslatorFor(deviceCall.getBaseMessageClass(), requestMessage.getResponseClass());
+ Translator, RS> tClientToKapua = translatorHub.getTranslatorFor(deviceCall.getBaseMessageClass(), requestMessage.getResponseClass());
return tClientToKapua.translate(responseMessage);
} catch (DeviceCallTimeoutException dcte) {
throw new DeviceManagementTimeoutException(dcte, timeout);
diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/setting/DeviceManagementSetting.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/setting/DeviceManagementSetting.java
index 0ed3a2d65aa..9380656dc54 100644
--- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/setting/DeviceManagementSetting.java
+++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/setting/DeviceManagementSetting.java
@@ -14,35 +14,26 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Class that offers access to device management settings
*
* @since 1.0
- *
*/
public class DeviceManagementSetting extends AbstractKapuaSetting {
/**
* Resource file from which source properties.
- *
*/
private static final String DEVICE_MANAGEMENT_SETTING_RESOURCE = "device-management-setting.properties";
- private static final DeviceManagementSetting INSTANCE = new DeviceManagementSetting();
-
/**
* Constructor
*/
- private DeviceManagementSetting() {
+ @Inject
+ public DeviceManagementSetting() {
super(DEVICE_MANAGEMENT_SETTING_RESOURCE);
}
- /**
- * Get a singleton instance of {@link DeviceManagementSetting}.
- *
- * @return
- */
- public static DeviceManagementSetting getInstance() {
- return INSTANCE;
- }
}
diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java
index 818d21eec4f..3756d7c6ae8 100644
--- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java
+++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceAssetXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceAssetFactory DEVICE_ASSET_FACTORY = LOCATOR.getFactory(DeviceAssetFactory.class);
+ private final DeviceAssetFactory deviceAssetFactory = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class);
/**
* Instantiate a new {@link DeviceAssets}.
@@ -34,7 +33,7 @@ public class DeviceAssetXmlRegistry {
* @since 1.0.0
*/
public DeviceAssets newAssetListResult() {
- return DEVICE_ASSET_FACTORY.newAssetListResult();
+ return deviceAssetFactory.newAssetListResult();
}
/**
@@ -44,7 +43,7 @@ public DeviceAssets newAssetListResult() {
* @since 1.0.0
*/
public DeviceAsset newDeviceAsset() {
- return DEVICE_ASSET_FACTORY.newDeviceAsset();
+ return deviceAssetFactory.newDeviceAsset();
}
/**
@@ -54,6 +53,6 @@ public DeviceAsset newDeviceAsset() {
* @since 1.0.0
*/
public DeviceAssetChannel newDeviceAssetChannel() {
- return DEVICE_ASSET_FACTORY.newDeviceAssetChannel();
+ return deviceAssetFactory.newDeviceAssetChannel();
}
}
diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java
index 81dbac6b272..7d81f6cff21 100644
--- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java
+++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java
@@ -27,8 +27,7 @@
*/
public class DeviceAssetChannelXmlAdapter extends XmlAdapter {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceAssetFactory DEVICE_ASSET_FACTORY = LOCATOR.getFactory(DeviceAssetFactory.class);
+ private final DeviceAssetFactory deviceAssetFactory = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class);
@Override
public XmlAdaptedDeviceAssetChannel marshal(DeviceAssetChannel deviceAssetChannel) throws Exception {
@@ -47,7 +46,7 @@ public XmlAdaptedDeviceAssetChannel marshal(DeviceAssetChannel deviceAssetChanne
@Override
public DeviceAssetChannel unmarshal(XmlAdaptedDeviceAssetChannel xmlAdaptedDeviceAssetChannel) throws Exception {
- DeviceAssetChannel adaptedDeviceAssetChannel = DEVICE_ASSET_FACTORY.newDeviceAssetChannel();
+ DeviceAssetChannel adaptedDeviceAssetChannel = deviceAssetFactory.newDeviceAssetChannel();
adaptedDeviceAssetChannel.setName(xmlAdaptedDeviceAssetChannel.getName());
adaptedDeviceAssetChannel.setType(xmlAdaptedDeviceAssetChannel.getValueType());
adaptedDeviceAssetChannel.setValue(ObjectValueConverter.fromString(xmlAdaptedDeviceAssetChannel.getValue(), adaptedDeviceAssetChannel.getType()));
diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java
index ae2a11c4302..a0ef5363703 100644
--- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java
+++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java
@@ -19,6 +19,7 @@
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory;
import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService;
import org.eclipse.kapua.service.device.management.asset.DeviceAssets;
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestChannel;
@@ -56,6 +57,7 @@ public class DeviceAssetManagementServiceImpl extends AbstractDeviceManagementTr
private static final String DEVICE_ASSETS = "deviceAssets";
private final DeviceAssetStoreService deviceAssetStoreService;
+ private final DeviceAssetFactory deviceAssetFactory;
public DeviceAssetManagementServiceImpl(
TxManager txManager,
@@ -64,7 +66,7 @@ public DeviceAssetManagementServiceImpl(
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
- DeviceAssetStoreService deviceAssetStoreService) {
+ DeviceAssetStoreService deviceAssetStoreService, DeviceAssetFactory deviceAssetFactory) {
super(txManager,
authorizationService,
permissionFactory,
@@ -72,6 +74,7 @@ public DeviceAssetManagementServiceImpl(
deviceEventFactory,
deviceRegistryService);
this.deviceAssetStoreService = deviceAssetStoreService;
+ this.deviceAssetFactory = deviceAssetFactory;
}
@Override
@@ -123,7 +126,7 @@ public DeviceAssets get(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceAs
// Create event
createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage);
// Check response
- DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets());
+ DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult()));
// Store value and return
if (deviceAssetStoreService.isServiceEnabled(scopeId) &&
deviceAssetStoreService.isApplicationEnabled(scopeId, deviceId)) {
@@ -189,7 +192,7 @@ public DeviceAssets read(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceA
// Create event
createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage);
// Check response
- DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets());
+ DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult()));
// Store value and return
if (deviceAssetStoreService.isServiceEnabled(scopeId) &&
deviceAssetStoreService.isApplicationEnabled(scopeId, deviceId)) {
@@ -255,6 +258,6 @@ public DeviceAssets write(KapuaId scopeId, KapuaId deviceId, DeviceAssets device
// Create event
createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult()));
}
}
diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java
index e102078fe7d..98b30a4773b 100644
--- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java
+++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java
@@ -39,7 +39,8 @@ DeviceAssetManagementService deviceAssetManagementService(AuthorizationService a
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
DeviceAssetStoreService deviceAssetStoreService,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceAssetFactory deviceAssetFactory) {
return new DeviceAssetManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
authorizationService,
@@ -47,7 +48,7 @@ DeviceAssetManagementService deviceAssetManagementService(AuthorizationService a
deviceEventService,
deviceEventFactory,
deviceRegistryService,
- deviceAssetStoreService
- );
+ deviceAssetStoreService,
+ deviceAssetFactory);
}
}
diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetRequestPayload.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetRequestPayload.java
index 890606147d7..f231508b54a 100644
--- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetRequestPayload.java
+++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetRequestPayload.java
@@ -15,13 +15,13 @@
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.internal.KapuaPayloadImpl;
-import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory;
import org.eclipse.kapua.service.device.management.asset.DeviceAssets;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.message.request.KapuaRequestPayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceAssets} {@link KapuaRequestPayload} implementation.
@@ -31,10 +31,7 @@
public class AssetRequestPayload extends KapuaPayloadImpl implements KapuaRequestPayload {
private static final long serialVersionUID = -4372614820336612199L;
-
- private static final DeviceAssetFactory DEVICE_ASSET_FACTORY = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class);
-
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceAssets} from the {@link #getBody()}.
@@ -43,13 +40,13 @@ public class AssetRequestPayload extends KapuaPayloadImpl implements KapuaReques
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.0.0
*/
- public DeviceAssets getDeviceAssets() throws Exception {
+ public Optional getDeviceAssets() throws Exception {
if (!hasBody()) {
- return DEVICE_ASSET_FACTORY.newAssetListResult();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceAssets.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceAssets.class));
}
/**
@@ -61,7 +58,7 @@ public DeviceAssets getDeviceAssets() throws Exception {
*/
public void setDeviceAssets(@NotNull DeviceAssets deviceAssets) throws Exception {
String bodyString = XmlUtil.marshal(deviceAssets);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetResponsePayload.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetResponsePayload.java
index 96ad3c39a5f..9645490baff 100644
--- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetResponsePayload.java
+++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/message/internal/AssetResponsePayload.java
@@ -14,7 +14,6 @@
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory;
import org.eclipse.kapua.service.device.management.asset.DeviceAssets;
import org.eclipse.kapua.service.device.management.commons.message.response.KapuaResponsePayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
@@ -22,6 +21,7 @@
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceAssets} {@link KapuaResponsePayload} implementation.
@@ -32,9 +32,7 @@ public class AssetResponsePayload extends KapuaResponsePayloadImpl implements Ka
private static final long serialVersionUID = -9087980446970521618L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceAssetFactory DEVICE_ASSET_FACTORY = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceAssets} from the {@link #getBody()}.
@@ -43,13 +41,13 @@ public class AssetResponsePayload extends KapuaResponsePayloadImpl implements Ka
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceAssets getDeviceAssets() throws Exception {
+ public Optional getDeviceAssets() throws Exception {
if (!hasBody()) {
- return DEVICE_ASSET_FACTORY.newAssetListResult();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceAssets.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.of(XmlUtil.unmarshal(bodyString, DeviceAssets.class));
}
/**
@@ -61,7 +59,7 @@ public DeviceAssets getDeviceAssets() throws Exception {
*/
public void setDeviceAssets(@NotNull DeviceAssets deviceAssets) throws Exception {
String bodyString = XmlUtil.marshal(deviceAssets);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/DeviceAssetWriteTargetProcessor.java b/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/DeviceAssetWriteTargetProcessor.java
index dc8a863c1fb..6a12e488cd1 100644
--- a/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/DeviceAssetWriteTargetProcessor.java
+++ b/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/DeviceAssetWriteTargetProcessor.java
@@ -33,11 +33,11 @@
* @since 1.0.0
*/
public class DeviceAssetWriteTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceAssetManagementService ASSET_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceAssetManagementService.class);
+ @Inject
+ DeviceAssetManagementService deviceAssetManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -52,6 +52,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
DeviceAssets assets = stepContextWrapper.getStepProperty(DeviceAssetWritePropertyKeys.ASSETS, DeviceAssets.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceAssetWritePropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> ASSET_MANAGEMENT_SERVICE.write(jobTarget.getScopeId(), jobTarget.getJobTargetId(), assets, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceAssetManagementService.write(jobTarget.getScopeId(), jobTarget.getJobTargetId(), assets, timeout));
}
}
diff --git a/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/definition/DeviceAssetWriteStepDefinition.java b/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/definition/DeviceAssetWriteStepDefinition.java
deleted file mode 100644
index 04fb2d79e95..00000000000
--- a/service/device/management/asset/job/src/main/java/org/eclipse/kapua/service/device/management/asset/job/definition/DeviceAssetWriteStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.asset.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.asset.DeviceAssets;
-import org.eclipse.kapua.service.device.management.asset.job.DeviceAssetWriteTargetProcessor;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DeviceAssetWriteStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Asset Write";
- }
-
- @Override
- public String getDescription() {
- return "Writes to an asset using the Device Asset Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DeviceAssetWriteTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyAssets = jobStepDefinitionFactory.newStepProperty(
- DeviceAssetWritePropertyKeys.ASSETS,
- DeviceAssets.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DeviceAssetWritePropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyAssets, propertyTimeout);
- }
-}
diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java
index 08227657b86..7b8055747a8 100644
--- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java
+++ b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java
@@ -20,6 +20,7 @@
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory;
import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService;
import org.eclipse.kapua.service.device.management.bundle.DeviceBundles;
import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleRequestChannel;
@@ -52,18 +53,21 @@ public class DeviceBundleManagementServiceImpl extends AbstractDeviceManagementT
private static final String SCOPE_ID = "scopeId";
private static final String DEVICE_ID = "deviceId";
+ private final DeviceBundleFactory deviceBundleFactory;
+
public DeviceBundleManagementServiceImpl(TxManager txManager,
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
- DeviceRegistryService deviceRegistryService) {
+ DeviceRegistryService deviceRegistryService, DeviceBundleFactory deviceBundleFactory) {
super(txManager,
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
deviceRegistryService);
+ this.deviceBundleFactory = deviceBundleFactory;
}
@Override
@@ -109,7 +113,7 @@ public DeviceBundles get(KapuaId scopeId, KapuaId deviceId, Long timeout)
// Create event
createDeviceEvent(scopeId, deviceId, bundleRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceBundles());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceBundles().orElse(deviceBundleFactory.newBundleListResult()));
}
@Override
diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java
index 4e0fceadfc2..9afc230f641 100644
--- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java
+++ b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java
@@ -50,14 +50,15 @@ DeviceBundleManagementService deviceBundleManagementService(
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceBundleFactory deviceBundleFactory) {
return new DeviceBundleManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
- deviceRegistryService
- );
+ deviceRegistryService,
+ deviceBundleFactory);
}
}
diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/message/internal/BundleResponsePayload.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/message/internal/BundleResponsePayload.java
index c8c9f1931fb..dc35a7bf89a 100644
--- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/message/internal/BundleResponsePayload.java
+++ b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/message/internal/BundleResponsePayload.java
@@ -15,7 +15,6 @@
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.management.bundle.DeviceBundle;
-import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory;
import org.eclipse.kapua.service.device.management.bundle.DeviceBundles;
import org.eclipse.kapua.service.device.management.commons.message.response.KapuaResponsePayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
@@ -23,6 +22,7 @@
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceBundle} {@link KapuaResponsePayload} implementation.
@@ -33,9 +33,7 @@ public class BundleResponsePayload extends KapuaResponsePayloadImpl implements K
private static final long serialVersionUID = 4380715272822080425L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceBundleFactory DEVICE_BUNDLE_FACTORY = KapuaLocator.getInstance().getFactory(DeviceBundleFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceBundles} from the {@link #getBody()}.
@@ -44,13 +42,13 @@ public class BundleResponsePayload extends KapuaResponsePayloadImpl implements K
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceBundles getDeviceBundles() throws Exception {
+ public Optional getDeviceBundles() throws Exception {
if (!hasBody()) {
- return DEVICE_BUNDLE_FACTORY.newBundleListResult();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceBundles.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceBundles.class));
}
/**
@@ -62,6 +60,6 @@ public DeviceBundles getDeviceBundles() throws Exception {
*/
public void setDeviceBundles(@NotNull DeviceBundles deviceBundles) throws Exception {
String bodyString = XmlUtil.marshal(deviceBundles);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStartTargetProcessor.java b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStartTargetProcessor.java
index 7782e7c7f6f..770a34c09f0 100644
--- a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStartTargetProcessor.java
+++ b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStartTargetProcessor.java
@@ -16,7 +16,6 @@
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.job.engine.commons.operation.AbstractDeviceTargetProcessor;
import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService;
import org.eclipse.kapua.service.device.management.bundle.job.definition.DeviceBundlePropertyKeys;
@@ -33,12 +32,11 @@
* @since 1.0.0
*/
public class DeviceBundleStartTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceBundleManagementService BUNDLE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceBundleManagementService.class);
+ @Inject
+ DeviceBundleManagementService deviceBundleManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -53,6 +51,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
String bundleId = stepContextWrapper.getStepProperty(DeviceBundlePropertyKeys.BUNDLE_ID, String.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceBundlePropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> BUNDLE_MANAGEMENT_SERVICE.start(jobTarget.getScopeId(), jobTarget.getJobTargetId(), bundleId, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceBundleManagementService.start(jobTarget.getScopeId(), jobTarget.getJobTargetId(), bundleId, timeout));
}
}
diff --git a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStopTargetProcessor.java b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStopTargetProcessor.java
index 7984b87f53f..ab4f6583e3c 100644
--- a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStopTargetProcessor.java
+++ b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/DeviceBundleStopTargetProcessor.java
@@ -32,11 +32,11 @@
* @since 1.0.0
*/
public class DeviceBundleStopTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceBundleManagementService BUNDLE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceBundleManagementService.class);
+ @Inject
+ DeviceBundleManagementService deviceBundleManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -51,6 +51,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
String bundleId = stepContextWrapper.getStepProperty(DeviceBundlePropertyKeys.BUNDLE_ID, String.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceBundlePropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> BUNDLE_MANAGEMENT_SERVICE.stop(jobTarget.getScopeId(), jobTarget.getJobTargetId(), bundleId, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceBundleManagementService.stop(jobTarget.getScopeId(), jobTarget.getJobTargetId(), bundleId, timeout));
}
}
diff --git a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStartStepDefinition.java b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStartStepDefinition.java
deleted file mode 100644
index 0b9c1156e89..00000000000
--- a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStartStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.bundle.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.bundle.job.DeviceBundleStartTargetProcessor;
-import org.eclipse.kapua.service.device.management.bundle.job.definition.DeviceBundlePropertyKeys;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DeviceBundleStartStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Bundle Start";
- }
-
- @Override
- public String getDescription() {
- return "Starts a bundle using the Device Bundle Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DeviceBundleStartTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyBundleId = jobStepDefinitionFactory.newStepProperty(
- DeviceBundlePropertyKeys.BUNDLE_ID,
- String.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DeviceBundlePropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyBundleId, propertyTimeout);
- }
-}
diff --git a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStopStepDefinition.java b/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStopStepDefinition.java
deleted file mode 100644
index c6f8d37df44..00000000000
--- a/service/device/management/bundle/job/src/main/java/org/eclipse/kapua/service/device/management/bundle/job/definition/DeviceBundleStopStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.bundle.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.bundle.job.DeviceBundleStopTargetProcessor;
-import org.eclipse.kapua.service.device.management.bundle.job.definition.DeviceBundlePropertyKeys;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DeviceBundleStopStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Bundle Stop";
- }
-
- @Override
- public String getDescription() {
- return "Stops a bundle using the Device Bundle Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DeviceBundleStopTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyBundleId = jobStepDefinitionFactory.newStepProperty(
- DeviceBundlePropertyKeys.BUNDLE_ID,
- String.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DeviceBundlePropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyBundleId, propertyTimeout);
- }
-}
diff --git a/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/DeviceCommandExecTargetProcessor.java b/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/DeviceCommandExecTargetProcessor.java
index 8d4764797a6..6e2cf365e6d 100644
--- a/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/DeviceCommandExecTargetProcessor.java
+++ b/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/DeviceCommandExecTargetProcessor.java
@@ -33,11 +33,10 @@
* @since 1.0.0
*/
public class DeviceCommandExecTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceCommandManagementService COMMAND_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceCommandManagementService.class);
-
+ @Inject
+ DeviceCommandManagementService deviceCommandManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -52,6 +51,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
DeviceCommandInput commandInput = stepContextWrapper.getStepProperty(DeviceCommandExecPropertyKeys.COMMAND_INPUT, DeviceCommandInput.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceCommandExecPropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> COMMAND_MANAGEMENT_SERVICE.exec(jobTarget.getScopeId(), jobTarget.getJobTargetId(), commandInput, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceCommandManagementService.exec(jobTarget.getScopeId(), jobTarget.getJobTargetId(), commandInput, timeout));
}
}
diff --git a/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/definition/DeviceCommandExecStepDefinition.java b/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/definition/DeviceCommandExecStepDefinition.java
deleted file mode 100644
index 003722996fb..00000000000
--- a/service/device/management/command/job/src/main/java/org/eclipse/kapua/service/device/management/command/job/definition/DeviceCommandExecStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.command.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.command.DeviceCommandInput;
-import org.eclipse.kapua.service.device.management.command.job.DeviceCommandExecTargetProcessor;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DeviceCommandExecStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Command Execution";
- }
-
- @Override
- public String getDescription() {
- return "Execution of a command using the Device Command Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DeviceCommandExecTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyCommandInput = jobStepDefinitionFactory.newStepProperty(
- DeviceCommandExecPropertyKeys.COMMAND_INPUT,
- DeviceCommandInput.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DeviceCommandExecPropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyCommandInput, propertyTimeout);
- }
-}
diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java
index 08624f9452d..df4f1d70f80 100644
--- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java
+++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceConfigurationXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = LOCATOR.getFactory(DeviceConfigurationFactory.class);
+ private final DeviceConfigurationFactory deviceConfigurationFactory = KapuaLocator.getInstance().getFactory(DeviceConfigurationFactory.class);
/**
* Creates a new device configuration
@@ -33,7 +32,7 @@ public class DeviceConfigurationXmlRegistry {
* @return
*/
public DeviceConfiguration newConfiguration() {
- return DEVICE_CONFIGURATION_FACTORY.newConfigurationInstance();
+ return deviceConfigurationFactory.newConfigurationInstance();
}
/**
@@ -42,6 +41,6 @@ public DeviceConfiguration newConfiguration() {
* @return
*/
public DeviceComponentConfiguration newComponentConfiguration() {
- return DEVICE_CONFIGURATION_FACTORY.newComponentConfigurationInstance(null);
+ return deviceConfigurationFactory.newComponentConfigurationInstance(null);
}
}
diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertiesAdapter.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertiesAdapter.java
index 990793a141d..e73c118a9db 100644
--- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertiesAdapter.java
+++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertiesAdapter.java
@@ -12,14 +12,24 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.management.configuration;
-import org.eclipse.kapua.commons.configuration.metatype.Password;
+import org.eclipse.kapua.commons.configuration.metatype.PasswordPropertyAdapter;
import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.locator.KapuaLocator;
+import org.eclipse.kapua.model.xml.adapters.BooleanPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.BytePropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.CharPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.DoublePropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.FloatPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.IntegerPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.LongPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.ShortPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.StringPropertyAdapter;
+import org.eclipse.kapua.model.xml.adapters.XmlPropertiesAdapter;
+import org.eclipse.kapua.model.xml.adapters.XmlPropertyAdapter;
import org.eclipse.kapua.service.device.management.configuration.DeviceXmlConfigPropertyAdapted.ConfigPropertyType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
-import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
/**
@@ -29,320 +39,33 @@
*/
public class DeviceXmlConfigPropertiesAdapter extends XmlAdapter> {
- @Override
- public DeviceXmlConfigPropertiesAdapted marshal(Map props) {
- List adaptedValues = new ArrayList<>();
-
- if (props != null) {
- props.forEach((name, value) -> {
-
- DeviceXmlConfigPropertyAdapted adaptedValue = new DeviceXmlConfigPropertyAdapted();
- adaptedValue.setName(name);
-
- if (value instanceof String) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.stringType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Long) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.longType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Double) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.doubleType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Float) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.floatType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Integer) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.integerType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Byte) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.byteType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Character) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.charType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Boolean) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.booleanType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Short) {
- adaptedValue.setArray(false);
- adaptedValue.setType(ConfigPropertyType.shortType);
- adaptedValue.setValues(new String[]{value.toString()});
- } else if (value instanceof Password) {
- adaptedValue.setArray(false);
- adaptedValue.setEncrypted(true);
- adaptedValue.setType(ConfigPropertyType.passwordType);
- adaptedValue.setValues(new String[]{CryptoUtil.encodeBase64(value.toString())});
- } else if (value instanceof String[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.stringType);
- adaptedValue.setValues((String[]) value);
- } else if (value instanceof Long[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.longType);
- Long[] nativeValues = (Long[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Double[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.doubleType);
- Double[] nativeValues = (Double[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Float[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.floatType);
- Float[] nativeValues = (Float[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Integer[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.integerType);
- Integer[] nativeValues = (Integer[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Byte[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.byteType);
- Byte[] nativeValues = (Byte[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Character[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.charType);
- Character[] nativeValues = (Character[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Boolean[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.booleanType);
- Boolean[] nativeValues = (Boolean[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Short[]) {
- adaptedValue.setArray(true);
- adaptedValue.setType(ConfigPropertyType.shortType);
- Short[] nativeValues = (Short[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = nativeValues[i].toString();
- }
- }
- adaptedValue.setValues(stringValues);
- } else if (value instanceof Password[]) {
- adaptedValue.setArray(true);
- adaptedValue.setEncrypted(true);
- adaptedValue.setType(ConfigPropertyType.passwordType);
- Password[] nativeValues = (Password[]) value;
- String[] stringValues = new String[nativeValues.length];
- for (int i = 0; i < nativeValues.length; i++) {
- if (nativeValues[i] != null) {
- stringValues[i] = CryptoUtil.encodeBase64(nativeValues[i].toString());
- }
- }
- adaptedValue.setValues(stringValues);
- }
-
- adaptedValues.add(adaptedValue);
- });
+ private XmlPropertiesAdapter adapter = new XmlPropertiesAdapter<>(DeviceXmlConfigPropertyAdapted.class, () -> new DeviceXmlConfigPropertyAdapted(), new HashMap() {
+ {
+ put(ConfigPropertyType.stringType, new StringPropertyAdapter());
+ put(ConfigPropertyType.longType, new LongPropertyAdapter());
+ put(ConfigPropertyType.doubleType, new DoublePropertyAdapter());
+ put(ConfigPropertyType.floatType, new FloatPropertyAdapter());
+ put(ConfigPropertyType.integerType, new IntegerPropertyAdapter());
+ put(ConfigPropertyType.byteType, new BytePropertyAdapter());
+ put(ConfigPropertyType.charType, new CharPropertyAdapter());
+ put(ConfigPropertyType.booleanType, new BooleanPropertyAdapter());
+ put(ConfigPropertyType.shortType, new ShortPropertyAdapter());
+ put(ConfigPropertyType.passwordType, new PasswordPropertyAdapter(KapuaLocator.getInstance().getComponent(CryptoUtil.class)));
}
+ });
- DeviceXmlConfigPropertiesAdapted result = new DeviceXmlConfigPropertiesAdapted();
- result.setProperties(adaptedValues.toArray(new DeviceXmlConfigPropertyAdapted[]{}));
- return result;
+ public DeviceXmlConfigPropertiesAdapter() {
}
@Override
- public Map unmarshal(DeviceXmlConfigPropertiesAdapted adaptedPropsAdapted) {
- DeviceXmlConfigPropertyAdapted[] adaptedProps = adaptedPropsAdapted.getProperties();
- if (adaptedProps == null) {
- return new HashMap<>();
- }
-
- Map properties = new HashMap<>();
- for (DeviceXmlConfigPropertyAdapted adaptedProp : adaptedProps) {
- String propName = adaptedProp.getName();
- ConfigPropertyType type = adaptedProp.getType();
- if (type != null) {
- Object propValue = null;
- if (!adaptedProp.getArray()) {
- switch (adaptedProp.getType()) {
- case stringType:
- propValue = adaptedProp.getValues()[0];
- break;
- case longType:
- propValue = Long.parseLong(adaptedProp.getValues()[0]);
- break;
- case doubleType:
- propValue = Double.parseDouble(adaptedProp.getValues()[0]);
- break;
- case floatType:
- propValue = Float.parseFloat(adaptedProp.getValues()[0]);
- break;
- case integerType:
- propValue = Integer.parseInt(adaptedProp.getValues()[0]);
- break;
- case byteType:
- propValue = Byte.parseByte(adaptedProp.getValues()[0]);
- break;
- case charType:
- String s = adaptedProp.getValues()[0];
- propValue = s.charAt(0);
- break;
- case booleanType:
- propValue = Boolean.parseBoolean(adaptedProp.getValues()[0]);
- break;
- case shortType:
- propValue = Short.parseShort(adaptedProp.getValues()[0]);
- break;
- case passwordType:
- propValue = adaptedProp.getValues()[0];
- propValue =
- adaptedProp.isEncrypted() ?
- new Password(CryptoUtil.decodeBase64((String) propValue)) :
- new Password((String) propValue);
-
- break;
- }
- } else {
- switch (adaptedProp.getType()) {
- case stringType:
- propValue = adaptedProp.getValues();
- break;
- case longType:
- Long[] longValues = new Long[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- longValues[i] = Long.parseLong(adaptedProp.getValues()[i]);
- }
- }
- propValue = longValues;
- break;
- case doubleType:
- Double[] doubleValues = new Double[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- doubleValues[i] = Double.parseDouble(adaptedProp.getValues()[i]);
- }
- }
- propValue = doubleValues;
- break;
- case floatType:
- Float[] floatValues = new Float[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- floatValues[i] = Float.parseFloat(adaptedProp.getValues()[i]);
- }
- }
- propValue = floatValues;
- break;
- case integerType:
- Integer[] intValues = new Integer[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- intValues[i] = Integer.parseInt(adaptedProp.getValues()[i]);
- }
- }
- propValue = intValues;
- break;
- case byteType:
- Byte[] byteValues = new Byte[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- byteValues[i] = Byte.parseByte(adaptedProp.getValues()[i]);
- }
- }
- propValue = byteValues;
- break;
- case charType:
- Character[] charValues = new Character[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- String s = adaptedProp.getValues()[i];
- charValues[i] = s.charAt(0);
- }
- }
- propValue = charValues;
- break;
- case booleanType:
- Boolean[] booleanValues = new Boolean[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- booleanValues[i] = Boolean.parseBoolean(adaptedProp.getValues()[i]);
- }
- }
- propValue = booleanValues;
- break;
- case shortType:
- Short[] shortValues = new Short[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- shortValues[i] = Short.parseShort(adaptedProp.getValues()[i]);
- }
- }
- propValue = shortValues;
- break;
- case passwordType:
- Password[] pwdValues = new Password[adaptedProp.getValues().length];
- for (int i = 0; i < adaptedProp.getValues().length; i++) {
- if (adaptedProp.getValues()[i] != null) {
- pwdValues[i] =
- adaptedProp.isEncrypted() ?
- new Password(CryptoUtil.decodeBase64(adaptedProp.getValues()[i])) :
- new Password(adaptedProp.getValues()[i]);
- }
- }
+ public Map unmarshal(DeviceXmlConfigPropertiesAdapted v) throws Exception {
+ return adapter.unmarshal(v.getProperties());
+ }
- propValue = pwdValues;
- break;
- }
- }
- properties.put(propName, propValue);
- }
- }
- return properties;
+ @Override
+ public DeviceXmlConfigPropertiesAdapted marshal(Map v) throws Exception {
+ final DeviceXmlConfigPropertiesAdapted res = new DeviceXmlConfigPropertiesAdapted();
+ res.setProperties(adapter.marshal(v));
+ return res;
}
}
diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertyAdapted.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertyAdapted.java
index 8c34ca911e4..6d02287541a 100644
--- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertyAdapted.java
+++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceXmlConfigPropertyAdapted.java
@@ -12,6 +12,8 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.management.configuration;
+import org.eclipse.kapua.model.xml.XmlPropertyAdapted;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@@ -27,20 +29,34 @@
* @since 1.0
*/
@XmlAccessorType(XmlAccessType.FIELD)
-public class DeviceXmlConfigPropertyAdapted {
+public class DeviceXmlConfigPropertyAdapted implements XmlPropertyAdapted {
@XmlEnum
public enum ConfigPropertyType {
- @XmlEnumValue("String")stringType,
- @XmlEnumValue("Long")longType,
- @XmlEnumValue("Double")doubleType,
- @XmlEnumValue("Float")floatType,
- @XmlEnumValue("Integer")integerType,
- @XmlEnumValue("Byte")byteType,
- @XmlEnumValue("Char")charType,
- @XmlEnumValue("Boolean")booleanType,
- @XmlEnumValue("Short")shortType,
- @XmlEnumValue("Password")passwordType
+ @XmlEnumValue("String") stringType,
+ @XmlEnumValue("Long") longType,
+ @XmlEnumValue("Double") doubleType,
+ @XmlEnumValue("Float") floatType,
+ @XmlEnumValue("Integer") integerType,
+ @XmlEnumValue("Byte") byteType,
+ @XmlEnumValue("Char") charType,
+ @XmlEnumValue("Boolean") booleanType,
+ @XmlEnumValue("Short") shortType,
+ @XmlEnumValue("Password") passwordType
+ }
+
+ public DeviceXmlConfigPropertyAdapted() {
+ }
+
+ public DeviceXmlConfigPropertyAdapted(String name,
+ ConfigPropertyType type,
+ String... values) {
+ super();
+ this.name = name;
+ this.type = type;
+ this.encrypted = false;
+ this.array = values != null && values.length > 1;
+ this.values = values;
}
/**
@@ -73,19 +89,6 @@ public enum ConfigPropertyType {
@XmlElement(name = "value")
private String[] values;
- public DeviceXmlConfigPropertyAdapted() {
- }
-
- public DeviceXmlConfigPropertyAdapted(String name,
- ConfigPropertyType type,
- String[] values) {
- super();
-
- this.type = type;
- this.values = values;
- this.encrypted = false;
- }
-
public String getName() {
return name;
}
diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/snapshot/DeviceSnapshotXmlRegistry.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/snapshot/DeviceSnapshotXmlRegistry.java
index f9e96358849..0fafdc1349d 100644
--- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/snapshot/DeviceSnapshotXmlRegistry.java
+++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/snapshot/DeviceSnapshotXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceSnapshotXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceSnapshotFactory DEVICE_SNAPSHOT_FACTORY = LOCATOR.getFactory(DeviceSnapshotFactory.class);
+ private final DeviceSnapshotFactory deviceSnapshotFactory = KapuaLocator.getInstance().getFactory(DeviceSnapshotFactory.class);
/**
* Creates a new device snapshots list
@@ -33,7 +32,7 @@ public class DeviceSnapshotXmlRegistry {
* @return
*/
public DeviceSnapshots newDeviceSnapshots() {
- return DEVICE_SNAPSHOT_FACTORY.newDeviceSnapshots();
+ return deviceSnapshotFactory.newDeviceSnapshots();
}
/**
@@ -42,6 +41,6 @@ public DeviceSnapshots newDeviceSnapshots() {
* @return
*/
public DeviceSnapshot newDeviceSnapshot() {
- return DEVICE_SNAPSHOT_FACTORY.newDeviceSnapshot();
+ return deviceSnapshotFactory.newDeviceSnapshot();
}
}
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java
index 2abf557a612..f823b9aa4c9 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java
@@ -57,7 +57,6 @@
public class DeviceConfigurationManagementServiceImpl extends AbstractDeviceManagementTransactionalServiceImpl implements DeviceConfigurationManagementService {
private static final Logger LOG = LoggerFactory.getLogger(DeviceConfigurationManagementServiceImpl.class);
-
private final DeviceConfigurationFactory deviceConfigurationFactory;
private static final String SCOPE_ID = "scopeId";
@@ -129,7 +128,7 @@ public DeviceConfiguration get(KapuaId scopeId, KapuaId deviceId, String configu
// Create event
createDeviceEvent(scopeId, deviceId, configurationRequestMessage, responseMessage);
// Check response
- DeviceConfiguration onlineDeviceConfiguration = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceConfigurations());
+ DeviceConfiguration onlineDeviceConfiguration = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceConfigurations().orElse(deviceConfigurationFactory.newConfigurationInstance()));
// Store config and return
if (deviceConfigurationStoreService.isServiceEnabled(scopeId) &&
deviceConfigurationStoreService.isApplicationEnabled(scopeId, deviceId)) {
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java
index e65cc39e82b..7d178049b61 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java
@@ -19,17 +19,20 @@
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationManagementService;
+import org.eclipse.kapua.service.device.management.configuration.internal.settings.DeviceConfigurationManagementSettings;
import org.eclipse.kapua.service.device.management.configuration.store.DeviceConfigurationStoreService;
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory;
import org.eclipse.kapua.service.device.registry.event.DeviceEventService;
import javax.inject.Inject;
+import javax.inject.Singleton;
public class DeviceManagementConfigurationModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(DeviceConfigurationFactory.class).to(DeviceConfigurationFactoryImpl.class);
+ bind(DeviceConfigurationFactory.class).to(DeviceConfigurationFactoryImpl.class).in(Singleton.class);
+ bind(DeviceConfigurationManagementSettings.class).in(Singleton.class);
}
@Provides
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/settings/DeviceConfigurationManagementSettings.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/settings/DeviceConfigurationManagementSettings.java
index 071949917bf..21a8290c9ed 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/settings/DeviceConfigurationManagementSettings.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/settings/DeviceConfigurationManagementSettings.java
@@ -16,6 +16,8 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationManagementService;
+import javax.inject.Inject;
+
/**
* {@link DeviceConfigurationManagementService} {@link AbstractBaseKapuaSetting}s
*
@@ -25,23 +27,13 @@ public class DeviceConfigurationManagementSettings extends AbstractKapuaSetting<
private static final String DEVICE_CONFIGURATION_MANAGEMENT_SETTING_RESOURCE = "device-configuration-management-setting.properties";
- private static final DeviceConfigurationManagementSettings INSTANCE = new DeviceConfigurationManagementSettings();
-
/**
* Constructor.
- * @since 2.0.0
- */
- private DeviceConfigurationManagementSettings() {
- super(DEVICE_CONFIGURATION_MANAGEMENT_SETTING_RESOURCE);
- }
-
- /**
- * Gets the instance of {@link DeviceConfigurationManagementSettings}.
*
- * @return The instance of {@link DeviceConfigurationManagementSettings}.
* @since 2.0.0
*/
- public static DeviceConfigurationManagementSettings getInstance() {
- return INSTANCE;
+ @Inject
+ public DeviceConfigurationManagementSettings() {
+ super(DEVICE_CONFIGURATION_MANAGEMENT_SETTING_RESOURCE);
}
}
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/internal/DeviceConfigurationEventPayloadImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/internal/DeviceConfigurationEventPayloadImpl.java
index ffa59633198..2d5db633fe2 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/internal/DeviceConfigurationEventPayloadImpl.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/internal/DeviceConfigurationEventPayloadImpl.java
@@ -19,10 +19,8 @@
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
-import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.configuration.message.event.DeviceConfigurationEventPayload;
-import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
@@ -35,9 +33,7 @@ public class DeviceConfigurationEventPayloadImpl extends KapuaEventPayloadImpl i
private static final long serialVersionUID = 1400605735748313538L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = KapuaLocator.getInstance().getFactory(DeviceConfigurationFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
@Override
public List getDeviceComponentConfigurations() throws Exception {
@@ -45,16 +41,13 @@ public List getDeviceComponentConfigurations() thr
return Collections.emptyList();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
+ String bodyString = new String(getBody(), charEncoding);
return XmlUtil.unmarshal(bodyString, DeviceConfiguration.class).getComponentConfigurations();
}
@Override
- public void setDeviceComponentConfigurations(@NotNull List deviceComponentConfigurations) throws Exception {
- DeviceConfiguration deviceConfiguration = DEVICE_CONFIGURATION_FACTORY.newConfigurationInstance();
- deviceConfiguration.setComponentConfigurations(deviceComponentConfigurations);
-
+ public void setDeviceComponentConfigurations(DeviceConfiguration deviceConfiguration) throws Exception {
String bodyString = XmlUtil.marshal(deviceConfiguration);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationRequestPayload.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationRequestPayload.java
index f3e10b2eeca..bbc13cd8bf5 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationRequestPayload.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationRequestPayload.java
@@ -18,10 +18,10 @@
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
-import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.message.request.KapuaRequestPayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceConfiguration} {@link KapuaRequestPayload} implementation.
@@ -32,9 +32,7 @@ public class ConfigurationRequestPayload extends KapuaPayloadImpl implements Kap
private static final long serialVersionUID = 1400605735748313538L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = KapuaLocator.getInstance().getFactory(DeviceConfigurationFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceConfiguration}from the {@link #getBody()}.
@@ -43,13 +41,13 @@ public class ConfigurationRequestPayload extends KapuaPayloadImpl implements Kap
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceConfiguration getDeviceConfigurations() throws Exception {
+ public Optional getDeviceConfigurations() throws Exception {
if (!hasBody()) {
- return DEVICE_CONFIGURATION_FACTORY.newConfigurationInstance();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceConfiguration.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceConfiguration.class));
}
/**
@@ -61,6 +59,6 @@ public DeviceConfiguration getDeviceConfigurations() throws Exception {
*/
public void setDeviceConfigurations(@NotNull DeviceConfiguration deviceConfiguration) throws Exception {
String bodyString = XmlUtil.marshal(deviceConfiguration);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationResponsePayload.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationResponsePayload.java
index 6cab4ed9ad2..f77b6943240 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationResponsePayload.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/internal/ConfigurationResponsePayload.java
@@ -20,7 +20,6 @@
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
-import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.configuration.internal.settings.DeviceConfigurationManagementSettings;
import org.eclipse.kapua.service.device.management.configuration.internal.settings.DeviceConfigurationManagementSettingsKeys;
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
@@ -28,6 +27,7 @@
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
import java.util.stream.Collectors;
/**
@@ -39,10 +39,9 @@ public class ConfigurationResponsePayload extends KapuaResponsePayloadImpl imple
private static final Logger LOG = LoggerFactory.getLogger(ConfigurationResponsePayload.class);
- private static final String PAYLOAD_TO_DISPLAY_STRING_MODE = DeviceConfigurationManagementSettings.getInstance().getString(DeviceConfigurationManagementSettingsKeys.PAYLOAD_TO_DISPLAY_STRING_MODE, "NONE");
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = KapuaLocator.getInstance().getFactory(DeviceConfigurationFactory.class);
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
+ private final String payloadToDisplayStringMode = KapuaLocator.getInstance().getComponent(DeviceConfigurationManagementSettings.class).getString(DeviceConfigurationManagementSettingsKeys.PAYLOAD_TO_DISPLAY_STRING_MODE, "NONE");
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceConfiguration}from the {@link #getBody()}.
@@ -51,13 +50,13 @@ public class ConfigurationResponsePayload extends KapuaResponsePayloadImpl imple
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceConfiguration getDeviceConfigurations() throws Exception {
+ public Optional getDeviceConfigurations() throws Exception {
if (!hasBody()) {
- return DEVICE_CONFIGURATION_FACTORY.newConfigurationInstance();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceConfiguration.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceConfiguration.class));
}
/**
@@ -69,7 +68,7 @@ public DeviceConfiguration getDeviceConfigurations() throws Exception {
*/
public void setDeviceConfigurations(@NotNull DeviceConfiguration deviceConfiguration) throws Exception {
String bodyString = XmlUtil.marshal(deviceConfiguration);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
@Override
@@ -77,9 +76,9 @@ public String toDisplayString() {
try {
PayloadToDisplayStringMode toDisplayStringMode;
try {
- toDisplayStringMode = PayloadToDisplayStringMode.valueOf(PAYLOAD_TO_DISPLAY_STRING_MODE);
+ toDisplayStringMode = PayloadToDisplayStringMode.valueOf(payloadToDisplayStringMode);
} catch (IllegalArgumentException iae) {
- LOG.warn("Invalid device.management.configuration.payload.toDisplayString.mode setting value {}. Please fix the configuration value. Allowed values are: NONE, DEFAULT, NUMBER_OF_COMPONENTS, LIST_OF_COMPONENTS. Defaulting to DEFAULT", PAYLOAD_TO_DISPLAY_STRING_MODE);
+ LOG.warn("Invalid device.management.configuration.payload.toDisplayString.mode setting value {}. Please fix the configuration value. Allowed values are: NONE, DEFAULT, NUMBER_OF_COMPONENTS, LIST_OF_COMPONENTS. Defaulting to DEFAULT", payloadToDisplayStringMode);
toDisplayStringMode = PayloadToDisplayStringMode.DEFAULT;
}
@@ -89,9 +88,10 @@ public String toDisplayString() {
case DEFAULT:
return super.toDisplayString();
case NUMBER_OF_COMPONENTS:
- return "Read " + getDeviceConfigurations().getComponentConfigurations().size() + " configuration components: " + getDeviceConfigurations().getComponentConfigurations().stream().map(DeviceComponentConfiguration::getId).sorted(String::compareTo).collect(Collectors.joining(", "));
+ return "Read " + getDeviceConfigurations().map(p -> p.getComponentConfigurations().size()).orElse(0) + " configuration components: " + getDeviceConfigurations()
+ .map(dc -> dc.getComponentConfigurations().stream().map(DeviceComponentConfiguration::getId).sorted(String::compareTo).collect(Collectors.joining(", "))).orElse("");
case LIST_OF_COMPONENTS:
- return "Read configuration components: " + getDeviceConfigurations().getComponentConfigurations().stream().map(DeviceComponentConfiguration::getId).sorted(String::compareTo).collect(Collectors.joining(", "));
+ return "Read configuration components: " + getDeviceConfigurations().map(dc -> dc.getComponentConfigurations().stream().map(DeviceComponentConfiguration::getId).sorted(String::compareTo).collect(Collectors.joining(", "))).orElse("");
}
} catch (Exception e) {
LOG.warn("Error while invoking ConfigurationResponsePayload.toDisplayString(). Defaulting to KapuaResponsePayload.toDisplayString(). Error: {}", e.getMessage());
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java
index 1c4247e3e9f..da4d6252c4b 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java
@@ -39,15 +39,16 @@ DeviceSnapshotManagementService deviceSnapshotManagementService(
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceSnapshotFactory deviceSnapshotFactory) {
return new DeviceSnapshotManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
- deviceRegistryService
- );
+ deviceRegistryService,
+ deviceSnapshotFactory);
}
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java
index 22b86aadd05..61c84ec95bc 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java
@@ -24,6 +24,7 @@
import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationAppProperties;
import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationManagementServiceImpl;
import org.eclipse.kapua.service.device.management.message.KapuaMethod;
+import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotManagementService;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshots;
import org.eclipse.kapua.service.device.management.snapshot.message.internal.SnapshotRequestChannel;
@@ -37,6 +38,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Date;
@@ -47,19 +49,24 @@
*/
@Singleton
public class DeviceSnapshotManagementServiceImpl extends AbstractDeviceManagementTransactionalServiceImpl implements DeviceSnapshotManagementService {
+
+ private final DeviceSnapshotFactory deviceSnapshotFactory;
+
+ @Inject
public DeviceSnapshotManagementServiceImpl(
TxManager txManager,
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
- DeviceRegistryService deviceRegistryService) {
+ DeviceRegistryService deviceRegistryService, DeviceSnapshotFactory deviceSnapshotFactory) {
super(txManager,
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
deviceRegistryService);
+ this.deviceSnapshotFactory = deviceSnapshotFactory;
}
private static final Logger LOG = LoggerFactory.getLogger(DeviceConfigurationManagementServiceImpl.class);
@@ -106,7 +113,7 @@ public DeviceSnapshots get(KapuaId scopeId, KapuaId deviceId, Long timeout)
// Create event
createDeviceEvent(scopeId, deviceId, snapshotRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceSnapshots());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceSnapshots().orElse(deviceSnapshotFactory.newDeviceSnapshots()));
}
@Override
diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/message/internal/SnapshotResponsePayload.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/message/internal/SnapshotResponsePayload.java
index 3cde044f481..0ec6af1c21a 100644
--- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/message/internal/SnapshotResponsePayload.java
+++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/message/internal/SnapshotResponsePayload.java
@@ -18,10 +18,10 @@
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
-import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshots;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceSnapshots} {@link KapuaResponsePayload} implementation.
@@ -32,9 +32,7 @@ public class SnapshotResponsePayload extends KapuaResponsePayloadImpl implements
private static final long serialVersionUID = -5650474443429208877L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceSnapshotFactory DEVICE_SNAPSHOT_FACTORY = KapuaLocator.getInstance().getFactory(DeviceSnapshotFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceSnapshots} from the {@link #getBody()}.
@@ -43,13 +41,13 @@ public class SnapshotResponsePayload extends KapuaResponsePayloadImpl implements
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceSnapshots getDeviceSnapshots() throws Exception {
+ public Optional getDeviceSnapshots() throws Exception {
if (!hasBody()) {
- return DEVICE_SNAPSHOT_FACTORY.newDeviceSnapshots();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceSnapshots.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceSnapshots.class));
}
/**
@@ -61,7 +59,7 @@ public DeviceSnapshots getDeviceSnapshots() throws Exception {
*/
public void setDeviceSnapshots(@NotNull DeviceSnapshots devicePackages) throws Exception {
String bodyString = XmlUtil.marshal(devicePackages);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/DeviceConfigurationPutTargetProcessor.java b/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/DeviceConfigurationPutTargetProcessor.java
index 454e067c252..44c085d8244 100644
--- a/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/DeviceConfigurationPutTargetProcessor.java
+++ b/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/DeviceConfigurationPutTargetProcessor.java
@@ -33,11 +33,11 @@
* @since 1.0.0
*/
public class DeviceConfigurationPutTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceConfigurationManagementService CONFIGURATION_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceConfigurationManagementService.class);
+ @Inject
+ DeviceConfigurationManagementService deviceConfigurationManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -52,6 +52,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
DeviceConfiguration configuration = stepContextWrapper.getStepProperty(DeviceConfigurationPutPropertyKeys.CONFIGURATION, DeviceConfiguration.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceConfigurationPutPropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> CONFIGURATION_MANAGEMENT_SERVICE.put(jobTarget.getScopeId(), jobTarget.getJobTargetId(), configuration, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceConfigurationManagementService.put(jobTarget.getScopeId(), jobTarget.getJobTargetId(), configuration, timeout));
}
}
diff --git a/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/definition/DeviceConfigurationPutStepDefinition.java b/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/definition/DeviceConfigurationPutStepDefinition.java
deleted file mode 100644
index 6054fa16cc0..00000000000
--- a/service/device/management/configuration/job/src/main/java/org/eclipse/kapua/service/device/management/configuration/job/definition/DeviceConfigurationPutStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.configuration.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
-import org.eclipse.kapua.service.device.management.configuration.job.DeviceConfigurationPutTargetProcessor;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DeviceConfigurationPutStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Configuration Put";
- }
-
- @Override
- public String getDescription() {
- return "Sends a configuration using the Device Configuration Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DeviceConfigurationPutTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyConfiguration = jobStepDefinitionFactory.newStepProperty(
- DeviceConfigurationPutPropertyKeys.CONFIGURATION,
- DeviceConfiguration.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DeviceConfigurationPutPropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyConfiguration, propertyTimeout);
- }
-}
diff --git a/service/device/management/configuration/message-api/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/DeviceConfigurationEventPayload.java b/service/device/management/configuration/message-api/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/DeviceConfigurationEventPayload.java
index 6690f1cebd5..5fc455af17b 100644
--- a/service/device/management/configuration/message-api/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/DeviceConfigurationEventPayload.java
+++ b/service/device/management/configuration/message-api/src/main/java/org/eclipse/kapua/service/device/management/configuration/message/event/DeviceConfigurationEventPayload.java
@@ -36,8 +36,8 @@ public interface DeviceConfigurationEventPayload extends KapuaManagementEventPay
/**
* Sets the {@link List} of changed {@link DeviceComponentConfiguration}s
*
- * @param deviceComponentConfigurations The {@link List} of changed {@link DeviceComponentConfiguration}s
+ * @param deviceConfiguration The device Configuration containing the {@link List} of changed {@link DeviceComponentConfiguration}s
* @since 2.0.0
*/
- void setDeviceComponentConfigurations(List deviceComponentConfigurations) throws Exception;
+ void setDeviceComponentConfigurations(DeviceConfiguration deviceConfiguration) throws Exception;
}
diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java
index 8587b285286..5a3ec7ea5cf 100644
--- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java
+++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceInventoryBundlesXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceInventoryManagementFactory factory = locator.getFactory(DeviceInventoryManagementFactory.class);
+ private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
/**
* Instantiates a new {@link DeviceInventoryBundles}.
diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java
index ef5cbe43744..a4aa82c82f9 100644
--- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java
+++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceInventoryContainersXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceInventoryManagementFactory factory = locator.getFactory(DeviceInventoryManagementFactory.class);
+ private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
/**
* Instantiates a new {@link DeviceInventoryContainers}.
diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java
index a04ee129cfe..ba258ea9de6 100644
--- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java
+++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceInventoryXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceInventoryManagementFactory factory = locator.getFactory(DeviceInventoryManagementFactory.class);
+ private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
/**
* Instantiates a new {@link DeviceInventory}.
diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java
index 4781be7e344..8ee0b2e15d3 100644
--- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java
+++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceInventoryPackagesXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceInventoryManagementFactory factory = locator.getFactory(DeviceInventoryManagementFactory.class);
+ private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
/**
* Instantiates a new {@link DeviceInventoryPackages}.
diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java
index 73af22a16da..9a4d0bc78f4 100644
--- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java
+++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceInventorySystemPackagesXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceInventoryManagementFactory factory = locator.getFactory(DeviceInventoryManagementFactory.class);
+ private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
/**
* Instantiates a new {@link DeviceInventorySystemPackages}.
diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java
index 2fbbf9c50ea..d2458609b13 100644
--- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java
+++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java
@@ -23,6 +23,7 @@
import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl;
import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder;
import org.eclipse.kapua.service.device.management.exception.DeviceManagementRequestContentException;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementService;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundleExecRequestMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundlesResponseMessage;
@@ -68,19 +69,22 @@ public class DeviceInventoryManagementServiceImpl extends AbstractDeviceManageme
private static final String SCOPE_ID = "scopeId";
private static final String DEVICE_ID = "deviceId";
+ private final DeviceInventoryManagementFactory deviceInventoryManagementFactory;
+
public DeviceInventoryManagementServiceImpl(
TxManager txManager,
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
- DeviceRegistryService deviceRegistryService) {
+ DeviceRegistryService deviceRegistryService, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
super(txManager,
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
deviceRegistryService);
+ this.deviceInventoryManagementFactory = deviceInventoryManagementFactory;
}
@Override
@@ -132,7 +136,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventory());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventory().orElse(deviceInventoryManagementFactory.newDeviceInventory()));
}
@Override
@@ -184,7 +188,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryBundles());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryBundles().orElse(deviceInventoryManagementFactory.newDeviceInventoryBundles()));
}
@Override
@@ -300,7 +304,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryContainers());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryContainers().orElse(deviceInventoryManagementFactory.newDeviceInventoryContainers()));
}
@Override
@@ -413,7 +417,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventorySystemPackages());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventorySystemPackages().orElse(deviceInventoryManagementFactory.newDeviceInventorySystemPackages()));
}
@Override
@@ -465,7 +469,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryPackages());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryPackages().orElse(deviceInventoryManagementFactory.newDeviceInventoryPackages()));
}
diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java
index fd14404c22e..21f99c40d43 100644
--- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java
+++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java
@@ -39,14 +39,15 @@ DeviceInventoryManagementService deviceInventoryManagementService(
DeviceEventService deviceEventService,
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
return new DeviceInventoryManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
authorizationService,
permissionFactory,
deviceEventService,
deviceEventFactory,
- deviceRegistryService
- );
+ deviceRegistryService,
+ deviceInventoryManagementFactory);
}
}
diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryRequestPayload.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryRequestPayload.java
index 7fe387b3edd..e1211573c82 100644
--- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryRequestPayload.java
+++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryRequestPayload.java
@@ -17,13 +17,13 @@
import org.eclipse.kapua.message.internal.KapuaPayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
-import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle;
import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainer;
import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory;
import org.eclipse.kapua.service.device.management.message.request.KapuaRequestPayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceInventory} {@link KapuaRequestPayload} implementation.
@@ -34,9 +34,7 @@ public class InventoryRequestPayload extends KapuaPayloadImpl implements KapuaRe
private static final long serialVersionUID = 837931637524736407L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceInventoryManagementFactory DEVICE_INVENTORY_MANAGEMENT_FACTORY = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceInventoryBundle} from the {@link #getBody()}.
@@ -45,13 +43,13 @@ public class InventoryRequestPayload extends KapuaPayloadImpl implements KapuaRe
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceInventoryBundle getDeviceInventoryBundle() throws Exception {
+ public Optional getDeviceInventoryBundle() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryBundle();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventoryBundle.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventoryBundle.class));
}
/**
@@ -63,7 +61,7 @@ public DeviceInventoryBundle getDeviceInventoryBundle() throws Exception {
*/
public void setDeviceInventoryBundle(@NotNull DeviceInventoryBundle deviceInventoryBundle) throws Exception {
String bodyString = XmlUtil.marshal(deviceInventoryBundle);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -73,13 +71,13 @@ public void setDeviceInventoryBundle(@NotNull DeviceInventoryBundle deviceInvent
* @throws Exception if reading {@link #getBody()} errors.
* @since 2.0.0
*/
- public DeviceInventoryContainer getDeviceInventoryContainer() throws Exception {
+ public Optional getDeviceInventoryContainer() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryContainer();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventoryContainer.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventoryContainer.class));
}
/**
@@ -91,6 +89,6 @@ public DeviceInventoryContainer getDeviceInventoryContainer() throws Exception {
*/
public void setDeviceInventoryContainer(@NotNull DeviceInventoryContainer deviceInventoryContainer) throws Exception {
String bodyString = XmlUtil.marshal(deviceInventoryContainer);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryResponsePayload.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryResponsePayload.java
index 1c995287b42..67633696672 100644
--- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryResponsePayload.java
+++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/message/InventoryResponsePayload.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.service.device.management.commons.message.response.KapuaResponsePayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
-import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundles;
import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers;
import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory;
@@ -26,6 +25,7 @@
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceInventory} {@link KapuaResponsePayload} implementation.
@@ -36,9 +36,7 @@ public class InventoryResponsePayload extends KapuaResponsePayloadImpl implement
private static final long serialVersionUID = 4380715272822080425L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceInventoryManagementFactory DEVICE_INVENTORY_MANAGEMENT_FACTORY = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceInventory} from the {@link #getBody()}.
@@ -47,13 +45,13 @@ public class InventoryResponsePayload extends KapuaResponsePayloadImpl implement
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceInventory getDeviceInventory() throws Exception {
+ public Optional getDeviceInventory() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventory();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventory.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventory.class));
}
/**
@@ -65,7 +63,7 @@ public DeviceInventory getDeviceInventory() throws Exception {
*/
public void setDeviceInventory(@NotNull DeviceInventory deviceInventory) throws Exception {
String bodyString = XmlUtil.marshal(deviceInventory);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -75,13 +73,13 @@ public void setDeviceInventory(@NotNull DeviceInventory deviceInventory) throws
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceInventoryBundles getDeviceInventoryBundles() throws Exception {
+ public Optional getDeviceInventoryBundles() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryBundles();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventoryBundles.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventoryBundles.class));
}
/**
@@ -93,7 +91,7 @@ public DeviceInventoryBundles getDeviceInventoryBundles() throws Exception {
*/
public void setDeviceInventoryBundles(@NotNull DeviceInventoryBundles inventoryBundles) throws Exception {
String bodyString = XmlUtil.marshal(inventoryBundles);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -103,13 +101,13 @@ public void setDeviceInventoryBundles(@NotNull DeviceInventoryBundles inventoryB
* @throws Exception if reading {@link #getBody()} errors.
* @since 2.0.0
*/
- public DeviceInventoryContainers getDeviceInventoryContainers() throws Exception {
+ public Optional getDeviceInventoryContainers() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryContainers();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventoryContainers.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventoryContainers.class));
}
/**
@@ -121,7 +119,7 @@ public DeviceInventoryContainers getDeviceInventoryContainers() throws Exception
*/
public void setDeviceInventoryContainers(@NotNull DeviceInventoryContainers inventoryContainers) throws Exception {
String bodyString = XmlUtil.marshal(inventoryContainers);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -131,13 +129,13 @@ public void setDeviceInventoryContainers(@NotNull DeviceInventoryContainers inve
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceInventorySystemPackages getDeviceInventorySystemPackages() throws Exception {
+ public Optional getDeviceInventorySystemPackages() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventorySystemPackages();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventorySystemPackages.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventorySystemPackages.class));
}
/**
@@ -149,7 +147,7 @@ public DeviceInventorySystemPackages getDeviceInventorySystemPackages() throws E
*/
public void setDeviceInventorySystemPackages(@NotNull DeviceInventorySystemPackages systemPackages) throws Exception {
String bodyString = XmlUtil.marshal(systemPackages);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -159,13 +157,13 @@ public void setDeviceInventorySystemPackages(@NotNull DeviceInventorySystemPacka
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceInventoryPackages getDeviceInventoryPackages() throws Exception {
+ public Optional getDeviceInventoryPackages() throws Exception {
if (!hasBody()) {
- return DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryPackages();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceInventoryPackages.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceInventoryPackages.class));
}
/**
@@ -177,6 +175,6 @@ public DeviceInventoryPackages getDeviceInventoryPackages() throws Exception {
*/
public void setDeviceInventoryPackages(@NotNull DeviceInventoryPackages packages) throws Exception {
String bodyString = XmlUtil.marshal(packages);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java
index f8412e4223d..604a0f8d1d0 100644
--- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java
+++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java
@@ -24,22 +24,21 @@
@XmlRegistry
public class JobDeviceManagementOperationXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobDeviceManagementOperationFactory JOB_STEP_FACTORY = LOCATOR.getFactory(JobDeviceManagementOperationFactory.class);
+ private final JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory = KapuaLocator.getInstance().getFactory(JobDeviceManagementOperationFactory.class);
public JobDeviceManagementOperation newJobDeviceManagementOperation() {
- return JOB_STEP_FACTORY.newEntity(null);
+ return jobDeviceManagementOperationFactory.newEntity(null);
}
public JobDeviceManagementOperationCreator newJobDeviceManagementOperationCreator() {
- return JOB_STEP_FACTORY.newCreator(null);
+ return jobDeviceManagementOperationFactory.newCreator(null);
}
public JobDeviceManagementOperationListResult newJobDeviceManagementOperationListResult() {
- return JOB_STEP_FACTORY.newListResult();
+ return jobDeviceManagementOperationFactory.newListResult();
}
public JobDeviceManagementOperationQuery newQuery() {
- return JOB_STEP_FACTORY.newQuery(null);
+ return jobDeviceManagementOperationFactory.newQuery(null);
}
}
diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java
index 048d4657ed0..aad30fefc6c 100644
--- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java
+++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.job.engine.JobEngineFactory;
import org.eclipse.kapua.job.engine.JobEngineService;
import org.eclipse.kapua.job.engine.JobStartOptions;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation;
import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationAttributes;
@@ -28,7 +27,6 @@
import org.eclipse.kapua.service.device.management.job.manager.JobDeviceManagementOperationManagerService;
import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus;
import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory;
import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationProperty;
import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService;
import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification;
@@ -42,6 +40,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Date;
@@ -55,19 +54,31 @@ public class JobDeviceManagementOperationManagerServiceImpl implements JobDevice
private static final Logger LOG = LoggerFactory.getLogger(JobDeviceManagementOperationManagerService.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final DeviceManagementOperationRegistryService DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE = LOCATOR.getService(DeviceManagementOperationRegistryService.class);
- private static final DeviceManagementOperationFactory DEVICE_MANAGEMENT_OPERATION_FACTORY = LOCATOR.getFactory(DeviceManagementOperationFactory.class);
-
- private static final JobDeviceManagementOperationService JOB_DEVICE_MANAGEMENT_OPERATION_SERVICE = LOCATOR.getService(JobDeviceManagementOperationService.class);
- private static final JobDeviceManagementOperationFactory JOB_DEVICE_MANAGEMENT_OPERATION_FACTORY = LOCATOR.getFactory(JobDeviceManagementOperationFactory.class);
-
- private static final JobEngineService JOB_ENGINE_SERVICE = LOCATOR.getService(JobEngineService.class);
- private static final JobEngineFactory JOB_ENGINE_FACTORY = LOCATOR.getFactory(JobEngineFactory.class);
-
- private static final JobTargetService JOB_TARGET_SERVICE = LOCATOR.getService(JobTargetService.class);
- private static final JobTargetFactory JOB_TARGET_FACTORY = LOCATOR.getFactory(JobTargetFactory.class);
+ private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService;
+ private final JobDeviceManagementOperationService jobDeviceManagementOperationService;
+ private final JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory;
+ private final JobEngineService jobEngineService;
+ private final JobEngineFactory jobEngineFactory;
+ private final JobTargetService jobTargetService;
+ private final JobTargetFactory jobTargetFactory;
+
+ @Inject
+ public JobDeviceManagementOperationManagerServiceImpl(
+ DeviceManagementOperationRegistryService deviceManagementOperationRegistryService,
+ JobDeviceManagementOperationService jobDeviceManagementOperationService,
+ JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory,
+ JobEngineService jobEngineService,
+ JobEngineFactory jobEngineFactory,
+ JobTargetService jobTargetService,
+ JobTargetFactory jobTargetFactory) {
+ this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService;
+ this.jobDeviceManagementOperationService = jobDeviceManagementOperationService;
+ this.jobDeviceManagementOperationFactory = jobDeviceManagementOperationFactory;
+ this.jobEngineService = jobEngineService;
+ this.jobEngineFactory = jobEngineFactory;
+ this.jobTargetService = jobTargetService;
+ this.jobTargetFactory = jobTargetFactory;
+ }
@Override
public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status) throws KapuaException {
@@ -89,7 +100,7 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId,
return;
}
- JobTargetQuery jobTargetQuery = JOB_TARGET_FACTORY.newQuery(scopeId);
+ JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId);
jobTargetQuery.setPredicate(
jobTargetQuery.andPredicate(
jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, jobDeviceManagementOperation.getJobId()),
@@ -103,7 +114,7 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId,
JobTarget jobTarget = null;
do {
try {
- JobTargetListResult jobTargets = JOB_TARGET_SERVICE.query(jobTargetQuery);
+ JobTargetListResult jobTargets = jobTargetService.query(jobTargetQuery);
jobTarget = jobTargets.getFirstItem();
if (jobTarget == null) {
@@ -123,7 +134,7 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId,
break;
}
- JOB_TARGET_SERVICE.update(jobTarget);
+ jobTargetService.update(jobTarget);
failed = false;
} catch (Exception e) {
failed = true;
@@ -146,12 +157,12 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId,
return;
}
// Start the job
- JobStartOptions jobStartOptions = JOB_ENGINE_FACTORY.newJobStartOptions();
+ JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions();
jobStartOptions.addTargetIdToSublist(jobTarget.getId());
jobStartOptions.setFromStepIndex(jobTarget.getStepIndex());
jobStartOptions.setEnqueue(true);
- JOB_ENGINE_SERVICE.startJob(scopeId, jobDeviceManagementOperation.getJobId(), jobStartOptions);
+ jobEngineService.startJob(scopeId, jobDeviceManagementOperation.getJobId(), jobStartOptions);
}
/**
@@ -199,10 +210,10 @@ private JobDeviceManagementOperation getJobDeviceManagementOperation(KapuaId sco
DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
- JobDeviceManagementOperationQuery query = JOB_DEVICE_MANAGEMENT_OPERATION_FACTORY.newQuery(scopeId);
+ JobDeviceManagementOperationQuery query = jobDeviceManagementOperationFactory.newQuery(scopeId);
query.setPredicate(query.attributePredicate(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, deviceManagementOperation.getId()));
- JobDeviceManagementOperationListResult operations = JOB_DEVICE_MANAGEMENT_OPERATION_SERVICE.query(query);
+ JobDeviceManagementOperationListResult operations = jobDeviceManagementOperationService.query(query);
JobDeviceManagementOperation jobDeviceManagementOperation = operations.getFirstItem();
if (jobDeviceManagementOperation == null) {
@@ -224,7 +235,7 @@ private JobDeviceManagementOperation getJobDeviceManagementOperation(KapuaId sco
* @since 1.1.0
*/
private DeviceManagementOperation getDeviceManagementOperation(KapuaId scopeId, KapuaId operationId) throws KapuaException {
- DeviceManagementOperation deviceManagementOperation = DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.findByOperationId(scopeId, operationId);
+ DeviceManagementOperation deviceManagementOperation = deviceManagementOperationRegistryService.findByOperationId(scopeId, operationId);
if (deviceManagementOperation == null) {
throw new KapuaEntityNotFoundException(DeviceManagementOperation.TYPE, operationId);
diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java
index f9dcf265dca..f2b1d51cdec 100644
--- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java
+++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.job.engine.JobEngineFactory;
import org.eclipse.kapua.job.engine.JobEngineService;
import org.eclipse.kapua.job.engine.JobStartOptions;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.model.query.predicate.AttributePredicate;
import org.eclipse.kapua.service.device.management.job.scheduler.manager.JobDeviceManagementTriggerManagerService;
@@ -44,6 +43,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Date;
@@ -57,77 +57,72 @@ public class JobDeviceManagementTriggerManagerServiceImpl implements JobDeviceMa
private static final Logger LOG = LoggerFactory.getLogger(JobDeviceManagementTriggerManagerServiceImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final JobEngineService JOB_ENGINE_SERVICE = LOCATOR.getService(JobEngineService.class);
- private static final JobEngineFactory JOB_ENGINE_FACTORY = LOCATOR.getFactory(JobEngineFactory.class);
-
- private static final JobStepService JOB_STEP_SERVICE = LOCATOR.getService(JobStepService.class);
- private static final JobStepFactory JOB_STEP_FACTORY = LOCATOR.getFactory(JobStepFactory.class);
-
- private static final JobTargetService JOB_TARGET_SERVICE = LOCATOR.getService(JobTargetService.class);
- private static final JobTargetFactory JOB_TARGET_FACTORY = LOCATOR.getFactory(JobTargetFactory.class);
-
- private static final TriggerDefinitionService TRIGGER_DEFINITION_SERVICE = LOCATOR.getService(TriggerDefinitionService.class);
-
- private static final TriggerService TRIGGER_SERVICE = LOCATOR.getService(TriggerService.class);
- private static final TriggerFactory TRIGGER_FACTORY = LOCATOR.getFactory(TriggerFactory.class);
-
- private static final TriggerDefinition DEVICE_CONNECT_TRIGGER;
-
- /**
- * Looks fot the "Device Connect" {@link TriggerDefinition} to have access to its {@link TriggerDefinition#getId()}
- *
- * @since 1.1.0
- */
- static {
- TriggerDefinition deviceConnectTrigger;
- try {
- deviceConnectTrigger = KapuaSecurityUtils.doPrivileged(() -> TRIGGER_DEFINITION_SERVICE.findByName("Device Connect"));
- if (deviceConnectTrigger == null) {
- throw new KapuaEntityNotFoundException(TriggerDefinition.TYPE, "Device Connect");
- }
- } catch (Exception e) {
- LOG.error("Error while searching the Trigger Definition named 'Device Connect'", e);
- throw new ExceptionInInitializerError(e);
- }
-
- DEVICE_CONNECT_TRIGGER = deviceConnectTrigger;
+ private final JobEngineService jobEngineService;
+ private final JobEngineFactory jobEngineFactory;
+ private final JobStepService jobStepService;
+ private final JobStepFactory jobStepFactory;
+ private final JobTargetService jobTargetService;
+ private final JobTargetFactory jobTargetFactory;
+ private final TriggerDefinitionService triggerDefinitionService;
+ private final TriggerService triggerService;
+ private final TriggerFactory triggerFactory;
+
+ @Inject
+ public JobDeviceManagementTriggerManagerServiceImpl(
+ JobEngineService jobEngineService,
+ JobEngineFactory jobEngineFactory,
+ JobStepService jobStepService,
+ JobStepFactory jobStepFactory,
+ JobTargetService jobTargetService,
+ JobTargetFactory jobTargetFactory,
+ TriggerDefinitionService triggerDefinitionService,
+ TriggerService triggerService,
+ TriggerFactory triggerFactory) {
+ this.jobEngineService = jobEngineService;
+ this.jobEngineFactory = jobEngineFactory;
+ this.jobStepService = jobStepService;
+ this.jobStepFactory = jobStepFactory;
+ this.jobTargetService = jobTargetService;
+ this.jobTargetFactory = jobTargetFactory;
+ this.triggerDefinitionService = triggerDefinitionService;
+ this.triggerService = triggerService;
+ this.triggerFactory = triggerFactory;
}
+
@Override
public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOnConnectException {
Date now = new Date();
try {
- JobTargetQuery jobTargetQuery = JOB_TARGET_FACTORY.newQuery(scopeId);
+ JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId);
jobTargetQuery.setPredicate(
jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_TARGET_ID, deviceId)
);
- JobTargetListResult jobTargetListResult = KapuaSecurityUtils.doPrivileged(() -> JOB_TARGET_SERVICE.query(jobTargetQuery));
+ JobTargetListResult jobTargetListResult = KapuaSecurityUtils.doPrivileged(() -> jobTargetService.query(jobTargetQuery));
for (JobTarget jt : jobTargetListResult.getItems()) {
- JobStepQuery jobStepQuery = JOB_STEP_FACTORY.newQuery(jt.getScopeId());
+ JobStepQuery jobStepQuery = jobStepFactory.newQuery(jt.getScopeId());
jobStepQuery.setPredicate(
jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jt.getJobId())
);
- long jobStepCount = JOB_STEP_SERVICE.count(jobStepQuery);
+ long jobStepCount = jobStepService.count(jobStepQuery);
if (JobTargetStatus.PROCESS_OK.equals(jt.getStatus()) && jobStepCount <= jt.getStepIndex() + 1) {
// The target is at the end of the job step processing
continue;
}
- TriggerQuery triggerQuery = TRIGGER_FACTORY.newQuery(scopeId);
+ TriggerQuery triggerQuery = triggerFactory.newQuery(scopeId);
triggerQuery.setPredicate(
triggerQuery.andPredicate(
- triggerQuery.attributePredicate(TriggerAttributes.TRIGGER_DEFINITION_ID, DEVICE_CONNECT_TRIGGER.getId()),
+ triggerQuery.attributePredicate(TriggerAttributes.TRIGGER_DEFINITION_ID, getTriggerDefinition().getId()),
triggerQuery.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_TYPE, KapuaId.class.getName()),
triggerQuery.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_VALUE, jt.getJobId().toCompactId()),
triggerQuery.attributePredicate(TriggerAttributes.STARTS_ON, now, AttributePredicate.Operator.LESS_THAN),
@@ -138,16 +133,16 @@ public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOn
)
);
- TriggerListResult jobTriggers = KapuaSecurityUtils.doPrivileged(() -> TRIGGER_SERVICE.query(triggerQuery));
+ TriggerListResult jobTriggers = KapuaSecurityUtils.doPrivileged(() -> triggerService.query(triggerQuery));
for (Trigger t : jobTriggers.getItems()) {
- JobStartOptions jobStartOptions = JOB_ENGINE_FACTORY.newJobStartOptions();
+ JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions();
jobStartOptions.addTargetIdToSublist(jt.getId());
jobStartOptions.setFromStepIndex(jt.getStepIndex());
jobStartOptions.setEnqueue(true);
- KapuaSecurityUtils.doPrivileged(() -> JOB_ENGINE_SERVICE.startJob(jt.getScopeId(), jt.getJobId(), jobStartOptions));
+ KapuaSecurityUtils.doPrivileged(() -> jobEngineService.startJob(jt.getScopeId(), jt.getJobId(), jobStartOptions));
}
}
@@ -155,4 +150,23 @@ public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOn
throw new ProcessOnConnectException(e, scopeId, deviceId);
}
}
+
+ private TriggerDefinition getTriggerDefinition() {
+ /**
+ * Looks fot the "Device Connect" {@link TriggerDefinition} to have access to its {@link TriggerDefinition#getId()}
+ *
+ * @since 1.1.0
+ */
+ TriggerDefinition deviceConnectTrigger;
+ try {
+ deviceConnectTrigger = KapuaSecurityUtils.doPrivileged(() -> triggerDefinitionService.findByName("Device Connect"));
+ if (deviceConnectTrigger == null) {
+ throw new KapuaEntityNotFoundException(TriggerDefinition.TYPE, "Device Connect");
+ }
+ } catch (Exception e) {
+ LOG.error("Error while searching the Trigger Definition named 'Device Connect'", e);
+ throw new ExceptionInInitializerError(e);
+ }
+ return deviceConnectTrigger;
+ }
}
diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java
index 9b4a02dda17..8451cd7d7ac 100644
--- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java
+++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java
@@ -22,8 +22,7 @@
*/
public class DeviceKeystoreXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final DeviceKeystoreManagementFactory factory = locator.getFactory(DeviceKeystoreManagementFactory.class);
+ private final DeviceKeystoreManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceKeystoreManagementFactory.class);
/**
* Instantiates a new {@link DeviceKeystores}.
diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java
index db1c584799e..63e33accaec 100644
--- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java
+++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java
@@ -28,6 +28,7 @@
import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl;
import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder;
import org.eclipse.kapua.service.device.management.exception.DeviceManagementRequestContentException;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCertificateRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCsrRequestMessage;
@@ -77,6 +78,7 @@ public class DeviceKeystoreManagementServiceImpl extends AbstractDeviceManagemen
protected final CertificateInfoService certificateInfoService;
protected final CertificateInfoFactory certificateInfoFactory;
+ private final DeviceKeystoreManagementFactory deviceKeystoreManagementFactory;
public DeviceKeystoreManagementServiceImpl(
TxManager txManager,
@@ -86,7 +88,7 @@ public DeviceKeystoreManagementServiceImpl(
DeviceEventFactory deviceEventFactory,
DeviceRegistryService deviceRegistryService,
CertificateInfoService certificateInfoService,
- CertificateInfoFactory certificateInfoFactory) {
+ CertificateInfoFactory certificateInfoFactory, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
super(txManager,
authorizationService,
permissionFactory,
@@ -95,6 +97,7 @@ public DeviceKeystoreManagementServiceImpl(
deviceRegistryService);
this.certificateInfoService = certificateInfoService;
this.certificateInfoFactory = certificateInfoFactory;
+ this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory;
}
@Override
@@ -144,7 +147,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystores());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystores().orElse(deviceKeystoreManagementFactory.newDeviceKeystores()));
}
@Override
@@ -213,7 +216,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItems());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItems().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItems()));
}
@Override
@@ -275,7 +278,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItem());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItem().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItem()));
}
@Override
@@ -474,7 +477,7 @@ public Class getResponseClass() {
// Create event
createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getCSR());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getCSR().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCSR()));
}
@Override
diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java
index 41861ae7b2d..a863682f9e7 100644
--- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java
+++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java
@@ -43,7 +43,8 @@ DeviceKeystoreManagementService deviceKeystoreManagementService(
DeviceRegistryService deviceRegistryService,
CertificateInfoService certificateInfoService,
CertificateInfoFactory certificateInfoFactory,
- KapuaJpaTxManagerFactory jpaTxManagerFactory
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceKeystoreManagementFactory deviceKeystoreManagementFactory
) {
return new DeviceKeystoreManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
@@ -53,7 +54,7 @@ DeviceKeystoreManagementService deviceKeystoreManagementService(
deviceEventFactory,
deviceRegistryService,
certificateInfoService,
- certificateInfoFactory
- );
+ certificateInfoFactory,
+ deviceKeystoreManagementFactory);
}
}
diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/request/KeystoreRequestPayload.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/request/KeystoreRequestPayload.java
index 86ab311b678..70cafea131c 100644
--- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/request/KeystoreRequestPayload.java
+++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/request/KeystoreRequestPayload.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.message.internal.KapuaPayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
-import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate;
@@ -25,6 +24,8 @@
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair;
import org.eclipse.kapua.service.device.management.message.request.KapuaRequestPayload;
+import java.util.Optional;
+
/**
* {@link DeviceKeystore} {@link KapuaRequestPayload} implementation.
*
@@ -34,9 +35,7 @@ public class KeystoreRequestPayload extends KapuaPayloadImpl implements KapuaReq
private static final long serialVersionUID = 837931637524736407L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceKeystoreManagementFactory DEVICE_KEYSTORE_MANAGEMENT_FACTORY = KapuaLocator.getInstance().getFactory(DeviceKeystoreManagementFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceKeystoreItemQuery} from the {@link KapuaRequestPayload#getBody()}
@@ -45,13 +44,13 @@ public class KeystoreRequestPayload extends KapuaPayloadImpl implements KapuaReq
* @throws Exception if {@link KapuaRequestPayload#getBody()} is not a {@link DeviceKeystoreItemQuery}.
* @since 1.5.0
*/
- public DeviceKeystoreItemQuery getItemQuery() throws Exception {
+ public Optional getItemQuery() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItemQuery();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreItemQuery.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreItemQuery.class));
}
/**
@@ -63,7 +62,7 @@ public DeviceKeystoreItemQuery getItemQuery() throws Exception {
*/
public void setItemQuery(DeviceKeystoreItemQuery itemQuery) throws Exception {
String bodyString = XmlUtil.marshal(itemQuery);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -73,13 +72,13 @@ public void setItemQuery(DeviceKeystoreItemQuery itemQuery) throws Exception {
* @throws Exception if {@link KapuaRequestPayload#getBody()} is not a {@link DeviceKeystoreCertificate}.
* @since 1.5.0
*/
- public DeviceKeystoreCertificate getCertificate() throws Exception {
+ public Optional getCertificate() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCertificate();
+ Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreCertificate.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreCertificate.class));
}
/**
@@ -91,7 +90,7 @@ public DeviceKeystoreCertificate getCertificate() throws Exception {
*/
public void setCertificate(DeviceKeystoreCertificate certificate) throws Exception {
String bodyString = XmlUtil.marshal(certificate);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -101,13 +100,13 @@ public void setCertificate(DeviceKeystoreCertificate certificate) throws Excepti
* @throws Exception if {@link KapuaRequestPayload#getBody()} is not a {@link DeviceKeystoreKeypair}.
* @since 1.5.0
*/
- public DeviceKeystoreKeypair getKeypair() throws Exception {
+ public Optional getKeypair() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreKeypair();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreKeypair.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.of(XmlUtil.unmarshal(bodyString, DeviceKeystoreKeypair.class));
}
/**
@@ -119,7 +118,7 @@ public DeviceKeystoreKeypair getKeypair() throws Exception {
*/
public void setKeypair(DeviceKeystoreKeypair keypair) throws Exception {
String bodyString = XmlUtil.marshal(keypair);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -129,13 +128,13 @@ public void setKeypair(DeviceKeystoreKeypair keypair) throws Exception {
* @throws Exception if {@link KapuaRequestPayload#getBody()} is not a {@link DeviceKeystoreCSRInfo}.
* @since 1.5.0
*/
- public DeviceKeystoreCSRInfo getCSRInfo() throws Exception {
+ public Optional getCSRInfo() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCSRInfo();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreCSRInfo.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreCSRInfo.class));
}
/**
@@ -147,6 +146,6 @@ public DeviceKeystoreCSRInfo getCSRInfo() throws Exception {
*/
public void setCsrInfo(DeviceKeystoreCSRInfo csrInfo) throws Exception {
String bodyString = XmlUtil.marshal(csrInfo);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/response/KeystoreResponsePayload.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/response/KeystoreResponsePayload.java
index a41b241b831..9cb86a9a1c4 100644
--- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/response/KeystoreResponsePayload.java
+++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/message/response/KeystoreResponsePayload.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.service.device.management.commons.message.response.KapuaResponsePayloadImpl;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
-import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItem;
@@ -26,6 +25,7 @@
import org.eclipse.kapua.service.device.management.message.response.KapuaResponsePayload;
import javax.validation.constraints.NotNull;
+import java.util.Optional;
/**
* {@link DeviceKeystore} {@link KapuaResponsePayload} implementation.
@@ -36,9 +36,7 @@ public class KeystoreResponsePayload extends KapuaResponsePayloadImpl implements
private static final long serialVersionUID = 4380715272822080425L;
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- private static final DeviceKeystoreManagementFactory DEVICE_KEYSTORE_MANAGEMENT_FACTORY = KapuaLocator.getInstance().getFactory(DeviceKeystoreManagementFactory.class);
+ private final String charEncoding = KapuaLocator.getInstance().getComponent(DeviceManagementSetting.class).getString(DeviceManagementSettingKey.CHAR_ENCODING);
/**
* Gets the {@link DeviceKeystores} from the {@link #getBody()}.
@@ -47,13 +45,13 @@ public class KeystoreResponsePayload extends KapuaResponsePayloadImpl implements
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceKeystores getKeystores() throws Exception {
+ public Optional getKeystores() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystores();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystores.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystores.class));
}
/**
@@ -65,7 +63,7 @@ public DeviceKeystores getKeystores() throws Exception {
*/
public void setKeystores(@NotNull DeviceKeystores keystores) throws Exception {
String bodyString = XmlUtil.marshal(keystores);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -75,13 +73,13 @@ public void setKeystores(@NotNull DeviceKeystores keystores) throws Exception {
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceKeystoreItems getKeystoreItems() throws Exception {
+ public Optional getKeystoreItems() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItems();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreItems.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreItems.class));
}
/**
@@ -93,7 +91,7 @@ public DeviceKeystoreItems getKeystoreItems() throws Exception {
*/
public void setKeystoreItems(@NotNull DeviceKeystoreItems keystoreItems) throws Exception {
String bodyString = XmlUtil.marshal(keystoreItems);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -103,13 +101,13 @@ public void setKeystoreItems(@NotNull DeviceKeystoreItems keystoreItems) throws
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceKeystoreItem getKeystoreItem() throws Exception {
+ public Optional getKeystoreItem() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItem();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreItem.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreItem.class));
}
/**
@@ -121,7 +119,7 @@ public DeviceKeystoreItem getKeystoreItem() throws Exception {
*/
public void setKeystoreItem(@NotNull DeviceKeystoreItem keystoreItem) throws Exception {
String bodyString = XmlUtil.marshal(keystoreItem);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -131,13 +129,13 @@ public void setKeystoreItem(@NotNull DeviceKeystoreItem keystoreItem) throws Exc
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DeviceKeystoreCSR getCSR() throws Exception {
+ public Optional getCSR() throws Exception {
if (!hasBody()) {
- return DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCSR();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DeviceKeystoreCSR.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DeviceKeystoreCSR.class));
}
/**
@@ -149,6 +147,6 @@ public DeviceKeystoreCSR getCSR() throws Exception {
*/
public void setCSR(@NotNull DeviceKeystoreCSR deviceCSR) throws Exception {
String bodyString = XmlUtil.marshal(deviceCSR);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java
index 35c9c357a88..8baf3bd5547 100644
--- a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java
+++ b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java
@@ -34,12 +34,13 @@
* @since 1.0.0
*/
public class DeviceKeystoreCertificateCreateTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceKeystoreManagementService KEYSTORE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceKeystoreManagementService.class);
- private static final DeviceKeystoreManagementFactory KEYSTORE_MANAGEMENT_FACTORY = LOCATOR.getFactory(DeviceKeystoreManagementFactory.class);
+ @Inject
+ DeviceKeystoreManagementService deviceKeystoreManagementService;
+ @Inject
+ DeviceKeystoreManagementFactory deviceKeystoreManagementFactory;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -56,12 +57,12 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
String certificate = stepContextWrapper.getStepProperty(DeviceCertificateCreatePropertyKeys.CERTIFICATE, String.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceCertificateCreatePropertyKeys.TIMEOUT, Long.class);
- DeviceKeystoreCertificate deviceKeystoreCertificate = KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCertificate();
+ DeviceKeystoreCertificate deviceKeystoreCertificate = deviceKeystoreManagementFactory.newDeviceKeystoreCertificate();
deviceKeystoreCertificate.setKeystoreId(keystoreId);
deviceKeystoreCertificate.setAlias(alias);
deviceKeystoreCertificate.setCertificate(certificate);
- KapuaSecurityUtils.doPrivileged(() -> KEYSTORE_MANAGEMENT_SERVICE.createKeystoreCertificate(jobTarget.getScopeId(), jobTarget.getJobTargetId(), deviceKeystoreCertificate, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceKeystoreManagementService.createKeystoreCertificate(jobTarget.getScopeId(), jobTarget.getJobTargetId(), deviceKeystoreCertificate, timeout));
}
}
diff --git a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreItemDeleteTargetProcessor.java b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreItemDeleteTargetProcessor.java
index f77da678f75..47de90bb546 100644
--- a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreItemDeleteTargetProcessor.java
+++ b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreItemDeleteTargetProcessor.java
@@ -33,11 +33,11 @@
* @since 1.0.0
*/
public class DeviceKeystoreItemDeleteTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceKeystoreManagementService KEYSTORE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceKeystoreManagementService.class);
+ @Inject
+ DeviceKeystoreManagementService deviceKeystoreManagementService;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -53,6 +53,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
String alias = stepContextWrapper.getStepProperty(DeviceKeystoreItemDeletePropertyKeys.ALIAS, String.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceKeystoreItemDeletePropertyKeys.TIMEOUT, Long.class);
- KapuaSecurityUtils.doPrivileged(() -> KEYSTORE_MANAGEMENT_SERVICE.deleteKeystoreItem(jobTarget.getScopeId(), jobTarget.getJobTargetId(), keystoreId, alias, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceKeystoreManagementService.deleteKeystoreItem(jobTarget.getScopeId(), jobTarget.getJobTargetId(), keystoreId, alias, timeout));
}
}
diff --git a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java
index b9a649346e5..25242016a4a 100644
--- a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java
+++ b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java
@@ -35,12 +35,13 @@
* @since 1.0.0
*/
public class DeviceKeystoreKeypairCreateTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceKeystoreManagementService KEYSTORE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceKeystoreManagementService.class);
- private static final DeviceKeystoreManagementFactory KEYSTORE_MANAGEMENT_FACTORY = LOCATOR.getFactory(DeviceKeystoreManagementFactory.class);
+ @Inject
+ DeviceKeystoreManagementService deviceKeystoreManagementService;
+ @Inject
+ DeviceKeystoreManagementFactory deviceKeystoreManagementFactory;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -60,7 +61,7 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
String attributes = stepContextWrapper.getStepProperty(DeviceKeypairCreatePropertyKeys.ATTRIBUTES, String.class);
Long timeout = stepContextWrapper.getStepProperty(DeviceKeypairCreatePropertyKeys.TIMEOUT, Long.class);
- DeviceKeystoreKeypair deviceKeystoreKeypair = KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreKeypair();
+ DeviceKeystoreKeypair deviceKeystoreKeypair = deviceKeystoreManagementFactory.newDeviceKeystoreKeypair();
deviceKeystoreKeypair.setKeystoreId(keystoreId);
deviceKeystoreKeypair.setAlias(alias);
@@ -69,6 +70,6 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
deviceKeystoreKeypair.setSignatureAlgorithm(signatureAlgorithm);
deviceKeystoreKeypair.setAttributes(attributes);
- KapuaSecurityUtils.doPrivileged(() -> KEYSTORE_MANAGEMENT_SERVICE.createKeystoreKeypair(jobTarget.getScopeId(), jobTarget.getJobTargetId(), deviceKeystoreKeypair, timeout));
+ KapuaSecurityUtils.doPrivileged(() -> deviceKeystoreManagementService.createKeystoreKeypair(jobTarget.getScopeId(), jobTarget.getJobTargetId(), deviceKeystoreKeypair, timeout));
}
}
diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java
index ff7f76fb950..11b81d2b41a 100644
--- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java
+++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java
@@ -31,8 +31,7 @@
@XmlRegistry
public class DevicePackageXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DevicePackageFactory DEVICE_PACKAGE_FACTORY = LOCATOR.getFactory(DevicePackageFactory.class);
+ private final DevicePackageFactory devicePackageFactory = KapuaLocator.getInstance().getFactory(DevicePackageFactory.class);
/**
* Creates a new device package instance
@@ -41,7 +40,7 @@ public class DevicePackageXmlRegistry {
* @since 1.0.0
*/
public DevicePackage newDevicePackage() {
- return DEVICE_PACKAGE_FACTORY.newDeviceDeploymentPackage();
+ return devicePackageFactory.newDeviceDeploymentPackage();
}
/**
@@ -51,7 +50,7 @@ public DevicePackage newDevicePackage() {
* @since 1.0.0
*/
public DevicePackages newDevicePackages() {
- return DEVICE_PACKAGE_FACTORY.newDeviceDeploymentPackages();
+ return devicePackageFactory.newDeviceDeploymentPackages();
}
/**
@@ -61,7 +60,7 @@ public DevicePackages newDevicePackages() {
* @since 1.0.0
*/
public DevicePackageBundleInfo newDevicePackageBundleInfo() {
- return DEVICE_PACKAGE_FACTORY.newDevicePackageBundleInfo();
+ return devicePackageFactory.newDevicePackageBundleInfo();
}
/**
@@ -71,7 +70,7 @@ public DevicePackageBundleInfo newDevicePackageBundleInfo() {
* @since 1.0.0
*/
public DevicePackageBundleInfos newDevicePackageBundleInfos() {
- return DEVICE_PACKAGE_FACTORY.newDevicePackageBundleInfos();
+ return devicePackageFactory.newDevicePackageBundleInfos();
}
/**
@@ -80,7 +79,7 @@ public DevicePackageBundleInfos newDevicePackageBundleInfos() {
* @return
*/
public DevicePackageDownloadRequest newDevicePackageDownloadRequest() {
- return DEVICE_PACKAGE_FACTORY.newPackageDownloadRequest();
+ return devicePackageFactory.newPackageDownloadRequest();
}
/**
@@ -90,7 +89,7 @@ public DevicePackageDownloadRequest newDevicePackageDownloadRequest() {
* @since 1.1.0
*/
public AdvancedPackageDownloadOptions newAdvancedPackageDownloadOptions() {
- return DEVICE_PACKAGE_FACTORY.newAdvancedPackageDownloadOptions();
+ return devicePackageFactory.newAdvancedPackageDownloadOptions();
}
/**
@@ -100,7 +99,7 @@ public AdvancedPackageDownloadOptions newAdvancedPackageDownloadOptions() {
* @since 1.5.0
*/
public DevicePackageDownloadOperation newDevicePackageDownloadOperation() {
- return DEVICE_PACKAGE_FACTORY.newPackageDownloadOperation();
+ return devicePackageFactory.newPackageDownloadOperation();
}
/**
@@ -110,7 +109,7 @@ public DevicePackageDownloadOperation newDevicePackageDownloadOperation() {
* @since 1.5.0
*/
public DevicePackageInstallOperation newDevicePackageInstallOperation() {
- return DEVICE_PACKAGE_FACTORY.newPackageInstallOperation();
+ return devicePackageFactory.newPackageInstallOperation();
}
/**
@@ -120,7 +119,7 @@ public DevicePackageInstallOperation newDevicePackageInstallOperation() {
* @since 1.0.0
*/
public DevicePackageUninstallRequest newDevicePackageUninstallRequest() {
- return DEVICE_PACKAGE_FACTORY.newPackageUninstallRequest();
+ return devicePackageFactory.newPackageUninstallRequest();
}
/**
@@ -130,6 +129,6 @@ public DevicePackageUninstallRequest newDevicePackageUninstallRequest() {
* @since 1.5.0
*/
public DevicePackageUninstallOperation newDevicePackageUninstallOperation() {
- return DEVICE_PACKAGE_FACTORY.newPackageUninstallOperation();
+ return devicePackageFactory.newPackageUninstallOperation();
}
}
diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java
index aea0326330c..bb583ea423e 100644
--- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java
+++ b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java
@@ -12,7 +12,6 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.management.packages.internal;
-import com.google.inject.Inject;
import com.google.inject.Provides;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
@@ -20,16 +19,21 @@
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory;
import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService;
+import org.eclipse.kapua.service.device.management.packages.internal.setting.PackageManagementServiceSetting;
import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory;
import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService;
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory;
import org.eclipse.kapua.service.device.registry.event.DeviceEventService;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
public class DeviceManagementPackagesModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(DevicePackageFactory.class).to(DevicePackageFactoryImpl.class);
+ bind(DevicePackageFactory.class).to(DevicePackageFactoryImpl.class).in(Singleton.class);
+ bind(PackageManagementServiceSetting.class).in(Singleton.class);
}
@Provides
@@ -43,7 +47,8 @@ DevicePackageManagementService devicePackageManagementService(
DeviceManagementOperationRegistryService deviceManagementOperationRegistryService,
DeviceManagementOperationFactory deviceManagementOperationFactory,
DevicePackageFactory devicePackageFactory,
- KapuaJpaTxManagerFactory jpaTxManagerFactory
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ PackageManagementServiceSetting packageManagementServiceSetting
) {
return new DevicePackageManagementServiceImpl(
jpaTxManagerFactory.create("kapua-device_management_operation_registry"),
@@ -54,7 +59,8 @@ DevicePackageManagementService devicePackageManagementService(
deviceRegistryService,
deviceManagementOperationRegistryService,
deviceManagementOperationFactory,
- devicePackageFactory
+ devicePackageFactory,
+ packageManagementServiceSetting
);
}
}
diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java
index bc45809c3d5..c2916002560 100644
--- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java
+++ b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java
@@ -67,6 +67,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.net.MalformedURLException;
import java.util.ArrayList;
@@ -84,7 +85,7 @@ public class DevicePackageManagementServiceImpl extends AbstractDeviceManagement
private static final Logger LOG = LoggerFactory.getLogger(DevicePackageManagementServiceImpl.class);
- private final PackageManagementServiceSetting packageManagementServiceSetting = PackageManagementServiceSetting.getInstance();
+ private final PackageManagementServiceSetting packageManagementServiceSetting;
private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService;
private final DeviceManagementOperationFactory deviceManagementOperationFactory;
@@ -93,6 +94,7 @@ public class DevicePackageManagementServiceImpl extends AbstractDeviceManagement
private static final String SCOPE_ID = "scopeId";
private static final String DEVICE_ID = "deviceId";
+ @Inject
public DevicePackageManagementServiceImpl(
TxManager txManager,
AuthorizationService authorizationService,
@@ -102,7 +104,8 @@ public DevicePackageManagementServiceImpl(
DeviceRegistryService deviceRegistryService,
DeviceManagementOperationRegistryService deviceManagementOperationRegistryService,
DeviceManagementOperationFactory deviceManagementOperationFactory,
- DevicePackageFactory devicePackageFactory) {
+ DevicePackageFactory devicePackageFactory,
+ PackageManagementServiceSetting packageManagementServiceSetting) {
super(txManager,
authorizationService,
permissionFactory,
@@ -112,6 +115,7 @@ public DevicePackageManagementServiceImpl(
this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService;
this.deviceManagementOperationFactory = deviceManagementOperationFactory;
this.devicePackageFactory = devicePackageFactory;
+ this.packageManagementServiceSetting = packageManagementServiceSetting;
}
// Installed
@@ -157,7 +161,7 @@ public DevicePackages getInstalled(KapuaId scopeId, KapuaId deviceId, Long timeo
// Create event
createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackages());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackages().orElse(devicePackageFactory.newDeviceDeploymentPackages()));
}
// Download
@@ -475,7 +479,7 @@ public DevicePackageInstallOperation installStatus(KapuaId scopeId, KapuaId devi
// Create event
createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageInstallOperation());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageInstallOperation().orElse(devicePackageFactory.newPackageInstallOperation()));
}
// Uninstall
@@ -592,7 +596,7 @@ public DevicePackageUninstallOperation uninstallStatus(KapuaId scopeId, KapuaId
// Create event
createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage);
// Check response
- return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageUninstallOperation());
+ return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageUninstallOperation().orElse(devicePackageFactory.newPackageUninstallOperation()));
}
private void verifyOverflowPackageFields(DevicePackageDownloadRequest packageDownloadRequest) throws KapuaIllegalArgumentException {
diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/setting/PackageManagementServiceSetting.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/setting/PackageManagementServiceSetting.java
index 41d2fe0cb42..3eed9717eac 100644
--- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/setting/PackageManagementServiceSetting.java
+++ b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/setting/PackageManagementServiceSetting.java
@@ -14,6 +14,8 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Class that offers access to {@link PackageManagementServiceSetting} settings.
*
@@ -26,21 +28,12 @@ public class PackageManagementServiceSetting extends AbstractKapuaSetting getDevicePackages() throws Exception {
if (!hasBody()) {
- return DEVICE_PACKAGE_FACTORY.newDeviceDeploymentPackages();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DevicePackages.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DevicePackages.class));
}
/**
@@ -153,7 +151,7 @@ public DevicePackages getDevicePackages() throws Exception {
*/
public void setDeploymentPackages(@NotNull DevicePackages devicePackages) throws Exception {
String bodyString = XmlUtil.marshal(devicePackages);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -163,13 +161,13 @@ public void setDeploymentPackages(@NotNull DevicePackages devicePackages) throws
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DevicePackageInstallOperation getDevicePackageInstallOperation() throws Exception {
+ public Optional getDevicePackageInstallOperation() throws Exception {
if (!hasBody()) {
- return DEVICE_PACKAGE_FACTORY.newPackageInstallOperation();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DevicePackageInstallOperation.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DevicePackageInstallOperation.class));
}
/**
@@ -181,7 +179,7 @@ public DevicePackageInstallOperation getDevicePackageInstallOperation() throws E
*/
public void setDevicePackageInstallOperations(@NotNull DevicePackageInstallOperation devicePackageInstallOperation) throws Exception {
String bodyString = XmlUtil.marshal(devicePackageInstallOperation);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
/**
@@ -191,13 +189,13 @@ public void setDevicePackageInstallOperations(@NotNull DevicePackageInstallOpera
* @throws Exception if reading {@link #getBody()} errors.
* @since 1.5.0
*/
- public DevicePackageUninstallOperation getDevicePackageUninstallOperation() throws Exception {
+ public Optional getDevicePackageUninstallOperation() throws Exception {
if (!hasBody()) {
- return DEVICE_PACKAGE_FACTORY.newPackageUninstallOperation();
+ return Optional.empty();
}
- String bodyString = new String(getBody(), CHAR_ENCODING);
- return XmlUtil.unmarshal(bodyString, DevicePackageUninstallOperation.class);
+ String bodyString = new String(getBody(), charEncoding);
+ return Optional.ofNullable(XmlUtil.unmarshal(bodyString, DevicePackageUninstallOperation.class));
}
/**
@@ -209,6 +207,6 @@ public DevicePackageUninstallOperation getDevicePackageUninstallOperation() thro
*/
public void setDevicePackageUninstallOperations(@NotNull DevicePackageUninstallOperation devicePackageUninstallOperation) throws Exception {
String bodyString = XmlUtil.marshal(devicePackageUninstallOperation);
- setBody(bodyString.getBytes(CHAR_ENCODING));
+ setBody(bodyString.getBytes(charEncoding));
}
}
diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java
index 8533923e0c7..9657e50dacb 100644
--- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java
+++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java
@@ -32,29 +32,35 @@
import org.eclipse.kapua.service.job.targets.JobTarget;
import org.eclipse.kapua.service.job.targets.JobTargetStatus;
+import javax.inject.Inject;
+
/**
* {@link AbstractDevicePackageTargetProcessor} for {@link DevicePackageManagementService} operations.
*
* @since 1.1.0
*/
public abstract class AbstractDevicePackageTargetProcessor extends AbstractDeviceTargetProcessor implements TargetProcessor {
- private static final DeviceManagementOperationRegistryService DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE = LOCATOR.getService(DeviceManagementOperationRegistryService.class);
- private static final JobDeviceManagementOperationService JOB_DEVICE_MANAGEMENT_OPERATION_SERVICE = LOCATOR.getService(JobDeviceManagementOperationService.class);
- private static final JobDeviceManagementOperationFactory JOB_DEVICE_MANAGEMENT_OPERATION_FACTORY = LOCATOR.getFactory(JobDeviceManagementOperationFactory.class);
-
- private static final JobEngineService JOB_ENGINE_SERVICE = LOCATOR.getService(JobEngineService.class);
- private static final JobEngineFactory JOB_ENGINE_FACTORY = LOCATOR.getFactory(JobEngineFactory.class);
+ @Inject
+ DeviceManagementOperationRegistryService deviceManagementOperationRegistryService;
+ @Inject
+ JobDeviceManagementOperationService jobDeviceManagementOperationService;
+ @Inject
+ JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory;
+ @Inject
+ JobEngineService jobEngineService;
+ @Inject
+ JobEngineFactory jobEngineFactory;
protected void createJobDeviceManagementOperation(KapuaId scopeId, KapuaId jobId, JobTarget jobTarget, KapuaId operationId) throws KapuaException {
// Save the jobId-deviceManagementOperationId pair to track resuming
- JobDeviceManagementOperationCreator jobDeviceManagementOperationCreator = JOB_DEVICE_MANAGEMENT_OPERATION_FACTORY.newCreator(scopeId);
+ JobDeviceManagementOperationCreator jobDeviceManagementOperationCreator = jobDeviceManagementOperationFactory.newCreator(scopeId);
jobDeviceManagementOperationCreator.setJobId(jobId);
jobDeviceManagementOperationCreator.setDeviceManagementOperationId(operationId);
- JobDeviceManagementOperation jobDeviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> JOB_DEVICE_MANAGEMENT_OPERATION_SERVICE.create(jobDeviceManagementOperationCreator));
+ JobDeviceManagementOperation jobDeviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> jobDeviceManagementOperationService.create(jobDeviceManagementOperationCreator));
// Check if the operation has already COMPLETED/FAILED
- DeviceManagementOperation deviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.find(scopeId, operationId));
+ DeviceManagementOperation deviceManagementOperation = KapuaSecurityUtils.doPrivileged(() -> deviceManagementOperationRegistryService.find(scopeId, operationId));
if (deviceManagementOperation == null) {
throw new KapuaEntityNotFoundException(DeviceManagementOperation.TYPE, operationId);
@@ -76,12 +82,12 @@ protected void createJobDeviceManagementOperation(KapuaId scopeId, KapuaId jobId
return;
}
// Enqueue the job
- JobStartOptions jobStartOptions = JOB_ENGINE_FACTORY.newJobStartOptions();
+ JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions();
jobStartOptions.addTargetIdToSublist(jobTarget.getId());
jobStartOptions.setFromStepIndex(jobTarget.getStepIndex());
jobStartOptions.setEnqueue(true);
- KapuaSecurityUtils.doPrivileged(() -> JOB_ENGINE_SERVICE.startJob(scopeId, jobDeviceManagementOperation.getJobId(), jobStartOptions));
+ KapuaSecurityUtils.doPrivileged(() -> jobEngineService.startJob(scopeId, jobDeviceManagementOperation.getJobId(), jobStartOptions));
}
}
diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java
index 97ebf684162..cc868c49c1f 100644
--- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java
+++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java
@@ -15,7 +15,6 @@
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory;
import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService;
@@ -36,13 +35,13 @@
* @since 1.0.0
*/
public class DevicePackageDownloadTargetProcessor extends AbstractDevicePackageTargetProcessor implements TargetProcessor {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DevicePackageManagementService PACKAGES_MANAGEMENT_SERVICE = LOCATOR.getService(DevicePackageManagementService.class);
- private static final DevicePackageFactory DEVICE_PACKAGE_FACTORY = LOCATOR.getFactory(DevicePackageFactory.class);
+ @Inject
+ DevicePackageManagementService devicePackageManagementService;
+ @Inject
+ DevicePackageFactory devicePackageFactory;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -64,10 +63,10 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
DevicePackageDownloadRequest packageDownloadRequest = stepContextWrapper.getStepProperty(DevicePackageDownloadPropertyKeys.PACKAGE_DOWNLOAD_REQUEST, DevicePackageDownloadRequest.class);
Long timeout = stepContextWrapper.getStepProperty(DevicePackageDownloadPropertyKeys.TIMEOUT, Long.class);
// Send the request
- DevicePackageDownloadOptions packageDownloadOptions = DEVICE_PACKAGE_FACTORY.newPackageDownloadOptions();
+ DevicePackageDownloadOptions packageDownloadOptions = devicePackageFactory.newPackageDownloadOptions();
packageDownloadOptions.setTimeout(timeout);
- KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> PACKAGES_MANAGEMENT_SERVICE.downloadExec(scopeId, jobTarget.getJobTargetId(), packageDownloadRequest, packageDownloadOptions));
+ KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> devicePackageManagementService.downloadExec(scopeId, jobTarget.getJobTargetId(), packageDownloadRequest, packageDownloadOptions));
// Save the jobId-deviceManagementOperationId pair to track resuming
createJobDeviceManagementOperation(scopeId, jobId, jobTarget, operationId);
}
diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java
index bf4900d1801..1b8d9171a2c 100644
--- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java
+++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java
@@ -15,7 +15,6 @@
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory;
import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService;
@@ -36,13 +35,13 @@
* @since 1.0.0
*/
public class DevicePackageUninstallTargetProcessor extends AbstractDevicePackageTargetProcessor implements TargetProcessor {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DevicePackageManagementService PACKAGES_MANAGEMENT_SERVICE = LOCATOR.getService(DevicePackageManagementService.class);
- private static final DevicePackageFactory DEVICE_PACKAGE_FACTORY = LOCATOR.getFactory(DevicePackageFactory.class);
+ @Inject
+ DevicePackageManagementService devicePackageManagementService;
+ @Inject
+ DevicePackageFactory devicePackageFactory;
@Inject
JobContext jobContext;
-
@Inject
StepContext stepContext;
@@ -60,10 +59,10 @@ public void processTarget(JobTarget jobTarget) throws KapuaException {
DevicePackageUninstallRequest packageUninstallRequest = stepContextWrapper.getStepProperty(DevicePackageUninstallPropertyKeys.PACKAGE_UNINSTALL_REQUEST, DevicePackageUninstallRequest.class);
Long timeout = stepContextWrapper.getStepProperty(DevicePackageUninstallPropertyKeys.TIMEOUT, Long.class);
// Send the request
- DevicePackageUninstallOptions packageUninstallOptions = DEVICE_PACKAGE_FACTORY.newPackageUninstallOptions();
+ DevicePackageUninstallOptions packageUninstallOptions = devicePackageFactory.newPackageUninstallOptions();
packageUninstallOptions.setTimeout(timeout);
- KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> PACKAGES_MANAGEMENT_SERVICE.uninstallExec(scopeId, jobTarget.getJobTargetId(), packageUninstallRequest, packageUninstallOptions));
+ KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> devicePackageManagementService.uninstallExec(scopeId, jobTarget.getJobTargetId(), packageUninstallRequest, packageUninstallOptions));
// Save the jobId-deviceManagementOperationId pair to track resuming
createJobDeviceManagementOperation(scopeId, jobId, jobTarget, operationId);
}
diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesDownloadStepDefinition.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesDownloadStepDefinition.java
deleted file mode 100644
index bf20d914d3e..00000000000
--- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesDownloadStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.packages.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.packages.job.DevicePackageDownloadTargetProcessor;
-import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DevicePackagesDownloadStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Package Download / Install";
- }
-
- @Override
- public String getDescription() {
- return "Downloads a package using the Device Packages Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DevicePackageDownloadTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyDownloadRequest = jobStepDefinitionFactory.newStepProperty(
- DevicePackageDownloadPropertyKeys.PACKAGE_DOWNLOAD_REQUEST,
- DevicePackageDownloadRequest.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DevicePackageDownloadPropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyDownloadRequest, propertyTimeout);
- }
-}
diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesUninstallStepDefinition.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesUninstallStepDefinition.java
deleted file mode 100644
index f0ec63b631a..00000000000
--- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/definition/DevicePackagesUninstallStepDefinition.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.management.packages.job.definition;
-
-import org.eclipse.kapua.job.engine.commons.step.definition.AbstractTargetJobStepDefinition;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.service.device.management.packages.job.DevicePackageUninstallTargetProcessor;
-import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinition;
-import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory;
-import org.eclipse.kapua.service.job.step.definition.JobStepProperty;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DevicePackagesUninstallStepDefinition extends AbstractTargetJobStepDefinition implements JobStepDefinition {
-
- private static final long serialVersionUID = -4994045121586264564L;
-
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final JobStepDefinitionFactory jobStepDefinitionFactory = locator.getFactory(JobStepDefinitionFactory.class);
-
- @Override
- public String getName() {
- return "Package Uninstall";
- }
-
- @Override
- public String getDescription() {
- return "Uninstalls a package using the Device Packages Management Service";
- }
-
- @Override
- public String getProcessorName() {
- return DevicePackageUninstallTargetProcessor.class.getName();
- }
-
- @Override
- public List getStepProperties() {
-
- JobStepProperty propertyUninstallRequest = jobStepDefinitionFactory.newStepProperty(
- DevicePackageUninstallPropertyKeys.PACKAGE_UNINSTALL_REQUEST,
- DevicePackageUninstallRequest.class.getName(),
- null,
- null);
-
- JobStepProperty propertyTimeout = jobStepDefinitionFactory.newStepProperty(
- DevicePackageDownloadPropertyKeys.TIMEOUT,
- Long.class.getName(),
- "30000",
- null);
-
- return Arrays.asList(propertyUninstallRequest, propertyTimeout);
- }
-}
diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/DeviceManagementRegistryManagerService.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/DeviceManagementRegistryManagerService.java
index 3f17d3e884b..bd2b1a93795 100644
--- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/DeviceManagementRegistryManagerService.java
+++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/DeviceManagementRegistryManagerService.java
@@ -12,165 +12,14 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.management.registry.manager;
-import com.google.common.base.Strings;
-import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.model.query.SortOrder;
import org.eclipse.kapua.service.KapuaService;
import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus;
import org.eclipse.kapua.service.device.management.registry.manager.exception.ManagementOperationNotificationProcessingException;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationProperty;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService;
-import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationAttributes;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery;
-import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.util.Date;
public interface DeviceManagementRegistryManagerService extends KapuaService {
- Logger LOG = LoggerFactory.getLogger(DeviceManagementRegistryManagerService.class);
-
- KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- DeviceManagementOperationRegistryService DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE = LOCATOR.getService(DeviceManagementOperationRegistryService.class);
- DeviceManagementOperationFactory DEVICE_MANAGEMENT_OPERATION_FACTORY = LOCATOR.getFactory(DeviceManagementOperationFactory.class);
-
- ManagementOperationNotificationService MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_SERVICE = LOCATOR.getService(ManagementOperationNotificationService.class);
- ManagementOperationNotificationFactory MANAGEMENT_OPERATION_NOTIFICATION_FACTORY = LOCATOR.getFactory(ManagementOperationNotificationFactory.class);
-
- String LOG_MESSAGE_GENERATING = "Generating...";
-
- default void processOperationNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status, Integer progress, String message) throws ManagementOperationNotificationProcessingException {
-
- try {
- storeManagementNotification(scopeId, operationId, updateOn, status, resource, progress, message);
-
- if (NotifyStatus.COMPLETED.equals(status)) {
- processCompletedNotification(scopeId, operationId, updateOn, resource, message);
- } else if (NotifyStatus.FAILED.equals(status)) {
- processFailedNotification(scopeId, operationId, updateOn, resource, message);
- }
-
- } catch (KapuaException ke) {
- throw new ManagementOperationNotificationProcessingException(ke, scopeId, operationId, status, updateOn, progress);
- }
- }
-
-
- default void processFailedNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, String message) throws KapuaException {
- closeDeviceManagementOperation(scopeId, operationId, updateOn, NotifyStatus.FAILED, message);
- }
-
- default void processCompletedNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, String message) throws KapuaException {
-
- DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
- // UGLY 'DEPLOY-V2'-related part
- boolean isLastNotification = true;
- for (DeviceManagementOperationProperty ip : deviceManagementOperation.getInputProperties()) {
- if (ip.getName().equals("kapua.package.download.install")) {
- if (resource.equals("download")) {
- isLastNotification = !Boolean.parseBoolean(ip.getPropertyValue());
- }
- break;
- }
- }
-
- if (isLastNotification) {
- closeDeviceManagementOperation(scopeId, operationId, updateOn, NotifyStatus.COMPLETED, message);
- }
- }
-
- default void storeManagementNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, NotifyStatus notifyStatus, String resource, Integer progress, String message) throws KapuaException {
- DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
-
- ManagementOperationNotificationCreator managementOperationNotificationCreator = MANAGEMENT_OPERATION_NOTIFICATION_FACTORY.newCreator(scopeId);
- managementOperationNotificationCreator.setOperationId(deviceManagementOperation.getId());
- managementOperationNotificationCreator.setSentOn(updateOn);
- managementOperationNotificationCreator.setStatus(DeviceManagementOperationStatus.readFrom(notifyStatus));
- managementOperationNotificationCreator.setResource(resource);
- managementOperationNotificationCreator.setProgress(progress);
- managementOperationNotificationCreator.setMessage(message);
-
- MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_SERVICE.create(managementOperationNotificationCreator);
- }
-
- default void closeDeviceManagementOperation(KapuaId scopeId, KapuaId operationId, Date updateOn, NotifyStatus finalStatus, String message) throws KapuaException {
-
- DeviceManagementOperation deviceManagementOperation = null;
-
- boolean failed;
- short attempts = 0;
- short limit = 3;
- do {
- try {
- deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
- deviceManagementOperation.setEndedOn(updateOn);
- deviceManagementOperation.setStatus(finalStatus);
-
- if (deviceManagementOperation.getLog() == null) {
- deviceManagementOperation.setLog(LOG_MESSAGE_GENERATING);
- }
-
- deviceManagementOperation = DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.update(deviceManagementOperation);
-
- LOG.info("Update DeviceManagementOperation {} with status {}... SUCCEEDED!", operationId, finalStatus);
- failed = false;
- } catch (Exception e) {
- failed = true;
- attempts++;
-
- if (attempts >= limit) {
- throw e;
- } else {
- LOG.warn("Update DeviceManagementOperation {} with status {}... FAILED! Retrying...", operationId, finalStatus);
- }
- }
- } while (failed);
-
- {
- ManagementOperationNotificationQuery query = MANAGEMENT_OPERATION_NOTIFICATION_FACTORY.newQuery(scopeId);
- query.setPredicate(query.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, deviceManagementOperation.getId()));
- query.setSortCriteria(query.fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING));
-
- ManagementOperationNotificationListResult notifications = MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_SERVICE.query(query);
-
- StringBuilder logSb = new StringBuilder();
-
- if (!LOG_MESSAGE_GENERATING.equals(deviceManagementOperation.getLog())) {
- logSb.append(deviceManagementOperation.getLog()).append("\n");
- }
-
- for (ManagementOperationNotification mon : notifications.getItems()) {
- if (!Strings.isNullOrEmpty(mon.getMessage())) {
- logSb.append(mon.getSentOn()).append(" - ").append(mon.getMessage()).append("\n");
- }
- MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_SERVICE.delete(mon.getScopeId(), mon.getId());
- }
-
- deviceManagementOperation.setLog(logSb.toString());
- DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.update(deviceManagementOperation);
- }
- }
-
- default DeviceManagementOperation getDeviceManagementOperation(KapuaId scopeId, KapuaId operationId) throws KapuaException {
- DeviceManagementOperation deviceManagementOperation = DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE.findByOperationId(scopeId, operationId);
-
- if (deviceManagementOperation == null) {
- throw new KapuaEntityNotFoundException(DeviceManagementOperation.TYPE, operationId);
- }
-
- return deviceManagementOperation;
- }
+ void processOperationNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status, Integer progress, String message) throws ManagementOperationNotificationProcessingException;
}
diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java
index 97e9da64da7..8e9ad286ab4 100644
--- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java
+++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java
@@ -24,23 +24,22 @@
@XmlRegistry
public class ManagementOperationNotificationXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final ManagementOperationNotificationFactory MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY = LOCATOR.getFactory(ManagementOperationNotificationFactory.class);
+ private final ManagementOperationNotificationFactory managementOperationNotificationFactory = KapuaLocator.getInstance().getFactory(ManagementOperationNotificationFactory.class);
ManagementOperationNotification newManagementOperationNotification() {
- return MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY.newEntity(null);
+ return managementOperationNotificationFactory.newEntity(null);
}
ManagementOperationNotificationCreator newManagementOperationNotificationCreator() {
- return MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY.newCreator(null);
+ return managementOperationNotificationFactory.newCreator(null);
}
ManagementOperationNotificationListResult newManagementOperationNotificationListResult() {
- return MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY.newListResult();
+ return managementOperationNotificationFactory.newListResult();
}
ManagementOperationNotificationQuery newQuery() {
- return MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY.newQuery(null);
+ return managementOperationNotificationFactory.newQuery(null);
}
}
diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java
index 5a38f16525f..4491da0e2fe 100644
--- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java
+++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java
@@ -12,10 +12,173 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.management.registry.manager.internal;
+import com.google.common.base.Strings;
+import org.eclipse.kapua.KapuaEntityNotFoundException;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.model.query.SortOrder;
+import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus;
import org.eclipse.kapua.service.device.management.registry.manager.DeviceManagementRegistryManagerService;
+import org.eclipse.kapua.service.device.management.registry.manager.exception.ManagementOperationNotificationProcessingException;
+import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation;
+import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationProperty;
+import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService;
+import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationAttributes;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery;
+import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
+import java.util.Date;
@Singleton
public class DeviceManagementRegistryManagerServiceImpl implements DeviceManagementRegistryManagerService {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DeviceManagementRegistryManagerService.class);
+
+ private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService;
+ private final ManagementOperationNotificationService managementOperationNotificationService;
+ private final ManagementOperationNotificationFactory managementOperationNotificationFactory;
+
+ private static final String LOG_MESSAGE_GENERATING = "Generating...";
+
+ @Inject
+ public DeviceManagementRegistryManagerServiceImpl(
+ DeviceManagementOperationRegistryService deviceManagementOperationRegistryService,
+ ManagementOperationNotificationService managementOperationNotificationService,
+ ManagementOperationNotificationFactory managementOperationNotificationFactory) {
+ this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService;
+ this.managementOperationNotificationService = managementOperationNotificationService;
+ this.managementOperationNotificationFactory = managementOperationNotificationFactory;
+ }
+
+ @Override
+ public void processOperationNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status, Integer progress, String message) throws ManagementOperationNotificationProcessingException {
+
+ try {
+ storeManagementNotification(scopeId, operationId, updateOn, status, resource, progress, message);
+
+ if (NotifyStatus.COMPLETED.equals(status)) {
+ processCompletedNotification(scopeId, operationId, updateOn, resource, message);
+ } else if (NotifyStatus.FAILED.equals(status)) {
+ processFailedNotification(scopeId, operationId, updateOn, resource, message);
+ }
+
+ } catch (KapuaException ke) {
+ throw new ManagementOperationNotificationProcessingException(ke, scopeId, operationId, status, updateOn, progress);
+ }
+ }
+
+
+ public void processFailedNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, String message) throws KapuaException {
+ closeDeviceManagementOperation(scopeId, operationId, updateOn, NotifyStatus.FAILED, message);
+ }
+
+ public void processCompletedNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, String message) throws KapuaException {
+
+ DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
+ // UGLY 'DEPLOY-V2'-related part
+ boolean isLastNotification = true;
+ for (DeviceManagementOperationProperty ip : deviceManagementOperation.getInputProperties()) {
+ if (ip.getName().equals("kapua.package.download.install")) {
+ if (resource.equals("download")) {
+ isLastNotification = !Boolean.parseBoolean(ip.getPropertyValue());
+ }
+ break;
+ }
+ }
+
+ if (isLastNotification) {
+ closeDeviceManagementOperation(scopeId, operationId, updateOn, NotifyStatus.COMPLETED, message);
+ }
+ }
+
+ public void storeManagementNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, NotifyStatus notifyStatus, String resource, Integer progress, String message) throws KapuaException {
+ DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
+
+ ManagementOperationNotificationCreator managementOperationNotificationCreator = managementOperationNotificationFactory.newCreator(scopeId);
+ managementOperationNotificationCreator.setOperationId(deviceManagementOperation.getId());
+ managementOperationNotificationCreator.setSentOn(updateOn);
+ managementOperationNotificationCreator.setStatus(DeviceManagementOperationStatus.readFrom(notifyStatus));
+ managementOperationNotificationCreator.setResource(resource);
+ managementOperationNotificationCreator.setProgress(progress);
+ managementOperationNotificationCreator.setMessage(message);
+
+ managementOperationNotificationService.create(managementOperationNotificationCreator);
+ }
+
+ public void closeDeviceManagementOperation(KapuaId scopeId, KapuaId operationId, Date updateOn, NotifyStatus finalStatus, String message) throws KapuaException {
+
+ DeviceManagementOperation deviceManagementOperation = null;
+
+ boolean failed;
+ short attempts = 0;
+ short limit = 3;
+ do {
+ try {
+ deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId);
+ deviceManagementOperation.setEndedOn(updateOn);
+ deviceManagementOperation.setStatus(finalStatus);
+
+ if (deviceManagementOperation.getLog() == null) {
+ deviceManagementOperation.setLog(LOG_MESSAGE_GENERATING);
+ }
+
+ deviceManagementOperation = deviceManagementOperationRegistryService.update(deviceManagementOperation);
+
+ LOG.info("Update DeviceManagementOperation {} with status {}... SUCCEEDED!", operationId, finalStatus);
+ failed = false;
+ } catch (Exception e) {
+ failed = true;
+ attempts++;
+
+ if (attempts >= limit) {
+ throw e;
+ } else {
+ LOG.warn("Update DeviceManagementOperation {} with status {}... FAILED! Retrying...", operationId, finalStatus);
+ }
+ }
+ } while (failed);
+
+ {
+ ManagementOperationNotificationQuery query = managementOperationNotificationFactory.newQuery(scopeId);
+ query.setPredicate(query.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, deviceManagementOperation.getId()));
+ query.setSortCriteria(query.fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING));
+
+ ManagementOperationNotificationListResult notifications = managementOperationNotificationService.query(query);
+
+ StringBuilder logSb = new StringBuilder();
+
+ if (!LOG_MESSAGE_GENERATING.equals(deviceManagementOperation.getLog())) {
+ logSb.append(deviceManagementOperation.getLog()).append("\n");
+ }
+
+ for (ManagementOperationNotification mon : notifications.getItems()) {
+ if (!Strings.isNullOrEmpty(mon.getMessage())) {
+ logSb.append(mon.getSentOn()).append(" - ").append(mon.getMessage()).append("\n");
+ }
+ managementOperationNotificationService.delete(mon.getScopeId(), mon.getId());
+ }
+
+ deviceManagementOperation.setLog(logSb.toString());
+ deviceManagementOperationRegistryService.update(deviceManagementOperation);
+ }
+ }
+
+ public DeviceManagementOperation getDeviceManagementOperation(KapuaId scopeId, KapuaId operationId) throws KapuaException {
+ DeviceManagementOperation deviceManagementOperation = deviceManagementOperationRegistryService.findByOperationId(scopeId, operationId);
+
+ if (deviceManagementOperation == null) {
+ throw new KapuaEntityNotFoundException(DeviceManagementOperation.TYPE, operationId);
+ }
+
+ return deviceManagementOperation;
+ }
}
diff --git a/service/device/management/request/api/src/main/java/org/eclipse/kapua/service/device/management/request/GenericRequestXmlRegistry.java b/service/device/management/request/api/src/main/java/org/eclipse/kapua/service/device/management/request/GenericRequestXmlRegistry.java
index 55358f29197..18abdcc07cf 100644
--- a/service/device/management/request/api/src/main/java/org/eclipse/kapua/service/device/management/request/GenericRequestXmlRegistry.java
+++ b/service/device/management/request/api/src/main/java/org/eclipse/kapua/service/device/management/request/GenericRequestXmlRegistry.java
@@ -25,30 +25,29 @@
@XmlRegistry
public class GenericRequestXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final GenericRequestFactory FACTORY = LOCATOR.getFactory(GenericRequestFactory.class);
+ private final GenericRequestFactory genericRequestFactory = KapuaLocator.getInstance().getFactory(GenericRequestFactory.class);
public GenericRequestChannel newRequestChannel() {
- return FACTORY.newRequestChannel();
+ return genericRequestFactory.newRequestChannel();
}
public GenericRequestPayload newRequestPayload() {
- return FACTORY.newRequestPayload();
+ return genericRequestFactory.newRequestPayload();
}
public GenericRequestMessage newRequestMessage() {
- return FACTORY.newRequestMessage();
+ return genericRequestFactory.newRequestMessage();
}
public GenericResponseChannel newResponseChannel() {
- return FACTORY.newResponseChannel();
+ return genericRequestFactory.newResponseChannel();
}
public GenericResponsePayload newResponsePayload() {
- return FACTORY.newResponsePayload();
+ return genericRequestFactory.newResponsePayload();
}
public GenericResponseMessage newResponseMessage() {
- return FACTORY.newResponseMessage();
+ return genericRequestFactory.newResponseMessage();
}
}
diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java
index fc2aa8e780c..573905a636b 100644
--- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java
+++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceFactory DEVICE_FACTORY = LOCATOR.getFactory(DeviceFactory.class);
+ private final DeviceFactory deviceFactory = KapuaLocator.getInstance().getFactory(DeviceFactory.class);
/**
* Creates a new {@link Device}
@@ -34,7 +33,7 @@ public class DeviceXmlRegistry {
* @since 1.0.0
*/
public Device newDevice() {
- return DEVICE_FACTORY.newEntity(null);
+ return deviceFactory.newEntity(null);
}
/**
@@ -44,7 +43,7 @@ public Device newDevice() {
* @since 1.0.0
*/
public DeviceCreator newDeviceCreator() {
- return DEVICE_FACTORY.newCreator(null, null);
+ return deviceFactory.newCreator(null, null);
}
/**
@@ -54,11 +53,11 @@ public DeviceCreator newDeviceCreator() {
* @since 1.0.0
*/
public DeviceListResult newDeviceListResult() {
- return DEVICE_FACTORY.newListResult();
+ return deviceFactory.newListResult();
}
public DeviceQuery newQuery() {
- return DEVICE_FACTORY.newQuery(null);
+ return deviceFactory.newQuery(null);
}
/**
@@ -68,6 +67,6 @@ public DeviceQuery newQuery() {
* @since 1.5.0
*/
public DeviceExtendedProperty newDeviceExtendedProperty() {
- return DEVICE_FACTORY.newExtendedProperty(null, null, null);
+ return deviceFactory.newExtendedProperty(null, null, null);
}
}
diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java
index aedb549fa70..b4812c01608 100644
--- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java
+++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceConnectionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceConnectionFactory DEVICE_CONNECTION_FACTORY = LOCATOR.getFactory(DeviceConnectionFactory.class);
+ private final DeviceConnectionFactory deviceConnectionFactory = KapuaLocator.getInstance().getFactory(DeviceConnectionFactory.class);
/**
* Creates a new {@link DeviceConnection}
@@ -33,7 +32,7 @@ public class DeviceConnectionXmlRegistry {
* @return
*/
public DeviceConnection newDeviceConnection() {
- return DEVICE_CONNECTION_FACTORY.newEntity(null);
+ return deviceConnectionFactory.newEntity(null);
}
/**
@@ -42,10 +41,10 @@ public DeviceConnection newDeviceConnection() {
* @return
*/
public DeviceConnectionListResult newDeviceConnectionListResult() {
- return DEVICE_CONNECTION_FACTORY.newListResult();
+ return deviceConnectionFactory.newListResult();
}
public DeviceConnectionQuery newQuery() {
- return DEVICE_CONNECTION_FACTORY.newQuery(null);
+ return deviceConnectionFactory.newQuery(null);
}
}
diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java
index 00c0ed1df34..c2da267c5a2 100644
--- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java
+++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceConnectionOptionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceConnectionOptionFactory DEVICE_CONNECTION_OPTION_FACTORY = LOCATOR.getFactory(DeviceConnectionOptionFactory.class);
+ private final DeviceConnectionOptionFactory deviceConnectionOptionFactory = KapuaLocator.getInstance().getFactory(DeviceConnectionOptionFactory.class);
/**
* Creates a new {@link DeviceConnectionOption}
@@ -33,7 +32,7 @@ public class DeviceConnectionOptionXmlRegistry {
* @return
*/
public DeviceConnectionOption newDeviceConnectionOption() {
- return DEVICE_CONNECTION_OPTION_FACTORY.newEntity(null);
+ return deviceConnectionOptionFactory.newEntity(null);
}
/**
@@ -42,10 +41,10 @@ public DeviceConnectionOption newDeviceConnectionOption() {
* @return
*/
public DeviceConnectionOptionListResult newDeviceConnectionOptionListResult() {
- return DEVICE_CONNECTION_OPTION_FACTORY.newListResult();
+ return deviceConnectionOptionFactory.newListResult();
}
public DeviceConnectionOptionQuery newQuery() {
- return DEVICE_CONNECTION_OPTION_FACTORY.newQuery(null);
+ return deviceConnectionOptionFactory.newQuery(null);
}
}
diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java
index 3f1e360552c..ca95c3f14eb 100644
--- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java
+++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class DeviceEventXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DeviceEventFactory DEVICE_EVENT_FACTORY = LOCATOR.getFactory(DeviceEventFactory.class);
+ private final DeviceEventFactory deviceEventFactory = KapuaLocator.getInstance().getFactory(DeviceEventFactory.class);
/**
* Creates a new device event
@@ -33,7 +32,7 @@ public class DeviceEventXmlRegistry {
* @return
*/
public DeviceEvent newDeviceEvent() {
- return DEVICE_EVENT_FACTORY.newEntity(null);
+ return deviceEventFactory.newEntity(null);
}
/**
@@ -42,10 +41,10 @@ public DeviceEvent newDeviceEvent() {
* @return
*/
public DeviceEventListResult newDeviceEventListResult() {
- return DEVICE_EVENT_FACTORY.newListResult();
+ return deviceEventFactory.newListResult();
}
public DeviceEventQuery newQuery() {
- return DEVICE_EVENT_FACTORY.newQuery(null);
+ return deviceEventFactory.newQuery(null);
}
}
diff --git a/service/device/registry/internal/pom.xml b/service/device/registry/internal/pom.xml
index 67713de5d73..9cdd74e59ca 100644
--- a/service/device/registry/internal/pom.xml
+++ b/service/device/registry/internal/pom.xml
@@ -62,10 +62,5 @@
org.eclipse.kapua
kapua-tag-api
-
-
- org.eclipse.kapua
- kapua-security-shiro
-
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java
index 3e4849f49eb..60399387804 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java
@@ -12,14 +12,15 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.connection.listener.internal;
-import javax.inject.Named;
-
+import com.google.inject.Module;
+import com.google.inject.multibindings.ProvidesIntoSet;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.core.ServiceModule;
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.event.ServiceEventBusException;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
@@ -28,8 +29,7 @@
import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettings;
import org.eclipse.kapua.storage.TxManager;
-import com.google.inject.Module;
-import com.google.inject.multibindings.ProvidesIntoSet;
+import javax.inject.Named;
/**
* {@code kapua-account-internal} {@link Module} implementation.
@@ -45,14 +45,16 @@ protected void configureModule() {
@ProvidesIntoSet
protected ServiceModule deviceConnectionEventListenerServiceModule(DeviceConnectionEventListenerService deviceConnectionEventListenerService,
- AuthorizationService authorizationService,
- PermissionFactory permissionFactory,
- @Named("DeviceRegistryTransactionManager") TxManager txManager,
- EventStoreFactory eventStoreFactory,
- EventStoreRecordRepository eventStoreRecordRepository
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings,
+ @Named("DeviceRegistryTransactionManager") TxManager txManager,
+ EventStoreFactory eventStoreFactory,
+ EventStoreRecordRepository eventStoreRecordRepository,
+ ServiceEventBus serviceEventBus
) throws ServiceEventBusException {
- String address = KapuaDeviceRegistrySettings.getInstance().getString(KapuaDeviceRegistrySettingKeys.DEVICE_EVENT_ADDRESS);
+ String address = kapuaDeviceRegistrySettings.getString(KapuaDeviceRegistrySettingKeys.DEVICE_EVENT_ADDRESS);
return new DeviceConnectionEventListenerServiceModule(
deviceConnectionEventListenerService,
address,
@@ -64,7 +66,9 @@ protected ServiceModule deviceConnectionEventListenerServiceModule(DeviceConnect
eventStoreFactory,
eventStoreRecordRepository
),
- txManager
- ));
+ txManager,
+ serviceEventBus
+ ),
+ serviceEventBus);
}
}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerServiceModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerServiceModule.java
index 4e219286846..a93ee2893f7 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerServiceModule.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerServiceModule.java
@@ -17,14 +17,16 @@
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactory;
import org.eclipse.kapua.commons.event.ServiceEventTransactionalModule;
import org.eclipse.kapua.commons.event.ServiceInspector;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.service.device.connection.listener.DeviceConnectionEventListenerService;
public class DeviceConnectionEventListenerServiceModule extends ServiceEventTransactionalModule implements ServiceModule {
- public DeviceConnectionEventListenerServiceModule(DeviceConnectionEventListenerService deviceConnectionEventListenerService, String eventAddress, ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory) {
+ public DeviceConnectionEventListenerServiceModule(DeviceConnectionEventListenerService deviceConnectionEventListenerService, String eventAddress, ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory,
+ ServiceEventBus serviceEventBus) {
super(ServiceInspector.getEventBusClients(deviceConnectionEventListenerService, DeviceConnectionEventListenerService.class).toArray(new ServiceEventClientConfiguration[0]),
eventAddress,
- serviceEventTransactionalHousekeeperFactory);
+ serviceEventTransactionalHousekeeperFactory, serviceEventBus);
}
}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceConnectionServiceConfigurationModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceConnectionServiceConfigurationModule.java
deleted file mode 100644
index 9124c5baf7e..00000000000
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceConnectionServiceConfigurationModule.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.device.registry;
-
-import com.google.inject.Provides;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
-import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
-import org.eclipse.kapua.commons.configuration.RootUserTester;
-import org.eclipse.kapua.commons.configuration.ServiceConfigImplJpaRepository;
-import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
-import org.eclipse.kapua.commons.configuration.ServiceConfigurationManagerCachingWrapper;
-import org.eclipse.kapua.commons.core.AbstractKapuaModule;
-import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
-import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
-import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter;
-import org.eclipse.kapua.service.device.registry.connection.internal.DeviceConnectionServiceConfigurationManager;
-
-import javax.inject.Named;
-import javax.inject.Singleton;
-import java.util.Map;
-
-/**
- * {@link DeviceConnectionServiceConfigurationManager}'s {@link AbstractKapuaModule}.
- *
- * @since 2.0.0
- */
-public class DeviceConnectionServiceConfigurationModule extends AbstractKapuaModule {
-
- @Override
- protected void configureModule() {
- // Nothing to bind here
- }
-
- @Provides
- @Singleton
- @Named("DeviceConnectionServiceConfigurationManager")
- protected ServiceConfigurationManager deviceConnectionServiceConfigurationManager(
- RootUserTester rootUserTester,
- KapuaJpaRepositoryConfiguration jpaRepoConfig,
- Map availableDeviceConnectionAdapters,
- KapuaMetatypeFactory kapuaMetatypeFactory) {
- return new ServiceConfigurationManagerCachingWrapper(
- new DeviceConnectionServiceConfigurationManager(
- new CachingServiceConfigRepository(
- new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
- ),
- rootUserTester,
- availableDeviceConnectionAdapters,
- kapuaMetatypeFactory)
- );
- }
-}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java
index a06b8d901a7..64c222d52ae 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.ResourceLimitedServiceConfigurationManagerImpl;
@@ -26,25 +25,34 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.core.ServiceModule;
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
+import org.eclipse.kapua.commons.jpa.EventStorer;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.event.ServiceEventBusException;
+import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.domain.Domain;
import org.eclipse.kapua.model.domain.DomainEntry;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.access.GroupQueryHelper;
+import org.eclipse.kapua.service.authorization.group.GroupService;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidation;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidationImpl;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionRepository;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService;
import org.eclipse.kapua.service.device.registry.connection.internal.CachingDeviceConnectionRepository;
import org.eclipse.kapua.service.device.registry.connection.internal.DeviceConnectionFactoryImpl;
import org.eclipse.kapua.service.device.registry.connection.internal.DeviceConnectionImplJpaRepository;
+import org.eclipse.kapua.service.device.registry.connection.internal.DeviceConnectionServiceConfigurationManager;
import org.eclipse.kapua.service.device.registry.connection.internal.DeviceConnectionServiceImpl;
import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionFactory;
import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionRepository;
@@ -66,6 +74,7 @@
import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryServiceImpl;
import org.eclipse.kapua.service.device.registry.lifecycle.DeviceLifeCycleService;
import org.eclipse.kapua.service.device.registry.lifecycle.internal.DeviceLifeCycleServiceImpl;
+import org.eclipse.kapua.service.tag.TagService;
import org.eclipse.kapua.storage.TxManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,14 +94,14 @@ public class DeviceRegistryModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(DeviceRegistryCacheFactory.class).toInstance(new DeviceRegistryCacheFactory());
- bind(DeviceFactory.class).to(DeviceFactoryImpl.class);
- bind(DeviceConnectionFactory.class).to(DeviceConnectionFactoryImpl.class);
- bind(DeviceConnectionOptionFactory.class).to(DeviceConnectionOptionFactoryImpl.class);
- bind(DeviceEventFactory.class).to(DeviceEventFactoryImpl.class);
- bind(DeviceLifeCycleService.class).to(DeviceLifeCycleServiceImpl.class);
- bind(DeviceConnectionService.class).to(DeviceConnectionServiceImpl.class);
- bind(DeviceRegistryService.class).to(DeviceRegistryServiceImpl.class);
+ bind(DeviceRegistryCacheFactory.class).in(Singleton.class);
+ bind(DeviceFactory.class).to(DeviceFactoryImpl.class).in(Singleton.class);
+ bind(DeviceConnectionFactory.class).to(DeviceConnectionFactoryImpl.class).in(Singleton.class);
+ bind(DeviceConnectionOptionFactory.class).to(DeviceConnectionOptionFactoryImpl.class).in(Singleton.class);
+ bind(DeviceEventFactory.class).to(DeviceEventFactoryImpl.class).in(Singleton.class);
+ bind(DeviceLifeCycleService.class).to(DeviceLifeCycleServiceImpl.class).in(Singleton.class);
+ bind(KapuaDeviceRegistrySettings.class).in(Singleton.class);
+ bind(DeviceConnectionService.class).to(DeviceConnectionServiceImpl.class).in(Singleton.class);
}
@ProvidesIntoSet
@@ -116,35 +125,87 @@ public Domain deviceEventDomain() {
}
@ProvidesIntoSet
- protected ServiceModule deviceServiceModule(DeviceConnectionService deviceConnectionService,
- DeviceRegistryService deviceRegistryService,
- AuthorizationService authorizationService,
- PermissionFactory permissionFactory,
- @Named("DeviceRegistryTransactionManager") TxManager txManager,
- EventStoreFactory eventStoreFactory,
- EventStoreRecordRepository eventStoreRecordRepository
+ ServiceModule deviceRegistryModule(DeviceConnectionService deviceConnectionService,
+ DeviceRegistryService deviceRegistryService,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ KapuaJpaTxManagerFactory txManagerFactory,
+ EventStoreFactory eventStoreFactory,
+ EventStoreRecordRepository eventStoreRecordRepository,
+ ServiceEventBus serviceEventBus,
+ KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings,
+ KapuaJpaTxManagerFactory jpaTxManagerFactory
) throws ServiceEventBusException {
return new DeviceServiceModule(
deviceConnectionService,
deviceRegistryService,
- KapuaDeviceRegistrySettings.getInstance(),
+ kapuaDeviceRegistrySettings,
new ServiceEventHouseKeeperFactoryImpl(
new EventStoreServiceImpl(
authorizationService,
permissionFactory,
- txManager,
+ jpaTxManagerFactory.create("kapua-device"),
eventStoreFactory,
eventStoreRecordRepository
),
- txManager
- ));
+ jpaTxManagerFactory.create("kapua-device"),
+ serviceEventBus
+ ),
+ serviceEventBus);
+ }
+
+ @Provides
+ @Singleton
+ DeviceValidation deviceValidation(KapuaDeviceRegistrySettings deviceRegistrySettings,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ GroupService groupService,
+ DeviceConnectionService deviceConnectionService,
+ DeviceEventService deviceEventService,
+ DeviceRepository deviceRepository,
+ DeviceFactory deviceFactory,
+ TagService tagService) {
+ return new DeviceValidationImpl(deviceRegistrySettings.getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX),
+ deviceRegistrySettings.getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX),
+ authorizationService,
+ permissionFactory,
+ groupService,
+ deviceConnectionService,
+ deviceEventService,
+ deviceRepository,
+ deviceFactory,
+ tagService);
+ }
+
+ @Provides
+ @Singleton
+ DeviceRegistryService deviceRegistryService(
+ @Named("DeviceRegistryServiceConfigurationManager") ServiceConfigurationManager serviceConfigurationManager,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ DeviceRepository deviceRepository,
+ DeviceFactory deviceFactory,
+ GroupQueryHelper groupQueryHelper,
+ EventStorer eventStorer,
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ DeviceValidation deviceValidation) {
+ return new DeviceRegistryServiceImpl(
+ serviceConfigurationManager,
+ authorizationService,
+ permissionFactory,
+ jpaTxManagerFactory.create("kapua-device"),
+ deviceRepository,
+ deviceFactory,
+ groupQueryHelper,
+ eventStorer,
+ deviceValidation);
}
@Provides
@Singleton
- protected DeviceRepository deviceRepository(DeviceFactory deviceFactory,
- DeviceRegistryCache deviceRegistryCache,
- KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ DeviceRepository deviceRepository(DeviceFactory deviceFactory,
+ DeviceRegistryCache deviceRegistryCache,
+ KapuaJpaRepositoryConfiguration jpaRepoConfig) {
return new CachingDeviceRepository(new DeviceImplJpaRepository(jpaRepoConfig),
deviceRegistryCache
);
@@ -165,14 +226,15 @@ protected ServiceConfigurationManager deviceRegistryServiceConfigurationManager(
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
DeviceRepository deviceRepository,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(
DeviceRegistryService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
@@ -184,7 +246,30 @@ protected ServiceConfigurationManager deviceRegistryServiceConfigurationManager(
@Provides
@Singleton
- protected DeviceRegistryCache deviceRegistryCache(DeviceRegistryCacheFactory deviceRegistryCacheFactory) {
+ @Named("DeviceConnectionServiceConfigurationManager")
+ ServiceConfigurationManager deviceConnectionServiceConfigurationManager(
+ RootUserTester rootUserTester,
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ Map availableDeviceConnectionAdapters,
+ KapuaMetatypeFactory kapuaMetatypeFactory,
+ EntityCacheFactory entityCacheFactory,
+ KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings) {
+ return new ServiceConfigurationManagerCachingWrapper(
+ new DeviceConnectionServiceConfigurationManager(
+ new CachingServiceConfigRepository(
+ new ServiceConfigImplJpaRepository(jpaRepoConfig),
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
+ ),
+ rootUserTester,
+ availableDeviceConnectionAdapters,
+ kapuaMetatypeFactory,
+ kapuaDeviceRegistrySettings)
+ );
+ }
+
+ @Provides
+ @Singleton
+ DeviceRegistryCache deviceRegistryCache(DeviceRegistryCacheFactory deviceRegistryCacheFactory) {
return (DeviceRegistryCache) deviceRegistryCacheFactory.createCache();
}
@@ -247,4 +332,4 @@ protected DeviceEventService deviceEventService(
protected DeviceEventRepository deviceEventRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) {
return new DeviceEventImplJpaRepository(jpaRepoConfig);
}
-}
+}
\ No newline at end of file
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceServiceModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceServiceModule.java
index 17d28f1f990..4de29c7101b 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceServiceModule.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceServiceModule.java
@@ -19,6 +19,7 @@
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactory;
import org.eclipse.kapua.commons.event.ServiceEventTransactionalModule;
import org.eclipse.kapua.commons.event.ServiceInspector;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService;
public class DeviceServiceModule extends ServiceEventTransactionalModule {
@@ -26,7 +27,8 @@ public class DeviceServiceModule extends ServiceEventTransactionalModule {
public DeviceServiceModule(DeviceConnectionService deviceConnectionService,
DeviceRegistryService deviceRegistryService,
KapuaDeviceRegistrySettings deviceRegistrySettings,
- ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory) {
+ ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory,
+ ServiceEventBus serviceEventBus) {
super(Arrays.asList(ServiceInspector.getEventBusClients(deviceRegistryService, DeviceRegistryService.class),
ServiceInspector.getEventBusClients(deviceConnectionService, DeviceConnectionService.class)
)
@@ -35,6 +37,7 @@ public DeviceServiceModule(DeviceConnectionService deviceConnectionService,
.collect(Collectors.toList())
.toArray(new ServiceEventClientConfiguration[0]),
deviceRegistrySettings.getString(KapuaDeviceRegistrySettingKeys.DEVICE_EVENT_ADDRESS),
- serviceEventTransactionalHousekeeperFactory);
+ serviceEventTransactionalHousekeeperFactory,
+ serviceEventBus);
}
}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/KapuaDeviceRegistrySettings.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/KapuaDeviceRegistrySettings.java
index fd59cb0a05d..f97f812e444 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/KapuaDeviceRegistrySettings.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/KapuaDeviceRegistrySettings.java
@@ -15,6 +15,8 @@
import org.eclipse.kapua.commons.setting.AbstractBaseKapuaSetting;
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* {@link AbstractBaseKapuaSetting} for `kapua-device-registry-internal` module.
*
@@ -24,25 +26,14 @@ public class KapuaDeviceRegistrySettings extends AbstractKapuaSetting GROUP_SERVICE.find(deviceCreator.getScopeId(), deviceCreator.getGroupId())
- ), "deviceCreator.groupId");
- }
-
- // .status
- ArgumentValidator.notNull(deviceCreator.getStatus(), "deviceCreator.status");
-
- // .connectionId
- if (deviceCreator.getConnectionId() != null) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> DEVICE_CONNECTION_SERVICE.find(deviceCreator.getScopeId(), deviceCreator.getConnectionId())
- ), "deviceCreator.connectionId");
- }
-
- // .lastEventId
- if (deviceCreator.getLastEventId() != null) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> DEVICE_EVENT_SERVICE.find(deviceCreator.getScopeId(), deviceCreator.getLastEventId())
- ), "deviceCreator.lastEventId");
- }
-
- // .displayName
- if (!Strings.isNullOrEmpty(deviceCreator.getDisplayName())) {
- ArgumentValidator.lengthRange(deviceCreator.getDisplayName(), 1, 255, "deviceCreator.displayName");
- }
-
- // .serialNumber
- if (!Strings.isNullOrEmpty(deviceCreator.getSerialNumber())) {
- ArgumentValidator.lengthRange(deviceCreator.getSerialNumber(), 1, 255, "deviceCreator.serialNumber");
- }
-
- // .modelId
- if (!Strings.isNullOrEmpty(deviceCreator.getModelId())) {
- ArgumentValidator.lengthRange(deviceCreator.getModelId(), 1, 255, "deviceCreator.modelId");
- }
-
- // .modelName
- if (!Strings.isNullOrEmpty(deviceCreator.getModelName())) {
- ArgumentValidator.lengthRange(deviceCreator.getModelName(), 1, 255, "deviceCreator.modelName");
- }
-
- // .imei
- if (!Strings.isNullOrEmpty(deviceCreator.getImei())) {
- ArgumentValidator.lengthRange(deviceCreator.getImei(), 1, 24, "deviceCreator.imei");
- }
-
- // .imsi
- if (!Strings.isNullOrEmpty(deviceCreator.getImsi())) {
- ArgumentValidator.lengthRange(deviceCreator.getImsi(), 1, 15, "deviceCreator.imsi");
- }
-
- // .iccid
- if (!Strings.isNullOrEmpty(deviceCreator.getIccid())) {
- ArgumentValidator.lengthRange(deviceCreator.getIccid(), 1, 22, "deviceCreator.iccid");
- }
-
- // .biosVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getBiosVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getBiosVersion(), 1, 255, "deviceCreator.biosVersion");
- }
-
- // .firmwareVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getFirmwareVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getFirmwareVersion(), 1, 255, "deviceCreator.firmwareVersion");
- }
-
- // .osVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getOsVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getOsVersion(), 1, 255, "deviceCreator.osVersion");
- }
-
- // .jvmVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getJvmVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getJvmVersion(), 1, 255, "deviceCreator.jvmVersion");
- }
-
- // .osgiFrameworkVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getOsgiFrameworkVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getOsgiFrameworkVersion(), 1, 255, "deviceCreator.osgiFrameworkVersion");
- }
-
- // .applicationFrameworkVersion
- if (!Strings.isNullOrEmpty(deviceCreator.getApplicationFrameworkVersion())) {
- ArgumentValidator.lengthRange(deviceCreator.getApplicationFrameworkVersion(), 1, 255, "deviceCreator.applicationFrameworkVersion");
- }
-
- // .connectionInterface
- if (!Strings.isNullOrEmpty(deviceCreator.getConnectionInterface())) {
- ArgumentValidator.lengthRange(deviceCreator.getConnectionInterface(), 1, BIRTH_FIELDS_CLOB_MAX_LENGTH, "deviceCreator.connectionInterface");
- }
-
- // .connectionIp
- if (!Strings.isNullOrEmpty(deviceCreator.getConnectionIp())) {
- ArgumentValidator.lengthRange(deviceCreator.getConnectionIp(), 1, BIRTH_FIELDS_CLOB_MAX_LENGTH, "deviceCreator.connectionIp");
- }
-
- // .applicationIdentifiers
- if (!Strings.isNullOrEmpty(deviceCreator.getApplicationIdentifiers())) {
- ArgumentValidator.lengthRange(deviceCreator.getApplicationIdentifiers(), 1, 1024, "deviceCreator.applicationIdentifiers");
- }
-
- // .acceptEncoding
- if (!Strings.isNullOrEmpty(deviceCreator.getAcceptEncoding())) {
- ArgumentValidator.lengthRange(deviceCreator.getAcceptEncoding(), 1, 255, "deviceCreator.acceptEncoding");
- }
-
- // .customAttribute1
- if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute1())) {
- ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute1(), 1, 255, "deviceCreator.customAttribute1");
- }
-
- // .customAttribute2
- if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute2())) {
- ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute2(), 1, 255, "deviceCreator.customAttribute2");
- }
-
- // .customAttribute3
- if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute3())) {
- ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute3(), 1, 255, "deviceCreator.customAttribute3");
- }
-
- // .customAttribute4
- if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute4())) {
- ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute4(), 1, 255, "deviceCreator.customAttribute4");
- }
-
- // .customAttribute5
- if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute5())) {
- ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute5(), 1, 255, "deviceCreator.customAttribute5");
- }
-
- // .extendedProperties
- for (DeviceExtendedProperty deviceExtendedProperty : deviceCreator.getExtendedProperties()) {
- // .groupName
- ArgumentValidator.notNull(deviceExtendedProperty.getGroupName(), "deviceCreator.extendedProperties[].groupName");
- ArgumentValidator.lengthRange(deviceExtendedProperty.getGroupName(), 1, 64, "deviceCreator.extendedProperties[].groupName");
-
- // .name
- ArgumentValidator.notNull(deviceExtendedProperty.getName(), "deviceCreator.extendedProperties[].name");
- ArgumentValidator.lengthRange(deviceExtendedProperty.getName(), 1, 64, "deviceCreator.extendedProperties[].name");
-
- // .value
- if (!Strings.isNullOrEmpty(deviceExtendedProperty.getValue())) {
- ArgumentValidator.lengthRange(deviceExtendedProperty.getValue(), 1, BIRTH_FIELDS_EXTENDED_PROPERTY_VALUE_MAX_LENGTH, "deviceCreator.extendedProperties[].value");
- }
- }
- // Check access
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.write, deviceCreator.getScopeId(), deviceCreator.getGroupId()));
- }
-
- /**
- * Validates the {@link Device} for {@link DeviceRegistryService#update(KapuaUpdatableEntity)} operation.
- *
- * @param device The {@link Device} to validate.
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link Device} fields is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateUpdatePreconditions(Device device) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(device, "device");
- ArgumentValidator.notNull(device.getScopeId(), "device.scopeId");
- ArgumentValidator.notNull(device.getId(), "device.id");
-
- // .clientId
- ArgumentValidator.notEmptyOrNull(device.getClientId(), "device.clientId");
- ArgumentValidator.lengthRange(device.getClientId(), 1, 255, "device.clientId");
- ArgumentValidator.match(device.getClientId(), DeviceValidationRegex.CLIENT_ID, "device.clientId");
-
- // .groupId
- // Check that current User can manage the current Group of the Device
- KapuaId currentGroupId = findCurrentGroupId(device.getScopeId(), device.getId());
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), currentGroupId));
-
- // Check that current User can manage the target Group of the Device
- if (device.getGroupId() != null) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> GROUP_SERVICE.find(device.getScopeId(), device.getGroupId())
- ), "device.groupId");
- }
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), device.getGroupId()));
-
- // .status
- ArgumentValidator.notNull(device.getStatus(), "device.status");
-
- // .connectionId
- if (device.getConnectionId() != null) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> DEVICE_CONNECTION_SERVICE.find(device.getScopeId(), device.getConnectionId())
- ), "device.connectionId");
- }
-
- // .lastEventId
- if (device.getLastEventId() != null) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> DEVICE_EVENT_SERVICE.find(device.getScopeId(), device.getLastEventId())
- ), "device.lastEventId");
- }
-
- // .displayName
- if (!Strings.isNullOrEmpty(device.getDisplayName())) {
- ArgumentValidator.lengthRange(device.getDisplayName(), 1, 255, "device.displayName");
- }
-
- // .serialNumber
- if (!Strings.isNullOrEmpty(device.getSerialNumber())) {
- ArgumentValidator.lengthRange(device.getSerialNumber(), 1, 255, "device.serialNumber");
- }
-
- // .modelId
- if (!Strings.isNullOrEmpty(device.getModelId())) {
- ArgumentValidator.lengthRange(device.getModelId(), 1, 255, "device.modelId");
- }
-
- // .modelName
- if (!Strings.isNullOrEmpty(device.getModelName())) {
- ArgumentValidator.lengthRange(device.getModelName(), 1, 255, "device.modelName");
- }
-
- // .imei
- if (!Strings.isNullOrEmpty(device.getImei())) {
- ArgumentValidator.lengthRange(device.getImei(), 1, 24, "device.imei");
- }
-
- // .imsi
- if (!Strings.isNullOrEmpty(device.getImsi())) {
- ArgumentValidator.lengthRange(device.getImsi(), 1, 15, "device.imsi");
- }
-
- // .iccid
- if (!Strings.isNullOrEmpty(device.getIccid())) {
- ArgumentValidator.lengthRange(device.getIccid(), 1, 22, "device.iccid");
- }
-
- // .biosVersion
- if (!Strings.isNullOrEmpty(device.getBiosVersion())) {
- ArgumentValidator.lengthRange(device.getBiosVersion(), 1, 255, "device.biosVersion");
- }
-
- // .firmwareVersion
- if (!Strings.isNullOrEmpty(device.getFirmwareVersion())) {
- ArgumentValidator.lengthRange(device.getFirmwareVersion(), 1, 255, "device.firmwareVersion");
- }
-
- // .osVersion
- if (!Strings.isNullOrEmpty(device.getOsVersion())) {
- ArgumentValidator.lengthRange(device.getOsVersion(), 1, 255, "device.osVersion");
- }
-
- // .jvmVersion
- if (!Strings.isNullOrEmpty(device.getJvmVersion())) {
- ArgumentValidator.lengthRange(device.getJvmVersion(), 1, 255, "device.jvmVersion");
- }
-
- // .osgiFrameworkVersion
- if (!Strings.isNullOrEmpty(device.getOsgiFrameworkVersion())) {
- ArgumentValidator.lengthRange(device.getOsgiFrameworkVersion(), 1, 255, "device.osgiFrameworkVersion");
- }
-
- // .applicationFrameworkVersion
- if (!Strings.isNullOrEmpty(device.getApplicationFrameworkVersion())) {
- ArgumentValidator.lengthRange(device.getApplicationFrameworkVersion(), 1, 255, "device.applicationFrameworkVersion");
- }
-
- // .connectionInterface
- if (!Strings.isNullOrEmpty(device.getConnectionInterface())) {
- ArgumentValidator.lengthRange(device.getConnectionInterface(), 1, BIRTH_FIELDS_CLOB_MAX_LENGTH, "device.connectionInterface");
- }
-
- // .connectionIp
- if (!Strings.isNullOrEmpty(device.getConnectionIp())) {
- ArgumentValidator.lengthRange(device.getConnectionIp(), 1, BIRTH_FIELDS_CLOB_MAX_LENGTH, "device.connectionIp");
- }
-
- // .applicationIdentifiers
- if (!Strings.isNullOrEmpty(device.getApplicationIdentifiers())) {
- ArgumentValidator.lengthRange(device.getApplicationIdentifiers(), 1, 1024, "device.applicationIdentifiers");
- }
-
- // .acceptEncoding
- if (!Strings.isNullOrEmpty(device.getAcceptEncoding())) {
- ArgumentValidator.lengthRange(device.getAcceptEncoding(), 1, 255, "device.acceptEncoding");
- }
-
- // .customAttribute1
- if (!Strings.isNullOrEmpty(device.getCustomAttribute1())) {
- ArgumentValidator.lengthRange(device.getCustomAttribute1(), 1, 255, "device.customAttribute1");
- }
-
- // .customAttribute2
- if (!Strings.isNullOrEmpty(device.getCustomAttribute2())) {
- ArgumentValidator.lengthRange(device.getCustomAttribute2(), 1, 255, "device.customAttribute2");
- }
-
- // .customAttribute3
- if (!Strings.isNullOrEmpty(device.getCustomAttribute3())) {
- ArgumentValidator.lengthRange(device.getCustomAttribute3(), 1, 255, "device.customAttribute3");
- }
-
- // .customAttribute4
- if (!Strings.isNullOrEmpty(device.getCustomAttribute4())) {
- ArgumentValidator.lengthRange(device.getCustomAttribute4(), 1, 255, "device.customAttribute4");
- }
-
- // .customAttribute5
- if (!Strings.isNullOrEmpty(device.getCustomAttribute5())) {
- ArgumentValidator.lengthRange(device.getCustomAttribute5(), 1, 255, "device.customAttribute5");
- }
-
- // .extendedProperties
- for (DeviceExtendedProperty deviceExtendedProperty : device.getExtendedProperties()) {
- // .groupName
- ArgumentValidator.notNull(deviceExtendedProperty.getGroupName(), "device.extendedProperties[].groupName");
- ArgumentValidator.lengthRange(deviceExtendedProperty.getGroupName(), 1, 64, "device.extendedProperties[].groupName");
-
- // .name
- ArgumentValidator.notNull(deviceExtendedProperty.getName(), "device.extendedProperties[].name");
- ArgumentValidator.lengthRange(deviceExtendedProperty.getName(), 1, 64, "device.extendedProperties[].name");
-
- // .value
- if (!Strings.isNullOrEmpty(deviceExtendedProperty.getValue())) {
- ArgumentValidator.lengthRange(deviceExtendedProperty.getValue(), 1, BIRTH_FIELDS_EXTENDED_PROPERTY_VALUE_MAX_LENGTH, "device.extendedProperties[].value");
- }
- }
-
- // .tagsIds
- for (KapuaId tagId : device.getTagIds()) {
- ArgumentValidator.notNull(
- KapuaSecurityUtils.doPrivileged(
- () -> TAG_SERVICE.find(device.getScopeId(), tagId))
- , "device.tagsIds[].id"
- );
- }
- }
-
- /**
- * Validates the parameters for {@link DeviceRegistryService#find(KapuaId, KapuaId)} operation.
- *
- * @param scopeId The {@link Device#getScopeId()}
- * @param deviceId The {@link Device#getId()}
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateFindPreconditions(KapuaId scopeId, KapuaId deviceId) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
- ArgumentValidator.notNull(deviceId, "deviceId");
- // Check access
- KapuaId groupId = findCurrentGroupId(scopeId, deviceId);
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.read, scopeId, groupId));
- }
-
- /**
- * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#query(KapuaQuery)} operation.
- *
- * @param query The {@link KapuaQuery} to validate.
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateQueryPreconditions(KapuaQuery query) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(query, "query");
-
- // .fetchAttributes
- List fetchAttributes = query.getFetchAttributes();
- if (fetchAttributes != null) {
- for (String fetchAttribute : fetchAttributes) {
- ArgumentValidator.match(fetchAttribute, DeviceValidationRegex.QUERY_FETCH_ATTRIBUTES, "fetchAttributes");
- }
- }
- // Check access
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY));
- }
-
- /**
- * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#count(KapuaQuery)} operation.
- *
- * @param query The {@link KapuaQuery} to validate.
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateCountPreconditions(KapuaQuery query) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(query, "query");
- // Check access
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY));
- }
-
- /**
- * Validates the parameters for {@link DeviceRegistryService#delete(KapuaId, KapuaId)} operation.
- *
- * @param scopeId The {@link Device#getScopeId()}
- * @param deviceId The {@link Device#getId()}
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateDeletePreconditions(KapuaId scopeId, KapuaId deviceId) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
- ArgumentValidator.notNull(deviceId, "deviceId");
- // Check access
- KapuaId groupId = findCurrentGroupId(scopeId, deviceId);
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.delete, scopeId, groupId));
- }
+ void validateUpdatePreconditions(TxContext txContext, Device device) throws KapuaException;
- /**
- * Validates the parameters for {@link DeviceRegistryService#findByClientId(KapuaId, String)} operation.
- *
- * @param scopeId The {@link Device#getScopeId()}
- * @param clientId The {@link Device#getClientId()}
- * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
- * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
- * @throws KapuaException if there are other errors.
- * @since 1.0.0
- */
- public static void validateFindByClientIdPreconditions(KapuaId scopeId, String clientId) throws KapuaException {
- // Argument validation
- ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
- ArgumentValidator.notEmptyOrNull(clientId, "clientId");
- // Check access is performed by the query method.
- }
+ void validateFindPreconditions(TxContext txContext, KapuaId scopeId, KapuaId deviceId) throws KapuaException;
- /**
- * Finds the current {@link Group} id assigned to the given {@link Device#getId()}.
- *
- * @param scopeId The {@link Device#getScopeId()}
- * @param entityId The {@link Device#getId()}
- * @return The {@link Group} id found.
- * @throws KapuaException if any error occurs while looking for the Group.
- * @since 1.0.0
- */
- private static KapuaId findCurrentGroupId(KapuaId scopeId, KapuaId entityId) throws KapuaException {
- DeviceQuery query = DEVICE_FACTORY.newQuery(scopeId);
- query.setPredicate(query.attributePredicate(KapuaEntityAttributes.ENTITY_ID, entityId));
+ void validateQueryPreconditions(KapuaQuery query) throws KapuaException;
- DeviceListResult results;
- try {
- results = KapuaSecurityUtils.doPrivileged(() -> DEVICE_REGISTRY_SERVICE.query(query));
- } catch (Exception e) {
- throw KapuaException.internalError(e, "Error while searching groupId");
- }
+ void validateCountPreconditions(KapuaQuery query) throws KapuaException;
- KapuaId groupId = null;
- if (results != null && !results.isEmpty()) {
- groupId = results.getFirstItem().getGroupId();
- }
+ void validateDeletePreconditions(TxContext txContext, KapuaId scopeId, KapuaId deviceId) throws KapuaException;
- return groupId;
- }
+ void validateFindByClientIdPreconditions(KapuaId scopeId, String clientId) throws KapuaException;
}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java
new file mode 100644
index 00000000000..0cf7699141c
--- /dev/null
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java
@@ -0,0 +1,582 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Red Hat
+ * Eurotech
+ *******************************************************************************/
+package org.eclipse.kapua.service.device.registry.common;
+
+import com.google.common.base.Strings;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.commons.model.domains.Domains;
+import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
+import org.eclipse.kapua.commons.util.ArgumentValidator;
+import org.eclipse.kapua.model.KapuaEntityAttributes;
+import org.eclipse.kapua.model.KapuaUpdatableEntity;
+import org.eclipse.kapua.model.domain.Actions;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.model.query.KapuaQuery;
+import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.group.Group;
+import org.eclipse.kapua.service.authorization.group.GroupService;
+import org.eclipse.kapua.service.authorization.permission.Permission;
+import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.registry.Device;
+import org.eclipse.kapua.service.device.registry.DeviceCreator;
+import org.eclipse.kapua.service.device.registry.DeviceExtendedProperty;
+import org.eclipse.kapua.service.device.registry.DeviceFactory;
+import org.eclipse.kapua.service.device.registry.DeviceListResult;
+import org.eclipse.kapua.service.device.registry.DeviceQuery;
+import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
+import org.eclipse.kapua.service.device.registry.DeviceRepository;
+import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService;
+import org.eclipse.kapua.service.device.registry.event.DeviceEventService;
+import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryServiceImpl;
+import org.eclipse.kapua.service.tag.TagService;
+import org.eclipse.kapua.service.user.User;
+import org.eclipse.kapua.storage.TxContext;
+
+import java.util.List;
+
+/**
+ * Logic used to validate preconditions required to execute the {@link DeviceRegistryServiceImpl} operations.
+ *
+ * @since 1.0.0
+ */
+public final class DeviceValidationImpl implements DeviceValidation {
+
+ private final Integer birthFieldsClobMaxLength;
+ private final Integer birthFieldsExtendedPropertyValueMaxLength;
+ private final AuthorizationService authorizationService;
+ private final PermissionFactory permissionFactory;
+ private final GroupService groupService;
+ private final DeviceConnectionService deviceConnectionService;
+ private final DeviceEventService deviceEventService;
+ private final DeviceRepository deviceRepository;
+ private final DeviceFactory deviceFactory;
+ private final TagService tagService;
+
+ public DeviceValidationImpl(
+ Integer birthFieldsClobMaxLength,
+ Integer birthFieldsExtendedPropertyValueMaxLength,
+ AuthorizationService authorizationService,
+ PermissionFactory permissionFactory,
+ GroupService groupService,
+ DeviceConnectionService deviceConnectionService,
+ DeviceEventService deviceEventService,
+ DeviceRepository deviceRepository,
+ DeviceFactory deviceFactory,
+ TagService tagService) {
+ this.birthFieldsClobMaxLength = birthFieldsClobMaxLength;
+ this.birthFieldsExtendedPropertyValueMaxLength = birthFieldsExtendedPropertyValueMaxLength;
+ this.authorizationService = authorizationService;
+ this.permissionFactory = permissionFactory;
+ this.groupService = groupService;
+ this.deviceConnectionService = deviceConnectionService;
+ this.deviceEventService = deviceEventService;
+ this.deviceRepository = deviceRepository;
+ this.deviceFactory = deviceFactory;
+ this.tagService = tagService;
+ }
+
+ /**
+ * Validates the {@link DeviceCreator}.
+ *
+ * @param deviceCreator The {@link DeviceCreator} to validate.
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link DeviceCreator} fields is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateCreatePreconditions(DeviceCreator deviceCreator) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(deviceCreator, "deviceCreator");
+ ArgumentValidator.notNull(deviceCreator.getScopeId(), "deviceCreator.scopeId");
+
+ // .clientId
+ ArgumentValidator.notEmptyOrNull(deviceCreator.getClientId(), "deviceCreator.clientId");
+ ArgumentValidator.lengthRange(deviceCreator.getClientId(), 1, 255, "deviceCreator.clientId");
+ ArgumentValidator.match(deviceCreator.getClientId(), DeviceValidationRegex.CLIENT_ID, "deviceCreator.clientId");
+
+ // .groupId
+ if (deviceCreator.getGroupId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> groupService.find(deviceCreator.getScopeId(), deviceCreator.getGroupId())
+ ), "deviceCreator.groupId");
+ }
+
+ // .status
+ ArgumentValidator.notNull(deviceCreator.getStatus(), "deviceCreator.status");
+
+ // .connectionId
+ if (deviceCreator.getConnectionId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> deviceConnectionService.find(deviceCreator.getScopeId(), deviceCreator.getConnectionId())
+ ), "deviceCreator.connectionId");
+ }
+
+ // .lastEventId
+ if (deviceCreator.getLastEventId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> deviceEventService.find(deviceCreator.getScopeId(), deviceCreator.getLastEventId())
+ ), "deviceCreator.lastEventId");
+ }
+
+ // .displayName
+ if (!Strings.isNullOrEmpty(deviceCreator.getDisplayName())) {
+ ArgumentValidator.lengthRange(deviceCreator.getDisplayName(), 1, 255, "deviceCreator.displayName");
+ }
+
+ // .serialNumber
+ if (!Strings.isNullOrEmpty(deviceCreator.getSerialNumber())) {
+ ArgumentValidator.lengthRange(deviceCreator.getSerialNumber(), 1, 255, "deviceCreator.serialNumber");
+ }
+
+ // .modelId
+ if (!Strings.isNullOrEmpty(deviceCreator.getModelId())) {
+ ArgumentValidator.lengthRange(deviceCreator.getModelId(), 1, 255, "deviceCreator.modelId");
+ }
+
+ // .modelName
+ if (!Strings.isNullOrEmpty(deviceCreator.getModelName())) {
+ ArgumentValidator.lengthRange(deviceCreator.getModelName(), 1, 255, "deviceCreator.modelName");
+ }
+
+ // .imei
+ if (!Strings.isNullOrEmpty(deviceCreator.getImei())) {
+ ArgumentValidator.lengthRange(deviceCreator.getImei(), 1, 24, "deviceCreator.imei");
+ }
+
+ // .imsi
+ if (!Strings.isNullOrEmpty(deviceCreator.getImsi())) {
+ ArgumentValidator.lengthRange(deviceCreator.getImsi(), 1, 15, "deviceCreator.imsi");
+ }
+
+ // .iccid
+ if (!Strings.isNullOrEmpty(deviceCreator.getIccid())) {
+ ArgumentValidator.lengthRange(deviceCreator.getIccid(), 1, 22, "deviceCreator.iccid");
+ }
+
+ // .biosVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getBiosVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getBiosVersion(), 1, 255, "deviceCreator.biosVersion");
+ }
+
+ // .firmwareVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getFirmwareVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getFirmwareVersion(), 1, 255, "deviceCreator.firmwareVersion");
+ }
+
+ // .osVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getOsVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getOsVersion(), 1, 255, "deviceCreator.osVersion");
+ }
+
+ // .jvmVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getJvmVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getJvmVersion(), 1, 255, "deviceCreator.jvmVersion");
+ }
+
+ // .osgiFrameworkVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getOsgiFrameworkVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getOsgiFrameworkVersion(), 1, 255, "deviceCreator.osgiFrameworkVersion");
+ }
+
+ // .applicationFrameworkVersion
+ if (!Strings.isNullOrEmpty(deviceCreator.getApplicationFrameworkVersion())) {
+ ArgumentValidator.lengthRange(deviceCreator.getApplicationFrameworkVersion(), 1, 255, "deviceCreator.applicationFrameworkVersion");
+ }
+
+ // .connectionInterface
+ if (!Strings.isNullOrEmpty(deviceCreator.getConnectionInterface())) {
+ ArgumentValidator.lengthRange(deviceCreator.getConnectionInterface(), 1, birthFieldsClobMaxLength, "deviceCreator.connectionInterface");
+ }
+
+ // .connectionIp
+ if (!Strings.isNullOrEmpty(deviceCreator.getConnectionIp())) {
+ ArgumentValidator.lengthRange(deviceCreator.getConnectionIp(), 1, birthFieldsClobMaxLength, "deviceCreator.connectionIp");
+ }
+
+ // .applicationIdentifiers
+ if (!Strings.isNullOrEmpty(deviceCreator.getApplicationIdentifiers())) {
+ ArgumentValidator.lengthRange(deviceCreator.getApplicationIdentifiers(), 1, 1024, "deviceCreator.applicationIdentifiers");
+ }
+
+ // .acceptEncoding
+ if (!Strings.isNullOrEmpty(deviceCreator.getAcceptEncoding())) {
+ ArgumentValidator.lengthRange(deviceCreator.getAcceptEncoding(), 1, 255, "deviceCreator.acceptEncoding");
+ }
+
+ // .customAttribute1
+ if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute1())) {
+ ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute1(), 1, 255, "deviceCreator.customAttribute1");
+ }
+
+ // .customAttribute2
+ if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute2())) {
+ ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute2(), 1, 255, "deviceCreator.customAttribute2");
+ }
+
+ // .customAttribute3
+ if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute3())) {
+ ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute3(), 1, 255, "deviceCreator.customAttribute3");
+ }
+
+ // .customAttribute4
+ if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute4())) {
+ ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute4(), 1, 255, "deviceCreator.customAttribute4");
+ }
+
+ // .customAttribute5
+ if (!Strings.isNullOrEmpty(deviceCreator.getCustomAttribute5())) {
+ ArgumentValidator.lengthRange(deviceCreator.getCustomAttribute5(), 1, 255, "deviceCreator.customAttribute5");
+ }
+
+ // .extendedProperties
+ for (DeviceExtendedProperty deviceExtendedProperty : deviceCreator.getExtendedProperties()) {
+ // .groupName
+ ArgumentValidator.notNull(deviceExtendedProperty.getGroupName(), "deviceCreator.extendedProperties[].groupName");
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getGroupName(), 1, 64, "deviceCreator.extendedProperties[].groupName");
+
+ // .name
+ ArgumentValidator.notNull(deviceExtendedProperty.getName(), "deviceCreator.extendedProperties[].name");
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getName(), 1, 64, "deviceCreator.extendedProperties[].name");
+
+ // .value
+ if (!Strings.isNullOrEmpty(deviceExtendedProperty.getValue())) {
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getValue(), 1, birthFieldsExtendedPropertyValueMaxLength, "deviceCreator.extendedProperties[].value");
+ }
+ }
+ // Check access
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, deviceCreator.getScopeId(), deviceCreator.getGroupId()));
+ }
+
+ /**
+ * Validates the {@link Device} for {@link DeviceRegistryService#update(KapuaUpdatableEntity)} operation.
+ *
+ * @param device The {@link Device} to validate.
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link Device} fields is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateUpdatePreconditions(TxContext txContext, Device device) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(device, "device");
+ ArgumentValidator.notNull(device.getScopeId(), "device.scopeId");
+ ArgumentValidator.notNull(device.getId(), "device.id");
+
+ // .clientId
+ ArgumentValidator.notEmptyOrNull(device.getClientId(), "device.clientId");
+ ArgumentValidator.lengthRange(device.getClientId(), 1, 255, "device.clientId");
+ ArgumentValidator.match(device.getClientId(), DeviceValidationRegex.CLIENT_ID, "device.clientId");
+
+ // .groupId
+ // Check that current User can manage the current Group of the Device
+ KapuaId currentGroupId = findCurrentGroupId(txContext, device.getScopeId(), device.getId());
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), currentGroupId));
+
+ // Check that current User can manage the target Group of the Device
+ if (device.getGroupId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> groupService.find(device.getScopeId(), device.getGroupId())
+ ), "device.groupId");
+ }
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), device.getGroupId()));
+
+ // .status
+ ArgumentValidator.notNull(device.getStatus(), "device.status");
+
+ // .connectionId
+ if (device.getConnectionId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> deviceConnectionService.find(device.getScopeId(), device.getConnectionId())
+ ), "device.connectionId");
+ }
+
+ // .lastEventId
+ if (device.getLastEventId() != null) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> deviceEventService.find(device.getScopeId(), device.getLastEventId())
+ ), "device.lastEventId");
+ }
+
+ // .displayName
+ if (!Strings.isNullOrEmpty(device.getDisplayName())) {
+ ArgumentValidator.lengthRange(device.getDisplayName(), 1, 255, "device.displayName");
+ }
+
+ // .serialNumber
+ if (!Strings.isNullOrEmpty(device.getSerialNumber())) {
+ ArgumentValidator.lengthRange(device.getSerialNumber(), 1, 255, "device.serialNumber");
+ }
+
+ // .modelId
+ if (!Strings.isNullOrEmpty(device.getModelId())) {
+ ArgumentValidator.lengthRange(device.getModelId(), 1, 255, "device.modelId");
+ }
+
+ // .modelName
+ if (!Strings.isNullOrEmpty(device.getModelName())) {
+ ArgumentValidator.lengthRange(device.getModelName(), 1, 255, "device.modelName");
+ }
+
+ // .imei
+ if (!Strings.isNullOrEmpty(device.getImei())) {
+ ArgumentValidator.lengthRange(device.getImei(), 1, 24, "device.imei");
+ }
+
+ // .imsi
+ if (!Strings.isNullOrEmpty(device.getImsi())) {
+ ArgumentValidator.lengthRange(device.getImsi(), 1, 15, "device.imsi");
+ }
+
+ // .iccid
+ if (!Strings.isNullOrEmpty(device.getIccid())) {
+ ArgumentValidator.lengthRange(device.getIccid(), 1, 22, "device.iccid");
+ }
+
+ // .biosVersion
+ if (!Strings.isNullOrEmpty(device.getBiosVersion())) {
+ ArgumentValidator.lengthRange(device.getBiosVersion(), 1, 255, "device.biosVersion");
+ }
+
+ // .firmwareVersion
+ if (!Strings.isNullOrEmpty(device.getFirmwareVersion())) {
+ ArgumentValidator.lengthRange(device.getFirmwareVersion(), 1, 255, "device.firmwareVersion");
+ }
+
+ // .osVersion
+ if (!Strings.isNullOrEmpty(device.getOsVersion())) {
+ ArgumentValidator.lengthRange(device.getOsVersion(), 1, 255, "device.osVersion");
+ }
+
+ // .jvmVersion
+ if (!Strings.isNullOrEmpty(device.getJvmVersion())) {
+ ArgumentValidator.lengthRange(device.getJvmVersion(), 1, 255, "device.jvmVersion");
+ }
+
+ // .osgiFrameworkVersion
+ if (!Strings.isNullOrEmpty(device.getOsgiFrameworkVersion())) {
+ ArgumentValidator.lengthRange(device.getOsgiFrameworkVersion(), 1, 255, "device.osgiFrameworkVersion");
+ }
+
+ // .applicationFrameworkVersion
+ if (!Strings.isNullOrEmpty(device.getApplicationFrameworkVersion())) {
+ ArgumentValidator.lengthRange(device.getApplicationFrameworkVersion(), 1, 255, "device.applicationFrameworkVersion");
+ }
+
+ // .connectionInterface
+ if (!Strings.isNullOrEmpty(device.getConnectionInterface())) {
+ ArgumentValidator.lengthRange(device.getConnectionInterface(), 1, birthFieldsClobMaxLength, "device.connectionInterface");
+ }
+
+ // .connectionIp
+ if (!Strings.isNullOrEmpty(device.getConnectionIp())) {
+ ArgumentValidator.lengthRange(device.getConnectionIp(), 1, birthFieldsClobMaxLength, "device.connectionIp");
+ }
+
+ // .applicationIdentifiers
+ if (!Strings.isNullOrEmpty(device.getApplicationIdentifiers())) {
+ ArgumentValidator.lengthRange(device.getApplicationIdentifiers(), 1, 1024, "device.applicationIdentifiers");
+ }
+
+ // .acceptEncoding
+ if (!Strings.isNullOrEmpty(device.getAcceptEncoding())) {
+ ArgumentValidator.lengthRange(device.getAcceptEncoding(), 1, 255, "device.acceptEncoding");
+ }
+
+ // .customAttribute1
+ if (!Strings.isNullOrEmpty(device.getCustomAttribute1())) {
+ ArgumentValidator.lengthRange(device.getCustomAttribute1(), 1, 255, "device.customAttribute1");
+ }
+
+ // .customAttribute2
+ if (!Strings.isNullOrEmpty(device.getCustomAttribute2())) {
+ ArgumentValidator.lengthRange(device.getCustomAttribute2(), 1, 255, "device.customAttribute2");
+ }
+
+ // .customAttribute3
+ if (!Strings.isNullOrEmpty(device.getCustomAttribute3())) {
+ ArgumentValidator.lengthRange(device.getCustomAttribute3(), 1, 255, "device.customAttribute3");
+ }
+
+ // .customAttribute4
+ if (!Strings.isNullOrEmpty(device.getCustomAttribute4())) {
+ ArgumentValidator.lengthRange(device.getCustomAttribute4(), 1, 255, "device.customAttribute4");
+ }
+
+ // .customAttribute5
+ if (!Strings.isNullOrEmpty(device.getCustomAttribute5())) {
+ ArgumentValidator.lengthRange(device.getCustomAttribute5(), 1, 255, "device.customAttribute5");
+ }
+
+ // .extendedProperties
+ for (DeviceExtendedProperty deviceExtendedProperty : device.getExtendedProperties()) {
+ // .groupName
+ ArgumentValidator.notNull(deviceExtendedProperty.getGroupName(), "device.extendedProperties[].groupName");
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getGroupName(), 1, 64, "device.extendedProperties[].groupName");
+
+ // .name
+ ArgumentValidator.notNull(deviceExtendedProperty.getName(), "device.extendedProperties[].name");
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getName(), 1, 64, "device.extendedProperties[].name");
+
+ // .value
+ if (!Strings.isNullOrEmpty(deviceExtendedProperty.getValue())) {
+ ArgumentValidator.lengthRange(deviceExtendedProperty.getValue(), 1, birthFieldsExtendedPropertyValueMaxLength, "device.extendedProperties[].value");
+ }
+ }
+
+ // .tagsIds
+ for (KapuaId tagId : device.getTagIds()) {
+ ArgumentValidator.notNull(
+ KapuaSecurityUtils.doPrivileged(
+ () -> tagService.find(device.getScopeId(), tagId))
+ , "device.tagsIds[].id"
+ );
+ }
+ }
+
+ /**
+ * Validates the parameters for {@link DeviceRegistryService#find(KapuaId, KapuaId)} operation.
+ *
+ * @param scopeId The {@link Device#getScopeId()}
+ * @param deviceId The {@link Device#getId()}
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateFindPreconditions(TxContext txContext, KapuaId scopeId, KapuaId deviceId) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
+ ArgumentValidator.notNull(deviceId, "deviceId");
+ // Check access
+ KapuaId groupId = findCurrentGroupId(txContext, scopeId, deviceId);
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, scopeId, groupId));
+ }
+
+ /**
+ * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#query(KapuaQuery)} operation.
+ *
+ * @param query The {@link KapuaQuery} to validate.
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateQueryPreconditions(KapuaQuery query) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(query, "query");
+
+ // .fetchAttributes
+ List fetchAttributes = query.getFetchAttributes();
+ if (fetchAttributes != null) {
+ for (String fetchAttribute : fetchAttributes) {
+ ArgumentValidator.match(fetchAttribute, DeviceValidationRegex.QUERY_FETCH_ATTRIBUTES, "fetchAttributes");
+ }
+ }
+ // Check access
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY));
+ }
+
+ /**
+ * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#count(KapuaQuery)} operation.
+ *
+ * @param query The {@link KapuaQuery} to validate.
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateCountPreconditions(KapuaQuery query) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(query, "query");
+ // Check access
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY));
+ }
+
+ /**
+ * Validates the parameters for {@link DeviceRegistryService#delete(KapuaId, KapuaId)} operation.
+ *
+ * @param scopeId The {@link Device#getScopeId()}
+ * @param deviceId The {@link Device#getId()}
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateDeletePreconditions(TxContext txContext, KapuaId scopeId, KapuaId deviceId) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
+ ArgumentValidator.notNull(deviceId, "deviceId");
+ // Check access
+ KapuaId groupId = findCurrentGroupId(txContext, scopeId, deviceId);
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.delete, scopeId, groupId));
+ }
+
+ /**
+ * Validates the parameters for {@link DeviceRegistryService#findByClientId(KapuaId, String)} operation.
+ *
+ * @param scopeId The {@link Device#getScopeId()}
+ * @param clientId The {@link Device#getClientId()}
+ * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid.
+ * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s
+ * @throws KapuaException if there are other errors.
+ * @since 1.0.0
+ */
+ @Override
+ public void validateFindByClientIdPreconditions(KapuaId scopeId, String clientId) throws KapuaException {
+ // Argument validation
+ ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID);
+ ArgumentValidator.notEmptyOrNull(clientId, "clientId");
+ // Check access is performed by the query method.
+ }
+
+ /**
+ * Finds the current {@link Group} id assigned to the given {@link Device#getId()}.
+ *
+ * @param scopeId The {@link Device#getScopeId()}
+ * @param entityId The {@link Device#getId()}
+ * @return The {@link Group} id found.
+ * @throws KapuaException if any error occurs while looking for the Group.
+ * @since 1.0.0
+ */
+ private KapuaId findCurrentGroupId(TxContext tx, KapuaId scopeId, KapuaId entityId) throws KapuaException {
+ DeviceQuery query = deviceFactory.newQuery(scopeId);
+ query.setPredicate(query.attributePredicate(KapuaEntityAttributes.ENTITY_ID, entityId));
+
+ DeviceListResult results;
+ try {
+ results = deviceRepository.query(tx, query);
+ } catch (Exception e) {
+ throw KapuaException.internalError(e, "Error while searching groupId");
+ }
+
+ KapuaId groupId = null;
+ if (results != null && !results.isEmpty()) {
+ groupId = results.getFirstItem().getGroupId();
+ }
+
+ return groupId;
+ }
+}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceConfigurationManager.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceConfigurationManager.java
index a38267858e4..763310b7133 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceConfigurationManager.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceConfigurationManager.java
@@ -43,7 +43,7 @@ public class DeviceConnectionServiceConfigurationManager extends ServiceConfigur
private final Map availableDeviceConnectionAdapters;
- private final KapuaDeviceRegistrySettings deviceRegistrySettings = KapuaDeviceRegistrySettings.getInstance();
+ private final KapuaDeviceRegistrySettings deviceRegistrySettings;
private final KapuaMetatypeFactory kapuaMetatypeFactory;
/**
@@ -55,11 +55,17 @@ public class DeviceConnectionServiceConfigurationManager extends ServiceConfigur
* @param kapuaMetatypeFactory The {@link KapuaMetatypeFactory} instance.
* @since 2.0.0
*/
- public DeviceConnectionServiceConfigurationManager(ServiceConfigRepository serviceConfigRepository, RootUserTester rootUserTester, Map availableDeviceConnectionAdapters, KapuaMetatypeFactory kapuaMetatypeFactory) {
+ public DeviceConnectionServiceConfigurationManager(
+ ServiceConfigRepository serviceConfigRepository,
+ RootUserTester rootUserTester,
+ Map availableDeviceConnectionAdapters,
+ KapuaMetatypeFactory kapuaMetatypeFactory,
+ KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings) {
super(DeviceConnectionService.class.getName(), serviceConfigRepository, rootUserTester);
this.availableDeviceConnectionAdapters = availableDeviceConnectionAdapters;
this.kapuaMetatypeFactory = kapuaMetatypeFactory;
+ this.deviceRegistrySettings = kapuaDeviceRegistrySettings;
}
/**
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCache.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCache.java
index 9dee80d67fe..a681b5b5bd5 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCache.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCache.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.registry.internal;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
import org.eclipse.kapua.commons.service.internal.cache.EntityCache;
import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
import org.eclipse.kapua.model.KapuaEntity;
@@ -34,10 +35,10 @@ public class DeviceRegistryCache extends EntityCache {
protected Cache deviceByClientIdCache;
protected Cache deviceByConnectionIdCache;
- public DeviceRegistryCache(String idCacheName, String deviceByClientIdCacheName, String deviceByConnectionIdCacheName) {
- super(idCacheName);
- deviceByClientIdCache = KapuaCacheManager.getCache(deviceByClientIdCacheName);
- deviceByConnectionIdCache = KapuaCacheManager.getCache(deviceByConnectionIdCacheName);
+ public DeviceRegistryCache(KapuaCacheManager cacheManager, CommonsMetric commonsMetric, String idCacheName, String deviceByClientIdCacheName, String deviceByConnectionIdCacheName) {
+ super(cacheManager, commonsMetric, idCacheName);
+ deviceByClientIdCache = cacheManager.getCache(deviceByClientIdCacheName);
+ deviceByConnectionIdCache = cacheManager.getCache(deviceByConnectionIdCacheName);
}
public KapuaEntity getByClientId(KapuaId scopeId, String clientId) {
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCacheFactory.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCacheFactory.java
index 69607267e6c..b716392ee6c 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCacheFactory.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryCacheFactory.java
@@ -12,32 +12,25 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.registry.internal;
-import org.eclipse.kapua.commons.jpa.AbstractEntityCacheFactory;
-import org.eclipse.kapua.commons.service.internal.cache.EntityCache;
+import com.google.inject.Inject;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
/**
* Cache factory for the {@link DeviceRegistryServiceImpl}
*/
-public class DeviceRegistryCacheFactory extends AbstractEntityCacheFactory {
+public class DeviceRegistryCacheFactory extends EntityCacheFactory {
- public DeviceRegistryCacheFactory() {
- super("DeviceId");
+ @Inject
+ public DeviceRegistryCacheFactory(KapuaCacheManager cacheManager, CommonsMetric commonsMetric) {
+ super(cacheManager, commonsMetric);
}
/**
* @return a {@link DeviceRegistryCache} instance.
*/
- @Override
- public EntityCache createCache() {
- return new DeviceRegistryCache(getEntityIdCacheName(), "DeviceClientId", "DeviceConnectionId");
- }
-
- /**
- * @return the built instance
- * @deprecated since 2.0.0 - Please use {@link DeviceRegistryCacheFactory#DeviceRegistryCacheFactory()} instead. This may be removed in future releases
- **/
- @Deprecated
- public static DeviceRegistryCacheFactory getInstance() {
- return new DeviceRegistryCacheFactory();
+ public DeviceRegistryCache createCache() {
+ return new DeviceRegistryCache(this.cacheManager, this.commonsMetric, "DeviceId", "DeviceClientId", "DeviceConnectionId");
}
}
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java
index d54dab96339..1020ecaed77 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java
@@ -12,10 +12,6 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.registry.internal;
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.inject.Singleton;
-
import org.eclipse.kapua.KapuaDuplicateNameException;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.KapuaConfigurableServiceBase;
@@ -23,7 +19,6 @@
import org.eclipse.kapua.commons.jpa.EventStorer;
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.event.ServiceEvent;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.model.query.KapuaQuery;
import org.eclipse.kapua.service.authorization.AuthorizationService;
@@ -42,6 +37,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
/**
* {@link DeviceRegistryService} implementation.
*
@@ -57,6 +56,7 @@ public class DeviceRegistryServiceImpl
private final DeviceFactory entityFactory;
private final GroupQueryHelper groupQueryHelper;
private final EventStorer eventStorer;
+ private final DeviceValidation deviceValidation;
@Inject
public DeviceRegistryServiceImpl(
@@ -67,18 +67,19 @@ public DeviceRegistryServiceImpl(
DeviceRepository deviceRepository,
DeviceFactory entityFactory,
GroupQueryHelper groupQueryHelper,
- EventStorer eventStorer) {
+ EventStorer eventStorer, DeviceValidation deviceValidation) {
super(txManager, serviceConfigurationManager, Domains.DEVICE, authorizationService, permissionFactory);
this.deviceRepository = deviceRepository;
this.entityFactory = entityFactory;
this.groupQueryHelper = groupQueryHelper;
this.eventStorer = eventStorer;
+ this.deviceValidation = deviceValidation;
}
@Override
public Device create(DeviceCreator deviceCreator)
throws KapuaException {
- DeviceValidation.validateCreatePreconditions(deviceCreator);
+ deviceValidation.validateCreatePreconditions(deviceCreator);
return txManager.execute(tx -> {
// Check entity limit
@@ -131,24 +132,28 @@ public Device create(DeviceCreator deviceCreator)
@Override
public Device update(Device device)
throws KapuaException {
- DeviceValidation.validateUpdatePreconditions(device);
// Do update
- return txManager.execute(tx -> deviceRepository.update(tx, device),
+ return txManager.execute(tx -> {
+ deviceValidation.validateUpdatePreconditions(tx, device);
+ return deviceRepository.update(tx, device);
+ },
eventStorer::accept);
}
@Override
public Device find(KapuaId scopeId, KapuaId entityId)
throws KapuaException {
- DeviceValidation.validateFindPreconditions(scopeId, entityId);
// Do find
- return txManager.execute(tx -> deviceRepository.find(tx, scopeId, entityId))
+ return txManager.execute(tx -> {
+ deviceValidation.validateFindPreconditions(tx, scopeId, entityId);
+ return deviceRepository.find(tx, scopeId, entityId);
+ })
.orElse(null);
}
@Override
public Device findByClientId(KapuaId scopeId, String clientId) throws KapuaException {
- DeviceValidation.validateFindByClientIdPreconditions(scopeId, clientId);
+ deviceValidation.validateFindByClientIdPreconditions(scopeId, clientId);
// Check cache and/or do find
return txManager.execute(tx -> deviceRepository.findByClientId(tx, scopeId, clientId))
.orElse(null);
@@ -157,7 +162,7 @@ public Device findByClientId(KapuaId scopeId, String clientId) throws KapuaExcep
@Override
public DeviceListResult query(KapuaQuery query)
throws KapuaException {
- DeviceValidation.validateQueryPreconditions(query);
+ deviceValidation.validateQueryPreconditions(query);
// Do query
return txManager.execute(tx -> {
@@ -168,7 +173,7 @@ public DeviceListResult query(KapuaQuery query)
@Override
public long count(KapuaQuery query) throws KapuaException {
- DeviceValidation.validateCountPreconditions(query);
+ deviceValidation.validateCountPreconditions(query);
// Do count
return txManager.execute(tx -> {
@@ -179,11 +184,13 @@ public long count(KapuaQuery query) throws KapuaException {
@Override
public void delete(KapuaId scopeId, KapuaId deviceId) throws KapuaException {
- DeviceValidation.validateDeletePreconditions(scopeId, deviceId);
// Do delete
txManager.execute(
- tx -> deviceRepository.delete(tx, scopeId, deviceId),
+ tx -> {
+ deviceValidation.validateDeletePreconditions(tx, scopeId, deviceId);
+ return deviceRepository.delete(tx, scopeId, deviceId);
+ },
eventStorer::accept);
}
@@ -218,10 +225,7 @@ private void deleteDeviceByGroupId(KapuaId scopeId, KapuaId groupId) throws Kapu
}
private void deleteDeviceByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException {
- KapuaLocator locator = KapuaLocator.getInstance();
- DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class);
-
- DeviceQuery query = deviceFactory.newQuery(accountId);
+ DeviceQuery query = entityFactory.newQuery(accountId);
txManager.execute(tx -> {
DeviceListResult devicesToDelete = deviceRepository.query(tx, query);
diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java
index 4a5433fe533..f4a7ff755f8 100644
--- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java
+++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java
@@ -21,7 +21,6 @@
import org.eclipse.kapua.KapuaOptimisticLockingException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.util.KapuaDateUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaPosition;
import org.eclipse.kapua.message.device.lifecycle.KapuaAppsMessage;
import org.eclipse.kapua.message.device.lifecycle.KapuaBirthChannel;
@@ -32,7 +31,7 @@
import org.eclipse.kapua.message.device.lifecycle.KapuaMissingMessage;
import org.eclipse.kapua.message.internal.device.lifecycle.model.BirthExtendedProperties;
import org.eclipse.kapua.message.internal.device.lifecycle.model.BirthExtendedProperty;
-import org.eclipse.kapua.model.KapuaEntity;
+import org.eclipse.kapua.model.KapuaUpdatableEntity;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.device.management.message.response.KapuaResponseCode;
import org.eclipse.kapua.service.device.registry.Device;
@@ -50,6 +49,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
@@ -71,18 +71,26 @@ public class DeviceLifeCycleServiceImpl implements DeviceLifeCycleService {
private static final int MAX_RETRY = 3;
private static final double MAX_WAIT = 500d;
- private static final ObjectMapper JSON_MAPPER = new ObjectMapper()
- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
- .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final DeviceEventService DEVICE_EVENT_SERVICE = LOCATOR.getService(DeviceEventService.class);
- private static final DeviceEventFactory DEVICE_EVENT_FACTORY = LOCATOR.getFactory(DeviceEventFactory.class);
-
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
- private static final DeviceFactory DEVICE_FACTORY = LOCATOR.getFactory(DeviceFactory.class);
+ protected final ObjectMapper jsonMapper;
+ protected final DeviceEventService deviceEventService;
+ protected final DeviceEventFactory deviceEventFactory;
+ protected final DeviceRegistryService deviceRegistryService;
+ protected final DeviceFactory deviceFactory;
+
+ @Inject
+ public DeviceLifeCycleServiceImpl(
+ DeviceEventService deviceEventService,
+ DeviceEventFactory deviceEventFactory,
+ DeviceRegistryService deviceRegistryService,
+ DeviceFactory deviceFactory) {
+ this.jsonMapper = new ObjectMapper()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+ this.deviceEventService = deviceEventService;
+ this.deviceEventFactory = deviceEventFactory;
+ this.deviceRegistryService = deviceRegistryService;
+ this.deviceFactory = deviceFactory;
+ }
@Override
public void birth(KapuaId connectionId, KapuaBirthMessage birthMessage) throws KapuaException {
@@ -95,7 +103,7 @@ public void birth(KapuaId connectionId, KapuaBirthMessage birthMessage) throws K
// Device update
Device device;
if (deviceId == null) {
- DeviceCreator deviceCreator = DEVICE_FACTORY.newCreator(scopeId);
+ DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId);
deviceCreator.setClientId(birthChannel.getClientId());
deviceCreator.setDisplayName(birthPayload.getDisplayName());
@@ -121,7 +129,7 @@ public void birth(KapuaId connectionId, KapuaBirthMessage birthMessage) throws K
// issue #57
deviceCreator.setConnectionId(connectionId);
- device = DEVICE_REGISTRY_SERVICE.create(deviceCreator);
+ device = deviceRegistryService.create(deviceCreator);
} else {
device = updateDeviceInfoFromMessage(scopeId, deviceId, birthPayload, connectionId);
}
@@ -163,7 +171,7 @@ public void death(KapuaId connectionId, KapuaDisconnectMessage message) throws K
* @param birthPayload The {@link KapuaBirthPayload} from which extract data.
* @param connectionId The {@link DeviceConnection#getId()}
* @return The updated {@link Device}.
- * @throws KapuaException If {@link Device} does not exists or {@link DeviceRegistryService#update(KapuaEntity)} causes an error.
+ * @throws KapuaException If {@link Device} does not exists or {@link DeviceRegistryService#update(KapuaUpdatableEntity)} causes an error.
* @since 1.2.0
*/
private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, KapuaBirthPayload birthPayload, KapuaId connectionId) throws KapuaException {
@@ -175,7 +183,7 @@ private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, Ka
retry++;
try {
- device = DEVICE_REGISTRY_SERVICE.find(scopeId, deviceId);
+ device = deviceRegistryService.find(scopeId, deviceId);
if (device == null) {
throw new KapuaEntityNotFoundException(Device.TYPE, deviceId);
@@ -208,7 +216,7 @@ private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, Ka
// issue #57
device.setConnectionId(connectionId);
- device = DEVICE_REGISTRY_SERVICE.update(device);
+ device = deviceRegistryService.update(device);
break;
} catch (KapuaOptimisticLockingException e) {
LOG.warn("Concurrent update for device: {}... Attempt: {}/{}. {}", device.getClientId(), retry, MAX_RETRY, retry < MAX_RETRY ? "Retrying..." : "Raising exception!");
@@ -245,7 +253,7 @@ private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, Ka
*/
private DeviceEvent createLifecycleEvent(@NotNull KapuaId scopeId, KapuaId deviceId, @NotNull String resource, @NotNull KapuaLifecycleMessage, ?> message) throws KapuaException {
- Device device = DEVICE_REGISTRY_SERVICE.find(scopeId, deviceId);
+ Device device = deviceRegistryService.find(scopeId, deviceId);
return createLifecycleEvent(device, resource, message);
}
@@ -261,7 +269,7 @@ private DeviceEvent createLifecycleEvent(@NotNull KapuaId scopeId, KapuaId devic
*/
private DeviceEvent createLifecycleEvent(@NotNull Device device, @NotNull String resource, @NotNull KapuaLifecycleMessage, ?> message) throws KapuaException {
- DeviceEventCreator deviceEventCreator = DEVICE_EVENT_FACTORY.newCreator(device.getScopeId(), device.getId(), message.getReceivedOn(), resource);
+ DeviceEventCreator deviceEventCreator = deviceEventFactory.newCreator(device.getScopeId(), device.getId(), message.getReceivedOn(), resource);
deviceEventCreator.setResponseCode(KapuaResponseCode.ACCEPTED);
deviceEventCreator.setSentOn(message.getSentOn());
deviceEventCreator.setReceivedOn(Date.from(KapuaDateUtils.getKapuaSysDate()));
@@ -275,7 +283,7 @@ private DeviceEvent createLifecycleEvent(@NotNull Device device, @NotNull String
deviceEventCreator.setPosition(position);
}
- return KapuaSecurityUtils.doPrivileged(() -> DEVICE_EVENT_SERVICE.create(deviceEventCreator));
+ return KapuaSecurityUtils.doPrivileged(() -> deviceEventService.create(deviceEventCreator));
}
/**
@@ -292,7 +300,7 @@ private List buildDeviceExtendedPropertyFromBirth(@Nulla
}
try {
- BirthExtendedProperties birthExtendedProperties = JSON_MAPPER.readValue(extendedPropertiesString, BirthExtendedProperties.class);
+ BirthExtendedProperties birthExtendedProperties = jsonMapper.readValue(extendedPropertiesString, BirthExtendedProperties.class);
List deviceExtendedProperties = new ArrayList<>();
for (Map.Entry eps : birthExtendedProperties.getExtendedProperties().entrySet()) {
diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java
index b4e720e27cb..011d74d5b99 100644
--- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java
+++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java
@@ -144,7 +144,7 @@ public class BrokerSteps extends TestBase {
*/
private static DeviceConnectionService deviceConnectionService;
private static DeviceAssetManagementService deviceAssetManagementService;
-
+ private BrokerSetting brokerSettings = new BrokerSetting();
/**
* Client simulating Kura device
*/
@@ -177,7 +177,7 @@ public void beforeScenarioNone(Scenario scenario) {
private void beforeInternal(Scenario scenario) {
updateScenario(scenario);
stepData.put(KURA_DEVICES, kuraDevices);
- BrokerSetting.resetInstance();
+ brokerSettings.resetInstance();
}
@After(value = "not (@setup or @teardown)", order = 10)
@@ -249,14 +249,14 @@ public void deviceConnected(int timeout) throws Exception {
try {
deviceBirthMessage();
boolean checkDone = false;
- while(!checkDone && timeout-->0) {
+ while (!checkDone && timeout-- > 0) {
checkDone = true;
logger.info("Device(s) status countdown check: {}", timeout);
for (KuraDevice kuraDevice : kuraDevices) {
Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId());
- boolean deviceStatusCheck = device!=null &&
- device.getConnection()!=null &&
- DeviceConnectionStatus.CONNECTED.equals(device.getConnection().getStatus());
+ boolean deviceStatusCheck = device != null &&
+ device.getConnection() != null &&
+ DeviceConnectionStatus.CONNECTED.equals(device.getConnection().getStatus());
checkDone = checkDone && deviceStatusCheck;
}
if (!checkDone) {
@@ -554,7 +554,7 @@ public void deviceStatusIs(String expectedStatus, int timeout, String clientId)
@Then("Device(s) status is {string} within {int} second(s)")
public void deviceStatusIs(String deviceStatus, int timeout) throws Exception {
boolean checkDone = false;
- while(!checkDone && timeout-->0) {
+ while (!checkDone && timeout-- > 0) {
checkDone = true;
logger.info("Device(s) status countdown check: {}", timeout);
for (KuraDevice kuraDevice : kuraDevices) {
diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementInventorySteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementInventorySteps.java
index 25abf67ef40..47e588d6755 100644
--- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementInventorySteps.java
+++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementInventorySteps.java
@@ -55,20 +55,21 @@ public class DeviceManagementInventorySteps extends TestBase {
private DeviceRegistryService deviceRegistryService;
private DeviceInventoryManagementService deviceInventoryManagementService;
+ private BrokerSetting brokerSettings = KapuaLocator.getInstance().getComponent(BrokerSetting.class);
@Inject
public DeviceManagementInventorySteps(StepData stepData) {
super(stepData);
}
- @Before(value="@env_docker or @env_docker_base or @env_none", order=10)
+ @Before(value = "@env_docker or @env_docker_base or @env_none", order = 10)
public void beforeScenarioNone(Scenario scenario) {
updateScenario(scenario);
}
- @After(value="@setup")
+ @After(value = "@setup")
public void setServices() {
- BrokerSetting.resetInstance();
+ brokerSettings.resetInstance();
KapuaLocator locator = KapuaLocator.getInstance();
deviceRegistryService = locator.getService(DeviceRegistryService.class);
diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java
index 55e54a1b7d6..10991d200ce 100644
--- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java
+++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java
@@ -12,6 +12,12 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.registry.steps;
+import com.google.inject.Singleton;
+import io.cucumber.java.After;
+import io.cucumber.java.Before;
+import io.cucumber.java.Scenario;
+import io.cucumber.java.en.Then;
+import io.cucumber.java.en.When;
import org.eclipse.kapua.broker.artemis.plugin.security.setting.BrokerSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.qa.common.StepData;
@@ -31,14 +37,6 @@
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.junit.Assert;
-import com.google.inject.Singleton;
-
-import io.cucumber.java.After;
-import io.cucumber.java.Before;
-import io.cucumber.java.Scenario;
-import io.cucumber.java.en.Then;
-import io.cucumber.java.en.When;
-
import javax.inject.Inject;
import java.util.List;
@@ -55,6 +53,7 @@ public class DeviceManagementKeystoreSteps extends TestBase {
private DeviceKeystoreManagementService deviceKeystoreManagementService;
private DeviceKeystoreManagementFactory deviceKeystoreManagementFactory;
+ private BrokerSetting brokerSettings = KapuaLocator.getInstance().getComponent(BrokerSetting.class);
/**
* Scenario scoped step data.
@@ -64,14 +63,14 @@ public DeviceManagementKeystoreSteps(StepData stepData) {
super(stepData);
}
- @Before(value="@env_docker or @env_docker_base or @env_none", order=10)
+ @Before(value = "@env_docker or @env_docker_base or @env_none", order = 10)
public void beforeScenarioNone(Scenario scenario) {
updateScenario(scenario);
}
- @After(value="@setup")
+ @After(value = "@setup")
public void setServices() {
- BrokerSetting.resetInstance();
+ brokerSettings.resetInstance();
KapuaLocator locator = KapuaLocator.getInstance();
deviceRegistryService = locator.getService(DeviceRegistryService.class);
diff --git a/service/device/registry/test/pom.xml b/service/device/registry/test/pom.xml
index 8e1e45fbff2..2e99e104a14 100644
--- a/service/device/registry/test/pom.xml
+++ b/service/device/registry/test/pom.xml
@@ -46,5 +46,10 @@
cucumber-junit
test
+
+ org.eclipse.kapua
+ kapua-tag-internal
+ test
+
diff --git a/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java b/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java
index f6598da6236..3d820c8f7be 100644
--- a/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java
+++ b/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.device.registry.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
@@ -23,11 +24,20 @@
import org.eclipse.kapua.commons.configuration.RootUserTester;
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.EventStorer;
import org.eclipse.kapua.commons.jpa.EventStorerImpl;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaMessageFactory;
import org.eclipse.kapua.message.internal.KapuaMessageFactoryImpl;
@@ -36,8 +46,13 @@
import org.eclipse.kapua.service.account.AccountFactory;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.authentication.CredentialsFactory;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.access.GroupQueryHelper;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
+import org.eclipse.kapua.service.authorization.group.GroupService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.device.authentication.UserPassDeviceConnectionCredentialAdapter;
@@ -45,6 +60,10 @@
import org.eclipse.kapua.service.device.registry.DeviceFactory;
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.DeviceRepository;
+import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettingKeys;
+import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettings;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidation;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidationImpl;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionRepository;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService;
@@ -61,6 +80,9 @@
import org.eclipse.kapua.service.device.registry.internal.DeviceImplJpaRepository;
import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryCacheFactory;
import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryServiceImpl;
+import org.eclipse.kapua.service.tag.internal.TagFactoryImpl;
+import org.eclipse.kapua.service.tag.internal.TagImplJpaRepository;
+import org.eclipse.kapua.service.tag.internal.TagServiceImpl;
import org.eclipse.kapua.storage.TxManager;
import org.mockito.Matchers;
import org.mockito.Mockito;
@@ -80,6 +102,17 @@ public void setupDI() {
@Override
protected void configure() {
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
@@ -104,7 +137,11 @@ protected void configure() {
bind(KapuaMetatypeFactory.class).toInstance(new KapuaMetatypeFactoryImpl());
// Inject actual Device registry service related services
- final DeviceRegistryCacheFactory deviceRegistryCacheFactory = new DeviceRegistryCacheFactory();
+ //TODO: FIXME: PRIORITY: build test instance
+ final CommonsMetric commonsMetric = null;
+ final KapuaCacheManager cacheManager = null;
+
+ final DeviceRegistryCacheFactory deviceRegistryCacheFactory = new DeviceRegistryCacheFactory(cacheManager, commonsMetric);
bind(DeviceRegistryCacheFactory.class).toInstance(deviceRegistryCacheFactory);
final Map availableDeviceConnectionAdapters = new HashMap<>();
@@ -116,7 +153,7 @@ protected void configure() {
final KapuaJpaRepositoryConfiguration jpaRepoConfig = new KapuaJpaRepositoryConfiguration();
final TxManager txManager = new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device");
final EventStorer eventStorer = new EventStorerImpl(new EventStoreRecordImplJpaRepository(jpaRepoConfig));
- bind(DeviceConnectionService.class).toInstance(new DeviceConnectionServiceImpl(
+ final DeviceConnectionService deviceConnectionService = new DeviceConnectionServiceImpl(
Mockito.mock(ServiceConfigurationManager.class),
mockedAuthorization,
permissionFactory,
@@ -124,22 +161,44 @@ protected void configure() {
txManager,
new DeviceConnectionImplJpaRepository(jpaRepoConfig),
availableDeviceConnectionAdapters,
- eventStorer));
+ eventStorer);
+ bind(DeviceConnectionService.class).toInstance(deviceConnectionService);
bind(DeviceConnectionFactory.class).toInstance(new DeviceConnectionFactoryImpl());
bind(DeviceRepository.class).toInstance(new DeviceImplJpaRepository(jpaRepoConfig));
bind(DeviceConnectionRepository.class).toInstance(new DeviceConnectionImplJpaRepository(jpaRepoConfig));
bind(DeviceEventRepository.class).toInstance(new DeviceEventImplJpaRepository(jpaRepoConfig));
- bind(DeviceEventService.class).toInstance(new DeviceEventServiceImpl(
+ final DeviceEventService deviceEventService = new DeviceEventServiceImpl(
mockedAuthorization,
permissionFactory,
txManager,
new DeviceImplJpaRepository(jpaRepoConfig),
new DeviceEventFactoryImpl(),
new DeviceEventImplJpaRepository(jpaRepoConfig)
- ));
+ );
+ bind(DeviceEventService.class).toInstance(deviceEventService);
bind(DeviceEventFactory.class).toInstance(new DeviceEventFactoryImpl());
bind(KapuaMessageFactory.class).toInstance(new KapuaMessageFactoryImpl());
+
+ final DeviceValidation deviceValidation = new DeviceValidationImpl(new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX),
+ new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX),
+ mockedAuthorization,
+ permissionFactory,
+ Mockito.mock(GroupService.class),
+ deviceConnectionService,
+ deviceEventService,
+ new DeviceImplJpaRepository(jpaRepoConfig),
+ new DeviceFactoryImpl(),
+ new TagServiceImpl(
+ permissionFactory,
+ mockedAuthorization,
+ Mockito.mock(ServiceConfigurationManager.class),
+ new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-tag"),
+ new TagImplJpaRepository(jpaRepoConfig),
+ new TagFactoryImpl())
+ );
+
+ bind(DeviceValidation.class).toInstance(deviceValidation);
bind(DeviceRegistryService.class).toInstance(new DeviceRegistryServiceImpl(
Mockito.mock(ServiceConfigurationManager.class),
mockedAuthorization,
@@ -148,7 +207,8 @@ protected void configure() {
new DeviceImplJpaRepository(jpaRepoConfig),
new DeviceFactoryImpl(),
Mockito.mock(GroupQueryHelper.class),
- eventStorer)
+ eventStorer,
+ deviceValidation)
);
}
};
diff --git a/service/device/registry/test/src/test/resources/locator.xml b/service/device/registry/test/src/test/resources/locator.xml
index e2a896d3184..d3a1774c99d 100644
--- a/service/device/registry/test/src/test/resources/locator.xml
+++ b/service/device/registry/test/src/test/resources/locator.xml
@@ -24,6 +24,7 @@
org.eclipse.kapua.test.user
org.eclipse.kapua.test.account
org.eclipse.kapua.test.authentication
+ org.eclipse.kapua.locator
org.eclipse.kapua.test.authorization
diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java
index b22b78d37a4..334e2f8380f 100644
--- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java
+++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class EndpointInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final EndpointInfoFactory FACTORY = LOCATOR.getFactory(EndpointInfoFactory.class);
+ private final EndpointInfoFactory endpointInfoFactory = KapuaLocator.getInstance().getFactory(EndpointInfoFactory.class);
/**
* Creates a new {@link EndpointInfo} instance
@@ -28,7 +27,7 @@ public class EndpointInfoXmlRegistry {
* @return
*/
public EndpointInfo newEntity() {
- return FACTORY.newEntity(null);
+ return endpointInfoFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public EndpointInfo newEntity() {
* @return
*/
public EndpointInfoCreator newCreator() {
- return FACTORY.newCreator(null);
+ return endpointInfoFactory.newCreator(null);
}
/**
@@ -46,7 +45,7 @@ public EndpointInfoCreator newCreator() {
* @return
*/
public EndpointInfoListResult newListResult() {
- return FACTORY.newListResult();
+ return endpointInfoFactory.newListResult();
}
/**
@@ -55,10 +54,10 @@ public EndpointInfoListResult newListResult() {
* @return
*/
public EndpointInfoQuery newQuery() {
- return FACTORY.newQuery(null);
+ return endpointInfoFactory.newQuery(null);
}
public EndpointUsage newEndpointUsage() {
- return FACTORY.newEndpointUsage(null);
+ return endpointInfoFactory.newEndpointUsage(null);
}
}
diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java
index 1579ff83e47..c8a7ee86d60 100644
--- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java
+++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class JobXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobFactory JOB_FACTORY = LOCATOR.getFactory(JobFactory.class);
+ private final JobFactory jobFactory = KapuaLocator.getInstance().getFactory(JobFactory.class);
/**
* Creates a new job instance
@@ -33,7 +32,7 @@ public class JobXmlRegistry {
* @return
*/
public Job newJob() {
- return JOB_FACTORY.newEntity(null);
+ return jobFactory.newEntity(null);
}
/**
@@ -42,7 +41,7 @@ public Job newJob() {
* @return
*/
public JobCreator newJobCreator() {
- return JOB_FACTORY.newCreator(null);
+ return jobFactory.newCreator(null);
}
/**
@@ -51,10 +50,10 @@ public JobCreator newJobCreator() {
* @return
*/
public JobListResult newJobListResult() {
- return JOB_FACTORY.newListResult();
+ return jobFactory.newListResult();
}
public JobQuery newQuery() {
- return JOB_FACTORY.newQuery(null);
+ return jobFactory.newQuery(null);
}
}
diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java
index f20b3c431f2..b1a6903c338 100644
--- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java
+++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class JobExecutionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobExecutionFactory JOB_EXECUTION_FACTORY = LOCATOR.getFactory(JobExecutionFactory.class);
+ private final JobExecutionFactory jobExecutionFactory = KapuaLocator.getInstance().getFactory(JobExecutionFactory.class);
/**
* Creates a new job instance
@@ -33,7 +32,7 @@ public class JobExecutionXmlRegistry {
* @return
*/
public JobExecution newJobExecution() {
- return JOB_EXECUTION_FACTORY.newEntity(null);
+ return jobExecutionFactory.newEntity(null);
}
/**
@@ -42,7 +41,7 @@ public JobExecution newJobExecution() {
* @return
*/
public JobExecutionCreator newJobExecutionCreator() {
- return JOB_EXECUTION_FACTORY.newCreator(null);
+ return jobExecutionFactory.newCreator(null);
}
/**
@@ -51,10 +50,10 @@ public JobExecutionCreator newJobExecutionCreator() {
* @return
*/
public JobExecutionListResult newJobExecutionListResult() {
- return JOB_EXECUTION_FACTORY.newListResult();
+ return jobExecutionFactory.newListResult();
}
public JobExecutionQuery newQuery() {
- return JOB_EXECUTION_FACTORY.newQuery(null);
+ return jobExecutionFactory.newQuery(null);
}
}
diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepXmlRegistry.java
index 5809745f9c4..9cc8763ba30 100644
--- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepXmlRegistry.java
+++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepXmlRegistry.java
@@ -25,8 +25,7 @@
@XmlRegistry
public class JobStepXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobStepFactory JOB_STEP_FACTORY = LOCATOR.getFactory(JobStepFactory.class);
+ private final JobStepFactory jobStepFactory = KapuaLocator.getInstance().getFactory(JobStepFactory.class);
/**
* Creates a new job instance
@@ -34,7 +33,7 @@ public class JobStepXmlRegistry {
* @return
*/
public JobStep newJobStep() {
- return JOB_STEP_FACTORY.newEntity(null);
+ return jobStepFactory.newEntity(null);
}
/**
@@ -43,7 +42,7 @@ public JobStep newJobStep() {
* @return
*/
public JobStepCreator newJobStepCreator() {
- return JOB_STEP_FACTORY.newCreator(null);
+ return jobStepFactory.newCreator(null);
}
/**
@@ -52,15 +51,15 @@ public JobStepCreator newJobStepCreator() {
* @return
*/
public JobStepListResult newJobStepListResult() {
- return JOB_STEP_FACTORY.newListResult();
+ return jobStepFactory.newListResult();
}
public JobStepQuery newQuery() {
- return JOB_STEP_FACTORY.newQuery(null);
+ return jobStepFactory.newQuery(null);
}
public JobStepProperty newJobStepProperty() {
- return JOB_STEP_FACTORY.newStepProperty(null, null, null);
+ return jobStepFactory.newStepProperty(null, null, null);
}
}
diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java
index a7e82742c94..019d7fd1776 100644
--- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java
+++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class JobStepDefinitionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobStepDefinitionFactory JOB_STEP_DEFINITION_FACTORY = LOCATOR.getFactory(JobStepDefinitionFactory.class);
+ private final JobStepDefinitionFactory jobStepDefinitionFactory = KapuaLocator.getInstance().getFactory(JobStepDefinitionFactory.class);
/**
* Creates a new job instance
@@ -33,7 +32,7 @@ public class JobStepDefinitionXmlRegistry {
* @return
*/
public JobStepDefinition newJobStepDefinition() {
- return JOB_STEP_DEFINITION_FACTORY.newEntity(null);
+ return jobStepDefinitionFactory.newEntity(null);
}
/**
@@ -42,7 +41,7 @@ public JobStepDefinition newJobStepDefinition() {
* @return
*/
public JobStepDefinitionCreator newJobStepDefinitionCreator() {
- return JOB_STEP_DEFINITION_FACTORY.newCreator(null);
+ return jobStepDefinitionFactory.newCreator(null);
}
/**
@@ -51,10 +50,10 @@ public JobStepDefinitionCreator newJobStepDefinitionCreator() {
* @return
*/
public JobStepDefinitionListResult newJobStepDefinitionListResult() {
- return JOB_STEP_DEFINITION_FACTORY.newListResult();
+ return jobStepDefinitionFactory.newListResult();
}
public JobStepDefinitionQuery newQuery() {
- return JOB_STEP_DEFINITION_FACTORY.newQuery(null);
+ return jobStepDefinitionFactory.newQuery(null);
}
}
diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetXmlRegistry.java
index 50f78571a12..0e09d0c313d 100644
--- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetXmlRegistry.java
+++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class JobTargetXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final JobTargetFactory JOB_TARGET_FACTORY = LOCATOR.getFactory(JobTargetFactory.class);
+ private final JobTargetFactory jobTargetFactory = KapuaLocator.getInstance().getFactory(JobTargetFactory.class);
/**
* Creates a new job instance
@@ -33,7 +32,7 @@ public class JobTargetXmlRegistry {
* @return
*/
public JobTarget newJobTarget() {
- return JOB_TARGET_FACTORY.newEntity(null);
+ return jobTargetFactory.newEntity(null);
}
/**
@@ -42,7 +41,7 @@ public JobTarget newJobTarget() {
* @return
*/
public JobTargetCreator newJobTargetCreator() {
- return JOB_TARGET_FACTORY.newCreator(null);
+ return jobTargetFactory.newCreator(null);
}
/**
@@ -51,10 +50,10 @@ public JobTargetCreator newJobTargetCreator() {
* @return
*/
public JobTargetListResult newJobTargetListResult() {
- return JOB_TARGET_FACTORY.newListResult();
+ return jobTargetFactory.newListResult();
}
public JobTargetQuery newQuery() {
- return JOB_TARGET_FACTORY.newQuery(null);
+ return jobTargetFactory.newQuery(null);
}
}
diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java
index c928fc9a7a5..320d92548ac 100644
--- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java
+++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java
@@ -60,7 +60,6 @@ public JobExecution create(JobExecutionCreator jobExecutionCreator) throws Kapua
ArgumentValidator.notNull(jobExecutionCreator.getScopeId(), "jobExecutionCreator.scopeId");
// Check access
authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobExecutionCreator.getScopeId()));
-
JobExecution jobExecution = new JobExecutionImpl(jobExecutionCreator.getScopeId());
jobExecution.setJobId(jobExecutionCreator.getJobId());
jobExecution.setStartedOn(jobExecutionCreator.getStartedOn());
diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java
index 6b23a1eafdb..6724cb59a1d 100644
--- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java
+++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.ResourceLimitedServiceConfigurationManagerImpl;
@@ -24,6 +23,7 @@
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManagerCachingWrapper;
import org.eclipse.kapua.commons.configuration.UsedEntitiesCounterImpl;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
@@ -82,14 +82,15 @@ public ServiceConfigurationManager jobServiceConfigurationManager(
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
JobRepository jobRepository,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(
JobService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/settings/JobServiceSettings.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/settings/JobServiceSettings.java
index d8f5bb77cf6..47d063306c7 100644
--- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/settings/JobServiceSettings.java
+++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/settings/JobServiceSettings.java
@@ -29,29 +29,13 @@ public class JobServiceSettings extends AbstractKapuaSettingorg.eclipse.kapua.commons
org.eclipse.kapua.service.generator.id.sequence
org.eclipse.kapua.service.job.internal
+ org.eclipse.kapua.translator
diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerXmlRegistry.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerXmlRegistry.java
index a8baf0498d6..60814fad7e5 100644
--- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerXmlRegistry.java
+++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerXmlRegistry.java
@@ -25,27 +25,26 @@
@XmlRegistry
public class TriggerXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final TriggerFactory TRIGGER_FACTORY = LOCATOR.getFactory(TriggerFactory.class);
+ private final TriggerFactory triggerFactory = KapuaLocator.getInstance().getFactory(TriggerFactory.class);
public Trigger newEntity() {
- return TRIGGER_FACTORY.newEntity(null);
+ return triggerFactory.newEntity(null);
}
public TriggerCreator newCreator() {
- return TRIGGER_FACTORY.newCreator(null);
+ return triggerFactory.newCreator(null);
}
public TriggerListResult newListResult() {
- return TRIGGER_FACTORY.newListResult();
+ return triggerFactory.newListResult();
}
public TriggerQuery newQuery() {
- return TRIGGER_FACTORY.newQuery(null);
+ return triggerFactory.newQuery(null);
}
public TriggerProperty newTriggerProperty() {
- return TRIGGER_FACTORY.newTriggerProperty(null, null, null);
+ return triggerFactory.newTriggerProperty(null, null, null);
}
}
diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java
index 98767651233..6303d16a524 100644
--- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java
+++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java
@@ -24,22 +24,21 @@
@XmlRegistry
public class TriggerDefinitionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final TriggerDefinitionFactory TRIGGER_DEFINITION_FACTORY = LOCATOR.getFactory(TriggerDefinitionFactory.class);
+ private final TriggerDefinitionFactory triggerDefinitionFactory = KapuaLocator.getInstance().getFactory(TriggerDefinitionFactory.class);
public TriggerDefinition newEntity() {
- return TRIGGER_DEFINITION_FACTORY.newEntity(null);
+ return triggerDefinitionFactory.newEntity(null);
}
public TriggerDefinitionCreator newCreator() {
- return TRIGGER_DEFINITION_FACTORY.newCreator(null);
+ return triggerDefinitionFactory.newCreator(null);
}
public TriggerDefinitionListResult newListResult() {
- return TRIGGER_DEFINITION_FACTORY.newListResult();
+ return triggerDefinitionFactory.newListResult();
}
public TriggerDefinitionQuery newQuery() {
- return TRIGGER_DEFINITION_FACTORY.newQuery(null);
+ return triggerDefinitionFactory.newQuery(null);
}
}
diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerXmlRegistry.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerXmlRegistry.java
index 3e5898bc505..a7f6222ca4c 100644
--- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerXmlRegistry.java
+++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerXmlRegistry.java
@@ -24,22 +24,21 @@
@XmlRegistry
public class FiredTriggerXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final FiredTriggerFactory FIRED_TRIGGER_FACTORY = LOCATOR.getFactory(FiredTriggerFactory.class);
+ private final FiredTriggerFactory firedTriggerFactory = KapuaLocator.getInstance().getFactory(FiredTriggerFactory.class);
public FiredTrigger newEntity() {
- return FIRED_TRIGGER_FACTORY.newEntity(null);
+ return firedTriggerFactory.newEntity(null);
}
public FiredTriggerCreator newCreator() {
- return FIRED_TRIGGER_FACTORY.newCreator(null);
+ return firedTriggerFactory.newCreator(null);
}
public FiredTriggerListResult newListResult() {
- return FIRED_TRIGGER_FACTORY.newListResult();
+ return firedTriggerFactory.newListResult();
}
public FiredTriggerQuery newQuery() {
- return FIRED_TRIGGER_FACTORY.newQuery(null);
+ return firedTriggerFactory.newQuery(null);
}
}
diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/persistence/KapuaQuartzConnectionProvider.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/persistence/KapuaQuartzConnectionProvider.java
index 7a0430bd5e3..6a4743fa716 100644
--- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/persistence/KapuaQuartzConnectionProvider.java
+++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/persistence/KapuaQuartzConnectionProvider.java
@@ -32,13 +32,13 @@ public class KapuaQuartzConnectionProvider implements ConnectionProvider {
private static final String JDBC_CONNECTION_URL = JdbcConnectionUrlResolvers.resolveJdbcUrl();
- private static final SystemSetting CONFIG = SystemSetting.getInstance();
- private static final String USERNAME = CONFIG.getString(SystemSettingKey.DB_USERNAME);
- private static final String PASSWORD = CONFIG.getString(SystemSettingKey.DB_PASSWORD);
+ private final SystemSetting systemSetting = SystemSetting.getInstance();
+ private final String username = systemSetting.getString(SystemSettingKey.DB_USERNAME);
+ private final String password = systemSetting.getString(SystemSettingKey.DB_PASSWORD);
@Override
public Connection getConnection() throws SQLException {
- return DriverManager.getConnection(JDBC_CONNECTION_URL, USERNAME, PASSWORD);
+ return DriverManager.getConnection(JDBC_CONNECTION_URL, username, password);
}
@Override
diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSetting.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSetting.java
deleted file mode 100644
index d8243b939de..00000000000
--- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSetting.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.scheduler.quartz.setting;
-
-import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
-
-/**
- * Class that offers access to scheduler settings
- *
- * @since 1.0.0
- */
-public class KapuaSchedulerSetting extends AbstractKapuaSetting {
-
- /**
- * Resource file from which source properties.
- */
- private static final String SCHEDULER_CONFIG_RESOURCE = "kapua-scheduler-setting.properties";
-
- private static final KapuaSchedulerSetting INSTANCE = new KapuaSchedulerSetting();
-
- /**
- * Initialize the {@link AbstractKapuaSetting} with the {@link KapuaSchedulerSettingKeys#SCHEDULER_KEY} value.
- */
- private KapuaSchedulerSetting() {
- super(SCHEDULER_CONFIG_RESOURCE);
- }
-
- /**
- * Gets a singleton instance of {@link KapuaSchedulerSetting}.
- *
- * @return A singleton instance of KapuaSchedulerSetting.
- */
- public static KapuaSchedulerSetting getInstance() {
- return INSTANCE;
- }
-}
diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSettingKeys.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSettingKeys.java
deleted file mode 100644
index c3630dd8e67..00000000000
--- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/setting/KapuaSchedulerSettingKeys.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.scheduler.quartz.setting;
-
-import org.eclipse.kapua.commons.setting.SettingKey;
-
-/**
- * Available settings key for scheduler service
- *
- * @since 1.0.0
- */
-public enum KapuaSchedulerSettingKeys implements SettingKey {
- /**
- * The key value in the configuration resources.
- */
- SCHEDULER_KEY("scheduler.key");
-
- private final String key;
-
- /**
- * Set up the {@code enum} with the key value provided
- *
- * @param key The value mapped by this {@link Enum} value
- */
- KapuaSchedulerSettingKeys(String key) {
- this.key = key;
- }
-
- /**
- * Gets the key for this {@link KapuaSchedulerSettingKeys}
- */
- @Override
- public String key() {
- return key;
- }
-}
diff --git a/service/scheduler/quartz/src/main/resources/kapua-scheduler-setting.properties b/service/scheduler/quartz/src/main/resources/kapua-scheduler-setting.properties
deleted file mode 100644
index 82109f69f89..00000000000
--- a/service/scheduler/quartz/src/main/resources/kapua-scheduler-setting.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-###############################################################################
-# Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
-#
-# This program and the accompanying materials are made
-# available under the terms of the Eclipse Public License 2.0
-# which is available at https://www.eclipse.org/legal/epl-2.0/
-#
-# SPDX-License-Identifier: EPL-2.0
-#
-# Contributors:
-# Eurotech - initial API and implementation
-#
-###############################################################################
diff --git a/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java b/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java
index 542ffee78cf..45a7cc44273 100644
--- a/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java
+++ b/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java
@@ -12,20 +12,31 @@
*******************************************************************************/
package org.eclipse.kapua.service.scheduler.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
+import com.google.inject.name.Names;
import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.RootUserTester;
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.model.query.QueryFactoryImpl;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.job.engine.client.JobEngineServiceClient;
+import org.eclipse.kapua.job.engine.client.settings.JobEngineClientSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
import org.eclipse.kapua.model.query.QueryFactory;
@@ -33,7 +44,11 @@
import org.eclipse.kapua.service.account.AccountFactory;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.account.internal.AccountFactoryImpl;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.job.JobFactory;
@@ -66,6 +81,17 @@ public void setupDI() {
@Override
protected void configure() {
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
@@ -110,7 +136,7 @@ protected void configure() {
);
bind(JobService.class).toInstance(new JobServiceImpl(
Mockito.mock(ServiceConfigurationManager.class),
- new JobEngineServiceClient(),
+ new JobEngineServiceClient(new JobEngineClientSetting()),
permissionFactory,
mockedAuthorization,
new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-job"),
diff --git a/service/scheduler/test/src/test/resources/locator.xml b/service/scheduler/test/src/test/resources/locator.xml
index debed76c663..f3c2fc14c76 100644
--- a/service/scheduler/test/src/test/resources/locator.xml
+++ b/service/scheduler/test/src/test/resources/locator.xml
@@ -20,5 +20,6 @@
org.eclipse.kapua.commons
org.eclipse.kapua.service.generator.id.sequence
org.eclipse.kapua.service.scheduler.internal
+ org.eclipse.kapua.translator
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java
index 9f78588e603..fca84cc0544 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java
@@ -17,8 +17,7 @@
public class AuthenticationXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final CredentialsFactory CREDENTIALS_FACTORY = LOCATOR.getFactory(CredentialsFactory.class);
+ private final CredentialsFactory credentialsFactory = KapuaLocator.getInstance().getFactory(CredentialsFactory.class);
/**
* Creates a new {@link UsernamePasswordCredentials} instance
@@ -26,7 +25,7 @@ public class AuthenticationXmlRegistry {
* @return
*/
public UsernamePasswordCredentials newUsernamePasswordCredentials() {
- return CREDENTIALS_FACTORY.newUsernamePasswordCredentials();
+ return credentialsFactory.newUsernamePasswordCredentials();
}
/**
@@ -35,7 +34,7 @@ public UsernamePasswordCredentials newUsernamePasswordCredentials() {
* @return
*/
public ApiKeyCredentials newApiKeyCredentials() {
- return CREDENTIALS_FACTORY.newApiKeyCredentials(null);
+ return credentialsFactory.newApiKeyCredentials(null);
}
/**
@@ -44,7 +43,7 @@ public ApiKeyCredentials newApiKeyCredentials() {
* @return
*/
public JwtCredentials newJwtCredentials() {
- return CREDENTIALS_FACTORY.newJwtCredentials(null, null);
+ return credentialsFactory.newJwtCredentials(null, null);
}
/**
@@ -53,7 +52,7 @@ public JwtCredentials newJwtCredentials() {
* @return
*/
public AccessTokenCredentials newAccessTokenCredentials() {
- return CREDENTIALS_FACTORY.newAccessTokenCredentials(null);
+ return credentialsFactory.newAccessTokenCredentials(null);
}
/**
@@ -62,6 +61,6 @@ public AccessTokenCredentials newAccessTokenCredentials() {
* @return
*/
public RefreshTokenCredentials newRefreshTokenCredentials() {
- return CREDENTIALS_FACTORY.newRefreshTokenCredentials(null, null);
+ return credentialsFactory.newRefreshTokenCredentials(null, null);
}
}
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialXmlRegistry.java
index f3b11b67ff8..8500325a8ea 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class CredentialXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final CredentialFactory CREDENTIAL_FACTORY = LOCATOR.getFactory(CredentialFactory.class);
+ private final CredentialFactory credentialFactory = KapuaLocator.getInstance().getFactory(CredentialFactory.class);
/**
* Creates a new credential instance
@@ -28,7 +27,7 @@ public class CredentialXmlRegistry {
* @return
*/
public Credential newCredential() {
- return CREDENTIAL_FACTORY.newEntity(null);
+ return credentialFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public Credential newCredential() {
* @return
*/
public CredentialListResult newCredentialListResult() {
- return CREDENTIAL_FACTORY.newListResult();
+ return credentialFactory.newListResult();
}
/**
@@ -46,10 +45,10 @@ public CredentialListResult newCredentialListResult() {
* @return
*/
public CredentialCreator newCredentialCreator() {
- return CREDENTIAL_FACTORY.newCreator(null, null, null, null, null, null);
+ return credentialFactory.newCreator(null, null, null, null, null, null);
}
public CredentialQuery newQuery() {
- return CREDENTIAL_FACTORY.newQuery(null);
+ return credentialFactory.newQuery(null);
}
}
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java
index 80b0d32c971..5387269bb9e 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class MfaOptionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final MfaOptionFactory MFA_OPTION_FACTORY = LOCATOR.getFactory(MfaOptionFactory.class);
+ private final MfaOptionFactory mfaOptionFactory = KapuaLocator.getInstance().getFactory(MfaOptionFactory.class);
/**
* Creates a new {@link MfaOption} instance
@@ -28,7 +27,7 @@ public class MfaOptionXmlRegistry {
* @return
*/
public MfaOption newMfaOption() {
- return MFA_OPTION_FACTORY.newEntity(null);
+ return mfaOptionFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public MfaOption newMfaOption() {
* @return
*/
public MfaOptionListResult newMfaOptionListResult() {
- return MFA_OPTION_FACTORY.newListResult();
+ return mfaOptionFactory.newListResult();
}
/**
@@ -46,10 +45,10 @@ public MfaOptionListResult newMfaOptionListResult() {
* @return
*/
public MfaOptionCreator newMfaOptionCreator() {
- return MFA_OPTION_FACTORY.newCreator(null, null, null);
+ return mfaOptionFactory.newCreator(null, null, null);
}
public MfaOptionQuery newQuery() {
- return MFA_OPTION_FACTORY.newQuery(null);
+ return mfaOptionFactory.newQuery(null);
}
}
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java
index 02a938dc1ba..e1c6110978e 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class ScratchCodeXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final ScratchCodeFactory SCRATCH_CODE_FACTORY = LOCATOR.getFactory(ScratchCodeFactory.class);
+ private final ScratchCodeFactory scratchCodeFactory = KapuaLocator.getInstance().getFactory(ScratchCodeFactory.class);
/**
* Creates a new {@link ScratchCode} instance
@@ -28,7 +27,7 @@ public class ScratchCodeXmlRegistry {
* @return
*/
public ScratchCode newScratchCode() {
- return SCRATCH_CODE_FACTORY.newEntity(null);
+ return scratchCodeFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public ScratchCode newScratchCode() {
* @return
*/
public ScratchCodeListResult newScratchCodeListResult() {
- return SCRATCH_CODE_FACTORY.newListResult();
+ return scratchCodeFactory.newListResult();
}
/**
@@ -46,10 +45,10 @@ public ScratchCodeListResult newScratchCodeListResult() {
* @return
*/
public ScratchCodeCreator newScratchCodeCreator() {
- return SCRATCH_CODE_FACTORY.newCreator(null, null, null);
+ return scratchCodeFactory.newCreator(null, null, null);
}
public ScratchCodeQuery newQuery() {
- return SCRATCH_CODE_FACTORY.newQuery(null);
+ return scratchCodeFactory.newQuery(null);
}
}
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java
index a50c1733c84..08b3fc699df 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java
@@ -14,16 +14,18 @@
import org.eclipse.kapua.locator.KapuaLocator;
+import javax.xml.bind.annotation.XmlRegistry;
+
+@XmlRegistry
public class AccessTokenXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final AccessTokenFactory ACCESS_TOKEN_FACTORY = LOCATOR.getFactory(AccessTokenFactory.class);
+ private final AccessTokenFactory accessTokenFactory = KapuaLocator.getInstance().getFactory(AccessTokenFactory.class);
public AccessToken newAccessToken() {
- return ACCESS_TOKEN_FACTORY.newEntity(null);
+ return accessTokenFactory.newEntity(null);
}
public AccessTokenCreator newAccessTokenCreator() {
- return ACCESS_TOKEN_FACTORY.newCreator(null, null, null, null, null, null);
+ return accessTokenFactory.newCreator(null, null, null, null, null, null);
}
}
diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java
index 7b2b1119dd2..e83e5ebe08a 100644
--- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java
+++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class UserCredentialsXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final UserCredentialsFactory USER_CREDENTIAL_FACTORY = LOCATOR.getFactory(UserCredentialsFactory.class);
+ private final UserCredentialsFactory userCredentialsFactory = KapuaLocator.getInstance().getFactory(UserCredentialsFactory.class);
/**
@@ -29,16 +28,17 @@ public class UserCredentialsXmlRegistry {
* @return
*/
public PasswordChangeRequest newPasswordChangeRequest() {
- return USER_CREDENTIAL_FACTORY.newPasswordChangeRequest();
+ return userCredentialsFactory.newPasswordChangeRequest();
}
/**
* Creates a new reset password request
+ *
* @return
*/
public PasswordResetRequest newPasswordResetRequest() {
- return USER_CREDENTIAL_FACTORY.newPasswordResetRequest();
+ return userCredentialsFactory.newPasswordResetRequest();
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java
index 7e0747edac3..f856ce81d65 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class AccessInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final AccessInfoFactory ACCESS_INFO_FACTORY = LOCATOR.getFactory(AccessInfoFactory.class);
+ private final AccessInfoFactory accessInfoFactory = KapuaLocator.getInstance().getFactory(AccessInfoFactory.class);
/**
* Creates a new access info instance
@@ -28,7 +27,7 @@ public class AccessInfoXmlRegistry {
* @return
*/
public AccessInfo newAccessInfo() {
- return ACCESS_INFO_FACTORY.newEntity(null);
+ return accessInfoFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public AccessInfo newAccessInfo() {
* @return
*/
public AccessInfoCreator newAccessInfoCreator() {
- return ACCESS_INFO_FACTORY.newCreator(null);
+ return accessInfoFactory.newCreator(null);
}
/**
@@ -46,10 +45,10 @@ public AccessInfoCreator newAccessInfoCreator() {
* @return
*/
public AccessInfoListResult newAccessInfoListResult() {
- return ACCESS_INFO_FACTORY.newListResult();
+ return accessInfoFactory.newListResult();
}
public AccessInfoQuery newQuery() {
- return ACCESS_INFO_FACTORY.newQuery(null);
+ return accessInfoFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionXmlRegistry.java
index 450e3774a50..c34f043188d 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class AccessPermissionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final AccessPermissionFactory ACCESS_PERMISSION_FACTORY = LOCATOR.getFactory(AccessPermissionFactory.class);
+ private final AccessPermissionFactory accessPermissionFactory = KapuaLocator.getInstance().getFactory(AccessPermissionFactory.class);
/**
* Creates a new {@link AccessPermission} instance
@@ -28,7 +27,7 @@ public class AccessPermissionXmlRegistry {
* @return
*/
public AccessPermission newAccessPermission() {
- return ACCESS_PERMISSION_FACTORY.newEntity(null);
+ return accessPermissionFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public AccessPermission newAccessPermission() {
* @return
*/
public AccessPermissionCreator newCreator() {
- return ACCESS_PERMISSION_FACTORY.newCreator(null);
+ return accessPermissionFactory.newCreator(null);
}
/**
@@ -46,10 +45,10 @@ public AccessPermissionCreator newCreator() {
* @return
*/
public AccessPermissionListResult newAccessPermissionListResult() {
- return ACCESS_PERMISSION_FACTORY.newListResult();
+ return accessPermissionFactory.newListResult();
}
public AccessPermissionQuery newQuery() {
- return ACCESS_PERMISSION_FACTORY.newQuery(null);
+ return accessPermissionFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleXmlRegistry.java
index fc9e6a3be0a..0b8ef61befc 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class AccessRoleXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final AccessRoleFactory ACCESS_ROLE_FACTORY = LOCATOR.getFactory(AccessRoleFactory.class);
+ private final AccessRoleFactory accessRoleFactory = KapuaLocator.getInstance().getFactory(AccessRoleFactory.class);
/**
* Creates a new {@link AccessRole} instance
@@ -28,7 +27,7 @@ public class AccessRoleXmlRegistry {
* @return
*/
public AccessRole newAccessRole() {
- return ACCESS_ROLE_FACTORY.newEntity(null);
+ return accessRoleFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public AccessRole newAccessRole() {
* @return
*/
public AccessRoleCreator newCreator() {
- return ACCESS_ROLE_FACTORY.newCreator(null);
+ return accessRoleFactory.newCreator(null);
}
/**
@@ -46,10 +45,10 @@ public AccessRoleCreator newCreator() {
* @return
*/
public AccessRoleListResult newAccessRoleListResult() {
- return ACCESS_ROLE_FACTORY.newListResult();
+ return accessRoleFactory.newListResult();
}
public AccessRoleQuery newQuery() {
- return ACCESS_ROLE_FACTORY.newQuery(null);
+ return accessRoleFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainXmlRegistry.java
index d1695028434..5a9157c13d2 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainXmlRegistry.java
@@ -19,10 +19,9 @@
@XmlRegistry
public class DomainXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DomainFactory DOMAIN_FACTORY = LOCATOR.getFactory(DomainFactory.class);
+ private final DomainFactory domainFactory = KapuaLocator.getInstance().getFactory(DomainFactory.class);
public DomainQuery newQuery() {
- return DOMAIN_FACTORY.newQuery(null);
+ return domainFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java
index 275d93e0ce3..31f777e9ca4 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class GroupXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final GroupFactory GROUP_FACTORY = LOCATOR.getFactory(GroupFactory.class);
+ private final GroupFactory groupFactory = KapuaLocator.getInstance().getFactory(GroupFactory.class);
/**
* Creates a new {@link Group} instance
@@ -29,7 +28,7 @@ public class GroupXmlRegistry {
* @since 1.0.0
*/
public Group newGroup() {
- return GROUP_FACTORY.newEntity(null);
+ return groupFactory.newEntity(null);
}
/**
@@ -39,7 +38,7 @@ public Group newGroup() {
* @since 1.0.0
*/
public GroupCreator newGroupCreator() {
- return GROUP_FACTORY.newCreator(null, null);
+ return groupFactory.newCreator(null, null);
}
/**
@@ -49,7 +48,7 @@ public GroupCreator newGroupCreator() {
* @since 1.0.0
*/
public GroupListResult newGroupListResult() {
- return GROUP_FACTORY.newListResult();
+ return groupFactory.newListResult();
}
/**
@@ -59,6 +58,6 @@ public GroupListResult newGroupListResult() {
* @since 1.0.0
*/
public GroupQuery newQuery() {
- return GROUP_FACTORY.newQuery(null);
+ return groupFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java
index ed7faa213c0..91b9a30a054 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class PermissionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class);
+ private final PermissionFactory permissionFactory = KapuaLocator.getInstance().getFactory(PermissionFactory.class);
/**
* Creates a new {@link Permission} instance
@@ -29,6 +28,6 @@ public class PermissionXmlRegistry {
* @since 1.0.0
*/
public Permission newPermission() {
- return PERMISSION_FACTORY.newPermission((String) null, null, null, null);
+ return permissionFactory.newPermission(null, null, null, null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionXmlRegistry.java
index 1aea1569905..583394b80c2 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class RolePermissionXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final RolePermissionFactory ROLE_PERMISSION_FACTORY = LOCATOR.getFactory(RolePermissionFactory.class);
+ private final RolePermissionFactory rolePermissionFactory = KapuaLocator.getInstance().getFactory(RolePermissionFactory.class);
/**
* Creates a new {@link RolePermission} instance
@@ -28,7 +27,7 @@ public class RolePermissionXmlRegistry {
* @return
*/
public RolePermission newRolePermission() {
- return ROLE_PERMISSION_FACTORY.newEntity(null);
+ return rolePermissionFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public RolePermission newRolePermission() {
* @return
*/
public RolePermissionCreator newCreator() {
- return ROLE_PERMISSION_FACTORY.newCreator(null);
+ return rolePermissionFactory.newCreator(null);
}
/**
@@ -46,10 +45,10 @@ public RolePermissionCreator newCreator() {
* @return
*/
public RolePermissionListResult newRolePermissionListResult() {
- return ROLE_PERMISSION_FACTORY.newListResult();
+ return rolePermissionFactory.newListResult();
}
public RolePermissionQuery newQuery() {
- return ROLE_PERMISSION_FACTORY.newQuery(null);
+ return rolePermissionFactory.newQuery(null);
}
}
diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java
index 17b6d2e4cc2..b46b8aa8af1 100644
--- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java
+++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class RoleXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final RoleFactory ROLE_FACTORY = LOCATOR.getFactory(RoleFactory.class);
+ private final RoleFactory roleFactory = KapuaLocator.getInstance().getFactory(RoleFactory.class);
/**
* Creates a new {@link Role} instance.
@@ -29,7 +28,7 @@ public class RoleXmlRegistry {
* @since 1.0.0
*/
public Role newRole() {
- return ROLE_FACTORY.newEntity(null);
+ return roleFactory.newEntity(null);
}
/**
@@ -39,7 +38,7 @@ public Role newRole() {
* @since 1.0.0
*/
public RoleCreator newRoleCreator() {
- return ROLE_FACTORY.newCreator(null);
+ return roleFactory.newCreator(null);
}
/**
@@ -49,7 +48,7 @@ public RoleCreator newRoleCreator() {
* @since 1.0.0
*/
public RoleListResult newRoleListResult() {
- return ROLE_FACTORY.newListResult();
+ return roleFactory.newListResult();
}
/**
@@ -59,6 +58,6 @@ public RoleListResult newRoleListResult() {
* @since 1.0.0
*/
public RoleQuery newQuery() {
- return ROLE_FACTORY.newQuery(null);
+ return roleFactory.newQuery(null);
}
}
diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java
index 821896051a9..8400f77b56f 100644
--- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java
+++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java
@@ -24,22 +24,21 @@
@XmlRegistry
public class CertificateInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final CertificateInfoFactory FACTORY = LOCATOR.getFactory(CertificateInfoFactory.class);
+ private final CertificateInfoFactory certificateInfoFactory = KapuaLocator.getInstance().getFactory(CertificateInfoFactory.class);
public CertificateInfo newCertificateInfo() {
- return FACTORY.newEntity(null);
+ return certificateInfoFactory.newEntity(null);
}
public CertificateInfoCreator newCreator() {
- return FACTORY.newCreator(null);
+ return certificateInfoFactory.newCreator(null);
}
public CertificateInfoQuery newQuery() {
- return FACTORY.newQuery(null);
+ return certificateInfoFactory.newQuery(null);
}
public CertificateInfoListResult newListResult() {
- return FACTORY.newListResult();
+ return certificateInfoFactory.newListResult();
}
}
diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java
index db9a39121ca..588be879c8f 100644
--- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java
+++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java
@@ -26,30 +26,29 @@
@XmlRegistry
public class CertificateXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final CertificateFactory FACTORY = LOCATOR.getFactory(CertificateFactory.class);
+ private final CertificateFactory certificateFactory = KapuaLocator.getInstance().getFactory(CertificateFactory.class);
public Certificate newCertificate() {
- return FACTORY.newEntity(null);
+ return certificateFactory.newEntity(null);
}
public CertificateCreator newCreator() {
- return FACTORY.newCreator(null);
+ return certificateFactory.newCreator(null);
}
public CertificateQuery newQuery() {
- return FACTORY.newQuery(null);
+ return certificateFactory.newQuery(null);
}
public CertificateListResult newListResult() {
- return FACTORY.newListResult();
+ return certificateFactory.newListResult();
}
public CertificateGenerator newCertificateGenerator() {
- return FACTORY.newCertificateGenerator();
+ return certificateFactory.newCertificateGenerator();
}
public CertificateUsage newCertificateUsage() {
- return FACTORY.newCertificateUsage(null);
+ return certificateFactory.newCertificateUsage(null);
}
}
diff --git a/service/security/certificate/internal/pom.xml b/service/security/certificate/internal/pom.xml
index 084402a31a8..1416bbaf5cd 100644
--- a/service/security/certificate/internal/pom.xml
+++ b/service/security/certificate/internal/pom.xml
@@ -33,9 +33,5 @@
org.eclipse.kapua
kapua-commons
-
- org.eclipse.kapua
- kapua-security-shiro
-
diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java
index 486bca4b9ee..0980122ac7c 100644
--- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java
+++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java
@@ -14,7 +14,6 @@
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.util.ArgumentValidator;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.model.query.KapuaQuery;
import org.eclipse.kapua.service.certificate.CertificateQuery;
@@ -27,14 +26,19 @@
import org.eclipse.kapua.service.certificate.info.CertificateInfoService;
import org.eclipse.kapua.service.certificate.internal.CertificateQueryImpl;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
@Singleton
public class CertificateInfoServiceImpl implements CertificateInfoService {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final CertificateService CERTIFICATE_SERVICE = LOCATOR.getService(CertificateService.class);
+ private final CertificateService certificateService;
+
+ @Inject
+ public CertificateInfoServiceImpl(CertificateService certificateService) {
+ this.certificateService = certificateService;
+ }
@Override
public CertificateInfo create(CertificateInfoCreator creator) {
@@ -54,7 +58,7 @@ public CertificateInfoListResult query(KapuaQuery query) throws KapuaException {
certificateQuery.setIncludeInherited(((CertificateInfoQuery) query).getIncludeInherited());
CertificateInfoListResult publicCertificates = new CertificateInfoListResultImpl();
- publicCertificates.addItem(CERTIFICATE_SERVICE.query(certificateQuery).getFirstItem());
+ publicCertificates.addItem(certificateService.query(certificateQuery).getFirstItem());
return publicCertificates;
}
@@ -66,7 +70,7 @@ public long count(KapuaQuery query) throws KapuaException {
CertificateQuery privateQuery = new CertificateQueryImpl(query);
privateQuery.setIncludeInherited(((CertificateInfoQuery) query).getIncludeInherited());
- return CERTIFICATE_SERVICE.count(privateQuery);
+ return certificateService.count(privateQuery);
}
@Override
diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateModule.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateModule.java
index 88487e16bd4..d490cede451 100644
--- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateModule.java
+++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateModule.java
@@ -20,12 +20,16 @@
import org.eclipse.kapua.model.domain.DomainEntry;
import org.eclipse.kapua.service.certificate.CertificateFactory;
import org.eclipse.kapua.service.certificate.CertificateService;
+import org.eclipse.kapua.service.certificate.internal.setting.KapuaCertificateSetting;
+
+import javax.inject.Singleton;
public class CertificateModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(CertificateFactory.class).to(CertificateFactoryImpl.class);
- bind(CertificateService.class).to(CertificateServiceImpl.class);
+ bind(CertificateFactory.class).to(CertificateFactoryImpl.class).in(Singleton.class);
+ bind(CertificateService.class).to(CertificateServiceImpl.class).in(Singleton.class);
+ bind(KapuaCertificateSetting.class).in(Singleton.class);
}
@ProvidesIntoSet
diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java
index 918c4d3859c..d898bc207bd 100644
--- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java
+++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java
@@ -20,7 +20,6 @@
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.util.ArgumentValidator;
import org.eclipse.kapua.commons.util.KapuaFileUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.config.metatype.KapuaTocd;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
@@ -44,6 +43,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Collections;
import java.util.List;
@@ -55,27 +55,24 @@ public class CertificateServiceImpl implements CertificateService {
private static final Logger LOG = LoggerFactory.getLogger(CertificateServiceImpl.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class);
- private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class);
-
- private static final CertificateFactory CERTIFICATE_FACTORY = LOCATOR.getFactory(CertificateFactory.class);
-
+ private final AuthorizationService authorizationService;
+ private final PermissionFactory permissionFactory;
+ private final CertificateFactory certificateFactory;
+ private final KapuaCertificateSetting kapuaCertificateSetting;
private String certificate;
private String privateKey;
-
private KapuaTocd emptyTocd;
- /**
- * Constructor
- */
- public CertificateServiceImpl() throws KapuaException {
+ @Inject
+ public CertificateServiceImpl(AuthorizationService authorizationService, PermissionFactory permissionFactory, CertificateFactory certificateFactory,
+ KapuaCertificateSetting kapuaCertificateSetting) throws KapuaException {
+ this.authorizationService = authorizationService;
+ this.permissionFactory = permissionFactory;
+ this.certificateFactory = certificateFactory;
+ this.kapuaCertificateSetting = kapuaCertificateSetting;
KapuaSecurityUtils.doPrivileged(() -> {
- KapuaCertificateSetting setting = KapuaCertificateSetting.getInstance();
-
- String privateKeyPath = setting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY);
- String certificatePath = setting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_CERTIFICATE);
+ String privateKeyPath = kapuaCertificateSetting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY);
+ String certificatePath = kapuaCertificateSetting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_CERTIFICATE);
if (Strings.isNullOrEmpty(privateKeyPath) && Strings.isNullOrEmpty(certificatePath)) {
LOG.error("No private key and certificate path specified.\nPlease set authentication.session.jwt.private.key and authentication.session.jwt.certificate system properties.");
@@ -105,7 +102,7 @@ public CertificateListResult query(KapuaQuery query) throws KapuaException {
// Argument Validation
ArgumentValidator.notNull(query, "query");
// Check Access
- AUTHORIZATION_SERVICE.checkPermission(PERMISSION_FACTORY.newPermission(Domains.CERTIFICATE, Actions.read, query.getScopeId()));
+ authorizationService.checkPermission(permissionFactory.newPermission(Domains.CERTIFICATE, Actions.read, query.getScopeId()));
// Create the default certificate
CertificateUsage jwtCertificateUsage = new CertificateUsageImpl("JWT");
Set certificateUsages = Sets.newHashSet(jwtCertificateUsage);
@@ -115,16 +112,14 @@ public CertificateListResult query(KapuaQuery query) throws KapuaException {
keyUsageSetting.setAllowed(true);
keyUsageSetting.setKapuaAllowed(true);
- KapuaCertificateSetting setting = KapuaCertificateSetting.getInstance();
-
Certificate kapuaCertificate = new CertificateImpl(KapuaId.ONE);
kapuaCertificate.setPrivateKey(privateKey);
kapuaCertificate.setCertificate(certificate);
kapuaCertificate.getKeyUsageSettings().add(keyUsageSetting);
kapuaCertificate.setCertificateUsages(certificateUsages);
- kapuaCertificate.setPassword(setting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY_PASSWORD));
+ kapuaCertificate.setPassword(kapuaCertificateSetting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY_PASSWORD));
- CertificateListResult result = CERTIFICATE_FACTORY.newListResult();
+ CertificateListResult result = certificateFactory.newListResult();
result.addItem(kapuaCertificate);
return result;
diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/setting/KapuaCertificateSetting.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/setting/KapuaCertificateSetting.java
index 31b08695c84..505abccf6a2 100644
--- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/setting/KapuaCertificateSetting.java
+++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/setting/KapuaCertificateSetting.java
@@ -14,31 +14,23 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Authentication setting implementation.
*
* @since 1.0
- *
*/
public class KapuaCertificateSetting extends AbstractKapuaSetting {
private static final String CERTIFICATE_SETTING_PROPERTIES = "kapua-certificate-setting.properties";
- private static final KapuaCertificateSetting INSTANCE = new KapuaCertificateSetting();
-
/**
* Construct a new authentication setting reading settings from {@link KapuaCertificateSetting#CERTIFICATE_SETTING_PROPERTIES}
*/
- private KapuaCertificateSetting() {
+ @Inject
+ public KapuaCertificateSetting() {
super(CERTIFICATE_SETTING_PROPERTIES);
}
-
- /**
- * Return the authentication setting instance (singleton)
- *
- * @return
- */
- public static KapuaCertificateSetting getInstance() {
- return INSTANCE;
- }
}
+
diff --git a/service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/NoopRegistrationProcessor.java b/service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/NoopRegistrationProcessor.java
new file mode 100644
index 00000000000..19ee559195a
--- /dev/null
+++ b/service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/NoopRegistrationProcessor.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Red Hat Inc and others.
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Red Hat Inc - initial API and implementation
+ * Eurotech
+ *******************************************************************************/
+package org.eclipse.kapua.security.registration;
+
+import org.eclipse.kapua.service.user.User;
+import org.jose4j.jwt.consumer.JwtContext;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Optional;
+
+public class NoopRegistrationProcessor implements RegistrationProcessorProvider {
+
+
+ @Override
+ public Collection extends RegistrationProcessor> createAll() {
+ return Collections.singleton(new RegistrationProcessor() {
+ @Override
+ public Optional createUser(JwtContext context) throws Exception {
+ return Optional.empty();
+ }
+
+ @Override
+ public void close() throws Exception {
+
+ }
+ });
+ }
+}
diff --git a/plug-ins/sso/openid-connect/provider-keycloak/src/main/java/org/eclipse/kapua/plugin/sso/openid/provider/keycloak/ProviderImpl.java b/service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/RegistrationModule.java
similarity index 55%
rename from plug-ins/sso/openid-connect/provider-keycloak/src/main/java/org/eclipse/kapua/plugin/sso/openid/provider/keycloak/ProviderImpl.java
rename to service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/RegistrationModule.java
index 444ce37c8e6..41c73acd20c 100644
--- a/plug-ins/sso/openid-connect/provider-keycloak/src/main/java/org/eclipse/kapua/plugin/sso/openid/provider/keycloak/ProviderImpl.java
+++ b/service/security/registration/api/src/main/java/org/eclipse/kapua/security/registration/RegistrationModule.java
@@ -11,20 +11,22 @@
* Red Hat Inc - initial API and implementation
* Eurotech
*******************************************************************************/
-package org.eclipse.kapua.plugin.sso.openid.provider.keycloak;
+package org.eclipse.kapua.security.registration;
-import org.eclipse.kapua.plugin.sso.openid.provider.OpenIDProvider;
+import com.google.inject.multibindings.ProvidesIntoSet;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
-public class ProviderImpl implements OpenIDProvider {
+import javax.inject.Singleton;
+public class RegistrationModule extends AbstractKapuaModule {
@Override
- public String getId() {
- return "keycloak";
- }
+ protected void configureModule() {
- @Override
- public ProviderLocator createLocator() {
- return new KeycloakOpenIDLocator();
}
+ @ProvidesIntoSet
+ @Singleton
+ RegistrationProcessorProvider noopRegistrationProcessor() {
+ return new NoopRegistrationProcessor();
+ }
}
diff --git a/service/security/registration/simple/pom.xml b/service/security/registration/simple/pom.xml
index a3023fcf232..918eb5d1d8c 100644
--- a/service/security/registration/simple/pom.xml
+++ b/service/security/registration/simple/pom.xml
@@ -48,25 +48,16 @@
org.eclipse.kapua
kapua-device-management-api
-
org.eclipse.kapua
kapua-device-registry-internal
+ test
org.eclipse.kapua
kapua-security-registration-api
-
-
-
- org.eclipse.kapua
- kapua-security-shiro
-
-
- org.eclipse.kapua
- kapua-user-internal
diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java
new file mode 100644
index 00000000000..4c86304e3c0
--- /dev/null
+++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Red Hat Inc and others.
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Red Hat Inc - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.security.registration.simple;
+
+import com.google.inject.multibindings.ProvidesIntoSet;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.liquibase.DatabaseCheckUpdate;
+import org.eclipse.kapua.security.registration.RegistrationProcessorProvider;
+import org.eclipse.kapua.security.registration.simple.setting.SimpleSetting;
+import org.eclipse.kapua.service.account.AccountFactory;
+import org.eclipse.kapua.service.account.AccountService;
+import org.eclipse.kapua.service.authentication.credential.CredentialFactory;
+import org.eclipse.kapua.service.authentication.credential.CredentialService;
+import org.eclipse.kapua.service.authorization.access.AccessInfoFactory;
+import org.eclipse.kapua.service.authorization.access.AccessInfoService;
+import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
+import org.eclipse.kapua.service.user.UserFactory;
+import org.eclipse.kapua.service.user.UserService;
+
+import javax.inject.Singleton;
+
+public class SimpleRegistrationModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ bind(SimpleSetting.class).in(Singleton.class);
+ }
+
+ @ProvidesIntoSet
+ @Singleton
+ RegistrationProcessorProvider simpleRegistrationProcessorProvider(
+ SimpleSetting simpleSetting,
+ AccountService accountService,
+ AccountFactory accountFactory,
+ CredentialService credentialService,
+ CredentialFactory credentialFactory,
+ DeviceRegistryService deviceRegistryService,
+ UserService userService,
+ UserFactory userFactory,
+ AccessInfoService accessInfoService,
+ AccessInfoFactory accessInfoFactory,
+ PermissionFactory permissionFactory,
+ //Liquibase must start before this
+ DatabaseCheckUpdate databaseCheckUpdate) {
+ return new SimpleRegistrationProcessorProvider(simpleSetting,
+ accountService,
+ accountFactory,
+ credentialService,
+ credentialFactory,
+ deviceRegistryService,
+ userService,
+ userFactory,
+ accessInfoService,
+ accessInfoFactory,
+ permissionFactory);
+ }
+}
diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java
index e6eacd66e7e..b0d1f6d251b 100644
--- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java
+++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java
@@ -17,7 +17,6 @@
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.security.KapuaSession;
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.security.registration.RegistrationProcessor;
@@ -80,7 +79,7 @@ public static class Settings {
private int maximumNumberOfDevices;
- public Settings(KapuaId rootAccount) {
+ private Settings(KapuaId rootAccount) {
this.rootAccount = rootAccount;
}
@@ -112,11 +111,11 @@ public int getMaximumNumberOfDevices() {
return maximumNumberOfDevices;
}
- public static Optional loadSimpleSettings(AbstractKapuaSetting settings) {
+ public static Optional loadSimpleSettings(UserService userService, AbstractKapuaSetting settings) {
try {
String accountName = settings.getString(SimpleSettingKeys.SIMPLE_ROOT_ACCOUNT);
if (accountName != null && !accountName.isEmpty()) {
- return loadFrom(accountName).map(rootAccount -> applySimpleSettings(rootAccount, settings));
+ return loadFrom(userService, accountName).map(rootAccount -> applySimpleSettings(rootAccount, settings));
}
return Optional.empty();
} catch (KapuaException e) {
@@ -124,8 +123,8 @@ public static Optional loadSimpleSettings(
}
}
- private static Optional loadFrom(String accountName) throws KapuaException {
- User user = KapuaSecurityUtils.doPrivileged(() -> KapuaLocator.getInstance().getService(UserService.class).findByName(accountName));
+ private static Optional loadFrom(UserService userService, String accountName) throws KapuaException {
+ User user = KapuaSecurityUtils.doPrivileged(() -> userService.findByName(accountName));
if (user != null) {
return Optional.of(user).map(User::getScopeId);
@@ -142,21 +141,22 @@ private static SimpleRegistrationProcessor.Settings applySimpleSettings(KapuaId
}
- private final AccountService accountService = KapuaLocator.getInstance().getService(AccountService.class);
- private final AccountFactory accountFactory = KapuaLocator.getInstance().getFactory(AccountFactory.class);
+ private final AccountService accountService;
+ private final AccountFactory accountFactory;
- private final CredentialService credentialService = KapuaLocator.getInstance().getService(CredentialService.class);
- private final CredentialFactory credentialFactory = KapuaLocator.getInstance().getFactory(CredentialFactory.class);
+ private final CredentialService credentialService;
+ private final CredentialFactory credentialFactory;
- private final DeviceRegistryService deviceRegistryService = KapuaLocator.getInstance().getService(DeviceRegistryService.class);
+ private final DeviceRegistryService deviceRegistryService;
- private final UserService userService = KapuaLocator.getInstance().getService(UserService.class);
- private final UserFactory userFactory = KapuaLocator.getInstance().getFactory(UserFactory.class);
+ private final UserService userService;
+ private final UserFactory userFactory;
- private final AccessInfoService accessInfoService = KapuaLocator.getInstance().getService(AccessInfoService.class);
- private final AccessInfoFactory accessInfoFactory = KapuaLocator.getInstance().getFactory(AccessInfoFactory.class);
+ private final AccessInfoService accessInfoService;
+ private final AccessInfoFactory accessInfoFactory;
- private final PermissionFactory permissionFactory = KapuaLocator.getInstance().getFactory(PermissionFactory.class);
+ private final PermissionFactory permissionFactory;
+ private final SimpleSetting simpleSetting;
private final String claimName;
private final Settings settings;
@@ -164,10 +164,45 @@ private static SimpleRegistrationProcessor.Settings applySimpleSettings(KapuaId
/**
* Create a new simple registration processor
*
- * @param claimName the claim to use as account name
- * @param settings the settings for the processor
+ * @param accountService
+ * @param accountFactory
+ * @param credentialService
+ * @param credentialFactory
+ * @param deviceRegistryService
+ * @param userService
+ * @param userFactory
+ * @param accessInfoService
+ * @param accessInfoFactory
+ * @param permissionFactory
+ * @param simpleSetting
+ * @param claimName the claim to use as account name
+ * @param settings the settings for the processor
*/
- public SimpleRegistrationProcessor(String claimName, Settings settings) {
+ public SimpleRegistrationProcessor(
+ AccountService accountService,
+ AccountFactory accountFactory,
+ CredentialService credentialService,
+ CredentialFactory credentialFactory,
+ DeviceRegistryService deviceRegistryService,
+ UserService userService,
+ UserFactory userFactory,
+ AccessInfoService accessInfoService,
+ AccessInfoFactory accessInfoFactory,
+ PermissionFactory permissionFactory,
+ SimpleSetting simpleSetting,
+ String claimName,
+ Settings settings) {
+ this.accountService = accountService;
+ this.accountFactory = accountFactory;
+ this.credentialService = credentialService;
+ this.credentialFactory = credentialFactory;
+ this.deviceRegistryService = deviceRegistryService;
+ this.userService = userService;
+ this.userFactory = userFactory;
+ this.accessInfoService = accessInfoService;
+ this.accessInfoFactory = accessInfoFactory;
+ this.permissionFactory = permissionFactory;
+ this.simpleSetting = simpleSetting;
this.claimName = claimName;
this.settings = settings;
}
@@ -211,7 +246,7 @@ private Optional internalCreateUser(JwtContext context) throws Exception {
accountCreator.setName(name);
accountCreator.setOrganizationEmail(email);
accountCreator.setOrganizationName(name);
- accountCreator.setExpirationDate(Date.from(Instant.now().plus(SimpleSetting.getInstance().getInt(SimpleSettingKeys.ACCOUNT_EXPIRATION_DATE_DAYS, 30), ChronoUnit.DAYS)));
+ accountCreator.setExpirationDate(Date.from(Instant.now().plus(simpleSetting.getInt(SimpleSettingKeys.ACCOUNT_EXPIRATION_DATE_DAYS, 30), ChronoUnit.DAYS)));
// create account
diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java
index 4213cd0332d..26ea71350e6 100644
--- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java
+++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java
@@ -12,23 +12,84 @@
*******************************************************************************/
package org.eclipse.kapua.security.registration.simple;
-import java.util.Collections;
-import java.util.Optional;
-import java.util.Set;
-
import org.eclipse.kapua.security.registration.RegistrationProcessor;
import org.eclipse.kapua.security.registration.RegistrationProcessorProvider;
import org.eclipse.kapua.security.registration.simple.SimpleRegistrationProcessor.Settings;
import org.eclipse.kapua.security.registration.simple.setting.SimpleSetting;
+import org.eclipse.kapua.service.account.AccountFactory;
+import org.eclipse.kapua.service.account.AccountService;
+import org.eclipse.kapua.service.authentication.credential.CredentialFactory;
+import org.eclipse.kapua.service.authentication.credential.CredentialService;
+import org.eclipse.kapua.service.authorization.access.AccessInfoFactory;
+import org.eclipse.kapua.service.authorization.access.AccessInfoService;
+import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
+import org.eclipse.kapua.service.user.UserFactory;
+import org.eclipse.kapua.service.user.UserService;
+
+import javax.inject.Inject;
+import java.util.Collections;
+import java.util.Optional;
+import java.util.Set;
public class SimpleRegistrationProcessorProvider implements RegistrationProcessorProvider {
+ private final SimpleSetting simpleSetting;
+ private final AccountService accountService;
+ private final AccountFactory accountFactory;
+ private final CredentialService credentialService;
+ private final CredentialFactory credentialFactory;
+ private final DeviceRegistryService deviceRegistryService;
+ private final UserService userService;
+ private final UserFactory userFactory;
+ private final AccessInfoService accessInfoService;
+ private final AccessInfoFactory accessInfoFactory;
+ private final PermissionFactory permissionFactory;
+
+ @Inject
+ public SimpleRegistrationProcessorProvider(
+ SimpleSetting simpleSetting,
+ AccountService accountService,
+ AccountFactory accountFactory,
+ CredentialService credentialService,
+ CredentialFactory credentialFactory,
+ DeviceRegistryService deviceRegistryService,
+ UserService userService,
+ UserFactory userFactory,
+ AccessInfoService accessInfoService,
+ AccessInfoFactory accessInfoFactory,
+ PermissionFactory permissionFactory) {
+ this.simpleSetting = simpleSetting;
+ this.accountService = accountService;
+ this.accountFactory = accountFactory;
+ this.credentialService = credentialService;
+ this.credentialFactory = credentialFactory;
+ this.deviceRegistryService = deviceRegistryService;
+ this.userService = userService;
+ this.userFactory = userFactory;
+ this.accessInfoService = accessInfoService;
+ this.accessInfoFactory = accessInfoFactory;
+ this.permissionFactory = permissionFactory;
+ }
+
@Override
public Set extends RegistrationProcessor> createAll() {
- final Optional result = SimpleRegistrationProcessor.Settings.loadSimpleSettings(SimpleSetting.getInstance());
-
+ final Optional result = SimpleRegistrationProcessor.Settings.loadSimpleSettings(userService, simpleSetting);
return result
- .map(settings -> new SimpleRegistrationProcessor("preferred_username", settings))
+ .map(settings -> new SimpleRegistrationProcessor(
+ accountService,
+ accountFactory,
+ credentialService,
+ credentialFactory,
+ deviceRegistryService,
+ userService,
+ userFactory,
+ accessInfoService,
+ accessInfoFactory,
+ permissionFactory,
+ simpleSetting,
+ "preferred_username",
+ settings))
.map(Collections::singleton)
.orElseGet(Collections::emptySet);
}
diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/setting/SimpleSetting.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/setting/SimpleSetting.java
index b79494662cd..9e12f29b0d4 100644
--- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/setting/SimpleSetting.java
+++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/setting/SimpleSetting.java
@@ -22,21 +22,10 @@ public class SimpleSetting extends AbstractKapuaSetting {
private static final String SETTING_RESOURCE = "kapua-security-registration-simple-setting.properties";
- private static final SimpleSetting INSTANCE = new SimpleSetting();
-
/**
* Construct a new setting reading settings from {@link SimpleSetting#SETTING_RESOURCE}
*/
- private SimpleSetting() {
+ public SimpleSetting() {
super(SETTING_RESOURCE);
}
-
- /**
- * Return the setting instance (singleton)
- *
- * @return the settings instance
- */
- public static SimpleSetting getInstance() {
- return INSTANCE;
- }
}
diff --git a/service/security/registration/simple/src/main/resources/META-INF/services/org.eclipse.kapua.security.registration.RegistrationProcessorProvider b/service/security/registration/simple/src/main/resources/META-INF/services/org.eclipse.kapua.security.registration.RegistrationProcessorProvider
deleted file mode 100644
index ead9bf83c0b..00000000000
--- a/service/security/registration/simple/src/main/resources/META-INF/services/org.eclipse.kapua.security.registration.RegistrationProcessorProvider
+++ /dev/null
@@ -1 +0,0 @@
-org.eclipse.kapua.security.registration.simple.SimpleRegistrationProcessorProvider
diff --git a/service/security/shiro/pom.xml b/service/security/shiro/pom.xml
index 61a346f83fc..98ce988a21d 100644
--- a/service/security/shiro/pom.xml
+++ b/service/security/shiro/pom.xml
@@ -66,10 +66,30 @@
org.eclipse.kapua
kapua-security-certificate-api
+
+ org.eclipse.kapua
+ kapua-security-certificate-internal
+ test
+
org.eclipse.kapua
kapua-user-internal
+
+ org.eclipse.kapua
+ kapua-security-registration-simple
+ test
+
+
+ org.eclipse.kapua
+ kapua-tag-internal
+ test
+
+
+ org.eclipse.kapua
+ kapua-device-registry-internal
+ test
+
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CacheMetric.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CacheMetric.java
index dcb689f2322..035100d93fb 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CacheMetric.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CacheMetric.java
@@ -12,16 +12,18 @@
*******************************************************************************/
package org.eclipse.kapua.service.authentication.credential.cache;
+import com.codahale.metrics.Counter;
import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.commons.metric.CommonsMetric;
-import org.eclipse.kapua.commons.metric.MetricServiceFactory;
import org.eclipse.kapua.commons.metric.MetricsLabel;
import org.eclipse.kapua.commons.metric.MetricsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.codahale.metrics.Counter;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+@Singleton
public class CacheMetric {
private static final Logger logger = LoggerFactory.getLogger(CacheMetric.class);
@@ -33,30 +35,18 @@ public class CacheMetric {
private Counter cachePutError;
private Counter passwordEncryptionError;
- private static CacheMetric instance;
-
- public synchronized static CacheMetric getInstance() {
- if (instance == null) {
- try {
- instance = new CacheMetric();
- } catch (KapuaException e) {
- //TODO throw runtime exception
- logger.error("Creating metrics error: {}", e.getMessage(), e);
- }
- }
- return instance;
- }
-
- private CacheMetric() throws KapuaException {
- MetricsService metricsService = MetricServiceFactory.getInstance();
- cacheMiss = metricsService.getCounter(CommonsMetric.module, AUTH_CACHE, "miss");
- cacheHit = metricsService.getCounter(CommonsMetric.module, AUTH_CACHE, "hit");
- cachePutError = metricsService.getCounter(CommonsMetric.module, AUTH_CACHE, "put", MetricsLabel.ERROR);
- passwordEncryptionError = metricsService.getCounter(CommonsMetric.module, AUTH_CACHE, "encryption", MetricsLabel.ERROR);
+ @Inject
+ public CacheMetric(MetricsService metricsService,
+ @Named("metricModuleName")
+ String metricModuleName) throws KapuaException {
+ cacheMiss = metricsService.getCounter(metricModuleName, AUTH_CACHE, "miss");
+ cacheHit = metricsService.getCounter(metricModuleName, AUTH_CACHE, "hit");
+ cachePutError = metricsService.getCounter(metricModuleName, AUTH_CACHE, "put", MetricsLabel.ERROR);
+ passwordEncryptionError = metricsService.getCounter(metricModuleName, AUTH_CACHE, "encryption", MetricsLabel.ERROR);
}
public Counter getCacheHit() {
- return cacheHit;
+ return cacheHit;
}
public Counter getCacheMiss() {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CachedPasswordMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CachedPasswordMatcher.java
index 1c5fc482e39..cb81d587ce1 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CachedPasswordMatcher.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/cache/CachedPasswordMatcher.java
@@ -12,26 +12,6 @@
*******************************************************************************/
package org.eclipse.kapua.service.authentication.credential.cache;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.KeySpec;
-import java.util.Base64;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.GCMParameterSpec;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.SecretKeySpec;
-
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.cache.Cache;
import org.eclipse.kapua.commons.cache.LocalCache;
@@ -44,24 +24,45 @@
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCrypt;
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.KeySpec;
+import java.util.Base64;
+
public class CachedPasswordMatcher implements PasswordMatcher {
protected static final Logger logger = LoggerFactory.getLogger(CachedPasswordMatcher.class);
- private static final Cache CACHED_CREDENTIALS = new LocalCache(
- KapuaAuthenticationSetting.getInstance().getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_CACHE_SIZE, 1000),
- KapuaAuthenticationSetting.getInstance().getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_CACHE_TTL, 60),
- null);
+ private final Cache cachedCredentials;
- //TODO inject!!!
private CacheMetric cacheMetric;
private SecretKey secret;
private byte[] salt;
private byte[] iv;
private int saltIvLength;
- public CachedPasswordMatcher() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, UnsupportedEncodingException, NoSuchPaddingException, InvalidAlgorithmParameterException {
- cacheMetric = CacheMetric.getInstance();
+ @Inject
+ public CachedPasswordMatcher(CacheMetric cacheMetric, KapuaAuthenticationSetting kapuaAuthenticationSetting) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, UnsupportedEncodingException, NoSuchPaddingException, InvalidAlgorithmParameterException {
+ this.cacheMetric = cacheMetric;
+ this.cachedCredentials = new LocalCache(
+ kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_CACHE_SIZE, 1000),
+ kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_CACHE_TTL, 60),
+ null);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] passwordBytes = new byte[64];
random.nextBytes(passwordBytes);
@@ -80,20 +81,19 @@ public CachedPasswordMatcher() throws NoSuchAlgorithmException, InvalidKeyExcept
}
public boolean checkPassword(String tokenUsername, String tokenPassword, Credential infoCredential) {
- CachedCredential cachedCredential = CACHED_CREDENTIALS.get(tokenUsername);
+ CachedCredential cachedCredential = cachedCredentials.get(tokenUsername);
try {
checkFromCache(cachedCredential, infoCredential, tokenPassword);
cacheMetric.getCacheHit().inc();
return true;
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (BCrypt.checkpw(tokenPassword, infoCredential.getCredentialKey())) {
//should be synchronized?
try {
- CACHED_CREDENTIALS.put(tokenUsername, new CachedCredential(
- infoCredential.getModifiedOn(),
- encodeText(tokenPassword.getBytes()),
- infoCredential.getCredentialKey()));
+ cachedCredentials.put(tokenUsername, new CachedCredential(
+ infoCredential.getModifiedOn(),
+ encodeText(tokenPassword.getBytes()),
+ infoCredential.getCredentialKey()));
} catch (KapuaException ke) {
//cannot cache password so no problem, we can return true (since password is matching) and ignore the error
cacheMetric.getCachePutError().inc();
@@ -102,12 +102,12 @@ public boolean checkPassword(String tokenUsername, String tokenPassword, Credent
return true;
}
}
- CACHED_CREDENTIALS.remove(tokenUsername);
+ cachedCredentials.remove(tokenUsername);
return false;
}
private void checkFromCache(CachedCredential cachedCredential, Credential infoCredential, String tokenPassword) throws KapuaException {
- if (cachedCredential==null ||
+ if (cachedCredential == null ||
!cachedCredential.isStillValid(infoCredential.getModifiedOn()) ||
!cachedCredential.isTokenMatches(encodeText(tokenPassword.getBytes()), infoCredential.getCredentialKey())) {
//not the proper exception btw
@@ -121,13 +121,12 @@ private String encodeText(byte[] text) throws KapuaException {
cipher.init(Cipher.ENCRYPT_MODE, secret, new GCMParameterSpec(128, iv));
byte[] cipherText = cipher.doFinal(text);
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(saltIvLength + cipherText.length)
- .put(iv)
- .put(salt)
- .put(cipherText)
- .array();
+ .put(iv)
+ .put(salt)
+ .put(cipherText)
+ .array();
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
- }
- catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) {
+ } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) {
cacheMetric.getPasswordEncryptionError().inc();
throw KapuaException.internalError(e);
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java
index a95644a4b33..c1607604bb4 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java
@@ -93,6 +93,7 @@ public class MfaOptionServiceImpl implements MfaOptionService {
private final AuthorizationService authorizationService;
private final PermissionFactory permissionFactory;
private final UserService userService;
+ private final AuthenticationUtils authenticationUtils;
public MfaOptionServiceImpl(
int trustKeyDuration,
@@ -103,7 +104,8 @@ public MfaOptionServiceImpl(
ScratchCodeFactory scratchCodeFactory,
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
- UserService userService) {
+ UserService userService,
+ AuthenticationUtils authenticationUtils) {
this.trustKeyDuration = trustKeyDuration;
this.mfaAuthenticator = mfaAuthenticator;
this.txManager = txManager;
@@ -114,6 +116,7 @@ public MfaOptionServiceImpl(
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
this.userService = userService;
+ this.authenticationUtils = authenticationUtils;
}
@Override
@@ -204,7 +207,7 @@ public ScratchCodeListResult createAllScratchCodes(ScratchCodeCreator scratchCod
for (String code : codes) {
scratchCodeCreator.setCode(code);
// Crypto code (it's ok to do than if BCrypt is used when checking a provided scratch code against the stored one)
- String encryptedCode = AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, scratchCodeCreator.getCode());
+ String encryptedCode = authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, scratchCodeCreator.getCode());
// Create code
ScratchCodeImpl codeImpl = new ScratchCodeImpl(scratchCodeCreator.getScopeId(), scratchCodeCreator.getMfaOptionId(), encryptedCode);
@@ -315,7 +318,7 @@ private String doEnableTrust(KapuaId scopeId, KapuaId mfaOptionId) throws KapuaE
// This allows the use only of a single trusted machine,
// until a solution with different trust keys is implemented!
final String trustKey = generateTrustKey();
- mfaOption.setTrustKey(AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, trustKey));
+ mfaOption.setTrustKey(authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, trustKey));
Date expirationDate = new Date(System.currentTimeMillis());
expirationDate = DateUtils.addDays(expirationDate, trustKeyDuration);
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java
index 5f7bfb163a9..7560cc7afda 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java
@@ -50,18 +50,21 @@ public class ScratchCodeServiceImpl implements ScratchCodeService {
private final ScratchCodeFactory scratchCodeFactory;
private final AuthorizationService authorizationService;
private final PermissionFactory permissionFactory;
+ private final AuthenticationUtils authenticationUtils;
public ScratchCodeServiceImpl(
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
TxManager txManager,
ScratchCodeRepository scratchCodeRepository,
- ScratchCodeFactory scratchCodeFactory) {
+ ScratchCodeFactory scratchCodeFactory,
+ AuthenticationUtils authenticationUtils) {
this.txManager = txManager;
this.scratchCodeRepository = scratchCodeRepository;
this.scratchCodeFactory = scratchCodeFactory;
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
+ this.authenticationUtils = authenticationUtils;
}
@Override
@@ -79,7 +82,7 @@ public ScratchCode create(ScratchCodeCreator scratchCodeCreator) throws KapuaExc
// Do create
final ScratchCode res = txManager.execute(tx -> {
// Crypto code (it's ok to do than if BCrypt is used when checking a provided scratch code against the stored one)
- String encryptedCode = AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, scratchCodeCreator.getCode());
+ String encryptedCode = authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, scratchCodeCreator.getCode());
// Create code
ScratchCodeImpl codeImpl = new ScratchCodeImpl(scratchCodeCreator.getScopeId(), scratchCodeCreator.getMfaOptionId(), encryptedCode);
return scratchCodeRepository.create(tx, codeImpl);
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialMapperImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialMapperImpl.java
index 1712819828d..111f16f16bc 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialMapperImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialMapperImpl.java
@@ -22,11 +22,17 @@
import org.eclipse.kapua.service.authentication.shiro.utils.CryptAlgorithm;
public class CredentialMapperImpl implements CredentialMapper {
- public CredentialMapperImpl(CredentialFactory credentialFactory) {
+ public CredentialMapperImpl(CredentialFactory credentialFactory,
+ KapuaAuthenticationSetting setting,
+ AuthenticationUtils authenticationUtils) {
this.credentialFactory = credentialFactory;
+ this.setting = setting;
+ this.authenticationUtils = authenticationUtils;
}
private final CredentialFactory credentialFactory;
+ private final KapuaAuthenticationSetting setting;
+ private final AuthenticationUtils authenticationUtils;
@Override
public Credential map(CredentialCreator credentialCreator) throws KapuaException {
@@ -53,17 +59,16 @@ public Credential map(CredentialCreator credentialCreator) throws KapuaException
// Private methods
private String cryptPassword(String credentialPlainKey) throws KapuaException {
- return AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, credentialPlainKey);
+ return authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, credentialPlainKey);
}
private String cryptApiKey(String credentialPlainKey) throws KapuaException {
- KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance();
int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR);
String hashedValue = credentialPlainKey.substring(0, preLength); // Add the pre in clear text
hashedValue += preSeparator; // Add separator
- hashedValue += AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, credentialPlainKey.substring(preLength, credentialPlainKey.length())); // Bcrypt the rest
+ hashedValue += authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, credentialPlainKey.substring(preLength, credentialPlainKey.length())); // Bcrypt the rest
return hashedValue;
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java
index 6301414735a..88024ddcf08 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java
@@ -66,6 +66,7 @@ public class CredentialServiceImpl extends KapuaConfigurableServiceBase implemen
private SecureRandom random;
private final CredentialRepository credentialRepository;
private final CredentialFactory credentialFactory;
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting;
private final CredentialMapper credentialMapper;
private final PasswordValidator passwordValidator;
@@ -77,10 +78,12 @@ public CredentialServiceImpl(
CredentialRepository credentialRepository,
CredentialFactory credentialFactory,
CredentialMapper credentialMapper,
- PasswordValidator passwordValidator) {
+ PasswordValidator passwordValidator,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting) {
super(txManager, serviceConfigurationManager, Domains.CREDENTIAL, authorizationService, permissionFactory);
this.credentialRepository = credentialRepository;
this.credentialFactory = credentialFactory;
+ this.kapuaAuthenticationSetting = kapuaAuthenticationSetting;
try {
random = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
@@ -128,9 +131,8 @@ public Credential create(CredentialCreator credentialCreatorer)
// Do pre persist magic on key values
switch (credentialCreator.getCredentialType()) {
case API_KEY: // Generate new api key
- KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance();
- int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
- int keyLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH);
+ int preLength = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
+ int keyLength = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_KEY_LENGTH);
byte[] bPre = new byte[preLength];
random.nextBytes(bPre);
@@ -262,15 +264,14 @@ public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId)
@Override
public Credential findByApiKey(String apiKey) throws KapuaException {
- KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance();
- int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
+ int preLength = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
// Argument Validation
ArgumentValidator.notEmptyOrNull(apiKey, "apiKey");
ArgumentValidator.lengthRange(apiKey, preLength, null, "apiKey");
// Do the find
Credential credential = txManager.execute(tx -> {
// Build search query
- String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR);
+ String preSeparator = kapuaAuthenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR);
String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator);
// Build query
KapuaQuery query = new CredentialQueryImpl();
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java
index f70bc78cc76..768ecce4e57 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java
@@ -15,7 +15,7 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
+import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.RootUserTester;
import org.eclipse.kapua.commons.configuration.ServiceConfigImplJpaRepository;
@@ -23,12 +23,14 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.core.ServiceModule;
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.event.ServiceEventBusException;
import org.eclipse.kapua.model.config.metatype.KapuaTocd;
import org.eclipse.kapua.model.domain.Actions;
@@ -41,6 +43,7 @@
import org.eclipse.kapua.service.authentication.credential.CredentialFactory;
import org.eclipse.kapua.service.authentication.credential.CredentialRepository;
import org.eclipse.kapua.service.authentication.credential.CredentialService;
+import org.eclipse.kapua.service.authentication.credential.cache.CacheMetric;
import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionFactory;
import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionRepository;
import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService;
@@ -60,6 +63,7 @@
import org.eclipse.kapua.service.authentication.credential.shiro.CredentialServiceImpl;
import org.eclipse.kapua.service.authentication.credential.shiro.PasswordValidator;
import org.eclipse.kapua.service.authentication.credential.shiro.PasswordValidatorImpl;
+import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationErrorCodes;
import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
import org.eclipse.kapua.service.authentication.registration.RegistrationService;
import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
@@ -71,6 +75,8 @@
import org.eclipse.kapua.service.authentication.shiro.registration.RegistrationServiceImpl;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaCryptoSetting;
+import org.eclipse.kapua.service.authentication.shiro.utils.AuthenticationUtils;
import org.eclipse.kapua.service.authentication.token.AccessTokenFactory;
import org.eclipse.kapua.service.authentication.token.AccessTokenRepository;
import org.eclipse.kapua.service.authentication.token.AccessTokenService;
@@ -83,20 +89,37 @@
import org.eclipse.kapua.storage.TxContext;
import javax.inject.Singleton;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
public class AuthenticationModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(AuthenticationService.class).to(AuthenticationServiceShiroImpl.class);
- bind(CredentialFactory.class).to(CredentialFactoryImpl.class);
- bind(CredentialsFactory.class).to(CredentialsFactoryImpl.class);
- bind(MfaOptionFactory.class).to(MfaOptionFactoryImpl.class);
- bind(ScratchCodeFactory.class).to(ScratchCodeFactoryImpl.class);
- bind(AccessTokenFactory.class).to(AccessTokenFactoryImpl.class);
- bind(RegistrationService.class).to(RegistrationServiceImpl.class);
- bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl());
+ bind(KapuaAuthenticationSetting.class).in(Singleton.class);
+ bind(AuthenticationService.class).to(AuthenticationServiceShiroImpl.class).in(Singleton.class);
+ bind(CredentialFactory.class).to(CredentialFactoryImpl.class).in(Singleton.class);
+ bind(CredentialsFactory.class).to(CredentialsFactoryImpl.class).in(Singleton.class);
+ bind(MfaOptionFactory.class).to(MfaOptionFactoryImpl.class).in(Singleton.class);
+ bind(ScratchCodeFactory.class).to(ScratchCodeFactoryImpl.class).in(Singleton.class);
+ bind(AccessTokenFactory.class).to(AccessTokenFactoryImpl.class).in(Singleton.class);
+ bind(RegistrationService.class).to(RegistrationServiceImpl.class).in(Singleton.class);
+ bind(MfaAuthenticator.class).to(MfaAuthenticatorImpl.class).in(Singleton.class);
+ bind(KapuaCryptoSetting.class).in(Singleton.class);
+ bind(CacheMetric.class).in(Singleton.class);
+ }
+
+ @Provides
+ @Singleton
+ AuthenticationUtils authenticationUtils(KapuaCryptoSetting kapuaCryptoSetting) {
+ final SecureRandom random;
+ try {
+ random = SecureRandom.getInstance("SHA1PRNG");
+ } catch (NoSuchAlgorithmException e) {
+ throw new KapuaRuntimeException(KapuaAuthenticationErrorCodes.CREDENTIAL_CRYPT_ERROR, e);
+ }
+ return new AuthenticationUtils(random, kapuaCryptoSetting);
}
@ProvidesIntoSet
@@ -116,12 +139,14 @@ public ServiceModule authenticationServiceModule(AccessTokenService accessTokenS
PermissionFactory permissionFactory,
KapuaJpaTxManagerFactory txManagerFactory,
EventStoreFactory eventStoreFactory,
- EventStoreRecordRepository eventStoreRecordRepository
+ EventStoreRecordRepository eventStoreRecordRepository,
+ ServiceEventBus serviceEventBus,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting
) throws ServiceEventBusException {
return new AuthenticationServiceModule(
credentialService,
accessTokenService,
- KapuaAuthenticationSetting.getInstance(),
+ kapuaAuthenticationSetting,
new ServiceEventHouseKeeperFactoryImpl(
new EventStoreServiceImpl(
authorizationService,
@@ -130,8 +155,10 @@ public ServiceModule authenticationServiceModule(AccessTokenService accessTokenS
eventStoreFactory,
eventStoreRecordRepository
),
- txManagerFactory.create("kapua-authentication")
- ));
+ txManagerFactory.create("kapua-authentication"),
+ serviceEventBus
+ ),
+ serviceEventBus);
}
@ProvidesIntoSet
@@ -163,8 +190,9 @@ PasswordValidator passwordValidator(CredentialServiceConfigurationManager creden
@Provides
@Singleton
- CredentialMapper credentialMapper(CredentialFactory credentialFactory) {
- return new CredentialMapperImpl(credentialFactory);
+ CredentialMapper credentialMapper(CredentialFactory credentialFactory, KapuaAuthenticationSetting kapuaAuthenticationSetting,
+ AuthenticationUtils authenticationUtils) {
+ return new CredentialMapperImpl(credentialFactory, kapuaAuthenticationSetting, authenticationUtils);
}
@Provides
@@ -194,10 +222,10 @@ MfaOptionService mfaOptionService(
AuthorizationService authorizationService,
PermissionFactory permissionFactory,
UserService userService,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
-
- final KapuaAuthenticationSetting authenticationSetting = KapuaAuthenticationSetting.getInstance();
- int trustKeyDuration = authenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_TRUST_KEY_DURATION);
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting,
+ AuthenticationUtils authenticationUtils) {
+ int trustKeyDuration = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_TRUST_KEY_DURATION);
return new MfaOptionServiceImpl(
trustKeyDuration,
@@ -209,7 +237,8 @@ MfaOptionService mfaOptionService(
scratchCodeFactory,
authorizationService,
permissionFactory,
- userService
+ userService,
+ authenticationUtils
);
}
@@ -220,13 +249,15 @@ ScratchCodeService scratchCodeService(
PermissionFactory permissionFactory,
ScratchCodeRepository scratchCodeRepository,
ScratchCodeFactory scratchCodeFactory,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ AuthenticationUtils authenticationUtils) {
return new ScratchCodeServiceImpl(
authorizationService,
permissionFactory,
jpaTxManagerFactory.create("kapua-authentication"),
scratchCodeRepository,
- scratchCodeFactory);
+ scratchCodeFactory,
+ authenticationUtils);
}
@Provides
@@ -257,7 +288,8 @@ public CredentialService credentialService(
CredentialFactory credentialFactory,
KapuaJpaTxManagerFactory jpaTxManagerFactory,
CredentialMapper credentialMapper,
- PasswordValidator passwordValidator) {
+ PasswordValidator passwordValidator,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting) {
return new CredentialServiceImpl(serviceConfigurationManager,
authorizationService,
permissionFactory,
@@ -265,7 +297,8 @@ public CredentialService credentialService(
credentialRepository,
credentialFactory,
credentialMapper,
- passwordValidator);
+ passwordValidator,
+ kapuaAuthenticationSetting);
}
@Provides
@@ -278,13 +311,16 @@ CredentialRepository credentialRepository(KapuaJpaRepositoryConfiguration jpaRep
@Singleton
public CredentialServiceConfigurationManager credentialServiceConfigurationManager(
RootUserTester rootUserTester,
- KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting,
+ EntityCacheFactory entityCacheFactory) {
final CredentialServiceConfigurationManagerImpl credentialServiceConfigurationManager = new CredentialServiceConfigurationManagerImpl(
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
- rootUserTester);
+ rootUserTester,
+ kapuaAuthenticationSetting);
final ServiceConfigurationManagerCachingWrapper cached = new ServiceConfigurationManagerCachingWrapper(credentialServiceConfigurationManager);
return new CredentialServiceConfigurationManager() {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceModule.java
index de0eba97a0c..422e023fd79 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceModule.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceModule.java
@@ -16,6 +16,7 @@
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactory;
import org.eclipse.kapua.commons.event.ServiceEventTransactionalModule;
import org.eclipse.kapua.commons.event.ServiceInspector;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.service.authentication.credential.CredentialService;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys;
@@ -30,7 +31,8 @@ public AuthenticationServiceModule(
CredentialService credentialService,
AccessTokenService accessTokenService,
KapuaAuthenticationSetting authenticationSetting,
- ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory) {
+ ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory,
+ ServiceEventBus serviceEventBus) {
super(Arrays.asList(
ServiceInspector.getEventBusClients(credentialService, CredentialService.class),
ServiceInspector.getEventBusClients(accessTokenService, AccessTokenService.class)
@@ -40,6 +42,7 @@ public AuthenticationServiceModule(
.collect(Collectors.toList())
.toArray(new ServiceEventClientConfiguration[0]),
authenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_EVENT_ADDRESS),
- serviceEventTransactionalHousekeeperFactory);
+ serviceEventTransactionalHousekeeperFactory,
+ serviceEventBus);
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java
index b479537ed74..8f747fb46be 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java
@@ -133,6 +133,7 @@ public class AuthenticationServiceShiroImpl implements AuthenticationService {
private final UserService userService;
private final Set credentialsHandlers;
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting;
@Inject
public AuthenticationServiceShiroImpl(
@@ -150,7 +151,8 @@ public AuthenticationServiceShiroImpl(
AccessPermissionService accessPermissionService,
AccessPermissionFactory accessPermissionFactory,
UserService userService,
- Set credentialsHandlers) {
+ Set credentialsHandlers,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting) {
this.credentialService = credentialService;
this.mfaOptionService = mfaOptionService;
this.accessTokenService = accessTokenService;
@@ -166,6 +168,7 @@ public AuthenticationServiceShiroImpl(
this.accessPermissionFactory = accessPermissionFactory;
this.userService = userService;
this.credentialsHandlers = credentialsHandlers;
+ this.kapuaAuthenticationSetting = kapuaAuthenticationSetting;
}
@Override
@@ -528,9 +531,8 @@ private AccessToken createAccessToken(Session session) throws KapuaException {
*/
private AccessToken createAccessToken(KapuaEid scopeId, KapuaEid userId) throws KapuaException {
// Retrieve TTL access token
- KapuaAuthenticationSetting settings = KapuaAuthenticationSetting.getInstance();
- long tokenTtl = settings.getLong(KapuaAuthenticationSettingKeys.AUTHENTICATION_TOKEN_EXPIRE_AFTER);
- long refreshTokenTtl = settings.getLong(KapuaAuthenticationSettingKeys.AUTHENTICATION_REFRESH_TOKEN_EXPIRE_AFTER);
+ long tokenTtl = kapuaAuthenticationSetting.getLong(KapuaAuthenticationSettingKeys.AUTHENTICATION_TOKEN_EXPIRE_AFTER);
+ long refreshTokenTtl = kapuaAuthenticationSetting.getLong(KapuaAuthenticationSettingKeys.AUTHENTICATION_REFRESH_TOKEN_EXPIRE_AFTER);
// Generate token
Date now = new Date();
@@ -592,13 +594,11 @@ private void establishSession(Subject subject, AccessToken accessToken, String o
}
private String generateJwt(KapuaEid scopeId, KapuaEid userId, Date now, long ttl) {
- KapuaAuthenticationSetting settings = KapuaAuthenticationSetting.getInstance();
-
// Build claims
JwtClaims claims = new JwtClaims();
// Reserved claims
- String issuer = settings.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_SESSION_JWT_ISSUER);
+ String issuer = kapuaAuthenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_SESSION_JWT_ISSUER);
Date issuedAtDate = now; // Issued at claim
Date expiresOnDate = new Date(now.getTime() + ttl); // Expires claim.
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialServiceConfigurationManagerImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialServiceConfigurationManagerImpl.java
index e99385cd6f3..dde53e4edf0 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialServiceConfigurationManagerImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialServiceConfigurationManagerImpl.java
@@ -36,13 +36,16 @@ public class CredentialServiceConfigurationManagerImpl extends ServiceConfigurat
private final int systemMinimumPasswordLength;
public static final int SYSTEM_MAXIMUM_PASSWORD_LENGTH = 255;
public static final String PASSWORD_MIN_LENGTH_ACCOUNT_CONFIG_KEY = "password.minLength";
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting;
public CredentialServiceConfigurationManagerImpl(
ServiceConfigRepository serviceConfigRepository,
- RootUserTester rootUserTester) {
+ RootUserTester rootUserTester,
+ KapuaAuthenticationSetting kapuaAuthenticationSetting) {
super(CredentialService.class.getName(),
serviceConfigRepository,
rootUserTester);
+ this.kapuaAuthenticationSetting = kapuaAuthenticationSetting;
systemMinimumPasswordLength = fixMinimumPasswordLength();
}
@@ -63,7 +66,7 @@ private int fixMinimumPasswordLength() {
//TODO: Why is this logic in a constructor?
int minPasswordLengthConfigValue;
try {
- minPasswordLengthConfigValue = KapuaAuthenticationSetting.getInstance().getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_PASSWORD_MINLENGTH);
+ minPasswordLengthConfigValue = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_PASSWORD_MINLENGTH);
} catch (NoSuchElementException ex) {
LOGGER.warn("Minimum password length not set, 12 characters minimum will be enforced");
minPasswordLengthConfigValue = 12;
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorImpl.java
index e7a41333533..ac226c28b41 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorImpl.java
@@ -25,6 +25,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCrypt;
+import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -38,16 +39,18 @@ public class MfaAuthenticatorImpl implements MfaAuthenticator {
private static final Logger LOG = LoggerFactory.getLogger(MfaAuthenticatorImpl.class);
- private static final KapuaAuthenticationSetting AUTHENTICATION_SETTING = KapuaAuthenticationSetting.getInstance();
- private static final GoogleAuthenticatorConfig GOOGLE_AUTHENTICATOR_CONFIG;
+ private final KapuaAuthenticationSetting authenticationSetting;
+ private final GoogleAuthenticatorConfig googleAuthenticatorConfig;
- static {
+ @Inject
+ public MfaAuthenticatorImpl(KapuaAuthenticationSetting authenticationSetting) {
+ this.authenticationSetting = authenticationSetting;
// Setup of Google Authenticator Configs
- int timeStepSize = AUTHENTICATION_SETTING.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_TIME_STEP_SIZE);
+ int timeStepSize = authenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_TIME_STEP_SIZE);
long timeStepSizeInMillis = TimeUnit.SECONDS.toMillis(timeStepSize);
- int windowSize = AUTHENTICATION_SETTING.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_WINDOW_SIZE);
- int scratchCodeNumber = AUTHENTICATION_SETTING.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_SCRATCH_CODES_NUMBER);
- int codeDigitsNumber = AUTHENTICATION_SETTING.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_CODE_DIGITS_NUMBER);
+ int windowSize = authenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_WINDOW_SIZE);
+ int scratchCodeNumber = authenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_SCRATCH_CODES_NUMBER);
+ int codeDigitsNumber = authenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_MFA_CODE_DIGITS_NUMBER);
try {
ArgumentValidator.notNegative(timeStepSizeInMillis, "timeStepSizeInMillis");
@@ -55,7 +58,7 @@ public class MfaAuthenticatorImpl implements MfaAuthenticator {
ArgumentValidator.numRange(scratchCodeNumber, 0, 1000, "scratchCodeNumber");
ArgumentValidator.numRange(codeDigitsNumber, 6, 8, "codeDigitsNumber");
- GOOGLE_AUTHENTICATOR_CONFIG = new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder()
+ googleAuthenticatorConfig = new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder()
.setTimeStepSizeInMillis(timeStepSizeInMillis) // The time step size, in milliseconds
.setWindowSize(windowSize) // The number of windows of size timeStepSizeInMillis checked during the validation
.setNumberOfScratchCodes(scratchCodeNumber) // Number of scratch codes
@@ -93,7 +96,7 @@ public boolean authorize(String mfaSecretKey, int verificationCode) throws Kapua
ArgumentValidator.notNull(mfaSecretKey, "mfaSecretKey");
ArgumentValidator.notNegative(verificationCode, "verificationCode");
// Do check
- GoogleAuthenticator ga = new GoogleAuthenticator(GOOGLE_AUTHENTICATOR_CONFIG);
+ GoogleAuthenticator ga = new GoogleAuthenticator(googleAuthenticatorConfig);
return ga.authorize(mfaSecretKey, verificationCode);
}
@@ -123,7 +126,7 @@ public String generateKey() {
*/
@Override
public List generateCodes() {
- GoogleAuthenticator gAuth = new GoogleAuthenticator(GOOGLE_AUTHENTICATOR_CONFIG);
+ GoogleAuthenticator gAuth = new GoogleAuthenticator(googleAuthenticatorConfig);
GoogleAuthenticatorKey key = gAuth.createCredentials();
List scratchCodes = new ArrayList<>();
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorServiceLocator.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorServiceLocator.java
index d71005ce3ad..4809a3149f1 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorServiceLocator.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/mfa/MfaAuthenticatorServiceLocator.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.authentication.shiro.mfa;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
/**
@@ -25,7 +26,7 @@ public class MfaAuthenticatorServiceLocator {
private MfaAuthenticatorServiceLocator() {
// for the moment the one implemented in MfaAuthenticatorImpl is the only available authenticator
- mfaAuthenticator = new MfaAuthenticatorImpl();
+ mfaAuthenticator = KapuaLocator.getInstance().getComponent(MfaAuthenticator.class);
}
public static MfaAuthenticatorServiceLocator getInstance() {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java
index 3f0145570b1..56d2a4384a9 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java
@@ -52,11 +52,10 @@ public class AccessTokenAuthenticatingRealm extends KapuaAuthenticatingRealm {
*/
public static final String REALM_NAME = "accessTokenAuthenticatingRealm";
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final AccessTokenService ACCESS_TOKEN_SERVICE = LOCATOR.getService(AccessTokenService.class);
- private static final AccessTokenFactory ACCESS_TOKEN_FACTORY = LOCATOR.getFactory(AccessTokenFactory.class);
- private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class);
+ private final AccessTokenService accessTokenService = KapuaLocator.getInstance().getService(AccessTokenService.class);
+ private final AccessTokenFactory accessTokenFactory = KapuaLocator.getInstance().getFactory(AccessTokenFactory.class);
+ private final UserService userService = KapuaLocator.getInstance().getService(UserService.class);
/**
* Constructor
@@ -81,7 +80,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
// Find accessToken
final AccessToken accessToken;
try {
- AccessTokenQuery accessTokenQuery = ACCESS_TOKEN_FACTORY.newQuery(null);
+ AccessTokenQuery accessTokenQuery = accessTokenFactory.newQuery(null);
AndPredicate andPredicate = accessTokenQuery.andPredicate(
accessTokenQuery.attributePredicate(AccessTokenAttributes.EXPIRES_ON, new java.sql.Timestamp(now.getTime()), Operator.GREATER_THAN_OR_EQUAL),
accessTokenQuery.attributePredicate(AccessTokenAttributes.INVALIDATED_ON, null, Operator.IS_NULL),
@@ -89,7 +88,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
);
accessTokenQuery.setPredicate(andPredicate);
accessTokenQuery.setLimit(1);
- accessToken = KapuaSecurityUtils.doPrivileged(() -> ACCESS_TOKEN_SERVICE.query(accessTokenQuery).getFirstItem());
+ accessToken = KapuaSecurityUtils.doPrivileged(() -> accessTokenService.query(accessTokenQuery).getFirstItem());
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
@@ -109,7 +108,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
// Get the associated user by name
final User user;
try {
- user = KapuaSecurityUtils.doPrivileged(() -> USER_SERVICE.find(accessToken.getScopeId(), accessToken.getUserId()));
+ user = KapuaSecurityUtils.doPrivileged(() -> userService.find(accessToken.getScopeId(), accessToken.getUserId()));
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java
index 0233233f1f6..d1885512060 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java
@@ -46,10 +46,9 @@ public class AccessTokenCredentialsMatcher implements CredentialsMatcher {
private static final Logger LOG = LoggerFactory.getLogger(AccessTokenCredentialsMatcher.class);
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final CertificateInfoService CERTIFICATE_INFO_SERVICE = LOCATOR.getService(CertificateInfoService.class);
- private static final CertificateInfoFactory CERTIFICATE_INFO_FACTORY = LOCATOR.getFactory(CertificateInfoFactory.class);
+ private final CertificateInfoService certificateInfoService = KapuaLocator.getInstance().getService(CertificateInfoService.class);
+ private final CertificateInfoFactory certificateInfoFactory = KapuaLocator.getInstance().getFactory(CertificateInfoFactory.class);
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting = KapuaLocator.getInstance().getComponent(KapuaAuthenticationSetting.class);
@Override
public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
@@ -61,11 +60,10 @@ public boolean doCredentialsMatch(AuthenticationToken authenticationToken, Authe
// Match token with info
boolean credentialMatch = false;
if (jwt.equals(infoCredential.getTokenId())) {
- KapuaAuthenticationSetting settings = KapuaAuthenticationSetting.getInstance();
try {
- String issuer = settings.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_SESSION_JWT_ISSUER);
+ String issuer = kapuaAuthenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_SESSION_JWT_ISSUER);
- CertificateInfoQuery certificateInfoQuery = CERTIFICATE_INFO_FACTORY.newQuery(null);
+ CertificateInfoQuery certificateInfoQuery = certificateInfoFactory.newQuery(null);
certificateInfoQuery.setPredicate(
certificateInfoQuery.andPredicate(
certificateInfoQuery.attributePredicate(CertificateAttributes.USAGE_NAME, "JWT"),
@@ -76,7 +74,7 @@ public boolean doCredentialsMatch(AuthenticationToken authenticationToken, Authe
certificateInfoQuery.setIncludeInherited(true);
certificateInfoQuery.setLimit(1);
- CertificateInfo certificateInfo = KapuaSecurityUtils.doPrivileged(() -> CERTIFICATE_INFO_SERVICE.query(certificateInfoQuery)).getFirstItem();
+ CertificateInfo certificateInfo = KapuaSecurityUtils.doPrivileged(() -> certificateInfoService.query(certificateInfoQuery)).getFirstItem();
if (certificateInfo == null) {
throw new JwtCertificateNotFoundException();
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyAuthenticatingRealm.java
index 1455eadea5f..a374f1c7885 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyAuthenticatingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyAuthenticatingRealm.java
@@ -20,7 +20,6 @@
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.account.Account;
@@ -28,6 +27,7 @@
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialService;
import org.eclipse.kapua.service.authentication.shiro.ApiKeyCredentialsImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.user.User;
import org.eclipse.kapua.service.user.UserService;
import org.slf4j.Logger;
@@ -43,8 +43,10 @@
public class ApiKeyAuthenticatingRealm extends KapuaAuthenticatingRealm {
private static final Logger LOG = LoggerFactory.getLogger(ApiKeyAuthenticatingRealm.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ // Get Services
+ private final UserService userService = KapuaLocator.getInstance().getService(UserService.class);
+ private final CredentialService credentialService = KapuaLocator.getInstance().getService(CredentialService.class);
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting = KapuaLocator.getInstance().getComponent(KapuaAuthenticationSetting.class);
/**
* Realm name.
@@ -59,7 +61,7 @@ public class ApiKeyAuthenticatingRealm extends KapuaAuthenticatingRealm {
public ApiKeyAuthenticatingRealm() {
setName(REALM_NAME);
- CredentialsMatcher credentialsMather = new ApiKeyCredentialsMatcher();
+ CredentialsMatcher credentialsMather = new ApiKeyCredentialsMatcher(kapuaAuthenticationSetting);
setCredentialsMatcher(credentialsMather);
}
@@ -69,16 +71,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
// Extract credentials
ApiKeyCredentialsImpl token = (ApiKeyCredentialsImpl) authenticationToken;
String tokenApiKey = token.getApiKey();
- // Get Services
- UserService userService;
- CredentialService credentialService;
- try {
- userService = LOCATOR.getService(UserService.class);
- credentialService = LOCATOR.getService(CredentialService.class);
- } catch (KapuaRuntimeException kre) {
- throw new ShiroException("Unexpected error while loading KapuaServices!", kre);
- }
// Find credential
Credential credential = null;
try {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcher.java
index a7193086f13..413ba862f26 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcher.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcher.java
@@ -22,12 +22,20 @@
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys;
import org.springframework.security.crypto.bcrypt.BCrypt;
+import javax.inject.Inject;
+
/**
* {@link UsernamePasswordCredentials} credential matcher implementation
*
* @since 1.0
*/
public class ApiKeyCredentialsMatcher implements CredentialsMatcher {
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting;
+
+ @Inject
+ public ApiKeyCredentialsMatcher(KapuaAuthenticationSetting kapuaAuthenticationSetting) {
+ this.kapuaAuthenticationSetting = kapuaAuthenticationSetting;
+ }
@Override
public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
@@ -41,13 +49,11 @@ public boolean doCredentialsMatch(AuthenticationToken authenticationToken, Authe
if (CredentialType.API_KEY.equals(infoCredential.getCredentialType())) {
String fullApiKey = infoCredential.getCredentialKey();
- KapuaAuthenticationSetting setting = KapuaAuthenticationSetting.getInstance();
-
- int preLength = setting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
+ int preLength = kapuaAuthenticationSetting.getInt(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_LENGTH);
String tokenPre = tokenApiFullKey.substring(0, preLength);
String tokenKey = tokenApiFullKey.substring(preLength);
- String preSeparator = setting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR);
+ String preSeparator = kapuaAuthenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_APIKEY_PRE_SEPARATOR);
String infoPre = fullApiKey.split(preSeparator)[0];
String infoHashedKey = fullApiKey.split(preSeparator)[1];
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java
index cfa02e793cc..7429c5e73e6 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java
@@ -22,13 +22,12 @@
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.Destroyable;
import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.plugin.sso.openid.JwtProcessor;
+import org.eclipse.kapua.plugin.sso.openid.OpenIDLocator;
import org.eclipse.kapua.plugin.sso.openid.OpenIDService;
import org.eclipse.kapua.plugin.sso.openid.exception.OpenIDException;
-import org.eclipse.kapua.plugin.sso.openid.provider.ProviderOpenIDLocator;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.authentication.ApiKeyCredentials;
import org.eclipse.kapua.service.authentication.JwtCredentials;
@@ -39,7 +38,6 @@
import org.eclipse.kapua.service.authentication.shiro.JwtCredentialsImpl;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys;
-import org.eclipse.kapua.service.authentication.shiro.utils.JwtProcessors;
import org.eclipse.kapua.service.user.User;
import org.eclipse.kapua.service.user.UserService;
import org.jose4j.jwt.consumer.JwtContext;
@@ -57,20 +55,21 @@ public class JwtAuthenticatingRealm extends KapuaAuthenticatingRealm implements
private static final Logger LOG = LoggerFactory.getLogger(JwtAuthenticatingRealm.class);
- private static final KapuaAuthenticationSetting AUTHENTICATION_SETTING = KapuaAuthenticationSetting.getInstance();
-
- private static final Boolean SSO_USER_EXTERNAL_ID_AUTOFILL = AUTHENTICATION_SETTING.getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_SSO_USER_EXTERNAL_ID_AUTOFILL);
- private static final Boolean SSO_USER_EXTERNAL_USERNAME_AUTOFILL = AUTHENTICATION_SETTING.getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_SSO_USER_EXTERNAL_USERNAME_AUTOFILL);
-
+ private final Boolean ssoUserExternalIdAutofill;
+ private final Boolean ssoUserExternalUsernameAutofill;
+ // Get services
+ private final UserService userService = KapuaLocator.getInstance().getService(UserService.class);
+ private final OpenIDService openIDService = KapuaLocator.getInstance().getComponent(OpenIDLocator.class).getService();
+ private final KapuaAuthenticationSetting authenticationSetting = KapuaLocator.getInstance().getComponent(KapuaAuthenticationSetting.class);
/**
- * Realm name.
+ * JWT Processor.
*/
- public static final String REALM_NAME = "jwtAuthenticatingRealm";
+ private final JwtProcessor jwtProcessor;
/**
- * JWT Processor.
+ * Realm name.
*/
- private JwtProcessor jwtProcessor;
+ public static final String REALM_NAME = "jwtAuthenticatingRealm";
/**
* Constructor.
@@ -79,25 +78,26 @@ public class JwtAuthenticatingRealm extends KapuaAuthenticatingRealm implements
*/
public JwtAuthenticatingRealm() {
setName(REALM_NAME);
+ try {
+ jwtProcessor = KapuaLocator.getInstance().getComponent(OpenIDLocator.class).getProcessor();
+ } catch (OpenIDException se) {
+ throw new ShiroException("Unexpected error while creating Jwt Processor!", se);
+ }
+ ssoUserExternalIdAutofill = authenticationSetting.getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_SSO_USER_EXTERNAL_ID_AUTOFILL);
+ ssoUserExternalUsernameAutofill = authenticationSetting.getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_SSO_USER_EXTERNAL_USERNAME_AUTOFILL);
}
@Override
protected void onInit() {
super.onInit();
- try {
- jwtProcessor = JwtProcessors.createDefault();
- setCredentialsMatcher(new JwtCredentialsMatcher(jwtProcessor));
- } catch (OpenIDException se) {
- throw new ShiroException("Unexpected error while creating Jwt Processor!", se);
- }
+ setCredentialsMatcher(new JwtCredentialsMatcher(jwtProcessor));
}
@Override
public void destroy() throws Exception {
if (jwtProcessor != null) {
jwtProcessor.close();
- jwtProcessor = null;
}
}
@@ -106,15 +106,6 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
// Extract credentials
JwtCredentialsImpl jwtCredentials = (JwtCredentialsImpl) authenticationToken;
String jwtIdToken = jwtCredentials.getIdToken();
- // Get Services
- KapuaLocator locator;
- UserService userService;
- try {
- locator = KapuaLocator.getInstance();
- userService = locator.getService(UserService.class);
- } catch (KapuaRuntimeException kre) {
- throw new ShiroException("Unexpected error while loading KapuaServices!", kre);
- }
// Get the associated user by external id
User user;
try {
@@ -123,7 +114,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
user = KapuaSecurityUtils.doPrivileged(() -> userService.findByExternalId(userExternalId));
// Update User.externalUsername if not populated and if autofill is enabled
- if (SSO_USER_EXTERNAL_USERNAME_AUTOFILL &&
+ if (ssoUserExternalUsernameAutofill &&
user != null &&
Strings.isNullOrEmpty(user.getExternalUsername())) {
@@ -151,7 +142,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
user = KapuaSecurityUtils.doPrivileged(() -> userService.findByExternalUsername(externalUsername));
// Update User.externalId if autofill is enabled
- if (SSO_USER_EXTERNAL_ID_AUTOFILL && user != null) {
+ if (ssoUserExternalIdAutofill && user != null) {
String userExternalId = extractExternalId(jwtIdToken);
user.setExternalId(userExternalId);
user = updateUser(user);
@@ -266,10 +257,6 @@ private String extractExternalUsername(JsonObject userInfo) {
* @since 2.0.0
*/
private User resolveExternalUsernameWithOpenIdProvider(JwtCredentials jwtCredentials) throws KapuaException {
- // Get services
- UserService userService = KapuaLocator.getInstance().getService(UserService.class);
- ProviderOpenIDLocator singleSignOnLocator = new ProviderOpenIDLocator();
- OpenIDService openIDService = singleSignOnLocator.getService();
// Ask to the OpenId Provider the user's info
JsonObject userInfo = openIDService.getUserInfo(jwtCredentials.getAccessToken());
@@ -281,7 +268,7 @@ private User resolveExternalUsernameWithOpenIdProvider(JwtCredentials jwtCredent
user = KapuaSecurityUtils.doPrivileged(() -> userService.findByExternalUsername(externalUsername));
// Update User.externalId if autofill is configured
- if (SSO_USER_EXTERNAL_ID_AUTOFILL && user != null) {
+ if (ssoUserExternalIdAutofill && user != null) {
String userExternalId = extractExternalId(jwtCredentials.getIdToken());
if (!Strings.isNullOrEmpty(userExternalId)) {
@@ -303,7 +290,6 @@ private User resolveExternalUsernameWithOpenIdProvider(JwtCredentials jwtCredent
* @since 2.0.0
*/
private User updateUser(User user) throws KapuaException {
- UserService userService = KapuaLocator.getInstance().getService(UserService.class);
return KapuaSecurityUtils.doPrivileged(() -> userService.update(user));
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/KapuaAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/KapuaAuthenticatingRealm.java
index 66f80c95082..c7695613d02 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/KapuaAuthenticatingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/KapuaAuthenticatingRealm.java
@@ -47,7 +47,9 @@
*/
public abstract class KapuaAuthenticatingRealm extends AuthenticatingRealm {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ protected final AccountService accountService = KapuaLocator.getInstance().getService(AccountService.class);
+ protected final CredentialService credentialService = KapuaLocator.getInstance().getService(CredentialService.class);
+
// Session
/**
@@ -81,8 +83,6 @@ protected void populateSession(@NotNull Subject subject, @NotNull LoginAuthentic
* @since 2.0.0
*/
protected Account checkAccount(KapuaId accountId) {
- AccountService accountService = LOCATOR.getService(AccountService.class);
-
Account account;
try {
account = KapuaSecurityUtils.doPrivileged(() -> accountService.find(accountId));
@@ -167,7 +167,6 @@ protected void checkCredentialLockout(Credential credential, Map
*/
protected Map getCredentialServiceConfig(KapuaId scopeId) {
try {
- CredentialService credentialService = LOCATOR.getService(CredentialService.class);
return KapuaSecurityUtils.doPrivileged(() -> credentialService.getConfigValues(scopeId));
} catch (KapuaException e) {
throw new ShiroException("Unexpected error while looking for the CredentialService!", e);
@@ -211,8 +210,6 @@ protected void increaseLockoutPolicyCount(LoginAuthenticationInfo loginAuthentic
failedCredential.setLockoutReset(resetDate);
}
}
-
- CredentialService credentialService = LOCATOR.getService(CredentialService.class);
credentialService.update(failedCredential);
});
} catch (KapuaException kex) {
@@ -230,7 +227,6 @@ protected void increaseLockoutPolicyCount(LoginAuthenticationInfo loginAuthentic
protected void resetCredentialLockout(Credential credential) {
//TODO find a proper way to update only if needed (obviously database update has a cost)
if (shouldResetCredentialLockout(credential)) {
- CredentialService credentialService = LOCATOR.getService(CredentialService.class);
credential.setFirstLoginFailure(null);
credential.setLoginFailuresReset(null);
credential.setLockoutReset(null);
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassAuthenticatingRealm.java
index a68a5a9758e..00cf445a811 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassAuthenticatingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassAuthenticatingRealm.java
@@ -19,14 +19,12 @@
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
-import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials;
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialListResult;
-import org.eclipse.kapua.service.authentication.credential.CredentialService;
import org.eclipse.kapua.service.authentication.credential.CredentialType;
import org.eclipse.kapua.service.authentication.shiro.UsernamePasswordCredentialsImpl;
import org.eclipse.kapua.service.authentication.shiro.exceptions.MfaRequiredException;
@@ -46,8 +44,8 @@
public class UserPassAuthenticatingRealm extends KapuaAuthenticatingRealm {
private static final Logger LOG = LoggerFactory.getLogger(UserPassAuthenticatingRealm.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ // Get Services
+ private final UserService userService = KapuaLocator.getInstance().getService(UserService.class);
/**
* Realm name.
@@ -72,16 +70,6 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent
// Extract credentials
UsernamePasswordCredentialsImpl token = (UsernamePasswordCredentialsImpl) authenticationToken;
String tokenUsername = token.getUsername();
- // Get Services
- UserService userService;
- CredentialService credentialService;
-
- try {
- userService = LOCATOR.getService(UserService.class);
- credentialService = LOCATOR.getService(CredentialService.class);
- } catch (KapuaRuntimeException kre) {
- throw new ShiroException("Unexpected error while loading KapuaServices!", kre);
- }
// Get the associated user by name
final User user;
try {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java
index 05f30a386a4..4b2037cdde1 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java
@@ -25,6 +25,7 @@
import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials;
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialType;
+import org.eclipse.kapua.service.authentication.credential.cache.CacheMetric;
import org.eclipse.kapua.service.authentication.credential.cache.CachedPasswordMatcher;
import org.eclipse.kapua.service.authentication.credential.cache.DefaultPasswordMatcher;
import org.eclipse.kapua.service.authentication.credential.cache.PasswordMatcher;
@@ -44,6 +45,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCrypt;
+import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
@@ -51,8 +53,6 @@
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
-import javax.crypto.NoSuchPaddingException;
-
/**
* {@link ApiKeyCredentials} {@link CredentialsMatcher} implementation.
*
@@ -68,7 +68,8 @@ public class UserPassCredentialsMatcher implements CredentialsMatcher {
private final MfaAuthenticatorServiceLocator mfaAuthServiceLocator;
private final MfaAuthenticator mfaAuthenticator;
//TODO inject????
- private PasswordMatcher passwordMatcher;
+ private final PasswordMatcher passwordMatcher;
+ private final KapuaAuthenticationSetting kapuaAuthenticationSetting;
public UserPassCredentialsMatcher() {
locator = KapuaLocator.getInstance();
@@ -76,15 +77,15 @@ public UserPassCredentialsMatcher() {
scratchCodeService = locator.getService(ScratchCodeService.class);
mfaAuthServiceLocator = MfaAuthenticatorServiceLocator.getInstance();
mfaAuthenticator = mfaAuthServiceLocator.getMfaAuthenticator();
- if (KapuaAuthenticationSetting.getInstance().getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_ENABLE, true)) {
+ kapuaAuthenticationSetting = locator.getComponent(KapuaAuthenticationSetting.class);
+ if (kapuaAuthenticationSetting.getBoolean(KapuaAuthenticationSettingKeys.AUTHENTICATION_CREDENTIAL_USERPASS_CACHE_ENABLE, true)) {
logger.info("Cache enabled. Initializing CachePasswordChecker...");
try {
- passwordMatcher = new CachedPasswordMatcher();
+ passwordMatcher = new CachedPasswordMatcher(locator.getComponent(CacheMetric.class), locator.getComponent(KapuaAuthenticationSetting.class));
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
throw KapuaRuntimeException.internalError(e, "Cannot instantiate CachedPasswordMatcher");
}
- }
- else {
+ } else {
logger.info("Cache disabled. Initializing NoCachePasswordChecker...");
passwordMatcher = new DefaultPasswordMatcher();
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImpl.java
index 04e74e810e6..e3e9af92f59 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImpl.java
@@ -15,6 +15,7 @@
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.plugin.sso.openid.JwtProcessor;
+import org.eclipse.kapua.plugin.sso.openid.OpenIDLocator;
import org.eclipse.kapua.plugin.sso.openid.exception.OpenIDException;
import org.eclipse.kapua.security.registration.RegistrationProcessor;
import org.eclipse.kapua.security.registration.RegistrationProcessorProvider;
@@ -22,16 +23,15 @@
import org.eclipse.kapua.service.authentication.registration.RegistrationService;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys;
-import org.eclipse.kapua.service.authentication.shiro.utils.JwtProcessors;
import org.eclipse.kapua.service.user.User;
import org.jose4j.jwt.consumer.JwtContext;
+import javax.inject.Inject;
+import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-import java.util.ServiceLoader;
-
-import javax.inject.Singleton;
+import java.util.Set;
@Singleton
public class RegistrationServiceImpl implements RegistrationService, AutoCloseable {
@@ -40,12 +40,14 @@ public class RegistrationServiceImpl implements RegistrationService, AutoCloseab
private final List processors = new ArrayList<>();
- private static final KapuaAuthenticationSetting SETTING = KapuaAuthenticationSetting.getInstance();
+ private final KapuaAuthenticationSetting authenticationSetting;
- public RegistrationServiceImpl() throws OpenIDException {
- jwtProcessor = JwtProcessors.createDefault();
+ @Inject
+ public RegistrationServiceImpl(KapuaAuthenticationSetting authenticationSetting, OpenIDLocator openIDLocator, Set registrationProcessorProvider) throws OpenIDException {
+ this.authenticationSetting = authenticationSetting;
+ jwtProcessor = openIDLocator.getProcessor();
- for (RegistrationProcessorProvider provider : ServiceLoader.load(RegistrationProcessorProvider.class)) {
+ for (RegistrationProcessorProvider provider : registrationProcessorProvider) {
processors.addAll(provider.createAll());
}
}
@@ -65,7 +67,7 @@ public void close() throws Exception {
@Override
public boolean isAccountCreationEnabled() {
- final String registrationServiceEnabled = SETTING.getString(
+ final String registrationServiceEnabled = authenticationSetting.getString(
KapuaAuthenticationSettingKeys.AUTHENTICATION_REGISTRATION_SERVICE_ENABLED, String.valueOf(false));
if (registrationServiceEnabled.equals(String.valueOf(false))) {
return false;
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSetting.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSetting.java
index eeecafee0c8..1287d0d2332 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSetting.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSetting.java
@@ -26,23 +26,10 @@ public class KapuaAuthenticationSetting extends AbstractKapuaSetting {
private static final String CRYPTO_CONFIG_RESOURCE = "kapua-crypto-setting.properties";
- private static final KapuaCryptoSetting INSTANCE = new KapuaCryptoSetting();
-
/**
* Construct a new crypto setting reading settings from {@link KapuaCryptoSetting#CRYPTO_CONFIG_RESOURCE}
*/
- private KapuaCryptoSetting() {
+ @Inject
+ public KapuaCryptoSetting() {
super(CRYPTO_CONFIG_RESOURCE);
}
- /**
- * Return the crypto setting instance (singleton)
- *
- * @return
- */
- public static KapuaCryptoSetting getInstance() {
- return INSTANCE;
- }
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtils.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtils.java
index 9bb24ac7968..4988c179f15 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtils.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtils.java
@@ -45,17 +45,12 @@ public class AuthenticationUtils {
private static final String CIPHER_ALGORITHM = "AES";
//thread safe
//consider using ThreadLocalRandom for performance reason. But it's not immediate to understand which option is the best one.
- private static SecureRandom random;
+ private final SecureRandom random;
+ private final KapuaCryptoSetting kapuaCryptoSetting;
- private AuthenticationUtils() {
- }
-
- static {
- try {
- random = SecureRandom.getInstance("SHA1PRNG");
- } catch (NoSuchAlgorithmException e) {
- throw new KapuaRuntimeException(KapuaAuthenticationErrorCodes.CREDENTIAL_CRYPT_ERROR, e);
- }
+ public AuthenticationUtils(SecureRandom random, KapuaCryptoSetting kapuaCryptoSetting) {
+ this.random = random;
+ this.kapuaCryptoSetting = kapuaCryptoSetting;
}
/**
@@ -65,7 +60,7 @@ private AuthenticationUtils() {
* @return the encrypted credential
* @throws KapuaException when something goes wrong
*/
- public static String cryptCredential(CryptAlgorithm algorithm, String plainValue)
+ public String cryptCredential(CryptAlgorithm algorithm, String plainValue)
throws KapuaException {
// Argument validator
ArgumentValidator.notEmptyOrNull(plainValue, "plainValue");
@@ -85,10 +80,9 @@ public static String cryptCredential(CryptAlgorithm algorithm, String plainValue
return cryptedValue;
}
- public static String doSha(String plainValue) {
- KapuaCryptoSetting settings = KapuaCryptoSetting.getInstance();
- int saltLength = settings.getInt(KapuaCryptoSettingKeys.CRYPTO_SHA_SALT_LENGTH);
- String shaAlgorithm = settings.getString(KapuaCryptoSettingKeys.CRYPTO_SHA_ALGORITHM);
+ public String doSha(String plainValue) {
+ int saltLength = kapuaCryptoSetting.getInt(KapuaCryptoSettingKeys.CRYPTO_SHA_SALT_LENGTH);
+ String shaAlgorithm = kapuaCryptoSetting.getString(KapuaCryptoSettingKeys.CRYPTO_SHA_ALGORITHM);
byte[] bSalt = new byte[saltLength];
random.nextBytes(bSalt);
String salt = Base64.encodeToString(bSalt);
@@ -105,9 +99,8 @@ public static String doSha(String plainValue) {
return salt + ":" + hashedValue;
}
- private static String doBCrypt(String plainValue) {
- KapuaCryptoSetting settings = KapuaCryptoSetting.getInstance();
- int logRound = settings.getInt(KapuaCryptoSettingKeys.CRYPTO_BCRYPT_LOG_ROUNDS);
+ private String doBCrypt(String plainValue) {
+ int logRound = kapuaCryptoSetting.getInt(KapuaCryptoSettingKeys.CRYPTO_BCRYPT_LOG_ROUNDS);
String salt = BCrypt.gensalt(logRound, random);
return BCrypt.hashpw(plainValue, salt);
}
@@ -120,7 +113,7 @@ private static String doBCrypt(String plainValue) {
* @deprecated Since 2.0.0. Please make use of {@link CryptoUtil#encryptAes(String)}.
*/
@Deprecated
- public static String encryptAes(String value) {
+ public String encryptAes(String value) {
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(CIPHER_ALGORITHM);
@@ -142,7 +135,7 @@ public static String encryptAes(String value) {
* @deprecated Since 2.0.0. Please make use of {@link CryptoUtil#decryptAes(String)}.
*/
@Deprecated
- public static String decryptAes(String encryptedValue) {
+ public String decryptAes(String encryptedValue) {
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(CIPHER_ALGORITHM);
@@ -164,12 +157,9 @@ public static String decryptAes(String encryptedValue) {
* @deprecated Since 2.0.0. Please make use of {@link CryptoUtil}
*/
@Deprecated
- private static Key generateKey() {
-
+ private Key generateKey() {
// Retrieve Cipher Settings
- KapuaCryptoSetting settings = KapuaCryptoSetting.getInstance();
- byte[] cipherSecretKey = settings.getString(KapuaCryptoSettingKeys.CIPHER_KEY).getBytes();
-
+ byte[] cipherSecretKey = kapuaCryptoSetting.getString(KapuaCryptoSettingKeys.CIPHER_KEY).getBytes();
return new SecretKeySpec(cipherSecretKey, CIPHER_ALGORITHM);
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessors.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessors.java
deleted file mode 100644
index 23435b8b7b8..00000000000
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessors.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017, 2022 Red Hat Inc and others.
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat Inc - initial API and implementation
- * Eurotech
- *******************************************************************************/
-package org.eclipse.kapua.service.authentication.shiro.utils;
-
-import org.eclipse.kapua.plugin.sso.openid.JwtProcessor;
-import org.eclipse.kapua.plugin.sso.openid.exception.OpenIDException;
-import org.eclipse.kapua.plugin.sso.openid.provider.ProviderOpenIDLocator;
-
-public final class JwtProcessors {
-
- private JwtProcessors() {
- }
-
- public static JwtProcessor createDefault() throws OpenIDException {
- ProviderOpenIDLocator singleSignOnLocator = new ProviderOpenIDLocator();
- return singleSignOnLocator.getProcessor();
- }
-}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCache.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCache.java
index 5c6bb19bbeb..717e4ca251a 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCache.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCache.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.service.authorization.access.shiro;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
import org.eclipse.kapua.commons.service.internal.cache.EntityCache;
import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
import org.eclipse.kapua.model.KapuaEntity;
@@ -31,9 +32,9 @@ public class AccessInfoCache extends EntityCache {
protected Cache accessInfoByUserIdCache;
- public AccessInfoCache(String idCacheName, String nameCacheName) {
- super(idCacheName);
- accessInfoByUserIdCache = KapuaCacheManager.getCache(nameCacheName);
+ public AccessInfoCache(KapuaCacheManager cacheManager, CommonsMetric commonsMetric, String idCacheName, String nameCacheName) {
+ super(cacheManager, commonsMetric, idCacheName);
+ accessInfoByUserIdCache = cacheManager.getCache(nameCacheName);
}
public KapuaEntity getByUserId(KapuaId scopeId, KapuaId userId) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactory.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactory.java
index 589062fa055..618bbdc279c 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactory.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactory.java
@@ -12,27 +12,28 @@
*******************************************************************************/
package org.eclipse.kapua.service.authorization.access.shiro;
-import org.eclipse.kapua.commons.jpa.AbstractEntityCacheFactory;
-import org.eclipse.kapua.commons.service.internal.cache.EntityCache;
+import com.google.inject.Inject;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
/**
* Cache factory for the {@link AccessInfoImpl}
*/
-public class AccessInfoCacheFactory extends AbstractEntityCacheFactory {
+public class AccessInfoCacheFactory {
+ protected final KapuaCacheManager cacheManager;
+ protected final CommonsMetric commonsMetric;
- public AccessInfoCacheFactory() {
- super("AccessInfoId");
+ @Inject
+ public AccessInfoCacheFactory(KapuaCacheManager cacheManager, CommonsMetric commonsMetric) {
+ this.cacheManager = cacheManager;
+ this.commonsMetric = commonsMetric;
}
+
/**
* @return an {@link AccessInfoCache}
*/
- @Override
- public EntityCache createCache() {
- return new AccessInfoCache(getEntityIdCacheName(), "AccessInfoUserIdId");
- }
-
- protected static AccessInfoCacheFactory getInstance() {
- return new AccessInfoCacheFactory();
+ public AccessInfoCache createCache() {
+ return new AccessInfoCache(cacheManager, commonsMetric, "AccessInfoId", "AccessInfoUserIdId");
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java
index 6d31a733626..cd226537484 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java
@@ -67,6 +67,7 @@ public class AccessInfoServiceImpl implements AccessInfoService {
private final AccessInfoFactory accessInfoFactory;
private final AccessPermissionRepository accessPermissionRepository;
private final AccessPermissionFactory accessPermissionFactory;
+ private final PermissionValidator permissionValidator;
public AccessInfoServiceImpl(AuthorizationService authorizationService,
PermissionFactory permissionFactory,
@@ -77,7 +78,8 @@ public AccessInfoServiceImpl(AuthorizationService authorizationService,
AccessInfoRepository accessInfoRepository,
AccessInfoFactory accessInfoFactory,
AccessPermissionRepository accessPermissionRepository,
- AccessPermissionFactory accessPermissionFactory) {
+ AccessPermissionFactory accessPermissionFactory,
+ PermissionValidator permissionValidator) {
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
this.txManager = txManager;
@@ -88,6 +90,7 @@ public AccessInfoServiceImpl(AuthorizationService authorizationService,
this.accessInfoFactory = accessInfoFactory;
this.accessPermissionRepository = accessPermissionRepository;
this.accessPermissionFactory = accessPermissionFactory;
+ this.permissionValidator = permissionValidator;
}
@Override
@@ -105,7 +108,7 @@ public AccessInfo create(AccessInfoCreator accessInfoCreator)
}
}
- PermissionValidator.validatePermissions(accessInfoCreator.getPermissions());
+ permissionValidator.validatePermissions(accessInfoCreator.getPermissions());
return txManager.execute(tx -> {
if (accessInfoCreator.getRoleIds() != null) {
for (KapuaId roleId : accessInfoCreator.getRoleIds()) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactory.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactory.java
deleted file mode 100644
index f351618c81b..00000000000
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactory.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authorization.access.shiro;
-
-import org.eclipse.kapua.commons.jpa.AbstractEntityCacheFactory;
-
-/**
- * Cache factory for the {@link AccessPermissionServiceImpl}
- */
-public class AccessPermissionCacheFactory extends AbstractEntityCacheFactory {
-
- public AccessPermissionCacheFactory() {
- super("AccessPermissionId");
- }
-
- protected static AccessPermissionCacheFactory getInstance() {
- return new AccessPermissionCacheFactory();
- }
-}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java
index aac630f606e..95831541558 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java
@@ -56,6 +56,7 @@ public class AccessPermissionServiceImpl implements AccessPermissionService {
private final TxManager txManager;
private final AccessPermissionRepository accessPermissionRepository;
private final AccessInfoRepository accessInfoRepository;
+ private final PermissionValidator permissionValidator;
@Inject
public AccessPermissionServiceImpl(
@@ -63,12 +64,14 @@ public AccessPermissionServiceImpl(
PermissionFactory permissionFactory,
TxManager txManager,
AccessPermissionRepository accessPermissionRepository,
- AccessInfoRepository accessInfoRepository) {
+ AccessInfoRepository accessInfoRepository,
+ PermissionValidator permissionValidator) {
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
this.txManager = txManager;
this.accessPermissionRepository = accessPermissionRepository;
this.accessInfoRepository = accessInfoRepository;
+ this.permissionValidator = permissionValidator;
}
@Override
@@ -86,7 +89,7 @@ public AccessPermission create(AccessPermissionCreator accessPermissionCreator)
authorizationService.checkPermission(permission);
}
- PermissionValidator.validatePermission(permission);
+ permissionValidator.validatePermission(permission);
return txManager.execute(tx -> {
// Check duplicates
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/GroupQueryHelperImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/GroupQueryHelperImpl.java
index 762ced23020..7fc6f02b2fb 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/GroupQueryHelperImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/GroupQueryHelperImpl.java
@@ -115,7 +115,7 @@ private void handleKapuaQueryGroupPredicate(TxContext txContext, KapuaSession ka
Role role = roleRepository.find(txContext, ar.getScopeId(), roleId)
.orElseThrow(() -> new KapuaEntityNotFoundException(Role.TYPE, roleId));
- RolePermissionListResult rolePermissions = rolePermissionRepository.findByRoleId(txContext, role.getScopeId(), role.getId());
+ RolePermissionListResult rolePermissions = rolePermissionRepository.findByRoleId(txContext, role.getScopeId(), roleId);
for (RolePermission rp : rolePermissions.getItems()) {
if (checkGroupPermission(domain, groupPermissions, rp.getPermission())) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java
index df6026f8f04..2749ba47981 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java
@@ -12,26 +12,9 @@
*******************************************************************************/
package org.eclipse.kapua.service.authorization.permission.shiro;
-import org.apache.shiro.authz.UnauthorizedException;
-import org.apache.shiro.authz.permission.WildcardPermission;
-import org.apache.shiro.subject.Subject;
-import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.model.id.KapuaEid;
-import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.model.KapuaEntity;
-import org.eclipse.kapua.model.KapuaEntityCreator;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.id.KapuaId;
-import org.eclipse.kapua.model.query.KapuaQuery;
-import org.eclipse.kapua.service.KapuaEntityService;
-import org.eclipse.kapua.service.account.Account;
-import org.eclipse.kapua.service.account.AccountService;
-import org.eclipse.kapua.service.authorization.AuthorizationService;
-import org.eclipse.kapua.service.authorization.domain.Domain;
-import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
-import org.eclipse.kapua.service.authorization.group.Group;
import org.eclipse.kapua.service.authorization.permission.Permission;
import javax.persistence.AttributeOverride;
@@ -50,15 +33,23 @@
* @since 1.0.0
*/
@Embeddable
-public class PermissionImpl extends WildcardPermission implements Permission, org.apache.shiro.authz.Permission, Serializable {
+public class PermissionImpl
+// extends
+// WildcardPermission
+ implements
+ Permission
+// , org.apache.shiro.authz.Permission
+ , Serializable {
- private static final long serialVersionUID = 1480557438886065675L;
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DomainRegistryService DOMAIN_SERVICE = LOCATOR.getService(DomainRegistryService.class);
+ private static final long serialVersionUID = 1480557438886065675L;
+//
+// //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class!
+// @Transient
+// private final AccountService accountService = KapuaLocator.getInstance().getService(AccountService.class);
+// //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class!
+// @Transient
+// private final DomainRegistryService domainService = KapuaLocator.getInstance().getService(DomainRegistryService.class);
@Basic
@Column(name = "domain", nullable = true, updatable = false)
@@ -138,7 +129,6 @@ public PermissionImpl(String domain, Actions action, KapuaId targetScopeId, Kapu
setGroupId(groupId);
setForwardable(forwardable);
- setParts(toString());
}
@Override
@@ -191,128 +181,6 @@ public void setForwardable(boolean forwardable) {
this.forwardable = forwardable;
}
- /**
- * This method needs to be overridden to support Access {@link Group} feature.
- *
- * {@link KapuaEntityService}s that access a specific {@link KapuaEntity} (i.e. {@link KapuaEntityService#create(KapuaEntityCreator)}, {@link KapuaEntityService#delete(KapuaId, KapuaId)})
- * can make the control taking in consideration of the {@link Group#getId()} parameter as it is known.
- *
- * Instead, methods that access multiple {@link KapuaEntity}s (i.e. {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)})
- * cannot make a direct control of the {@link Group#getId()} parameter as it is not known and they can be a lot.
- * The access control then, is performed by hiding the data that a {@link Subject} cannot see instead of throwing {@link UnauthorizedException}.
- *
- *
- * The access control for {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)}) must specify that {@link Group#ANY} group assigned to the permission is
- * enough to pass the {@link AuthorizationService#checkPermission(Permission)}.
- *
- *
- * In case of the {@link Permission#getForwardable()} equals to {@code true}, more lookup is required.
- * If a parent account access the resources of one of its child accounts it won't have the direct permission to access it.
- * A lookup of {@link Account#getParentAccountPath()} will be required to search if the current user scope id is
- * one of the parent of the given {@link Permission#getTargetScopeId()}
- *
- *
- * @since 1.0.0
- */
- @Override
- public boolean implies(org.apache.shiro.authz.Permission shiroPermission) {
-
- Permission targetPermission = (Permission) shiroPermission;
-
- // Check target Permission domain
- checkTargetPermissionIsGroupable(targetPermission);
-
- // If checked Permission ask for ANY targetScopeId, promote this Permission.targetScopeId to `null` (a.k.a. ALL scopes).
- if (KapuaId.ANY.equals(targetPermission.getTargetScopeId())) {
- this.setTargetScopeId(null);
- }
-
- // If checked Permission ask for ANY groupId, promote this Permission.groupId to `null` (a.k.a. ALL groups).
- if (Group.ANY.equals(targetPermission.getGroupId())) {
- this.setGroupId(null);
- }
-
- // Set part of the Shiro Permission to then run 'implies' with the target Permission
- this.setParts(this.toString());
-
- boolean implies = super.implies(shiroPermission);
-
- // If it fails try forward permission if this Permission is forwardable
- if (!implies && targetPermission.getTargetScopeId() != null && this.getForwardable()) {
- implies = forwardPermission(shiroPermission);
- }
-
- // Return result
- return implies;
- }
-
- /**
- * Checks whether the given {@link Permission#getDomain()} is {@link Domain#getGroupable()}.
- *
- * If it is, promotes this {@link Permission#getGroupId()} to {@code null} (a.k.a. ALL groups).
- *
- * @param targetPermission The target {@link Permission} to check.
- * @since 2.0.0
- */
- private void checkTargetPermissionIsGroupable(Permission targetPermission) {
- if (targetPermission.getDomain() != null) {
- try {
- Domain domainDefinition = KapuaSecurityUtils.doPrivileged(() -> DOMAIN_SERVICE.findByName(targetPermission.getDomain()));
-
- if (!domainDefinition.getGroupable()) {
- this.setGroupId(null);
- }
- } catch (Exception e) {
- throw KapuaRuntimeException.internalError(e, "Error while resolving target Permission.domain: " + targetPermission.getDomain());
- }
- }
- }
-
- /**
- * Checks {@code this} Permission against the given {@link Permission} parameter.
- *
- * It tries to forward {@code this} Permission to the {@link #getTargetScopeId()} of the given {@link org.apache.shiro.authz.Permission} parameter.
- * This means that if the required permission has scope id 'B' and {@code this} {@link Permission} has scope id 'A',
- * this methods search the {@link Account#getParentAccountPath()} of the scope id 'B' and checks the {@link Permission} forwarding {@code this} Permission
- * to the same level of the given {@link org.apache.shiro.authz.Permission}.
- *
- *
- *
Example:
- * User 'A' in account 'A' has scopeId 'A' and this permission (A) "*:*:A:*".
- * Account 'A' has a child account 'B', then 'B' has this parent account path: '/A/B';
- * User 'A' tries to access a resource of account 'B' an the direct check {@link org.apache.shiro.authz.Permission#implies(org.apache.shiro.authz.Permission)} fails.
- * So this method searches the parent account path of account 'B', found that 'A' is a parent of 'B'
- * so then {@code this} {@link Permission} is checked again with 'B' as scopeId.
- *
- *
- * @param shiroPermission The permission to check against.
- * @return {@code true} if this permission is forward-able and is valid when forwarded, {@code false otherwise}
- * @since 1.0.0
- */
- private boolean forwardPermission(org.apache.shiro.authz.Permission shiroPermission) {
- Permission targetPermission = (Permission) shiroPermission;
-
- try {
- Account account = KapuaSecurityUtils.doPrivileged(() -> ACCOUNT_SERVICE.find(targetPermission.getTargetScopeId()));
-
- if (account != null && account.getScopeId() != null) {
- String parentAccountPath = account.getParentAccountPath();
-
- // If it doesn't contain the scope id in the parent, don't even try to check against
- if (parentAccountPath.contains("/" + getTargetScopeId().toStringId() + "/")) {
- this.setTargetScopeId(targetPermission.getTargetScopeId());
- this.setParts(this.toString());
-
- return super.implies(shiroPermission);
- }
- }
- } catch (KapuaException e) {
- throw KapuaRuntimeException.internalError(e, "Error while forwarding target Permission: " + shiroPermission);
- }
-
- return false;
- }
-
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java
index 865ce646e58..8bf3d742c02 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java
@@ -15,7 +15,6 @@
import com.google.common.collect.Sets;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.KapuaIllegalArgumentException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.authorization.domain.Domain;
import org.eclipse.kapua.service.authorization.domain.DomainFactory;
import org.eclipse.kapua.service.authorization.domain.DomainListResult;
@@ -23,26 +22,28 @@
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionAttributes;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.Set;
public class PermissionValidator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final DomainRegistryService DOMAIN_SERVICE = LOCATOR.getService(DomainRegistryService.class);
- private static final DomainFactory DOMAIN_FACTORY = LOCATOR.getFactory(DomainFactory.class);
+ private final DomainRegistryService domainService;
+ private final DomainFactory domainFactory;
- private PermissionValidator() {
+ @Inject
+ public PermissionValidator(DomainRegistryService domainService, DomainFactory domainFactory) {
+ this.domainService = domainService;
+ this.domainFactory = domainFactory;
}
- public static void validatePermission(@NotNull Permission permission) throws KapuaException {
+ public void validatePermission(@NotNull Permission permission) throws KapuaException {
validatePermissions(Sets.newHashSet(permission));
}
- public static void validatePermissions(@NotNull Set permissions) throws KapuaException {
-
+ public void validatePermissions(@NotNull Set permissions) throws KapuaException {
if (!permissions.isEmpty()) {
- DomainListResult domains = DOMAIN_SERVICE.query(DOMAIN_FACTORY.newQuery(null));
+ DomainListResult domains = domainService.query(domainFactory.newQuery(null));
for (Permission p : permissions) {
if (p.getDomain() != null) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java
index 7d15b4a7165..d1a5e863dcd 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java
@@ -56,16 +56,19 @@ public class RolePermissionServiceImpl implements RolePermissionService {
private final TxManager txManager;
private final RoleRepository roleRepository;
private final RolePermissionRepository rolePermissionRepository;
+ private final PermissionValidator permissionValidator;
public RolePermissionServiceImpl(
AuthorizationService authorizationService, PermissionFactory permissionFactory, TxManager txManager,
RoleRepository roleRepository,
- RolePermissionRepository rolePermissionRepository) {
+ RolePermissionRepository rolePermissionRepository,
+ PermissionValidator permissionValidator) {
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
this.txManager = txManager;
this.roleRepository = roleRepository;
this.rolePermissionRepository = rolePermissionRepository;
+ this.permissionValidator = permissionValidator;
}
@Override
@@ -82,7 +85,7 @@ public RolePermission create(RolePermissionCreator rolePermissionCreator)
final Role role = roleRepository.find(tx, rolePermissionCreator.getScopeId(), rolePermissionCreator.getRoleId())
.orElseThrow(() -> new KapuaEntityNotFoundException(Role.TYPE, rolePermissionCreator.getRoleId()));
// Check that the given permission matches the definition of the Domains.
- PermissionValidator.validatePermission(rolePermissionCreator.getPermission());
+ permissionValidator.validatePermission(rolePermissionCreator.getPermission());
// If permission are created out of the role permission scope, check that the current user has the permission on the external scopeId.
Permission permission = rolePermissionCreator.getPermission();
if (permission.getTargetScopeId() == null || !permission.getTargetScopeId().equals(rolePermissionCreator.getScopeId())) {
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java
index b78941c0562..0262786c4c4 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java
@@ -58,6 +58,7 @@ public class RoleServiceImpl extends KapuaConfigurableServiceBase implements Rol
private final RolePermissionFactory rolePermissionFactory;
private final RoleRepository roleRepository;
private final RolePermissionRepository rolePermissionRepository;
+ private final PermissionValidator permissionValidator;
/**
* Injectable constructor
@@ -78,11 +79,13 @@ public RoleServiceImpl(
ServiceConfigurationManager serviceConfigurationManager,
TxManager txManager,
RoleRepository roleRepository,
- RolePermissionRepository rolePermissionRepository) {
+ RolePermissionRepository rolePermissionRepository,
+ PermissionValidator permissionValidator) {
super(txManager, serviceConfigurationManager, Domains.ROLE, authorizationService, permissionFactory);
this.rolePermissionFactory = rolePermissionFactory;
this.roleRepository = roleRepository;
this.rolePermissionRepository = rolePermissionRepository;
+ this.permissionValidator = permissionValidator;
}
@Override
@@ -114,7 +117,7 @@ public Role create(RoleCreator roleCreator) throws KapuaException {
}
// Check that the given permission matches the definition of the Domains.
- PermissionValidator.validatePermissions(roleCreator.getPermissions());
+ permissionValidator.validatePermissions(roleCreator.getPermissions());
// Do create
Role newRole = new RoleImpl(roleCreator.getScopeId());
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java
index 820c468f611..d2722b3a615 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.ResourceLimitedServiceConfigurationManagerImpl;
@@ -26,14 +25,18 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.core.ServiceModule;
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.jpa.NamedCacheFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.populators.DataPopulator;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl;
-import org.eclipse.kapua.commons.service.internal.cache.NamedEntityCache;
+import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.event.ServiceEventBusException;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.domain.Domain;
@@ -49,17 +52,14 @@
import org.eclipse.kapua.service.authorization.access.AccessRoleRepository;
import org.eclipse.kapua.service.authorization.access.AccessRoleService;
import org.eclipse.kapua.service.authorization.access.GroupQueryHelper;
-import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoCache;
import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoCacheFactory;
import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoCachingRepository;
import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoFactoryImpl;
import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoImplJpaRepository;
import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoServiceImpl;
-import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionCacheFactory;
import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionFactoryImpl;
import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionImplJpaRepository;
import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionServiceImpl;
-import org.eclipse.kapua.service.authorization.access.shiro.AccessRoleCacheFactory;
import org.eclipse.kapua.service.authorization.access.shiro.AccessRoleFactoryImpl;
import org.eclipse.kapua.service.authorization.access.shiro.AccessRoleImplJpaRepository;
import org.eclipse.kapua.service.authorization.access.shiro.AccessRoleServiceImpl;
@@ -81,17 +81,16 @@
import org.eclipse.kapua.service.authorization.group.shiro.GroupServiceImpl;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.authorization.permission.shiro.PermissionFactoryImpl;
+import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator;
import org.eclipse.kapua.service.authorization.role.RoleFactory;
import org.eclipse.kapua.service.authorization.role.RolePermissionFactory;
import org.eclipse.kapua.service.authorization.role.RolePermissionRepository;
import org.eclipse.kapua.service.authorization.role.RolePermissionService;
import org.eclipse.kapua.service.authorization.role.RoleRepository;
import org.eclipse.kapua.service.authorization.role.RoleService;
-import org.eclipse.kapua.service.authorization.role.shiro.RoleCacheFactory;
import org.eclipse.kapua.service.authorization.role.shiro.RoleCachingRepository;
import org.eclipse.kapua.service.authorization.role.shiro.RoleFactoryImpl;
import org.eclipse.kapua.service.authorization.role.shiro.RoleImplJpaRepository;
-import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionCacheFactory;
import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionCachingRepository;
import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionFactoryImpl;
import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionImplJpaRepository;
@@ -106,20 +105,23 @@
public class AuthorizationModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(AuthorizationService.class).to(AuthorizationServiceImpl.class);
- bind(RoleFactory.class).to(RoleFactoryImpl.class);
+ bind(AuthorizationService.class).to(AuthorizationServiceImpl.class).in(Singleton.class);
+ bind(RoleFactory.class).to(RoleFactoryImpl.class).in(Singleton.class);
- bind(DomainFactory.class).to(DomainFactoryImpl.class);
+ bind(DomainFactory.class).to(DomainFactoryImpl.class).in(Singleton.class);
- bind(PermissionFactory.class).to(PermissionFactoryImpl.class);
+ bind(PermissionFactory.class).to(PermissionFactoryImpl.class).in(Singleton.class);
- bind(AccessInfoFactory.class).to(AccessInfoFactoryImpl.class);
- bind(AccessPermissionFactory.class).to(AccessPermissionFactoryImpl.class);
- bind(AccessRoleFactory.class).to(AccessRoleFactoryImpl.class);
+ bind(AccessInfoFactory.class).to(AccessInfoFactoryImpl.class).in(Singleton.class);
+ bind(AccessPermissionFactory.class).to(AccessPermissionFactoryImpl.class).in(Singleton.class);
+ bind(AccessRoleFactory.class).to(AccessRoleFactoryImpl.class).in(Singleton.class);
- bind(RolePermissionFactory.class).to(RolePermissionFactoryImpl.class);
+ bind(RolePermissionFactory.class).to(RolePermissionFactoryImpl.class).in(Singleton.class);
- bind(GroupFactory.class).to(GroupFactoryImpl.class);
+ bind(GroupFactory.class).to(GroupFactoryImpl.class).in(Singleton.class);
+ bind(KapuaAuthorizationSetting.class).in(Singleton.class);
+ bind(PermissionValidator.class).in(Singleton.class);
+ bind(PermissionMapper.class).to(PermissionMapperImpl.class).in(Singleton.class);
}
@ProvidesIntoSet
@@ -151,14 +153,16 @@ ServiceModule authorizationServiceModule(AccessInfoService accessInfoService,
PermissionFactory permissionFactory,
KapuaJpaTxManagerFactory txManagerFactory,
EventStoreFactory eventStoreFactory,
- EventStoreRecordRepository eventStoreRecordRepository
+ EventStoreRecordRepository eventStoreRecordRepository,
+ ServiceEventBus serviceEventBus,
+ KapuaAuthorizationSetting kapuaAuthorizationSetting
) throws ServiceEventBusException {
return new AuthorizationServiceModule(
accessInfoService,
roleService,
domainRegistryService,
groupService,
- KapuaAuthorizationSetting.getInstance(),
+ kapuaAuthorizationSetting,
new ServiceEventHouseKeeperFactoryImpl(
new EventStoreServiceImpl(
authorizationService,
@@ -167,8 +171,9 @@ ServiceModule authorizationServiceModule(AccessInfoService accessInfoService,
eventStoreFactory,
eventStoreRecordRepository
),
- txManagerFactory.create("kapua-authorization")
- ));
+ txManagerFactory.create("kapua-authorization"),
+ serviceEventBus
+ ), serviceEventBus);
}
@ProvidesIntoSet
@@ -216,13 +221,15 @@ RolePermissionService rolePermissionService(PermissionFactory permissionFactory,
AuthorizationService authorizationService,
RoleRepository roleRepository,
RolePermissionRepository rolePermissionRepository,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ PermissionValidator permissionValidator) {
return new RolePermissionServiceImpl(
authorizationService,
permissionFactory,
jpaTxManagerFactory.create("kapua-authorization"),
roleRepository,
- rolePermissionRepository
+ rolePermissionRepository,
+ permissionValidator
);
}
@@ -234,7 +241,8 @@ RoleService roleService(PermissionFactory permissionFactory,
@Named("RoleServiceConfigurationManager") ServiceConfigurationManager serviceConfigurationManager,
RoleRepository roleRepository,
RolePermissionRepository rolePermissionRepository,
- KapuaJpaTxManagerFactory jpaTxManagerFactory
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ PermissionValidator permissionValidator
) {
return new RoleServiceImpl(
permissionFactory,
@@ -243,7 +251,8 @@ RoleService roleService(PermissionFactory permissionFactory,
serviceConfigurationManager,
jpaTxManagerFactory.create("kapua-authorization"),
roleRepository,
- rolePermissionRepository
+ rolePermissionRepository,
+ permissionValidator
);
}
@@ -255,14 +264,15 @@ public ServiceConfigurationManager roleServiceConfigurationManager(
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
RoleRepository roleRepository,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(
RoleService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
@@ -274,16 +284,17 @@ public ServiceConfigurationManager roleServiceConfigurationManager(
@Provides
@Singleton
- RoleRepository roleRepository(RoleCacheFactory roleCacheFactory, KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ RoleRepository roleRepository(NamedCacheFactory namedCacheFactory, KapuaJpaRepositoryConfiguration jpaRepoConfig) {
return new RoleCachingRepository(new RoleImplJpaRepository(jpaRepoConfig),
- (NamedEntityCache) roleCacheFactory.createCache());
+ namedCacheFactory.createCache("RoleId", "RoleName"));
}
@Provides
@Singleton
- RolePermissionRepository rolePermissionRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ RolePermissionRepository rolePermissionRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory) {
return new RolePermissionCachingRepository(new RolePermissionImplJpaRepository(jpaRepoConfig),
- new RolePermissionCacheFactory().createCache());
+ entityCacheFactory.createCache("RolePermissionId"));
}
@Provides
@@ -306,14 +317,15 @@ public ServiceConfigurationManager groupServiceConfigurationManager(
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
GroupRepository groupRepository,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(
GroupService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
@@ -341,7 +353,8 @@ AccessInfoService accessInfoService(
AccessInfoFactory accessInfoFactory,
AccessPermissionRepository accessPermissionRepository,
AccessPermissionFactory accessPermissionFactory,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ PermissionValidator permissionValidator) {
return new AccessInfoServiceImpl(authorizationService,
permissionFactory,
jpaTxManagerFactory.create("kapua-authorization"),
@@ -351,15 +364,16 @@ AccessInfoService accessInfoService(
accessInfoRepository,
accessInfoFactory,
accessPermissionRepository,
- accessPermissionFactory);
+ accessPermissionFactory,
+ permissionValidator);
}
@Provides
@Singleton
- AccessInfoRepository accessInfoRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ AccessInfoRepository accessInfoRepository(KapuaCacheManager kapuaCacheManager, CommonsMetric commonsMetric, KapuaJpaRepositoryConfiguration jpaRepoConfig) {
return new AccessInfoCachingRepository(
new AccessInfoImplJpaRepository(jpaRepoConfig),
- (AccessInfoCache) new AccessInfoCacheFactory().createCache()
+ new AccessInfoCacheFactory(kapuaCacheManager, commonsMetric).createCache()
);
}
@@ -370,21 +384,24 @@ AccessPermissionService accessPermissionService(
PermissionFactory permissionFactory,
AccessPermissionRepository accessPermissionRepository,
AccessInfoRepository accessInfoRepository,
- KapuaJpaTxManagerFactory jpaTxManagerFactory) {
+ KapuaJpaTxManagerFactory jpaTxManagerFactory,
+ PermissionValidator permissionValidator) {
return new AccessPermissionServiceImpl(authorizationService,
permissionFactory,
jpaTxManagerFactory.create("kapua-authorization"),
accessPermissionRepository,
- accessInfoRepository);
+ accessInfoRepository,
+ permissionValidator);
}
@Provides
@Singleton
- AccessPermissionRepository accessPermissionRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ AccessPermissionRepository accessPermissionRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory) {
return new CachingAccessPermissionRepository(
new AccessPermissionImplJpaRepository(jpaRepoConfig),
- new AccessPermissionCacheFactory().createCache()
+ entityCacheFactory.createCache("AccessPermissionId")
);
}
@@ -408,10 +425,10 @@ AccessRoleService accessRoleService(RoleRepository roleRepository,
@Provides
@Singleton
- AccessRoleRepository accessRoleRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ AccessRoleRepository accessRoleRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory) {
return new CachingAccessRoleRepository(
- new AccessRoleImplJpaRepository(jpaRepoConfig)
- , new AccessRoleCacheFactory().createCache()
+ new AccessRoleImplJpaRepository(jpaRepoConfig), entityCacheFactory.createCache("AccessRoleId")
);
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceImpl.java
index f74fed8f5f1..6065aeddc10 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceImpl.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceImpl.java
@@ -21,6 +21,7 @@
import org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException;
import org.eclipse.kapua.service.authorization.permission.Permission;
+import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Arrays;
import java.util.List;
@@ -33,6 +34,12 @@
*/
@Singleton
public class AuthorizationServiceImpl implements AuthorizationService {
+ private final PermissionMapper permissionMapper;
+
+ @Inject
+ public AuthorizationServiceImpl(PermissionMapper permissionMapper) {
+ this.permissionMapper = permissionMapper;
+ }
@Override
public boolean[] isPermitted(List permissions) throws KapuaException {
@@ -47,7 +54,7 @@ public boolean[] isPermitted(List permissions) throws KapuaException
return returnedPermissions;
} else {
List permissionsShiro = permissions.stream()
- .map(permission -> (org.apache.shiro.authz.Permission) permission)
+ .map(permission -> permissionMapper.mapPermission(permission))
.collect(Collectors.toList());
return SecurityUtils.getSubject().isPermitted(permissionsShiro);
}
@@ -63,7 +70,7 @@ public boolean isPermitted(Permission permission)
}
return session.isTrustedMode() ||
- SecurityUtils.getSubject().isPermitted((org.apache.shiro.authz.Permission) permission);
+ SecurityUtils.getSubject().isPermitted(permissionMapper.mapPermission(permission));
}
@Override
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceModule.java
index c7dfb2250a2..864a4d72f55 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceModule.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationServiceModule.java
@@ -16,6 +16,7 @@
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactory;
import org.eclipse.kapua.commons.event.ServiceEventTransactionalModule;
import org.eclipse.kapua.commons.event.ServiceInspector;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.service.authorization.access.AccessInfoService;
import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.group.GroupService;
@@ -33,7 +34,8 @@ public AuthorizationServiceModule(AccessInfoService accessInfoService,
DomainRegistryService domainRegistryService,
GroupService groupService,
KapuaAuthorizationSetting kapuaAuthorizationSettings,
- ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory) {
+ ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory,
+ ServiceEventBus serviceEventBus) {
super(Arrays.asList(
ServiceInspector.getEventBusClients(accessInfoService, AccessInfoService.class),
ServiceInspector.getEventBusClients(roleService, RoleService.class),
@@ -45,6 +47,7 @@ public AuthorizationServiceModule(AccessInfoService accessInfoService,
.collect(Collectors.toList())
.toArray(new ServiceEventClientConfiguration[0]),
kapuaAuthorizationSettings.getString(KapuaAuthorizationSettingKeys.AUTHORIZATION_EVENT_ADDRESS),
- serviceEventTransactionalHousekeeperFactory);
+ serviceEventTransactionalHousekeeperFactory,
+ serviceEventBus);
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java
index d053bdcfa2d..fb0ceb47430 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java
@@ -58,8 +58,12 @@ public class KapuaAuthorizingRealm extends AuthorizingRealm {
public static final String REALM_NAME = "kapuaAuthorizingRealm";
+ private final PermissionMapper permissionMapper;
+
public KapuaAuthorizingRealm() throws KapuaException {
setName(REALM_NAME);
+
+ permissionMapper = KapuaLocator.getInstance().getComponent(PermissionMapperImpl.class);
}
/**
@@ -128,7 +132,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal
for (AccessPermission accessPermission : accessPermissions.getItems()) {
PermissionImpl p = accessPermission.getPermission();
logger.trace("User: {} has permission: {}", username, p);
- info.addObjectPermission(p);
+ info.addObjectPermission(permissionMapper.mapPermission(p));
}
// Access Role Id
@@ -169,7 +173,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal
PermissionImpl p = rolePermission.getPermission();
logger.trace("Role: {} has permission: {}", role, p);
- info.addObjectPermission(p);
+ info.addObjectPermission(permissionMapper.mapPermission(p));
}
}
}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapper.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapper.java
new file mode 100644
index 00000000000..c603cdd54c1
--- /dev/null
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapper.java
@@ -0,0 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.authorization.shiro;
+
+import org.apache.shiro.authz.Permission;
+
+public interface PermissionMapper {
+ Permission mapPermission(org.eclipse.kapua.service.authorization.permission.Permission permission);
+}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java
new file mode 100644
index 00000000000..fbaaf5e53ba
--- /dev/null
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java
@@ -0,0 +1,296 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.authorization.shiro;
+
+import org.apache.shiro.authz.Permission;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.authz.permission.WildcardPermission;
+import org.apache.shiro.subject.Subject;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.KapuaRuntimeException;
+import org.eclipse.kapua.commons.model.id.KapuaEid;
+import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
+import org.eclipse.kapua.model.KapuaEntity;
+import org.eclipse.kapua.model.KapuaEntityCreator;
+import org.eclipse.kapua.model.domain.Actions;
+import org.eclipse.kapua.model.id.KapuaId;
+import org.eclipse.kapua.model.query.KapuaQuery;
+import org.eclipse.kapua.service.KapuaEntityService;
+import org.eclipse.kapua.service.account.Account;
+import org.eclipse.kapua.service.account.AccountService;
+import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
+import org.eclipse.kapua.service.authorization.group.Group;
+
+import javax.inject.Inject;
+
+public class PermissionMapperImpl implements PermissionMapper {
+ private final DomainRegistryService domainService;
+ private final AccountService accountService;
+
+ @Inject
+ public PermissionMapperImpl(DomainRegistryService domainService, AccountService accountService) {
+ this.domainService = domainService;
+ this.accountService = accountService;
+ }
+
+ @Override
+ public Permission mapPermission(org.eclipse.kapua.service.authorization.permission.Permission permission) {
+ return new KapuaPermission(permission.getDomain(), permission.getAction(), permission.getTargetScopeId(), permission.getGroupId(), permission.getForwardable());
+ }
+
+ public class KapuaPermission extends WildcardPermission implements org.eclipse.kapua.service.authorization.permission.Permission, Permission {
+ private String domain;
+ private Actions action;
+ private KapuaId targetScopeId;
+ private KapuaId groupId;
+ private boolean forwardable;
+
+ public KapuaPermission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId, boolean forwardable) {
+ this.domain = domain;
+ this.action = action;
+ this.targetScopeId = targetScopeId;
+ this.groupId = groupId;
+ this.forwardable = forwardable;
+ setParts(toString());
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append(domain != null ? domain : org.eclipse.kapua.service.authorization.permission.Permission.WILDCARD)
+ .append(org.eclipse.kapua.service.authorization.permission.Permission.SEPARATOR)
+ .append(action != null ? action.name() : org.eclipse.kapua.service.authorization.permission.Permission.WILDCARD)
+ .append(org.eclipse.kapua.service.authorization.permission.Permission.SEPARATOR)
+ .append(targetScopeId != null ? targetScopeId.getId() : org.eclipse.kapua.service.authorization.permission.Permission.WILDCARD)
+ .append(org.eclipse.kapua.service.authorization.permission.Permission.SEPARATOR)
+ .append(groupId != null ? groupId.getId() : org.eclipse.kapua.service.authorization.permission.Permission.WILDCARD);
+
+ return sb.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ int prime = 31;
+ int result = 1;
+ result = prime * result + (action == null ? 0 : action.hashCode());
+ result = prime * result + (domain == null ? 0 : domain.hashCode());
+ result = prime * result + (targetScopeId == null ? 0 : targetScopeId.hashCode());
+ result = prime * result + (groupId == null ? 0 : groupId.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ KapuaPermission other = (KapuaPermission) obj;
+ if (action != other.action) {
+ return false;
+ }
+ if (domain == null) {
+ if (other.domain != null) {
+ return false;
+ }
+ } else if (!domain.equals(other.domain)) {
+ return false;
+ }
+ if (targetScopeId == null) {
+ if (other.targetScopeId != null) {
+ return false;
+ }
+ } else if (!targetScopeId.equals(other.targetScopeId)) {
+ return false;
+ }
+ if (groupId == null) {
+ return other.groupId == null;
+ } else {
+ return groupId.equals(other.groupId);
+ }
+ }
+
+ /**
+ * This method needs to be overridden to support Access {@link Group} feature.
+ *
+ * {@link KapuaEntityService}s that access a specific {@link KapuaEntity} (i.e. {@link KapuaEntityService#create(KapuaEntityCreator)}, {@link KapuaEntityService#delete(KapuaId, KapuaId)})
+ * can make the control taking in consideration of the {@link Group#getId()} parameter as it is known.
+ *
+ * Instead, methods that access multiple {@link KapuaEntity}s (i.e. {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)})
+ * cannot make a direct control of the {@link Group#getId()} parameter as it is not known and they can be a lot.
+ * The access control then, is performed by hiding the data that a {@link Subject} cannot see instead of throwing {@link UnauthorizedException}.
+ *
+ *
+ * The access control for {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)}) must specify that {@link Group#ANY} group assigned to the permission is
+ * enough to pass the {@link AuthorizationService#checkPermission(org.eclipse.kapua.service.authorization.permission.Permission)}.
+ *
+ *
+ * In case of the {@link org.eclipse.kapua.service.authorization.permission.Permission#getForwardable()} equals to {@code true}, more lookup is required.
+ * If a parent account access the resources of one of its child accounts it won't have the direct permission to access it.
+ * A lookup of {@link Account#getParentAccountPath()} will be required to search if the current user scope id is
+ * one of the parent of the given {@link org.eclipse.kapua.service.authorization.permission.Permission#getTargetScopeId()}
+ *
+ *
+ * @since 1.0.0
+ */
+ @Override
+ public boolean implies(Permission shiroPermission) {
+
+ org.eclipse.kapua.service.authorization.permission.Permission targetPermission = (org.eclipse.kapua.service.authorization.permission.Permission) shiroPermission;
+
+ // Check target Permission domain
+ checkTargetPermissionIsGroupable(targetPermission);
+
+ // If checked Permission ask for ANY targetScopeId, promote this Permission.targetScopeId to `null` (a.k.a. ALL scopes).
+ if (KapuaId.ANY.equals(targetPermission.getTargetScopeId())) {
+ this.setTargetScopeId(null);
+ }
+
+ // If checked Permission ask for ANY groupId, promote this Permission.groupId to `null` (a.k.a. ALL groups).
+ if (Group.ANY.equals(targetPermission.getGroupId())) {
+ this.setGroupId(null);
+ }
+
+ // Set part of the Shiro Permission to then run 'implies' with the target Permission
+ this.setParts(this.toString());
+
+ boolean implies = super.implies(shiroPermission);
+
+ // If it fails try forward permission if this Permission is forwardable
+ if (!implies && targetPermission.getTargetScopeId() != null && this.getForwardable()) {
+ implies = forwardPermission(shiroPermission);
+ }
+
+ // Return result
+ return implies;
+ }
+
+ /**
+ * Checks whether the given {@link org.eclipse.kapua.service.authorization.permission.Permission#getDomain()} is {@link org.eclipse.kapua.service.authorization.domain.Domain#getGroupable()}.
+ *
+ * If it is, promotes this {@link org.eclipse.kapua.service.authorization.permission.Permission#getGroupId()} to {@code null} (a.k.a. ALL groups).
+ *
+ * @param targetPermission The target {@link Permission} to check.
+ * @since 2.0.0
+ */
+ private void checkTargetPermissionIsGroupable(org.eclipse.kapua.service.authorization.permission.Permission targetPermission) {
+ if (targetPermission.getDomain() != null) {
+ try {
+ org.eclipse.kapua.service.authorization.domain.Domain domainDefinition = KapuaSecurityUtils.doPrivileged(() -> domainService.findByName(targetPermission.getDomain()));
+
+ if (!domainDefinition.getGroupable()) {
+ this.setGroupId(null);
+ }
+ } catch (Exception e) {
+ throw KapuaRuntimeException.internalError(e, "Error while resolving target Permission.domain: " + targetPermission.getDomain());
+ }
+ }
+ }
+
+ /**
+ * Checks {@code this} Permission against the given {@link Permission} parameter.
+ *
+ * It tries to forward {@code this} Permission to the {@link #getTargetScopeId()} of the given {@link Permission} parameter.
+ * This means that if the required permission has scope id 'B' and {@code this} {@link Permission} has scope id 'A',
+ * this methods search the {@link Account#getParentAccountPath()} of the scope id 'B' and checks the {@link Permission} forwarding {@code this} Permission
+ * to the same level of the given {@link Permission}.
+ *
+ *
+ *
Example:
+ * User 'A' in account 'A' has scopeId 'A' and this permission (A) "*:*:A:*".
+ * Account 'A' has a child account 'B', then 'B' has this parent account path: '/A/B';
+ * User 'A' tries to access a resource of account 'B' an the direct check {@link Permission#implies(Permission)} fails.
+ * So this method searches the parent account path of account 'B', found that 'A' is a parent of 'B'
+ * so then {@code this} {@link Permission} is checked again with 'B' as scopeId.
+ *
+ *
+ * @param shiroPermission The permission to check against.
+ * @return {@code true} if this permission is forward-able and is valid when forwarded, {@code false otherwise}
+ * @since 1.0.0
+ */
+ private boolean forwardPermission(Permission shiroPermission) {
+ org.eclipse.kapua.service.authorization.permission.Permission targetPermission = (org.eclipse.kapua.service.authorization.permission.Permission) shiroPermission;
+
+ try {
+ Account account = KapuaSecurityUtils.doPrivileged(() -> accountService.find(targetPermission.getTargetScopeId()));
+
+ if (account != null && account.getScopeId() != null) {
+ String parentAccountPath = account.getParentAccountPath();
+
+ // If it doesn't contain the scope id in the parent, don't even try to check against
+ if (parentAccountPath.contains("/" + getTargetScopeId().toStringId() + "/")) {
+ this.setTargetScopeId(targetPermission.getTargetScopeId());
+ this.setParts(this.toString());
+
+ return super.implies(shiroPermission);
+ }
+ }
+ } catch (KapuaException e) {
+ throw KapuaRuntimeException.internalError(e, "Error while forwarding target Permission: " + shiroPermission);
+ }
+
+ return false;
+ }
+
+
+ @Override
+ public void setDomain(String domain) {
+ this.domain = domain;
+ }
+
+ public String getDomain() {
+ return domain;
+ }
+
+ public void setAction(Actions action) {
+ this.action = action;
+ }
+
+ public Actions getAction() {
+ return action;
+ }
+
+ public void setTargetScopeId(KapuaId targetScopeId) {
+ this.targetScopeId = KapuaEid.parseKapuaId(targetScopeId);
+ }
+
+ public KapuaId getTargetScopeId() {
+ return targetScopeId;
+ }
+
+ public void setGroupId(KapuaId groupId) {
+ this.groupId = KapuaEid.parseKapuaId(groupId);
+ }
+
+ public KapuaId getGroupId() {
+ return groupId;
+ }
+
+ public boolean getForwardable() {
+ return forwardable;
+ }
+
+ public void setForwardable(boolean forwardable) {
+ this.forwardable = forwardable;
+ }
+
+ }
+
+}
diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSetting.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSetting.java
index 705d96ee8a9..b698ab92355 100644
--- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSetting.java
+++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSetting.java
@@ -14,6 +14,8 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Authorization setting implementation.
*/
@@ -21,21 +23,12 @@ public class KapuaAuthorizationSetting extends AbstractKapuaSettingv87a-lue to encrypt"),
- AuthenticationUtils.encryptAes("value_to$#encr-0y()pt"),
- AuthenticationUtils.encryptAes("va09l-ue|,,,.to00encrypt")
+ authenticationUtils.encryptAes("value to encrypt"),
+ authenticationUtils.encryptAes("value@#$ en-999crypt"),
+ authenticationUtils.encryptAes("!<>v87a-lue to encrypt"),
+ authenticationUtils.encryptAes("value_to$#encr-0y()pt"),
+ authenticationUtils.encryptAes("va09l-ue|,,,.to00encrypt")
};
verificationCodes = new int[]{
@@ -57,10 +70,10 @@ public void initialize() throws KapuaException {
};
hashedScratchCodes = new String[]{
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "val-ue99_<11>"),
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, " !@#$v66a0l-ueee"),
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "val *&^%087,...ueee "),
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "_877V.A;;LUE")
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "val-ue99_<11>"),
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, " !@#$v66a0l-ueee"),
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "val *&^%087,...ueee "),
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "_877V.A;;LUE")
};
stringVerificationCodes = new String[]{
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcherTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcherTest.java
index 0b5b3b24976..bd561746e9f 100644
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcherTest.java
+++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsMatcherTest.java
@@ -16,6 +16,7 @@
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialType;
import org.eclipse.kapua.service.authentication.shiro.JwtCredentialsImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -33,7 +34,7 @@ public class ApiKeyCredentialsMatcherTest {
@Before
public void initialize() {
- apiKeyCredentialsMatcher = new ApiKeyCredentialsMatcher();
+ apiKeyCredentialsMatcher = new ApiKeyCredentialsMatcher(new KapuaAuthenticationSetting());
authenticationToken = Mockito.mock(JwtCredentialsImpl.class);
authenticationInfo = Mockito.mock(LoginAuthenticationInfo.class);
credential = Mockito.mock(Credential.class);
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImplTest.java
index 9895a5611b4..cf135ee5667 100644
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImplTest.java
+++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/registration/RegistrationServiceImplTest.java
@@ -13,21 +13,51 @@
package org.eclipse.kapua.service.authentication.shiro.registration;
import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.plugin.sso.openid.JwtProcessor;
+import org.eclipse.kapua.plugin.sso.openid.OpenIDLocator;
+import org.eclipse.kapua.plugin.sso.openid.OpenIDService;
+import org.eclipse.kapua.plugin.sso.openid.exception.OpenIDException;
+import org.eclipse.kapua.plugin.sso.openid.provider.internal.DisabledJwtProcessor;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
+import org.eclipse.kapua.security.registration.RegistrationProcessor;
+import org.eclipse.kapua.security.registration.RegistrationProcessorProvider;
import org.eclipse.kapua.service.authentication.JwtCredentials;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
+import java.util.Collection;
+import java.util.Collections;
+
@Category(JUnitTests.class)
public class RegistrationServiceImplTest {
+ private RegistrationServiceImpl createDummyInstance() throws OpenIDException {
+ return new RegistrationServiceImpl(new KapuaAuthenticationSetting(), new OpenIDLocator() {
+ @Override
+ public OpenIDService getService() {
+ return null;
+ }
+
+ @Override
+ public JwtProcessor getProcessor() throws OpenIDException {
+ return new DisabledJwtProcessor();
+ }
+ }, Collections.singleton(new RegistrationProcessorProvider() {
+ @Override
+ public Collection extends RegistrationProcessor> createAll() {
+ return Collections.emptyList();
+ }
+ }));
+ }
+
@Test
public void registrationServiceImplTest() {
try {
- new RegistrationServiceImpl();
+ createDummyInstance();
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
@@ -35,7 +65,7 @@ public void registrationServiceImplTest() {
@Test
public void closeTest() throws Exception {
- RegistrationServiceImpl registrationServiceImpl = new RegistrationServiceImpl();
+ RegistrationServiceImpl registrationServiceImpl = createDummyInstance();
try {
registrationServiceImpl.close();
} catch (Exception e) {
@@ -46,25 +76,25 @@ public void closeTest() throws Exception {
@Test
public void isAccountCreationEnabledTrueEmptyProcessorsTest() throws KapuaException {
System.setProperty("authentication.registration.service.enabled", "true");
- RegistrationServiceImpl registrationService = new RegistrationServiceImpl();
+ RegistrationServiceImpl registrationService = createDummyInstance();
Assert.assertFalse("False expected.", registrationService.isAccountCreationEnabled());
}
@Test
public void isAccountCreationEnabledFalseTest() throws KapuaException {
System.setProperty("authentication.registration.service.enabled", "false");
- RegistrationServiceImpl registrationService = new RegistrationServiceImpl();
+ RegistrationServiceImpl registrationService = createDummyInstance();
Assert.assertFalse("False expected.", registrationService.isAccountCreationEnabled());
}
@Test
public void createAccountCreationNotEnabledTest() throws KapuaException {
JwtCredentials jwtCredentials = Mockito.mock(JwtCredentials.class);
- Assert.assertFalse("False expected.", new RegistrationServiceImpl().createAccount(jwtCredentials));
+ Assert.assertFalse("False expected.", createDummyInstance().createAccount(jwtCredentials));
}
@Test
public void createAccountNullTest() throws KapuaException {
- Assert.assertFalse("False expected.", new RegistrationServiceImpl().createAccount(null));
+ Assert.assertFalse("False expected.", createDummyInstance().createAccount(null));
}
}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSettingTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSettingTest.java
deleted file mode 100644
index b4a8c322743..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaAuthenticationSettingTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authentication.shiro.setting;
-
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-@Category(JUnitTests.class)
-public class KapuaAuthenticationSettingTest {
-
- //TODO: What is the value of testing the correct implementation of the Singleton pattern, in a class that does NOT need to be a singleton?
- @Test
- public void kapuaAuthenticationSettingTest() throws Exception {
- Constructor kapuaAuthenticationSetting = KapuaAuthenticationSetting.class.getDeclaredConstructor();
- kapuaAuthenticationSetting.setAccessible(true);
- kapuaAuthenticationSetting.newInstance();
- Assert.assertFalse("False expected.", Modifier.isPrivate(kapuaAuthenticationSetting.getModifiers()));
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertTrue("True expected.", KapuaAuthenticationSetting.getInstance() instanceof KapuaAuthenticationSetting);
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaCryptoSettingTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaCryptoSettingTest.java
deleted file mode 100644
index 916052f655a..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/setting/KapuaCryptoSettingTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authentication.shiro.setting;
-
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-
-@Category(JUnitTests.class)
-public class KapuaCryptoSettingTest {
-
- @Test
- public void kapuaCryptoSettingTest() throws Exception {
- Constructor kapuaCryptoSetting = KapuaCryptoSetting.class.getDeclaredConstructor();
- kapuaCryptoSetting.setAccessible(true);
- kapuaCryptoSetting.newInstance();
- Assert.assertTrue("True expected.", Modifier.isPrivate(kapuaCryptoSetting.getModifiers()));
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertTrue("True expected.", KapuaCryptoSetting.getInstance() instanceof KapuaCryptoSetting);
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtilsTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtilsTest.java
index 7dda3f9de83..2966f01fce5 100644
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtilsTest.java
+++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/AuthenticationUtilsTest.java
@@ -16,6 +16,8 @@
import org.eclipse.kapua.KapuaIllegalNullArgumentException;
import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
+import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationErrorCodes;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaCryptoSetting;
import org.eclipse.kapua.service.authentication.shiro.setting.KapuaCryptoSettingKeys;
import org.junit.After;
import org.junit.Assert;
@@ -23,8 +25,8 @@
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
@Category(JUnitTests.class)
@@ -33,12 +35,20 @@ public class AuthenticationUtilsTest {
String[] plainValues, encryptedValues;
private String cypherKeyPropKey = KapuaCryptoSettingKeys.CIPHER_KEY.key();
private String cryptoShaAlgorithmPropKey = KapuaCryptoSettingKeys.CRYPTO_SHA_ALGORITHM.key();
+ private AuthenticationUtils authenticationUtils;
@Before
public void initialize() {
plainValues = new String[]{"plain_..val9&^%ue123!!", " value#999 ?><,,..;''a ", "valu e plain*&^% $#45", "value,,,,va?>< ", "... s_er%%67nsaa4356&^% a *(me"};
encryptedValues = new String[]{"2c3mAagxwaEuAhmR1UzyafpKdA8R-poaS2upJPj4kzE", "QprB8vCeyft4pU8AJdxSWlIFL1b02s-UqTQwirKj9Dw", "RrRtzYPLFDgVdmKo9kOipZv723WBs2J3IxSoPwSJM7g",
"gcGjWNELoVl9R-71-Nm8aAoNgf3lxr5FziYhj8dmML0", "lCysXXE00k64hm_FzQ8aK1GlVMFqR6So3knfnb5R_CQKDYH95ca-Rc4mIY_HZjC9"};
+ final SecureRandom random;
+ try {
+ random = SecureRandom.getInstance("SHA1PRNG");
+ } catch (NoSuchAlgorithmException e) {
+ throw new KapuaRuntimeException(KapuaAuthenticationErrorCodes.CREDENTIAL_CRYPT_ERROR, e);
+ }
+ authenticationUtils = new AuthenticationUtils(random, new KapuaCryptoSetting());
}
@After
@@ -47,19 +57,11 @@ public void tearDown() {
System.clearProperty(cryptoShaAlgorithmPropKey);
}
- @Test
- public void authenticationUtilsTest() throws Exception {
- Constructor authenticationUtils = AuthenticationUtils.class.getDeclaredConstructor();
- authenticationUtils.setAccessible(true);
- authenticationUtils.newInstance();
- Assert.assertTrue("True expected.", Modifier.isPrivate(authenticationUtils.getModifiers()));
- }
-
@Test
public void cryptCredentialBCRYPTAlgorithmTest() throws KapuaException {
for (String plainValue : plainValues) {
- Assert.assertTrue("True expected.", AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, plainValue).startsWith("$2a$12$"));
- Assert.assertEquals("Expected and actual values should be the same.", 60, AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "plain value").length());
+ Assert.assertTrue("True expected.", authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, plainValue).startsWith("$2a$12$"));
+ Assert.assertEquals("Expected and actual values should be the same.", 60, authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "plain value").length());
}
}
@@ -71,25 +73,25 @@ public void cryptCredentialSHAAlgorithmTest() throws KapuaException {
for (int i = 0; i < shaAlgorithm.length; i++) {
System.setProperty(cryptoShaAlgorithmPropKey, shaAlgorithm[i]);
for (String plainValue : plainValues) {
- Assert.assertTrue("True expected.", AuthenticationUtils.cryptCredential(CryptAlgorithm.SHA, plainValue).contains("=:"));
- Assert.assertEquals("Expected and actual values should be the same.", expectedLength[i], AuthenticationUtils.cryptCredential(CryptAlgorithm.SHA, plainValue).length());
+ Assert.assertTrue("True expected.", authenticationUtils.cryptCredential(CryptAlgorithm.SHA, plainValue).contains("=:"));
+ Assert.assertEquals("Expected and actual values should be the same.", expectedLength[i], authenticationUtils.cryptCredential(CryptAlgorithm.SHA, plainValue).length());
}
}
}
@Test(expected = NullPointerException.class)
public void cryptCredentialNullAlgorithmTest() throws KapuaException {
- AuthenticationUtils.cryptCredential(null, "plain value");
+ authenticationUtils.cryptCredential(null, "plain value");
}
@Test(expected = KapuaIllegalNullArgumentException.class)
public void cryptCredentialNullPlainValueTest() throws KapuaException {
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, null);
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, null);
}
@Test(expected = KapuaIllegalNullArgumentException.class)
public void cryptCredentialEmptyPlainValueTest() throws KapuaException {
- AuthenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "");
+ authenticationUtils.cryptCredential(CryptAlgorithm.BCRYPT, "");
}
@Test
@@ -97,7 +99,7 @@ public void encryptAesTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
for (String plainValue : plainValues) {
try {
- AuthenticationUtils.encryptAes(plainValue);
+ authenticationUtils.encryptAes(plainValue);
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
@@ -108,21 +110,21 @@ public void encryptAesTest() {
public void encryptAesIncorrectKeyTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse32918@#");
for (String plainValue : plainValues) {
- AuthenticationUtils.encryptAes(plainValue);
+ authenticationUtils.encryptAes(plainValue);
}
}
@Test(expected = NullPointerException.class)
public void encryptAesNullTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
- AuthenticationUtils.encryptAes(null);
+ authenticationUtils.encryptAes(null);
}
@Test
public void encryptAesEmptyValueTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
try {
- AuthenticationUtils.encryptAes("");
+ authenticationUtils.encryptAes("");
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
@@ -131,7 +133,7 @@ public void encryptAesEmptyValueTest() {
@Test(expected = IllegalArgumentException.class)
public void encryptAesEmptyKeyTest() {
System.setProperty(cypherKeyPropKey, "");
- AuthenticationUtils.encryptAes("plain value");
+ authenticationUtils.encryptAes("plain value");
}
@Test
@@ -139,7 +141,7 @@ public void decryptAesTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
for (String encryptedValue : encryptedValues) {
try {
- AuthenticationUtils.decryptAes(encryptedValue);
+ authenticationUtils.decryptAes(encryptedValue);
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
@@ -150,27 +152,27 @@ public void decryptAesTest() {
public void decryptAesIncorrectKeyTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse32918@#");
for (String encryptedValue : encryptedValues) {
- AuthenticationUtils.decryptAes(encryptedValue);
+ authenticationUtils.decryptAes(encryptedValue);
}
}
@Test(expected = NullPointerException.class)
public void decryptAesNullTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
- AuthenticationUtils.decryptAes(null);
+ authenticationUtils.decryptAes(null);
}
@Test(expected = IllegalArgumentException.class)
public void decryptAesNllTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
- AuthenticationUtils.decryptAes("value");
+ authenticationUtils.decryptAes("value");
}
@Test
public void decryptAesEmptyValueTest() {
System.setProperty(cypherKeyPropKey, "rv;ipse329183!@#");
try {
- AuthenticationUtils.decryptAes("");
+ authenticationUtils.decryptAes("");
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
@@ -179,6 +181,6 @@ public void decryptAesEmptyValueTest() {
@Test(expected = IllegalArgumentException.class)
public void decryptAesEmptyKeyTest() {
System.setProperty(cypherKeyPropKey, "");
- AuthenticationUtils.decryptAes("2c3mAagxwaEuAhmR1UzyafpKdA8R-poaS2upJPj4kzE");
+ authenticationUtils.decryptAes("2c3mAagxwaEuAhmR1UzyafpKdA8R-poaS2upJPj4kzE");
}
}
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessorsTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessorsTest.java
deleted file mode 100644
index 21e0a2531bd..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/utils/JwtProcessorsTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authentication.shiro.utils;
-
-import org.eclipse.kapua.plugin.sso.openid.JwtProcessor;
-import org.eclipse.kapua.plugin.sso.openid.exception.OpenIDException;
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-
-@Category(JUnitTests.class)
-public class JwtProcessorsTest {
-
- @Test
- public void jwtProcessorsTest() throws Exception {
- Constructor jwtProcessors = JwtProcessors.class.getDeclaredConstructor();
- jwtProcessors.setAccessible(true);
- jwtProcessors.newInstance();
- Assert.assertTrue("True expected.", Modifier.isPrivate(jwtProcessors.getModifiers()));
- }
-
- @Test
- public void createDefaultTest() throws OpenIDException {
- Assert.assertTrue("True expected.", JwtProcessors.createDefault() instanceof JwtProcessor);
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactoryTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactoryTest.java
deleted file mode 100644
index f726aef7f9f..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheFactoryTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authorization.access.shiro;
-
-import org.eclipse.kapua.commons.service.internal.cache.EntityCache;
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-
-@Category(JUnitTests.class)
-public class AccessInfoCacheFactoryTest {
-
- AccessInfoCacheFactory accessInfoCacheFactory;
-
- @Before
- public void initialize() {
- accessInfoCacheFactory = new AccessInfoCacheFactory();
- }
-
- @Test
- public void accessInfoCacheFactoryTest() {
- Assert.assertEquals("Expected and actual values should be the same.", "AccessInfoId", accessInfoCacheFactory.getEntityIdCacheName());
- }
-
- @Test
- public void createCacheTest() {
- Assert.assertTrue("True expected.", accessInfoCacheFactory.createCache() instanceof EntityCache);
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertEquals("Expected and actual values should be the same.", "AccessInfoId", AccessInfoCacheFactory.getInstance().getEntityIdCacheName());
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheTest.java
index b16c8960c53..d6750c3fe30 100644
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheTest.java
+++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCacheTest.java
@@ -12,6 +12,11 @@
*******************************************************************************/
package org.eclipse.kapua.service.authorization.access.shiro;
+import com.codahale.metrics.Counter;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.eclipse.kapua.service.authorization.access.AccessInfo;
@@ -27,19 +32,29 @@ public class AccessInfoCacheTest {
String[] idCacheNames, nameCacheNames;
AccessInfo kapuaEntity;
+ private KapuaCacheManager kapuaCacheManager;
+ private CommonsMetric commonsMetric;
@Before
public void initialize() {
idCacheNames = new String[]{"", " id 123<> cache(*&% NAME", ")(87CASHE name ^%$id", "98ID name%$^#62522", ",, #@IDcacheNAME-09", "cache_ID 0998@#$", "C12_...cache==_NAME ID "};
nameCacheNames = new String[]{"", "name &^5CACHE-name;'...,,, ", "!@@@name123CACHE ;,.,,name", "cache--987name,*(NAME", "CACHE 32%$#$%^ name", "CaChE 098) (name "};
kapuaEntity = Mockito.mock(AccessInfo.class);
+ System.setProperty(org.eclipse.kapua.locator.KapuaLocator.LOCATOR_CLASS_NAME_SYSTEM_PROPERTY, MockitoLocator.class.getName());
+ commonsMetric = Mockito.mock(CommonsMetric.class);
+ Mockito.when(commonsMetric.getRegisteredCache()).thenReturn(new Counter());
+ Mockito.when(commonsMetric.getCacheError()).thenReturn(new Counter());
+ Mockito.when(commonsMetric.getCacheHit()).thenReturn(new Counter());
+ Mockito.when(commonsMetric.getCacheMiss()).thenReturn(new Counter());
+ final CacheManagerProvider cacheManagerProvider = new CacheManagerProvider(commonsMetric, SystemSetting.getInstance());
+ kapuaCacheManager = new KapuaCacheManager(cacheManagerProvider.get(), commonsMetric, SystemSetting.getInstance());
}
@Test
public void accessInfoCacheTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
Assert.assertNotNull("NotNull expected.", accessInfoCache.accessInfoByUserIdCache);
}
}
@@ -48,14 +63,14 @@ public void accessInfoCacheTest() {
@Test(expected = NullPointerException.class)
public void accessInfoCacheNullIdCacheNameTest() {
for (String nameCacheName : nameCacheNames) {
- new AccessInfoCache(null, nameCacheName);
+ new AccessInfoCache(kapuaCacheManager, commonsMetric, null, nameCacheName);
}
}
@Test(expected = NullPointerException.class)
public void accessInfoCacheNullNameCacheNameTest() {
for (String idCacheName : idCacheNames) {
- new AccessInfoCache(idCacheName, null);
+ new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, null);
}
}
@@ -63,7 +78,7 @@ public void accessInfoCacheNullNameCacheNameTest() {
public void getByUserIdTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
//COMMENT: This method always returns null, due to method get(Object key) in Cache.java which always returns null
Assert.assertNull("Null expected.", accessInfoCache.getByUserId(KapuaId.ONE, KapuaId.ONE));
}
@@ -74,7 +89,7 @@ public void getByUserIdTest() {
public void getByUserIdNullScopeIdTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
//COMMENT: This method always returns null, due to method get(Object key) in Cache.java which always returns null
Assert.assertNull("Null expected.", accessInfoCache.getByUserId(null, KapuaId.ONE));
}
@@ -85,7 +100,7 @@ public void getByUserIdNullScopeIdTest() {
public void getByNullUserIdTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
Assert.assertNull("Null expected.", accessInfoCache.getByUserId(KapuaId.ONE, null));
}
}
@@ -95,7 +110,7 @@ public void getByNullUserIdTest() {
public void putTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
try {
accessInfoCache.put(kapuaEntity);
} catch (Exception e) {
@@ -109,7 +124,7 @@ public void putTest() {
public void putNullEntityTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
try {
accessInfoCache.put(null);
} catch (Exception e) {
@@ -123,7 +138,7 @@ public void putNullEntityTest() {
public void removeTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
//COMMENT: kapuaEntity is always null(see method get(Object key) in Cache.java which always returns null)
// Due to that reason the following part of code could not be tested in AccessInfoCache.java:
// if (kapuaEntity != null) {
@@ -139,7 +154,7 @@ public void removeTest() {
public void removeNullScopeIdTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
//COMMENT: kapuaEntity is always null(see method get(Object key) in Cache.java which always returns null)
// Due to that reason the following part of code could not be tested in AccessInfoCache.java:
// if (kapuaEntity != null) {
@@ -155,7 +170,7 @@ public void removeNullScopeIdTest() {
public void removeNullKapuaIdTest() {
for (String idCacheName : idCacheNames) {
for (String nameCacheName : nameCacheNames) {
- AccessInfoCache accessInfoCache = new AccessInfoCache(idCacheName, nameCacheName);
+ AccessInfoCache accessInfoCache = new AccessInfoCache(kapuaCacheManager, commonsMetric, idCacheName, nameCacheName);
Assert.assertNull("Null expected.", accessInfoCache.remove(KapuaId.ONE, (KapuaId) null));
}
}
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactoryTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactoryTest.java
deleted file mode 100644
index 498da770624..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCacheFactoryTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authorization.access.shiro;
-
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-
-@Category(JUnitTests.class)
-public class AccessPermissionCacheFactoryTest {
-
- @Test
- public void accessPermissionCacheFactoryTest() throws Exception {
- Constructor accessPermissionCacheFactory = AccessPermissionCacheFactory.class.getDeclaredConstructor();
- accessPermissionCacheFactory.setAccessible(true);
- accessPermissionCacheFactory.newInstance();
- Assert.assertFalse("False expected.", Modifier.isPrivate(accessPermissionCacheFactory.getModifiers()));
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertTrue("True expected.", AccessPermissionCacheFactory.getInstance() instanceof AccessPermissionCacheFactory);
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactoryTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactoryTest.java
deleted file mode 100644
index cff76d4eb74..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactoryTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authorization.access.shiro;
-
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-
-@Category(JUnitTests.class)
-public class AccessRoleCacheFactoryTest {
-
- @Test
- public void accessRoleCacheFactoryTest() throws Exception {
- Constructor accessRoleCacheFactory = AccessRoleCacheFactory.class.getDeclaredConstructor();
- accessRoleCacheFactory.setAccessible(true);
- accessRoleCacheFactory.newInstance();
- Assert.assertFalse("False expected.", Modifier.isPrivate(accessRoleCacheFactory.getModifiers()));
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertTrue("True expected.", AccessRoleCacheFactory.getInstance() instanceof AccessRoleCacheFactory);
- Assert.assertEquals("Expected and actual values should be the same.", "AccessRoleId", AccessRoleCacheFactory.getInstance().getEntityIdCacheName());
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/MockitoLocator.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/MockitoLocator.java
new file mode 100644
index 00000000000..f55006f8447
--- /dev/null
+++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/MockitoLocator.java
@@ -0,0 +1,83 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.service.authorization.access.shiro;
+
+import com.codahale.metrics.Counter;
+import com.codahale.metrics.ExponentiallyDecayingReservoir;
+import com.codahale.metrics.Gauge;
+import com.codahale.metrics.Histogram;
+import com.codahale.metrics.Timer;
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.locator.KapuaLocator;
+import org.eclipse.kapua.model.KapuaObjectFactory;
+import org.eclipse.kapua.service.KapuaService;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.List;
+
+public class MockitoLocator extends KapuaLocator {
+
+ @Override
+ public S getService(Class serviceClass) {
+ return Mockito.mock(serviceClass);
+ }
+
+ @Override
+ public F getFactory(Class factoryClass) {
+ return Mockito.mock(factoryClass);
+ }
+
+ @Override
+ public List getServices() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public T getComponent(Class componentClass) {
+ final MetricsService metricsService = new MetricsService() {
+ @Override
+ public Counter getCounter(String module, String component, String... names) {
+ return new Counter();
+ }
+
+ @Override
+ public Histogram getHistogram(String module, String component, String... names) {
+ return new Histogram(new ExponentiallyDecayingReservoir());
+ }
+
+ @Override
+ public Timer getTimer(String module, String component, String... names) {
+ return new Timer();
+ }
+
+ @Override
+ public void registerGauge(Gauge> gauge, String module, String component, String... names) throws KapuaException {
+
+ }
+ };
+ if (MetricsService.class.equals(componentClass)) {
+ return (T) metricsService;
+ }
+ if (CommonsMetric.class.equals(componentClass)) {
+ try {
+ return (T) new CommonsMetric(metricsService, "tests");
+ } catch (KapuaException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return Mockito.mock(componentClass);
+ }
+}
diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSettingTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSettingTest.java
deleted file mode 100644
index 344199df7f4..00000000000
--- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/shiro/setting/KapuaAuthorizationSettingTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.service.authorization.shiro.setting;
-
-import org.eclipse.kapua.qa.markers.junit.JUnitTests;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-
-@Category(JUnitTests.class)
-public class KapuaAuthorizationSettingTest {
-
- @Test
- public void kapuaAuthorizationSettingTest() throws Exception {
- Constructor kapuaAuthorizationSetting = KapuaAuthorizationSetting.class.getDeclaredConstructor();
- Assert.assertTrue("True expected.", Modifier.isPrivate(kapuaAuthorizationSetting.getModifiers()));
- kapuaAuthorizationSetting.setAccessible(true);
- kapuaAuthorizationSetting.newInstance();
- }
-
- @Test
- public void getInstanceTest() {
- Assert.assertTrue("True expected.", KapuaAuthorizationSetting.getInstance() instanceof KapuaAuthorizationSetting);
- }
-}
\ No newline at end of file
diff --git a/service/security/shiro/src/test/resources/locator.xml b/service/security/shiro/src/test/resources/locator.xml
new file mode 100644
index 00000000000..b594a2be143
--- /dev/null
+++ b/service/security/shiro/src/test/resources/locator.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+ org.eclipse.kapua
+
+
diff --git a/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java b/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java
index 54c3025a987..c79647cec05 100644
--- a/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java
+++ b/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java
@@ -12,10 +12,12 @@
*******************************************************************************/
package org.eclipse.kapua.service.security.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
+import com.google.inject.name.Names;
import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
@@ -23,11 +25,19 @@
import org.eclipse.kapua.commons.configuration.ServiceConfigImplJpaRepository;
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.EventStorerImpl;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.model.query.QueryFactoryImpl;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
import org.eclipse.kapua.model.query.QueryFactory;
@@ -39,8 +49,14 @@
import org.eclipse.kapua.service.authentication.credential.shiro.CredentialMapperImpl;
import org.eclipse.kapua.service.authentication.credential.shiro.CredentialServiceImpl;
import org.eclipse.kapua.service.authentication.credential.shiro.PasswordValidatorImpl;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
import org.eclipse.kapua.service.authentication.shiro.CredentialServiceConfigurationManagerImpl;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaCryptoSetting;
+import org.eclipse.kapua.service.authentication.shiro.utils.AuthenticationUtils;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.group.GroupFactory;
import org.eclipse.kapua.service.authorization.group.GroupService;
import org.eclipse.kapua.service.authorization.group.shiro.GroupFactoryImpl;
@@ -48,6 +64,7 @@
import org.eclipse.kapua.service.authorization.group.shiro.GroupServiceImpl;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator;
import org.eclipse.kapua.service.authorization.role.RoleFactory;
import org.eclipse.kapua.service.authorization.role.RolePermissionFactory;
import org.eclipse.kapua.service.authorization.role.RoleService;
@@ -64,6 +81,9 @@
import org.mockito.Matchers;
import org.mockito.Mockito;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+
@Singleton
public class SecurityLocatorConfiguration {
@@ -76,6 +96,18 @@ public void setupDI() {
@Override
protected void configure() {
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
+
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
try {
@@ -103,7 +135,8 @@ protected void configure() {
Mockito.mock(ServiceConfigurationManager.class),
new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-authorization"),
new RoleImplJpaRepository(jpaRepoConfig),
- new RolePermissionImplJpaRepository(jpaRepoConfig)
+ new RolePermissionImplJpaRepository(jpaRepoConfig),
+ Mockito.mock(PermissionValidator.class)
));
bind(RoleFactory.class).toInstance(new RoleFactoryImpl());
bind(RolePermissionFactory.class).toInstance(new RolePermissionFactoryImpl());
@@ -119,16 +152,21 @@ protected void configure() {
bind(CredentialFactory.class).toInstance(new CredentialFactoryImpl());
final CredentialServiceConfigurationManagerImpl credentialServiceConfigurationManager = new CredentialServiceConfigurationManagerImpl(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- Mockito.mock(RootUserTester.class));
- bind(CredentialService.class).toInstance(new CredentialServiceImpl(
- credentialServiceConfigurationManager,
- mockedAuthorization,
- mockPermissionFactory,
- new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-authorization"),
- new CredentialImplJpaRepository(jpaRepoConfig),
- new CredentialFactoryImpl(),
- new CredentialMapperImpl(new CredentialFactoryImpl()),
- new PasswordValidatorImpl(credentialServiceConfigurationManager)));
+ Mockito.mock(RootUserTester.class),
+ new KapuaAuthenticationSetting());
+ try {
+ bind(CredentialService.class).toInstance(new CredentialServiceImpl(
+ credentialServiceConfigurationManager,
+ mockedAuthorization,
+ mockPermissionFactory,
+ new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-authorization"),
+ new CredentialImplJpaRepository(jpaRepoConfig),
+ new CredentialFactoryImpl(),
+ new CredentialMapperImpl(new CredentialFactoryImpl(), new KapuaAuthenticationSetting(), new AuthenticationUtils(SecureRandom.getInstance("SHA1PRNG"), new KapuaCryptoSetting())),
+ new PasswordValidatorImpl(credentialServiceConfigurationManager), new KapuaAuthenticationSetting()));
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
final UserFactoryImpl userFactory = new UserFactoryImpl();
bind(UserFactory.class).toInstance(userFactory);
final RootUserTester rootUserTester = Mockito.mock(RootUserTester.class);
diff --git a/service/security/test/src/test/resources/locator.xml b/service/security/test/src/test/resources/locator.xml
index 09fe7e04e8c..a117d4aff63 100644
--- a/service/security/test/src/test/resources/locator.xml
+++ b/service/security/test/src/test/resources/locator.xml
@@ -20,5 +20,6 @@
org.eclipse.kapua.commons
org.eclipse.kapua.service.generator.id.sequence
org.eclipse.kapua.service.tag.internal
+ org.eclipse.kapua.translator
diff --git a/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java b/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java
index 29aa756a3a8..5d526827e8f 100644
--- a/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java
+++ b/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java
@@ -38,6 +38,7 @@
import org.eclipse.kapua.service.endpoint.EndpointInfoService;
import org.eclipse.kapua.service.stream.StreamService;
import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.TranslatorHub;
import org.eclipse.kapua.translator.exception.TranslatorNotFoundException;
import org.eclipse.kapua.transport.TransportClientFactory;
import org.eclipse.kapua.transport.TransportFacade;
@@ -64,6 +65,7 @@ public class StreamServiceImpl implements StreamService {
private final EndpointInfoService endpointInfoService;
private final EndpointInfoFactory endpointInfoFactory;
private final TransportClientFactory transportClientFactory;
+ private final TranslatorHub translatorHub;
@Inject
public StreamServiceImpl(
@@ -72,13 +74,15 @@ public StreamServiceImpl(
DeviceRegistryService deviceRegistryService,
EndpointInfoService endpointInfoService,
EndpointInfoFactory endpointInfoFactory,
- TransportClientFactory transportClientFactory) {
+ TransportClientFactory transportClientFactory,
+ TranslatorHub translatorHub) {
this.authorizationService = authorizationService;
this.permissionFactory = permissionFactory;
this.deviceRegistryService = deviceRegistryService;
this.endpointInfoService = endpointInfoService;
this.endpointInfoFactory = endpointInfoFactory;
this.transportClientFactory = transportClientFactory;
+ this.translatorHub = translatorHub;
}
@Override
@@ -221,7 +225,7 @@ private String getEndpointInfoDNS(KapuaDataMessage dataMessage) throws KapuaExce
protected , T extends Message, ?>> Translator getTranslator(Class from, Class to) throws KuraDeviceCallException {
Translator translator;
try {
- translator = Translator.getTranslatorFor(from, to);
+ translator = translatorHub.getTranslatorFor(from, to);
} catch (TranslatorNotFoundException e) {
throw new KuraDeviceCallException(KuraDeviceCallErrorCodes.CALL_ERROR, e, from, to);
}
diff --git a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java
index 3d3de8b93ca..d0a6c602c9c 100644
--- a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java
+++ b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java
@@ -18,8 +18,8 @@
@XmlRegistry
public class SystemInfoXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final SystemInfoFactory SYSTEM_INFO_FACTORY = LOCATOR.getFactory(SystemInfoFactory.class);
+
+ private final SystemInfoFactory systemInfoFactory = KapuaLocator.getInstance().getFactory(SystemInfoFactory.class);
/**
@@ -28,6 +28,6 @@ public class SystemInfoXmlRegistry {
* @return new SystemInfo instance.
*/
public SystemInfo newSystemInfo() {
- return SYSTEM_INFO_FACTORY.newSystemInfo();
+ return systemInfoFactory.newSystemInfo();
}
}
diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java
index 2fa275822ee..236cb4abab9 100644
--- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java
+++ b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java
@@ -13,6 +13,7 @@
package org.eclipse.kapua.service.systeminfo.internal;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.service.systeminfo.SystemInfoFactory;
import org.eclipse.kapua.service.systeminfo.SystemInfoService;
@@ -21,5 +22,6 @@ public class SystemInfoModule extends AbstractKapuaModule {
protected void configureModule() {
bind(SystemInfoService.class).to(SystemInfoServiceImpl.class);
bind(SystemInfoFactory.class).to(SystemInfoFactoryImpl.class);
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
}
}
diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java
index 3de0509d8aa..42f8236f8e2 100644
--- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java
+++ b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java
@@ -14,28 +14,33 @@
import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.commons.setting.system.SystemSettingKey;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.systeminfo.SystemInfo;
import org.eclipse.kapua.service.systeminfo.SystemInfoFactory;
import org.eclipse.kapua.service.systeminfo.SystemInfoService;
+import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class SystemInfoServiceImpl implements SystemInfoService {
- private final KapuaLocator locator = KapuaLocator.getInstance();
+ private final SystemInfoFactory systemInfoFactory;
+ private final SystemSetting systemSetting;
+
+ @Inject
+ public SystemInfoServiceImpl(SystemInfoFactory systemInfoFactory, SystemSetting systemSetting) {
+ this.systemInfoFactory = systemInfoFactory;
+ this.systemSetting = systemSetting;
+ }
@Override
public SystemInfo getSystemInfo() {
- SystemSetting systemSetting = SystemSetting.getInstance();
String version = systemSetting.getString(SystemSettingKey.VERSION);
String revision = systemSetting.getString(SystemSettingKey.BUILD_REVISION);
String branch = systemSetting.getString(SystemSettingKey.BUILD_BRANCH);
String timestamp = systemSetting.getString(SystemSettingKey.BUILD_TIMESTAMP);
String buildNumber = systemSetting.getString(SystemSettingKey.BUILD_NUMBER);
- SystemInfoFactory systemInfoFactory = locator.getFactory(SystemInfoFactory.class);
SystemInfo systemInfo = systemInfoFactory.newSystemInfo();
systemInfo.setVersion(version);
systemInfo.setRevision(revision);
diff --git a/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java b/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java
index 1b953f88ab4..6d472a6a28c 100644
--- a/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java
+++ b/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java
@@ -12,14 +12,24 @@
*******************************************************************************/
package org.eclipse.kapua.service.systeminfo.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
+import com.google.inject.name.Names;
import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.model.query.QueryFactoryImpl;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
import org.eclipse.kapua.model.query.QueryFactory;
@@ -27,7 +37,11 @@
import org.eclipse.kapua.service.account.AccountFactory;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.account.internal.AccountFactoryImpl;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.systeminfo.SystemInfoFactory;
@@ -53,6 +67,17 @@ public void setupDI() {
@Override
protected void configure() {
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
@@ -75,7 +100,7 @@ protected void configure() {
bind(AccountFactory.class).toInstance(Mockito.spy(new AccountFactoryImpl()));
// Inject actual System Info service related services
- bind(SystemInfoService.class).toInstance(new SystemInfoServiceImpl());
+ bind(SystemInfoService.class).toInstance(new SystemInfoServiceImpl(new SystemInfoFactoryImpl(), SystemSetting.getInstance()));
bind(SystemInfoFactory.class).toInstance(new SystemInfoFactoryImpl());
}
diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java
index 299554d25b8..e0934428188 100644
--- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java
+++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java
@@ -19,8 +19,7 @@
@XmlRegistry
public class TagXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final TagFactory TAG_FACTORY = LOCATOR.getFactory(TagFactory.class);
+ private final TagFactory tagFactory = KapuaLocator.getInstance().getFactory(TagFactory.class);
/**
* Creates a new tag instance
@@ -28,7 +27,7 @@ public class TagXmlRegistry {
* @return
*/
public Tag newTag() {
- return TAG_FACTORY.newEntity(null);
+ return tagFactory.newEntity(null);
}
/**
@@ -37,7 +36,7 @@ public Tag newTag() {
* @return
*/
public TagCreator newTagCreator() {
- return TAG_FACTORY.newCreator(null, null);
+ return tagFactory.newCreator(null, null);
}
/**
@@ -46,10 +45,10 @@ public TagCreator newTagCreator() {
* @return
*/
public TagListResult newTagListResult() {
- return TAG_FACTORY.newListResult();
+ return tagFactory.newListResult();
}
public TagQuery newQuery() {
- return TAG_FACTORY.newQuery(null);
+ return tagFactory.newQuery(null);
}
}
diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java
index 1836a136937..4305f4da826 100644
--- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java
+++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.ResourceLimitedServiceConfigurationManagerImpl;
@@ -24,6 +23,7 @@
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManagerCachingWrapper;
import org.eclipse.kapua.commons.configuration.UsedEntitiesCounterImpl;
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
@@ -72,14 +72,15 @@ ServiceConfigurationManager tagServiceConfigurationManager(
TagFactory factory,
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
- TagRepository tagRepository
+ TagRepository tagRepository,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(
TagService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(new KapuaJpaRepositoryConfiguration()),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
diff --git a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java b/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java
index 5e71619c1d2..9e8df12ee9b 100644
--- a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java
+++ b/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java
@@ -99,28 +99,4 @@ public void createTagPerformsInputValidation() {
() -> instance.create(new TagCreatorImpl(new KapuaIdImpl(BigInteger.ONE), null)),
"Does not accept tagCreator with null name");
}
-
-//TODO: FIXME
-// @Test
-// public void createTagCallsCollaboratorsAsExpected() throws KapuaException {
-// final KapuaIdImpl scopeId = new KapuaIdImpl(BigInteger.ONE);
-//
-// final Tag got = instance.create(new TagCreatorImpl(scopeId, "testTag"));
-// Assertions.assertEquals(scopeId, got.getScopeId());
-// Assertions.assertEquals("tag", got.getType());
-// Assertions.assertEquals("testTag", got.getName());
-//
-// Mockito.verify(permissionFactory).newPermission(Mockito.eq(TagDomains.TAG_DOMAIN), Mockito.eq(Actions.write), Mockito.eq(scopeId));
-// Mockito.verify(permissionFactory).newPermission(Mockito.eq(TagDomains.TAG_DOMAIN), Mockito.eq(Actions.read), Mockito.eq(scopeId));
-// Mockito.verify(authorizationService, Mockito.times(2)).checkPermission(Mockito.eq(FAKE_PERMISSION));
-// Mockito.verify(serviceConfigurationManager).checkAllowedEntities(Mockito.eq(scopeId), Mockito.any());
-// Mockito.verify(tagRepository).create(Mockito.any(), Mockito.any());
-// Mockito.verify(tagRepository).count(Mockito.any(), Mockito.any());
-// Mockito.verify(tagFactory).newEntity(scopeId);
-// Mockito.verifyNoMoreInteractions(serviceConfigurationManager);
-// Mockito.verifyNoMoreInteractions(permissionFactory);
-// Mockito.verifyNoMoreInteractions(authorizationService);
-// Mockito.verifyNoMoreInteractions(tagRepository);
-// Mockito.verifyNoMoreInteractions(tagFactory);
-// }
}
\ No newline at end of file
diff --git a/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java b/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java
index 29bb4884da5..b3e747c5b4b 100644
--- a/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java
+++ b/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java
@@ -12,19 +12,32 @@
*******************************************************************************/
package org.eclipse.kapua.service.tag.test;
-import java.util.Collections;
-
+import com.codahale.metrics.MetricRegistry;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Singleton;
+import com.google.inject.name.Names;
+import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.RootUserTester;
import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.EventStorer;
import org.eclipse.kapua.commons.jpa.EventStorerImpl;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.model.query.QueryFactoryImpl;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaMessageFactory;
import org.eclipse.kapua.message.internal.KapuaMessageFactoryImpl;
@@ -34,13 +47,22 @@
import org.eclipse.kapua.service.account.AccountFactory;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.account.internal.AccountFactoryImpl;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
import org.eclipse.kapua.service.authorization.access.GroupQueryHelper;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
+import org.eclipse.kapua.service.authorization.group.GroupService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.device.registry.DeviceFactory;
import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
import org.eclipse.kapua.service.device.registry.DeviceRepository;
+import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettingKeys;
+import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettings;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidation;
+import org.eclipse.kapua.service.device.registry.common.DeviceValidationImpl;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionRepository;
import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService;
@@ -65,13 +87,7 @@
import org.mockito.Matchers;
import org.mockito.Mockito;
-import com.google.inject.AbstractModule;
-import com.google.inject.Guice;
-import com.google.inject.Injector;
-import com.google.inject.Singleton;
-import com.google.inject.name.Names;
-
-import io.cucumber.java.Before;
+import java.util.Collections;
@Singleton
public class TagLocatorConfiguration {
@@ -90,7 +106,18 @@ public void setupDI() {
@Override
protected void configure() {
-
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
+
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration());
@@ -123,6 +150,43 @@ protected void configure() {
final KapuaJpaRepositoryConfiguration jpaRepoConfig = new KapuaJpaRepositoryConfiguration();
final EventStorer eventStorer = new EventStorerImpl(new EventStoreRecordImplJpaRepository(jpaRepoConfig));
bind(TagRepository.class).toInstance(new TagImplJpaRepository(jpaRepoConfig));
+
+ final DeviceConnectionServiceImpl deviceConnectionService = new DeviceConnectionServiceImpl(
+ Mockito.mock(ServiceConfigurationManager.class),
+ mockedAuthorization,
+ permissionFactory,
+ new DeviceConnectionFactoryImpl(),
+ new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"),
+ new DeviceConnectionImplJpaRepository(jpaRepoConfig),
+ Collections.emptyMap(),
+ eventStorer);
+ bind(DeviceEventRepository.class).toInstance(new DeviceEventImplJpaRepository(jpaRepoConfig));
+ final DeviceEventServiceImpl deviceEventService = new DeviceEventServiceImpl(
+ mockedAuthorization,
+ permissionFactory,
+ new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"),
+ new DeviceImplJpaRepository(jpaRepoConfig),
+ new DeviceEventFactoryImpl(),
+ new DeviceEventImplJpaRepository(jpaRepoConfig)
+ );
+
+ final DeviceValidation deviceValidation = new DeviceValidationImpl(new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX),
+ new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX),
+ mockedAuthorization,
+ permissionFactory,
+ Mockito.mock(GroupService.class),
+ deviceConnectionService,
+ deviceEventService,
+ new DeviceImplJpaRepository(jpaRepoConfig),
+ new DeviceFactoryImpl(),
+ new TagServiceImpl(
+ permissionFactory,
+ mockedAuthorization,
+ Mockito.mock(ServiceConfigurationManager.class),
+ new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-tag"),
+ new TagImplJpaRepository(jpaRepoConfig),
+ new TagFactoryImpl())
+ );
bind(DeviceRegistryService.class).toInstance(
new DeviceRegistryServiceImpl(
Mockito.mock(ServiceConfigurationManager.class),
@@ -132,7 +196,8 @@ protected void configure() {
new DeviceImplJpaRepository(jpaRepoConfig),
new DeviceFactoryImpl(),
Mockito.mock(GroupQueryHelper.class),
- eventStorer)
+ eventStorer,
+ deviceValidation)
);
bind(DeviceFactory.class).toInstance(new DeviceFactoryImpl());
@@ -149,15 +214,7 @@ protected void configure() {
bind(DeviceRepository.class).toInstance(new DeviceImplJpaRepository(jpaRepoConfig));
bind(DeviceConnectionRepository.class).toInstance(new DeviceConnectionImplJpaRepository(jpaRepoConfig));
- bind(DeviceEventRepository.class).toInstance(new DeviceEventImplJpaRepository(jpaRepoConfig));
- bind(DeviceEventService.class).toInstance(new DeviceEventServiceImpl(
- mockedAuthorization,
- permissionFactory,
- new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"),
- new DeviceImplJpaRepository(jpaRepoConfig),
- new DeviceEventFactoryImpl(),
- new DeviceEventImplJpaRepository(jpaRepoConfig)
- ));
+ bind(DeviceEventService.class).toInstance(deviceEventService);
bind(DeviceEventFactory.class).toInstance(new DeviceEventFactoryImpl());
bind(KapuaMessageFactory.class).toInstance(new KapuaMessageFactoryImpl());
bind(TagFactory.class).to(TagFactoryImpl.class);
diff --git a/service/tag/test/src/test/resources/locator.xml b/service/tag/test/src/test/resources/locator.xml
index aef999c4253..19dcdbe56e0 100644
--- a/service/tag/test/src/test/resources/locator.xml
+++ b/service/tag/test/src/test/resources/locator.xml
@@ -18,7 +18,7 @@
org.eclipse.kapua.commons
- org.eclipse.kapua.service.generator.id.sequence
- org.eclipse.kapua.service.tag.internal
+ org.eclipse.kapua.service
+ org.eclipse.kapua.translator
diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java
index 7dbefd9d96b..a9b33088658 100644
--- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java
+++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java
@@ -24,8 +24,7 @@
@XmlRegistry
public class UserXmlRegistry {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class);
+ private final UserFactory userFactory = KapuaLocator.getInstance().getFactory(UserFactory.class);
/**
* Creates a new user instance
@@ -33,7 +32,7 @@ public class UserXmlRegistry {
* @return
*/
public User newUser() {
- return USER_FACTORY.newEntity(null);
+ return userFactory.newEntity(null);
}
/**
@@ -42,7 +41,7 @@ public User newUser() {
* @return
*/
public UserCreator newUserCreator() {
- return USER_FACTORY.newCreator(null, null);
+ return userFactory.newCreator(null, null);
}
/**
@@ -51,10 +50,10 @@ public UserCreator newUserCreator() {
* @return
*/
public UserListResult newUserListResult() {
- return USER_FACTORY.newListResult();
+ return userFactory.newListResult();
}
public UserQuery newQuery() {
- return USER_FACTORY.newQuery(null);
+ return userFactory.newQuery(null);
}
}
diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java
index 2fc01215bda..63aaa4f3865 100644
--- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java
+++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java
@@ -18,9 +18,8 @@
@XmlRegistry
public class UserProfileXmlRegistry {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final UserProfileFactory userProfileFactory = locator.getFactory(UserProfileFactory.class);
+ private final UserProfileFactory userProfileFactory = KapuaLocator.getInstance().getFactory(UserProfileFactory.class);
public UserProfile newUserProfile() {
return userProfileFactory.newUserProfile();
diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java
index be18c39af78..d3b84ba2693 100644
--- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java
+++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java
@@ -14,7 +14,6 @@
import com.google.inject.Provides;
import com.google.inject.multibindings.ProvidesIntoSet;
-import org.eclipse.kapua.commons.configuration.AbstractKapuaConfigurableServiceCache;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
import org.eclipse.kapua.commons.configuration.CachingServiceConfigRepository;
import org.eclipse.kapua.commons.configuration.ResourceLimitedServiceConfigurationManagerImpl;
@@ -27,14 +26,16 @@
import org.eclipse.kapua.commons.core.AbstractKapuaModule;
import org.eclipse.kapua.commons.core.ServiceModule;
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl;
+import org.eclipse.kapua.commons.jpa.EntityCacheFactory;
import org.eclipse.kapua.commons.jpa.EventStorer;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.jpa.NamedCacheFactory;
import org.eclipse.kapua.commons.model.domains.Domains;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory;
import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl;
-import org.eclipse.kapua.commons.service.internal.cache.NamedEntityCache;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.event.ServiceEventBusException;
import org.eclipse.kapua.model.domain.Actions;
import org.eclipse.kapua.model.domain.Domain;
@@ -52,8 +53,8 @@
public class UserModule extends AbstractKapuaModule {
@Override
protected void configureModule() {
- bind(UserFactory.class).to(UserFactoryImpl.class);
- bind(UserCacheFactory.class).toInstance(new UserCacheFactory());
+ bind(UserFactory.class).to(UserFactoryImpl.class).in(Singleton.class);
+ bind(KapuaUserSetting.class).in(Singleton.class);
}
@Provides
@@ -95,11 +96,13 @@ public ServiceModule userServiceModule(UserService userService,
PermissionFactory permissionFactory,
KapuaJpaTxManagerFactory txManagerFactory,
EventStoreFactory eventStoreFactory,
- EventStoreRecordRepository eventStoreRecordRepository
+ EventStoreRecordRepository eventStoreRecordRepository,
+ ServiceEventBus serviceEventBus,
+ KapuaUserSetting kapuaUserSetting
) throws ServiceEventBusException {
return new UserServiceModule(
userService,
- KapuaUserSetting.getInstance(),
+ kapuaUserSetting,
new ServiceEventHouseKeeperFactoryImpl(
new EventStoreServiceImpl(
authorizationService,
@@ -108,8 +111,9 @@ public ServiceModule userServiceModule(UserService userService,
eventStoreFactory,
eventStoreRecordRepository
),
- txManagerFactory.create("kapua-user")
- ));
+ txManagerFactory.create("kapua-user"),
+ serviceEventBus
+ ), serviceEventBus);
}
@Provides
@@ -120,13 +124,14 @@ ServiceConfigurationManager userServiceConfigurationManager(
RootUserTester rootUserTester,
AccountChildrenFinder accountChildrenFinder,
UserRepository userRepository,
- KapuaJpaRepositoryConfiguration jpaRepoConfig
+ KapuaJpaRepositoryConfiguration jpaRepoConfig,
+ EntityCacheFactory entityCacheFactory
) {
return new ServiceConfigurationManagerCachingWrapper(
new ResourceLimitedServiceConfigurationManagerImpl(UserService.class.getName(),
new CachingServiceConfigRepository(
new ServiceConfigImplJpaRepository(jpaRepoConfig),
- new AbstractKapuaConfigurableServiceCache().createCache()
+ entityCacheFactory.createCache("AbstractKapuaConfigurableServiceCacheId")
),
rootUserTester,
accountChildrenFinder,
@@ -138,10 +143,10 @@ ServiceConfigurationManager userServiceConfigurationManager(
@Provides
@Singleton
- UserRepository userRepository(UserCacheFactory userCacheFactory, KapuaJpaRepositoryConfiguration jpaRepoConfig) {
+ UserRepository userRepository(NamedCacheFactory namedCacheFactory, KapuaJpaRepositoryConfiguration jpaRepoConfig) {
return new UserCachedRepository(
new UserImplJpaRepository(jpaRepoConfig),
- (NamedEntityCache) userCacheFactory.createCache()
+ namedCacheFactory.createCache("UserId", "UserName")
);
}
}
diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceModule.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceModule.java
index 2be531171db..d34b10afd47 100644
--- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceModule.java
+++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceModule.java
@@ -16,15 +16,17 @@
import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactory;
import org.eclipse.kapua.commons.event.ServiceEventTransactionalModule;
import org.eclipse.kapua.commons.event.ServiceInspector;
+import org.eclipse.kapua.event.ServiceEventBus;
import org.eclipse.kapua.service.user.UserService;
import org.eclipse.kapua.service.user.internal.setting.KapuaUserSetting;
import org.eclipse.kapua.service.user.internal.setting.KapuaUserSettingKeys;
public class UserServiceModule extends ServiceEventTransactionalModule {
- public UserServiceModule(UserService userService, KapuaUserSetting kapuaUserSetting, ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory) {
+ public UserServiceModule(UserService userService, KapuaUserSetting kapuaUserSetting, ServiceEventHouseKeeperFactory serviceEventTransactionalHousekeeperFactory,
+ ServiceEventBus serviceEventBus) {
super(ServiceInspector.getEventBusClients(userService, UserService.class).toArray(new ServiceEventClientConfiguration[0]),
kapuaUserSetting.getString(KapuaUserSettingKeys.USER_EVENT_ADDRESS),
- serviceEventTransactionalHousekeeperFactory);
+ serviceEventTransactionalHousekeeperFactory, serviceEventBus);
}
}
diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java
index deed6104cdd..0e67b2d734c 100644
--- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java
+++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java
@@ -18,21 +18,25 @@
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.util.ArgumentValidator;
import org.eclipse.kapua.commons.util.CommonsValidationRegex;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.user.User;
import org.eclipse.kapua.service.user.UserService;
import org.eclipse.kapua.service.user.profile.UserProfile;
import org.eclipse.kapua.service.user.profile.UserProfileFactory;
import org.eclipse.kapua.service.user.profile.UserProfileService;
+import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class UserProfileServiceImpl implements UserProfileService {
- private final KapuaLocator locator = KapuaLocator.getInstance();
- private final UserService userService = locator.getService(UserService.class);
- private final UserProfileFactory userProfileFactory = locator.getFactory(UserProfileFactory.class);
+ private final UserService userService;
+ private final UserProfileFactory userProfileFactory;
+ @Inject
+ public UserProfileServiceImpl(UserService userService, UserProfileFactory userProfileFactory) {
+ this.userService = userService;
+ this.userProfileFactory = userProfileFactory;
+ }
@Override
public void changeUserProfile(UserProfile userProfile) throws KapuaException {
diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/setting/KapuaUserSetting.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/setting/KapuaUserSetting.java
index 15fcc709c94..7a1433e3645 100644
--- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/setting/KapuaUserSetting.java
+++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/setting/KapuaUserSetting.java
@@ -14,41 +14,25 @@
import org.eclipse.kapua.commons.setting.AbstractKapuaSetting;
+import javax.inject.Inject;
+
/**
* Class that offers access to user settings
*
- *
* @since 1.0
- *
*/
public class KapuaUserSetting extends AbstractKapuaSetting {
/**
* Resource file from which source properties.
- *
*/
private static final String USER_SETTING_RESOURCE = "kapua-user-setting.properties";
- /**
- * Singleton instance of this {@link Class}.
- *
- */
- private static final KapuaUserSetting INSTANCE = new KapuaUserSetting();
-
/**
* Initialize the {@link AbstractKapuaSetting} with the {@link KapuaUserSettingKeys#USER_KEY} value.
- *
*/
- private KapuaUserSetting() {
+ @Inject
+ public KapuaUserSetting() {
super(USER_SETTING_RESOURCE);
}
-
- /**
- * Gets a singleton instance of {@link KapuaUserSetting}.
- *
- * @return A singleton instance of JmsClientSetting.
- */
- public static KapuaUserSetting getInstance() {
- return INSTANCE;
- }
}
diff --git a/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java b/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java
index 6a7e9dd2bbe..a7aaecbb482 100644
--- a/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java
+++ b/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java
@@ -12,10 +12,12 @@
*******************************************************************************/
package org.eclipse.kapua.service.user.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
+import com.google.inject.name.Names;
import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.AccountChildrenFinder;
@@ -24,16 +26,29 @@
import org.eclipse.kapua.commons.configuration.ServiceConfigImplJpaRepository;
import org.eclipse.kapua.commons.configuration.UsedEntitiesCounterImpl;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.EventStorerImpl;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
import org.eclipse.kapua.commons.model.query.QueryFactoryImpl;
import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
import org.eclipse.kapua.model.query.QueryFactory;
import org.eclipse.kapua.qa.common.MockedLocator;
+import org.eclipse.kapua.service.account.AccountService;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
import org.eclipse.kapua.service.user.UserFactory;
@@ -62,8 +77,20 @@ public void setupDI() {
@Override
protected void configure() {
- // Inject mocked Authorization Service method checkPermission
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(AccountService.class).toInstance(Mockito.mock(AccountService.class));
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration());
+ // Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
try {
diff --git a/service/user/test/src/test/resources/locator.xml b/service/user/test/src/test/resources/locator.xml
index 1194d7c42ca..fdcfe0c79e8 100644
--- a/service/user/test/src/test/resources/locator.xml
+++ b/service/user/test/src/test/resources/locator.xml
@@ -18,7 +18,8 @@
org.eclipse.kapua.commons
- org.eclipse.kapua.service.user.internal
- org.eclipse.kapua.service.generator.id.sequence
+ org.eclipse.kapua.service
+ org.eclipse.kapua.security
+ org.eclipse.kapua.translator
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/Translator.java b/translator/api/src/main/java/org/eclipse/kapua/translator/Translator.java
index e16d7c0efee..3d14fc1b76a 100644
--- a/translator/api/src/main/java/org/eclipse/kapua/translator/Translator.java
+++ b/translator/api/src/main/java/org/eclipse/kapua/translator/Translator.java
@@ -16,19 +16,14 @@
import org.eclipse.kapua.message.Channel;
import org.eclipse.kapua.message.Message;
import org.eclipse.kapua.message.Payload;
-import org.eclipse.kapua.translator.cache.TranslatorCache;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidMessageException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
import org.eclipse.kapua.translator.exception.TranslatorException;
-import org.eclipse.kapua.translator.exception.TranslatorNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.validation.constraints.NotNull;
-import java.util.ServiceLoader;
-
/**
* {@link javassist.Translator} defintions.
*
@@ -49,50 +44,6 @@ public abstract class Translator {
private static final Logger LOG = LoggerFactory.getLogger(Translator.class);
- private static final ServiceLoader AVAILABLE_TRANSLATORS;
-
- static {
- try {
- AVAILABLE_TRANSLATORS = ServiceLoader.load(Translator.class);
- } catch (Throwable e) {
- LOG.error("Error while loading available translators!", e);
- throw new ExceptionInInitializerError(e);
- }
- }
-
- /**
- * Return a {@link Translator} for the given {@link Message}s types.
- *
- * This method will lookup instances of {@link Translator} through {@link java.util.ServiceLoader}
- *
- * @param fromMessageClass {@link Message} type from which {@link #translate(Message)}.
- * @param toMessageClass {@link Message} type to which {@link #translate(Message)}.
- * @return The matching {@link Translator} for the given {@link Message}s types.
- * @throws TranslatorNotFoundException if no {@link Translator} if found for the given {@link Message} types.
- * @since 1.0.0
- */
- public static , TO_M extends Message, T extends Translator> T getTranslatorFor(@NotNull Class extends FROM_M> fromMessageClass, @NotNull Class extends TO_M> toMessageClass) {
-
- T cachedTranslator = TranslatorCache.getCachedTranslator(fromMessageClass, toMessageClass);
-
- if (cachedTranslator != null) {
- return cachedTranslator;
- }
-
- synchronized (AVAILABLE_TRANSLATORS) {
- for (Translator translator : AVAILABLE_TRANSLATORS) {
- if ((fromMessageClass.isAssignableFrom(translator.getClassFrom())) &&
- toMessageClass.isAssignableFrom(translator.getClassTo())) {
- TranslatorCache.cacheTranslator(fromMessageClass, toMessageClass, translator);
-
- return (T) translator;
- }
- }
- }
-
- throw new TranslatorNotFoundException(fromMessageClass, toMessageClass);
- }
-
/**
* Translates {@link Message} from the domain FROM_M to the domain TO_M
*
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHub.java b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHub.java
new file mode 100644
index 00000000000..a136cc8d009
--- /dev/null
+++ b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHub.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator;
+
+import org.eclipse.kapua.message.Message;
+
+import javax.validation.constraints.NotNull;
+
+public interface TranslatorHub {
+
+ >
+ TRANSLATOR getTranslatorFor(
+ @NotNull Class extends FROM_MESSAGE> fromMessageClass,
+ @NotNull Class extends TO_MESSAGE> toMessageClass);
+}
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubImpl.java b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubImpl.java
new file mode 100644
index 00000000000..b42175157fc
--- /dev/null
+++ b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubImpl.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator;
+
+import com.google.inject.Inject;
+import org.eclipse.kapua.message.Message;
+import org.eclipse.kapua.translator.exception.TranslatorNotFoundException;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class TranslatorHubImpl implements TranslatorHub {
+ private final Set availableTranslators;
+
+ /**
+ * Sometimes just translators-api is imported a dependency - with no implementation class. In such cases, there is not Translator implementation to inject.
+ * In order to be able to inject an empty list of Translators, this trick must be used, as java does not support default parameters and guice does not support optional injection in the constructors.
+ * The static class uses optional setter injection, providing a default value as fallback at the same time.
+ * https://github.com/google/guice/wiki/FrequentlyAskedQuestions#how-do-i-inject-a-method-interceptor
+ */
+ static class TranslatorsHolder {
+ @Inject(optional = true)
+ Set value = new HashSet<>();
+ }
+
+ @Inject
+ public TranslatorHubImpl(TranslatorsHolder availableTranslators) {
+ this.availableTranslators = availableTranslators.value;
+ }
+
+ @Override
+ public > TRANSLATOR getTranslatorFor(Class extends FROM_MESSAGE> fromMessageClass, Class extends TO_MESSAGE> toMessageClass) {
+ return this.availableTranslators
+ .stream()
+ .filter(t -> fromMessageClass != null)
+ .filter(t -> toMessageClass != null)
+ .filter(t -> fromMessageClass.isAssignableFrom(t.getClassFrom()))
+ .filter(t -> toMessageClass.isAssignableFrom(t.getClassTo()))
+ .map(t -> (TRANSLATOR) t)
+ .findFirst()
+ .orElseThrow(() -> new TranslatorNotFoundException(fromMessageClass, toMessageClass));
+ }
+}
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubModule.java b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubModule.java
new file mode 100644
index 00000000000..f057901d22b
--- /dev/null
+++ b/translator/api/src/main/java/org/eclipse/kapua/translator/TranslatorHubModule.java
@@ -0,0 +1,23 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator;
+
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+
+public class TranslatorHubModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ bind(TranslatorHub.class).to(TranslatorHubImpl.class);
+ }
+}
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCache.java b/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCache.java
deleted file mode 100644
index 8c3b13fa504..00000000000
--- a/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCache.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.translator.cache;
-
-import org.eclipse.kapua.commons.cache.Cache;
-import org.eclipse.kapua.commons.cache.LocalCache;
-import org.eclipse.kapua.message.Message;
-import org.eclipse.kapua.translator.Translator;
-
-import javax.validation.constraints.NotNull;
-
-/**
- * Local {@link Cache} for {@link Translator}.
- *
- * This has been introduced to avoid each time to look throught the {@link java.util.ServiceLoader} available {@link Class}es.
- *
- * @see Cache
- * @see LocalCache
- * @since 1.2.0
- */
-public class TranslatorCache extends LocalCache> implements Cache> {
-
- private static final TranslatorCache TRANSLATOR_CACHE = new TranslatorCache();
-
- private TranslatorCache() {
- super(50, null);
- }
-
- /**
- * Gets the {@link Translator} for the given {@link Message} classes if cached.
- *
- * @param fromMessageClass The {@link Message} type from which the {@link Translator} {@link Translator#translate(Message)} from.
- * @param toMessageClass The {@link Message} type to which the {@link Translator} {@link Translator#translate(Message)} to.
- * @return The matching cached {@link Translator} or {@code null} if not yet cached.
- * @since 1.2.0
- */
- public static , TO_M extends Message, ?>, T extends Translator> T getCachedTranslator(@NotNull Class extends FROM_M> fromMessageClass, @NotNull Class extends TO_M> toMessageClass) {
- return (T) TRANSLATOR_CACHE.get(new TranslatorCacheKey(fromMessageClass, toMessageClass));
- }
-
- /**
- * Caches the {@link Translator} for the given {@link Message} classes.
- *
- * @param fromMessageClass The {@link Message} type from which the {@link Translator} {@link Translator#translate(Message)} from.
- * @param toMessageClass The {@link Message} type to which the {@link Translator} {@link Translator#translate(Message)} to.
- * @param translator The {@link Translator} to cache.
- * @since 1.2.0
- */
- public static , TO_M extends Message, ?>, T extends Translator> void cacheTranslator(@NotNull Class extends FROM_M> fromMessageClass, @NotNull Class extends TO_M> toMessageClass, T translator) {
- TranslatorCacheKey key = new TranslatorCacheKey(fromMessageClass, toMessageClass);
-
- TRANSLATOR_CACHE.put(key, translator);
- }
-}
diff --git a/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCacheKey.java b/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCacheKey.java
deleted file mode 100644
index ad56e3a554e..00000000000
--- a/translator/api/src/main/java/org/eclipse/kapua/translator/cache/TranslatorCacheKey.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- *******************************************************************************/
-package org.eclipse.kapua.translator.cache;
-
-import com.google.common.base.Objects;
-
-/**
- * {@link TranslatorCache} key {@link Object}.
- *
- * This combines the {@code from} and {@code to} to create a unique reference for the {@link org.eclipse.kapua.translator.Translator}
- * {@link #equals(Object)} and {@link #hashCode()} are {@link Override}n to use only {@link #fromClassName} and {@link #toClassName}
- *
- * @since 1.2.0
- */
-class TranslatorCacheKey {
- final String fromClassName;
- final String toClassName;
- final String toString;
-
- /**
- * Constructor.
- *
- * @param fromClass The {@link org.eclipse.kapua.message.Message} type from which Translate.
- * @param toClass The {@link org.eclipse.kapua.message.Message} type to which Translate.
- * @since 1.2.0
- */
- public TranslatorCacheKey(Class> fromClass, Class> toClass) {
- this.fromClassName = fromClass.getName();
- this.toClassName = toClass.getName();
- this.toString = fromClass.getSimpleName() + " -> " + toClass.getSimpleName();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- TranslatorCacheKey that = (TranslatorCacheKey) o;
- return Objects.equal(fromClassName, that.fromClassName) &&
- Objects.equal(toClassName, that.toClassName);
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(fromClassName, toClassName);
- }
-
- @Override
- public String toString() {
- return toString;
- }
-}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/KapuaKuraTranslatorsModule.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/KapuaKuraTranslatorsModule.java
new file mode 100644
index 00000000000..0915ecc4f51
--- /dev/null
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/KapuaKuraTranslatorsModule.java
@@ -0,0 +1,132 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.multibindings.Multibinder;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
+import org.eclipse.kapua.message.KapuaMessageFactory;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppAssetKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppBundleKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppCommandKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppConfigurationKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppPackageKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppRequestKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorAppSnapshotKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.TranslatorDataKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryBundleExecKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryContainerExecKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryEmptyKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreCertificateKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreCsrKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreKeypairKapuaKura;
+import org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreQueryKapuaKura;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppAssetKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppBundleKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppCommandKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppConfigurationKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppNotifyKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppPackageKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppResponseKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorAppSnapshotKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorDataKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtils;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtilsImpl;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorLifeAppsKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorLifeBirthKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorLifeDisconnectKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.TranslatorLifeMissingKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.event.TranslatorEventConfigurationKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryBundlesKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryContainersKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryListKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryNoContentKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryPackagesKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventorySystemPackagesKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreCsrKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreItemKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreItemsKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreNoContentKuraKapua;
+import org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoresKuraKapua;
+
+public class KapuaKuraTranslatorsModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ final Multibinder translatorMultibinder = Multibinder.newSetBinder(binder(), Translator.class);
+ //org.eclipse.kapua.translator.kapua.kura
+ translatorMultibinder.addBinding().to(TranslatorAppAssetKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppBundleKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppCommandKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppConfigurationKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppPackageKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppRequestKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppSnapshotKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorDataKapuaKura.class);
+ //org.eclipse.kapua.translator.kapua.kura.inventory
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryBundleExecKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryContainerExecKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryEmptyKapuaKura.class);
+ //org.eclipse.kapua.translator.kapua.kura.keystore
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreCertificateKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreCsrKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreKeypairKapuaKura.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreQueryKapuaKura.class);
+ //org.eclipse.kapua.translator.kura.kapua
+ translatorMultibinder.addBinding().to(TranslatorAppAssetKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppBundleKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppCommandKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppConfigurationKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppPackageKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppResponseKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppSnapshotKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorDataKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeAppsKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeBirthKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeDisconnectKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeMissingKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppNotifyKuraKapua.class);
+ //org.eclipse.kapua.translator.kura.kapua.event
+ translatorMultibinder.addBinding().to(TranslatorEventConfigurationKuraKapua.class);
+ //org.eclipse.kapua.translator.kura.kapua.inventory
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryBundlesKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryContainersKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryListKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryNoContentKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventoryPackagesKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppInventorySystemPackagesKuraKapua.class);
+ //org.eclipse.kapua.translator.kura.kapua.keystore
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreItemKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreItemsKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreNoContentKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoreCsrKuraKapua.class);
+ translatorMultibinder.addBinding().to(TranslatorAppKeystoresKuraKapua.class);
+
+ bind(ObjectMapper.class).toInstance(new ObjectMapper()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .setSerializationInclusion(JsonInclude.Include.NON_NULL));
+
+ }
+
+ @Provides
+ @Singleton
+ public TranslatorKuraKapuaUtils translatorKuraKapuaUtils(KapuaMessageFactory kapuaMessageFactory) {
+ return new TranslatorKuraKapuaUtilsImpl(kapuaMessageFactory, SystemSetting.getInstance().getMessageClassifier());
+ }
+}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/AbstractTranslatorKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/AbstractTranslatorKapuaKura.java
index 154e29ed8d4..e4d8b5de0ac 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/AbstractTranslatorKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/AbstractTranslatorKapuaKura.java
@@ -13,12 +13,9 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kapua.kura;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.commons.setting.system.SystemSetting;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaChannel;
import org.eclipse.kapua.message.KapuaMessage;
import org.eclipse.kapua.message.KapuaPayload;
@@ -35,6 +32,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} abstract implementation from {@link KapuaMessage} to {@link KuraRequestMessage}
*
@@ -44,24 +43,21 @@ public abstract class AbstractTranslatorKapuaKura ACCOUNT_SERVICE.find(kapuaMessage.getScopeId()));
+ Account account = KapuaSecurityUtils.doPrivileged(() -> accountService.find(kapuaMessage.getScopeId()));
Device device = null;
if (kapuaMessage.getDeviceId() != null) {
- device = DEVICE_REGISTRY_SERVICE.find(kapuaMessage.getScopeId(), kapuaMessage.getDeviceId());
+ device = deviceRegistryService.find(kapuaMessage.getScopeId(), kapuaMessage.getDeviceId());
}
KuraRequestChannel kuraRequestChannel = translateChannel(kapuaMessage.getChannel());
@@ -101,7 +97,7 @@ protected static String getControlMessageClassifier() {
* @since 1.5.0
*/
protected ObjectMapper getJsonMapper() {
- return JSON_MAPPER;
+ return jsonMapper;
}
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/MethodDictionaryKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/MethodDictionaryKapuaKura.java
index 6e7598afefe..a599d83ee6b 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/MethodDictionaryKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/MethodDictionaryKapuaKura.java
@@ -26,6 +26,7 @@
* @see KuraMethod
* @since 1.0.0
*/
+//TODO: FIXME: promote from static utility to injectable collaborator
public class MethodDictionaryKapuaKura {
/**
@@ -60,19 +61,6 @@ public class MethodDictionaryKapuaKura {
private MethodDictionaryKapuaKura() {
}
- /**
- * Gets the given {@link KapuaMethod} in the matching {@link KuraMethod}
- *
- * @param kapuaMethod The {@link KapuaMethod} to match.
- * @return The matching {@link KuraMethod}
- * @since 1.0.0
- * @deprecated Since 1.2.0. Renamed to {@link #translate(KapuaMethod)}
- */
- @Deprecated
- public static KuraMethod get(KapuaMethod kapuaMethod) {
- return translate(kapuaMethod);
- }
-
/**
* Translates the given {@link KapuaMethod} in the matching {@link KuraMethod}
*
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java
index dd6afac1f51..87059b422ec 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java
@@ -21,6 +21,7 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
+import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory;
import org.eclipse.kapua.service.device.management.asset.DeviceAssets;
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestChannel;
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestMessage;
@@ -29,6 +30,7 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.xml.sax.SAXException;
+import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.StringWriter;
@@ -42,6 +44,13 @@
*/
public class TranslatorAppAssetKapuaKura extends AbstractTranslatorKapuaKura {
+ private final DeviceAssetFactory deviceAssetFactory;
+
+ @Inject
+ public TranslatorAppAssetKapuaKura(DeviceAssetFactory deviceAssetFactory) {
+ this.deviceAssetFactory = deviceAssetFactory;
+ }
+
@Override
protected KuraRequestChannel translateChannel(AssetRequestChannel kapuaChannel) throws InvalidChannelException {
try {
@@ -70,7 +79,7 @@ protected KuraRequestPayload translatePayload(AssetRequestPayload kapuaPayload)
try {
DeviceAssets deviceAssets;
try {
- deviceAssets = kapuaPayload.getDeviceAssets();
+ deviceAssets = kapuaPayload.getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult());
} catch (UnsupportedEncodingException | JAXBException | SAXException e) {
throw new InvalidPayloadException(e, kapuaPayload);
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppCommandKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppCommandKapuaKura.java
index 39825ee5c18..c10f62665c2 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppCommandKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppCommandKapuaKura.java
@@ -32,6 +32,7 @@
*
* @since 1.0
*/
+//TODO: FIXME: promote from static utility to injectable collaborator
public class TranslatorAppCommandKapuaKura extends AbstractTranslatorKapuaKura {
private static final Map PROPERTIES_DICTIONARY = new EnumMap<>(CommandAppProperties.class);
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java
index b4f2c89ae8c..81dc1aef292 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java
@@ -30,12 +30,14 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
+import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestChannel;
import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestMessage;
import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestPayload;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -48,6 +50,9 @@
*/
public class TranslatorAppConfigurationKapuaKura extends AbstractTranslatorKapuaKura {
+ @Inject
+ protected DeviceConfigurationFactory deviceConfigurationFactory;
+
@Override
protected KuraRequestChannel translateChannel(ConfigurationRequestChannel kapuaChannel) throws InvalidChannelException {
try {
@@ -84,7 +89,7 @@ protected KuraRequestPayload translatePayload(ConfigurationRequestPayload kapuaP
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (kapuaPayload.hasBody()) {
- DeviceConfiguration kapuaDeviceConfiguration = kapuaPayload.getDeviceConfigurations();
+ DeviceConfiguration kapuaDeviceConfiguration = kapuaPayload.getDeviceConfigurations().orElse(deviceConfigurationFactory.newConfigurationInstance());
KuraDeviceConfiguration kuraDeviceConfiguration = translate(kapuaDeviceConfiguration);
byte[] body;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppPackageKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppPackageKapuaKura.java
index cae215bdd29..61976226b6b 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppPackageKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppPackageKapuaKura.java
@@ -38,40 +38,39 @@
*/
public class TranslatorAppPackageKapuaKura extends AbstractTranslatorKapuaKura {
- private static final Map PROPERTIES_DICTIONARY = new EnumMap<>(PackageAppProperties.class);
+ private final Map propertiesDictionary = new EnumMap<>(PackageAppProperties.class);
- static {
+ public TranslatorAppPackageKapuaKura() {
// Commons properties
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_OPERATION_ID, PackageMetrics.APP_METRIC_PACKAGE_OPERATION_ID);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT, PackageMetrics.APP_METRIC_PACKAGE_REBOOT);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT_DELAY, PackageMetrics.APP_METRIC_PACKAGE_REBOOT_DELAY);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_OPERATION_ID, PackageMetrics.APP_METRIC_PACKAGE_OPERATION_ID);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT, PackageMetrics.APP_METRIC_PACKAGE_REBOOT);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT_DELAY, PackageMetrics.APP_METRIC_PACKAGE_REBOOT_DELAY);
// Download properties
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_URI, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_URI);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_NAME);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_VERSION);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_USERNAME, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_USERNAME);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PASSWORD, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PASSWORD);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_HASH, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_HASH);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_TYPE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL_SYSTEM_UPDATE);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_INSTALL, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_URI, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_URI);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_NAME);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PACKAGE_VERSION);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_USERNAME, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_USERNAME);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PASSWORD, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PASSWORD);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_HASH, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_HASH);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_TYPE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL_SYSTEM_UPDATE);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_INSTALL, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL);
// Download advanced properties
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_RESTART, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_FORCE);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_SIZE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_BLOCK_SIZE);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_DELAY, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_BLOCK_DELAY);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_TIMEOUT, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_TIMEOUT);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_RESTART, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_FORCE);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_SIZE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_BLOCK_SIZE);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_DELAY, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_BLOCK_DELAY);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_TIMEOUT, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_TIMEOUT);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI, PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI);
// Install properties
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_INSTALL_PACKAGE_NAME);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_INSTALL_PACKAGE_VERSION);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_INSTALL_PACKAGE_NAME);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_INSTALL_PACKAGE_VERSION);
// Uninstall properties
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_UNINSTALL_PACKAGE_NAME);
- PROPERTIES_DICTIONARY.put(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_UNINSTALL_PACKAGE_VERSION);
-
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_NAME, PackageMetrics.APP_METRIC_PACKAGE_UNINSTALL_PACKAGE_NAME);
+ propertiesDictionary.put(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_VERSION, PackageMetrics.APP_METRIC_PACKAGE_UNINSTALL_PACKAGE_VERSION);
}
@Override
@@ -113,37 +112,37 @@ protected KuraRequestPayload translatePayload(PackageRequestPayload kapuaPayload
KapuaId operationId = kapuaPayload.getOperationId();
if (operationId != null) {
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_OPERATION_ID).getName(), operationId.getId().longValue());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_OPERATION_ID).getName(), operationId.getId().longValue());
}
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT).getName(), kapuaPayload.isReboot());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT_DELAY).getName(), kapuaPayload.getRebootDelay());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT).getName(), kapuaPayload.isReboot());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_REBOOT_DELAY).getName(), kapuaPayload.getRebootDelay());
if (kapuaPayload.isDownloadRequest()) {
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_URI).getName(), kapuaPayload.getPackageDownloadURI().toString());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_NAME).getName(), kapuaPayload.getPackageDownloadName());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_VERSION).getName(), kapuaPayload.getPackageDownloadVersion());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_USERNAME).getName(), kapuaPayload.getPackageDownloadUsername());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PASSWORD).getName(), kapuaPayload.getPackageDownloadPassword());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_HASH).getName(), kapuaPayload.getPackageDownloadFileHash());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_TYPE).getName(), FileType.EXECUTABLE_SCRIPT.equals(kapuaPayload.getPackageDownloadFileType()));
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_URI).getName(), kapuaPayload.getPackageDownloadURI().toString());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_NAME).getName(), kapuaPayload.getPackageDownloadName());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_VERSION).getName(), kapuaPayload.getPackageDownloadVersion());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_USERNAME).getName(), kapuaPayload.getPackageDownloadUsername());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PASSWORD).getName(), kapuaPayload.getPackageDownloadPassword());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_HASH).getName(), kapuaPayload.getPackageDownloadFileHash());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_FILE_TYPE).getName(), FileType.EXECUTABLE_SCRIPT.equals(kapuaPayload.getPackageDownloadFileType()));
metrics.put(PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_PROTOCOL.getName(), "HTTP");
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_INSTALL).getName(), kapuaPayload.isPackageDownloadInstall());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_PACKAGE_INSTALL).getName(), kapuaPayload.isPackageDownloadInstall());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_RESTART).getName(), kapuaPayload.getPackageDownloadRestart());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_SIZE).getName(), kapuaPayload.getPackageDownloadBlockSize());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_DELAY).getName(), kapuaPayload.getPackageDownloadBlockDelay());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_TIMEOUT).getName(), kapuaPayload.getPackageDownloadBlockTimeout());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE).getName(), kapuaPayload.getPackageDownloadNotifyBlockSize());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI).getName(), kapuaPayload.getPackageDownloadInstallVerifierURI());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_RESTART).getName(), kapuaPayload.getPackageDownloadRestart());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_SIZE).getName(), kapuaPayload.getPackageDownloadBlockSize());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_DELAY).getName(), kapuaPayload.getPackageDownloadBlockDelay());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_BLOCK_TIMEOUT).getName(), kapuaPayload.getPackageDownloadBlockTimeout());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_NOTIFY_BLOCK_SIZE).getName(), kapuaPayload.getPackageDownloadNotifyBlockSize());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_DOWNLOAD_INSTALL_VERIFIER_URI).getName(), kapuaPayload.getPackageDownloadInstallVerifierURI());
} else if (kapuaPayload.isInstallRequest()) {
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_NAME).getName(), kapuaPayload.getPackageInstallName());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_VERSION).getName(), kapuaPayload.getPackageInstallVersion());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_NAME).getName(), kapuaPayload.getPackageInstallName());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_INSTALL_PACKAGE_VERSION).getName(), kapuaPayload.getPackageInstallVersion());
metrics.put(PackageMetrics.APP_METRIC_PACKAGE_INSTALL_SYS_UPDATE.getName(), false);
} else if (kapuaPayload.isUninstallRequest()) {
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_NAME).getName(), kapuaPayload.getPackageUninstallName());
- metrics.put(PROPERTIES_DICTIONARY.get(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_VERSION).getName(), kapuaPayload.getPackageUninstallVersion());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_NAME).getName(), kapuaPayload.getPackageUninstallName());
+ metrics.put(propertiesDictionary.get(PackageAppProperties.APP_PROPERTY_PACKAGE_UNINSTALL_PACKAGE_VERSION).getName(), kapuaPayload.getPackageUninstallVersion());
}
// Return Kura Payload
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorDataKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorDataKapuaKura.java
index d52425e985b..b3e14166aa0 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorDataKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorDataKapuaKura.java
@@ -14,7 +14,6 @@
import org.eclipse.kapua.KapuaEntityNotFoundException;
import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.data.KapuaDataChannel;
import org.eclipse.kapua.message.device.data.KapuaDataMessage;
import org.eclipse.kapua.message.device.data.KapuaDataPayload;
@@ -29,6 +28,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KapuaDataMessage} to {@link KuraDataMessage}
*
@@ -36,14 +37,13 @@
*/
public class TranslatorDataKapuaKura extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
+ @Inject
+ private AccountService accountService;
@Override
public KuraDataMessage translate(KapuaDataMessage kapuaMessage) throws TranslateException {
try {
- Account account = ACCOUNT_SERVICE.find(kapuaMessage.getScopeId());
+ Account account = accountService.find(kapuaMessage.getScopeId());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kapuaMessage.getScopeId());
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java
index eba25e12af4..da1655513d7 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java
@@ -20,6 +20,7 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundleExecRequestMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestChannel;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestPayload;
@@ -30,6 +31,8 @@
import org.eclipse.kapua.translator.kapua.kura.AbstractTranslatorKapuaKura;
import org.eclipse.kapua.translator.kapua.kura.TranslatorKapuaKuraUtils;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link InventoryBundleExecRequestMessage} to {@link KuraRequestMessage}
*
@@ -37,7 +40,15 @@
*/
public class TranslatorAppInventoryBundleExecKapuaKura extends AbstractTranslatorKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+ private final DeviceInventoryManagementFactory deviceInventoryManagementFactory;
+
+ @Inject
+ public TranslatorAppInventoryBundleExecKapuaKura(DeviceManagementSetting deviceManagementSetting,
+ DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ this.deviceInventoryManagementFactory = deviceInventoryManagementFactory;
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestChannel translateChannel(InventoryRequestChannel inventoryRequestChannel) throws InvalidChannelException {
@@ -68,7 +79,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (inventoryRequestPayload.hasBody()) {
- DeviceInventoryBundle deviceInventoryBundle = inventoryRequestPayload.getDeviceInventoryBundle();
+ DeviceInventoryBundle deviceInventoryBundle = inventoryRequestPayload.getDeviceInventoryBundle().orElse(deviceInventoryManagementFactory.newDeviceInventoryBundle());
KuraInventoryBundle kuraInventoryBundle = new KuraInventoryBundle();
kuraInventoryBundle.setId(Integer.valueOf(deviceInventoryBundle.getId()));
@@ -77,7 +88,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR
kuraInventoryBundle.setState(deviceInventoryBundle.getStatus());
kuraInventoryBundle.setSigned(deviceInventoryBundle.getSigned());
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraInventoryBundle).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraInventoryBundle).getBytes(charEncoding));
}
return kuraRequestPayload;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java
index 933c58d4826..55dddfe858b 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java
@@ -20,6 +20,7 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryContainerExecRequestMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestChannel;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestPayload;
@@ -30,6 +31,8 @@
import org.eclipse.kapua.translator.kapua.kura.AbstractTranslatorKapuaKura;
import org.eclipse.kapua.translator.kapua.kura.TranslatorKapuaKuraUtils;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link InventoryContainerExecRequestMessage} to {@link KuraRequestMessage}
*
@@ -37,7 +40,14 @@
*/
public class TranslatorAppInventoryContainerExecKapuaKura extends AbstractTranslatorKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+ private final DeviceInventoryManagementFactory deviceInventoryManagementFactory;
+
+ @Inject
+ public TranslatorAppInventoryContainerExecKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ this.deviceInventoryManagementFactory = deviceInventoryManagementFactory;
+ this.charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestChannel translateChannel(InventoryRequestChannel inventoryRequestChannel) throws InvalidChannelException {
@@ -68,7 +78,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (inventoryRequestPayload.hasBody()) {
- DeviceInventoryContainer deviceInventoryContainer = inventoryRequestPayload.getDeviceInventoryContainer();
+ DeviceInventoryContainer deviceInventoryContainer = inventoryRequestPayload.getDeviceInventoryContainer().orElse(deviceInventoryManagementFactory.newDeviceInventoryContainer());
KuraInventoryContainer kuraInventoryContainer = new KuraInventoryContainer();
kuraInventoryContainer.setName(deviceInventoryContainer.getName());
@@ -78,7 +88,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR
kuraInventoryContainer.setState(deviceInventoryContainer.getState().name());
}
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraInventoryContainer).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraInventoryContainer).getBytes(charEncoding));
}
return kuraRequestPayload;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java
index a38662739a6..ffcb6cff617 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java
@@ -15,6 +15,7 @@
import org.eclipse.kapua.service.device.call.kura.model.keystore.KeystoreMetrics;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestChannel;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload;
@@ -29,6 +30,11 @@
* @since 1.5.0
*/
public abstract class AbstractTranslatorAppKeystoreKapuaKura> extends AbstractTranslatorKapuaKura {
+ protected final DeviceKeystoreManagementFactory deviceKeystoreManagementFactory;
+
+ public AbstractTranslatorAppKeystoreKapuaKura(DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory;
+ }
@Override
protected KuraRequestChannel translateChannel(KeystoreRequestChannel kapuaChannel) throws InvalidChannelException {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java
index 1af6c13037b..843e6029c09 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java
@@ -17,12 +17,15 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCertificateRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KeystoreCertificateRequestMessage} to {@link KuraRequestMessage}
*
@@ -30,7 +33,13 @@
*/
public class TranslatorAppKeystoreCertificateKapuaKura extends AbstractTranslatorAppKeystoreKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+
+ @Inject
+ public TranslatorAppKeystoreCertificateKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceKeystoreManagementFactory);
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreRequestPayload) throws InvalidPayloadException {
@@ -38,14 +47,14 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (keystoreRequestPayload.hasBody()) {
- DeviceKeystoreCertificate keystoreCertificate = keystoreRequestPayload.getCertificate();
+ DeviceKeystoreCertificate keystoreCertificate = keystoreRequestPayload.getCertificate().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCertificate());
KuraKeystoreCertificate kuraKeystoreCertificate = new KuraKeystoreCertificate();
kuraKeystoreCertificate.setKeystoreServicePid(keystoreCertificate.getKeystoreId());
kuraKeystoreCertificate.setAlias(keystoreCertificate.getAlias());
kuraKeystoreCertificate.setCertificate(keystoreCertificate.getCertificate());
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreCertificate).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreCertificate).getBytes(charEncoding));
}
return kuraRequestPayload;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java
index dddbb246518..c1b3adae39e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java
@@ -17,12 +17,15 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCsrRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KeystoreCsrRequestMessage} to {@link KuraRequestMessage}
*
@@ -30,7 +33,13 @@
*/
public class TranslatorAppKeystoreCsrKapuaKura extends AbstractTranslatorAppKeystoreKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+
+ @Inject
+ public TranslatorAppKeystoreCsrKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceKeystoreManagementFactory);
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreRequestPayload) throws InvalidPayloadException {
@@ -38,7 +47,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (keystoreRequestPayload.hasBody()) {
- DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = keystoreRequestPayload.getCSRInfo();
+ DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = keystoreRequestPayload.getCSRInfo().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCSRInfo());
KuraKeystoreCSRInfo kuraKeystoreCSRInfo = new KuraKeystoreCSRInfo();
kuraKeystoreCSRInfo.setKeystoreServicePid(deviceKeystoreCSRInfo.getKeystoreId());
@@ -46,7 +55,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq
kuraKeystoreCSRInfo.setSignatureAlgorithm(deviceKeystoreCSRInfo.getSignatureAlgorithm());
kuraKeystoreCSRInfo.setAttributes(deviceKeystoreCSRInfo.getAttributes());
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreCSRInfo).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreCSRInfo).getBytes(charEncoding));
}
return kuraRequestPayload;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java
index 27ec19f9a76..71931dbf21e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java
@@ -17,12 +17,15 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreKeypairRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KeystoreKeypairRequestMessage} to {@link KuraRequestMessage}
*
@@ -30,7 +33,13 @@
*/
public class TranslatorAppKeystoreKeypairKapuaKura extends AbstractTranslatorAppKeystoreKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+
+ @Inject
+ public TranslatorAppKeystoreKeypairKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceKeystoreManagementFactory);
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreRequestPayload) throws InvalidPayloadException {
@@ -38,7 +47,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (keystoreRequestPayload.hasBody()) {
- DeviceKeystoreKeypair deviceKeystoreKeypair = keystoreRequestPayload.getKeypair();
+ DeviceKeystoreKeypair deviceKeystoreKeypair = keystoreRequestPayload.getKeypair().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreKeypair());
KuraKeystoreKeypair kuraKeystoreKeypair = new KuraKeystoreKeypair();
kuraKeystoreKeypair.setKeystoreServicePid(deviceKeystoreKeypair.getKeystoreId());
@@ -48,7 +57,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq
kuraKeystoreKeypair.setSignatureAlgorithm(deviceKeystoreKeypair.getSignatureAlgorithm());
kuraKeystoreKeypair.setAttributes(deviceKeystoreKeypair.getAttributes());
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreKeypair).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraKeystoreKeypair).getBytes(charEncoding));
}
return kuraRequestPayload;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java
index 9f65b69e583..f33b50ecbac 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java
@@ -17,12 +17,15 @@
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreQueryRequestMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload;
import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KeystoreQueryRequestMessage} to {@link KuraRequestMessage}
*
@@ -30,7 +33,13 @@
*/
public class TranslatorAppKeystoreQueryKapuaKura extends AbstractTranslatorAppKeystoreKapuaKura {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ private final String charEncoding;
+
+ @Inject
+ public TranslatorAppKeystoreQueryKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceKeystoreManagementFactory);
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ }
@Override
protected KuraRequestPayload translatePayload(KeystoreRequestPayload kapuaPayload) throws InvalidPayloadException {
@@ -38,7 +47,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload kapuaPayloa
KuraRequestPayload kuraRequestPayload = new KuraRequestPayload();
if (kapuaPayload.hasBody()) {
- DeviceKeystoreItemQuery deviceKeystoreItemQuery = kapuaPayload.getItemQuery();
+ DeviceKeystoreItemQuery deviceKeystoreItemQuery = kapuaPayload.getItemQuery().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItemQuery());
if (deviceKeystoreItemQuery.hasFilters()) {
@@ -46,7 +55,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload kapuaPayloa
kuraItemQuery.setKeystoreServicePid(deviceKeystoreItemQuery.getKeystoreId());
kuraItemQuery.setAlias(deviceKeystoreItemQuery.getAlias());
- kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraItemQuery).getBytes(CHAR_ENCODING));
+ kuraRequestPayload.setBody(getJsonMapper().writeValueAsString(kuraItemQuery).getBytes(charEncoding));
}
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractSimpleTranslatorResponseKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractSimpleTranslatorResponseKuraKapua.java
index 5d13f6e6017..10de3437330 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractSimpleTranslatorResponseKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractSimpleTranslatorResponseKuraKapua.java
@@ -13,11 +13,9 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua;
-import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.util.xml.XmlUtil;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMetrics;
@@ -36,6 +34,7 @@
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
@@ -47,15 +46,13 @@
public abstract class AbstractSimpleTranslatorResponseKuraKapua>
extends AbstractTranslatorResponseKuraKapua {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
- private static final boolean SHOW_STACKTRACE = DeviceManagementSetting.getInstance().getBoolean(DeviceManagementSettingKey.SHOW_STACKTRACE, false);
+ private final String charEncoding;
+ private final boolean showStacktrace;
- private static final ObjectMapper JSON_MAPPER = new ObjectMapper()
- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
- .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ @Inject
+ private ObjectMapper jsonMapper;
+ @Inject
+ private GenericRequestFactory genericRequestFactory;
private final Class messageClazz;
private final Class payloadClazz;
@@ -67,15 +64,15 @@ public abstract class AbstractSimpleTranslatorResponseKuraKapua messageClazz, Class payloadClazz) {
+ public AbstractSimpleTranslatorResponseKuraKapua(DeviceManagementSetting deviceManagementSetting, Class messageClazz, Class payloadClazz) {
this.messageClazz = messageClazz;
this.payloadClazz = payloadClazz;
+ charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING);
+ showStacktrace = deviceManagementSetting.getBoolean(DeviceManagementSettingKey.SHOW_STACKTRACE, false);
}
@Override
protected TO_M createMessage() throws KapuaException {
- GenericRequestFactory genericRequestFactory = LOCATOR.getFactory(GenericRequestFactory.class);
-
try {
if (this.messageClazz.equals(GenericResponseMessage.class)) {
return this.messageClazz.cast(genericRequestFactory.newResponseMessage());
@@ -103,8 +100,6 @@ public Class getClassTo() {
@Override
protected TO_P translatePayload(KuraResponsePayload kuraResponsePayload) throws InvalidPayloadException {
try {
- GenericRequestFactory genericRequestFactory = LOCATOR.getFactory(GenericRequestFactory.class);
-
TO_P appResponsePayload;
if (payloadClazz.equals(GenericResponsePayload.class)) {
appResponsePayload = this.payloadClazz.cast(genericRequestFactory.newResponsePayload());
@@ -114,7 +109,7 @@ protected TO_P translatePayload(KuraResponsePayload kuraResponsePayload) throws
appResponsePayload.setExceptionMessage(kuraResponsePayload.getExceptionMessage());
- if (SHOW_STACKTRACE) {
+ if (showStacktrace) {
appResponsePayload.setExceptionStack(kuraResponsePayload.getExceptionStack());
kuraResponsePayload.getMetrics().remove(KuraResponseMetrics.EXCEPTION_STACK.getName());
}
@@ -139,7 +134,7 @@ protected TO_P translatePayload(KuraResponsePayload kuraResponsePayload) throws
* @since 1.5.0
*/
protected T readXmlBodyAs(@NotNull byte[] bytesToRead, @NotNull Class returnAs) throws InvalidBodyException {
- String bodyString = readBodyAsString(bytesToRead, CHAR_ENCODING);
+ String bodyString = readBodyAsString(bytesToRead, charEncoding);
try {
return XmlUtil.unmarshal(bodyString, returnAs);
@@ -160,7 +155,7 @@ protected T readXmlBodyAs(@NotNull byte[] bytesToRead, @NotNull Class ret
* @since 1.5.0
*/
protected T readJsonBodyAs(@NotNull byte[] bytesToRead, @NotNull Class returnAs) throws InvalidBodyException {
- String bodyString = readBodyAsString(bytesToRead, CHAR_ENCODING);
+ String bodyString = readBodyAsString(bytesToRead, charEncoding);
try {
return getJsonMapper().readValue(bodyString, returnAs);
@@ -195,6 +190,6 @@ protected String readBodyAsString(@NotNull byte[] body, @NotNull String encoding
* @since 1.5.0
*/
protected ObjectMapper getJsonMapper() {
- return JSON_MAPPER;
+ return jsonMapper;
}
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorKuraKapua.java
index aad54b3a6bc..f85bdb30422 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorKuraKapua.java
@@ -15,7 +15,6 @@
import org.eclipse.kapua.KapuaEntityNotFoundException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.KapuaChannel;
import org.eclipse.kapua.message.KapuaMessage;
import org.eclipse.kapua.message.KapuaPayload;
@@ -30,6 +29,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} {@code abstract} implementation from {@link KuraResponseMessage} to {@link KapuaMessage}
*
@@ -37,14 +38,13 @@
*/
public abstract class AbstractTranslatorKuraKapua> extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
+ @Inject
+ private AccountService accountService;
@Override
public TO_M translate(KuraResponseMessage kuraMessage) throws TranslateException {
try {
- Account account = KapuaSecurityUtils.doPrivileged(() -> ACCOUNT_SERVICE.findByName(kuraMessage.getChannel().getScope()));
+ Account account = KapuaSecurityUtils.doPrivileged(() -> accountService.findByName(kuraMessage.getChannel().getScope()));
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraMessage.getChannel().getScope());
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorResponseKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorResponseKuraKapua.java
index 813e63200d9..b175a73ffdb 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorResponseKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/AbstractTranslatorResponseKuraKapua.java
@@ -27,6 +27,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link org.eclipse.kapua.translator.Translator} {@code abstract} implementation from {@link KuraResponseMessage} to {@link KapuaResponseMessage}
*
@@ -35,10 +37,11 @@
public abstract class AbstractTranslatorResponseKuraKapua> extends AbstractTranslatorKuraKapua {
private static final String CONTROL_MESSAGE_CLASSIFIER = SystemSetting.getInstance().getMessageClassifier();
+ @Inject
+ protected TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
protected TO_M translateMessage(KuraResponseMessage kuraMessage, Account account) throws TranslateException {
-
try {
// Translate channel
TO_C bundleResponseChannel = translateChannel(kuraMessage.getChannel());
@@ -54,7 +57,7 @@ protected TO_M translateMessage(KuraResponseMessage kuraMessage, Account account
kapuaMessage.setCapturedOn(kuraMessage.getPayload().getTimestamp());
kapuaMessage.setSentOn(kuraMessage.getPayload().getTimestamp());
kapuaMessage.setReceivedOn(kuraMessage.getTimestamp());
- kapuaMessage.setResponseCode(TranslatorKuraKapuaUtils.translate(kuraMessage.getPayload().getResponseCode()));
+ kapuaMessage.setResponseCode(translatorKuraKapuaUtils.translate(kuraMessage.getPayload().getResponseCode()));
// Return Kapua Message
return kapuaMessage;
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/MethodDictionaryKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/MethodDictionaryKuraKapua.java
deleted file mode 100644
index df46ec7d180..00000000000
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/MethodDictionaryKuraKapua.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
- *
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Eurotech - initial API and implementation
- * Red Hat Inc
- *******************************************************************************/
-package org.eclipse.kapua.translator.kura.kapua;
-
-import org.eclipse.kapua.service.device.call.kura.KuraMethod;
-import org.eclipse.kapua.service.device.management.message.KapuaMethod;
-
-import java.util.EnumMap;
-import java.util.Map;
-
-/**
- * Dictionary class to define actions translations between {@link org.eclipse.kapua.service.device.call.kura.Kura} domain to Kapua domain.
- *
- * @see KapuaMethod
- * @see KuraMethod
- * @since 1.0.0
- */
-public class MethodDictionaryKuraKapua {
-
- /**
- * Translations dictionary map
- */
- private static final Map DICTIONARY;
-
- static {
- DICTIONARY = new EnumMap<>(KuraMethod.class);
-
- DICTIONARY.put(KuraMethod.GET, KapuaMethod.READ);
- DICTIONARY.put(KuraMethod.POST, KapuaMethod.CREATE);
- DICTIONARY.put(KuraMethod.PUT, KapuaMethod.WRITE);
- DICTIONARY.put(KuraMethod.DEL, KapuaMethod.DELETE);
- DICTIONARY.put(KuraMethod.EXEC, KapuaMethod.EXECUTE);
- DICTIONARY.put(KuraMethod.SUBMIT, KapuaMethod.SUBMIT);
- DICTIONARY.put(KuraMethod.CANCEL, KapuaMethod.CANCEL);
- }
-
- /**
- * Constructor.
- *
- * @since 1.0.0
- */
- private MethodDictionaryKuraKapua() {
- }
-
- /**
- * Returns the method translation from Kura domain to Kapua domain
- *
- * @param kuraMethod The {@link KuraMethod} to translate.
- * @return The method translation from Kura domain to Kapua domain
- * @since 1.0.0
- * @deprecated Since 1.2.0. Renamed to
- */
- @Deprecated
- public static KapuaMethod get(KuraMethod kuraMethod) {
- return translate(kuraMethod);
- }
-
- /**
- * Translates the given {@link KuraMethod} to the matching {@link KapuaMethod}.
- *
- * @param kuraMethod The {@link KuraMethod} to translate.
- * @return The matching {@link KapuaMethod}
- * @since 1.2.0
- */
- public static KapuaMethod translate(KuraMethod kuraMethod) {
- return DICTIONARY.get(kuraMethod);
- }
-}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java
index 81610c80170..071caba0785 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java
@@ -16,7 +16,6 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.kapua.commons.util.xml.XmlUtil;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.asset.AssetMetrics;
import org.eclipse.kapua.service.device.call.kura.model.asset.KuraAssetChannelMode;
import org.eclipse.kapua.service.device.call.kura.model.asset.KuraAssets;
@@ -31,9 +30,11 @@
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetResponseChannel;
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetResponseMessage;
import org.eclipse.kapua.service.device.management.asset.message.internal.AssetResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.Date;
/**
@@ -43,16 +44,18 @@
*/
public class TranslatorAppAssetKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceAssetFactory deviceAssetFactory;
- public TranslatorAppAssetKuraKapua() {
- super(AssetResponseMessage.class, AssetResponsePayload.class);
+ @Inject
+ public TranslatorAppAssetKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceAssetFactory deviceAssetFactory) {
+ super(deviceManagementSetting, AssetResponseMessage.class, AssetResponsePayload.class);
+ this.deviceAssetFactory = deviceAssetFactory;
}
@Override
protected AssetResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, AssetMetrics.APP_ID, AssetMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, AssetMetrics.APP_ID, AssetMetrics.APP_VERSION);
return new AssetResponseChannel();
} catch (Exception e) {
@@ -65,7 +68,6 @@ protected AssetResponsePayload translatePayload(KuraResponsePayload kuraResponse
AssetResponsePayload assetResponsePayload = super.translatePayload(kuraResponsePayload);
try {
- DeviceAssetFactory deviceAssetFactory = LOCATOR.getFactory(DeviceAssetFactory.class);
if (kuraResponsePayload.hasBody()) {
ObjectMapper mapper = new ObjectMapper();
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java
index 5a2d397690f..7b7b2664448 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java
@@ -13,7 +13,6 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.bundle.BundleMetrics;
import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundles;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
@@ -25,9 +24,11 @@
import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleResponseChannel;
import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleResponseMessage;
import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
@@ -38,16 +39,18 @@
*/
public class TranslatorAppBundleKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceBundleFactory deviceBundleFactory;
- public TranslatorAppBundleKuraKapua() {
- super(BundleResponseMessage.class, BundleResponsePayload.class);
+ @Inject
+ public TranslatorAppBundleKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceBundleFactory deviceBundleFactory) {
+ super(deviceManagementSetting, BundleResponseMessage.class, BundleResponsePayload.class);
+ this.deviceBundleFactory = deviceBundleFactory;
}
@Override
protected BundleResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, BundleMetrics.APP_ID, BundleMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, BundleMetrics.APP_ID, BundleMetrics.APP_VERSION);
return new BundleResponseChannel();
} catch (Exception e) {
@@ -80,8 +83,6 @@ protected BundleResponsePayload translatePayload(KuraResponsePayload kuraRespons
* @since 1.0.0
*/
private DeviceBundles translate(KuraBundles kuraBundles) {
- DeviceBundleFactory deviceBundleFactory = LOCATOR.getFactory(DeviceBundleFactory.class);
-
DeviceBundles deviceBundles = deviceBundleFactory.newBundleListResult();
List deviceBundlesList = deviceBundles.getBundles();
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppCommandKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppCommandKuraKapua.java
index 95b18b5e6ef..0907b84b8a1 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppCommandKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppCommandKuraKapua.java
@@ -20,9 +20,11 @@
import org.eclipse.kapua.service.device.management.command.message.internal.CommandResponseChannel;
import org.eclipse.kapua.service.device.management.command.message.internal.CommandResponseMessage;
import org.eclipse.kapua.service.device.management.command.message.internal.CommandResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.Map;
/**
@@ -32,14 +34,15 @@
*/
public class TranslatorAppCommandKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- public TranslatorAppCommandKuraKapua() {
- super(CommandResponseMessage.class, CommandResponsePayload.class);
+ @Inject
+ public TranslatorAppCommandKuraKapua(DeviceManagementSetting deviceManagementSetting) {
+ super(deviceManagementSetting, CommandResponseMessage.class, CommandResponsePayload.class);
}
@Override
protected CommandResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, CommandMetrics.APP_ID, CommandMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, CommandMetrics.APP_ID, CommandMetrics.APP_VERSION);
return new CommandResponseChannel();
} catch (Exception e) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java
index 97c668539ad..aa0759627ef 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java
@@ -28,7 +28,6 @@
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
-import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
import org.eclipse.kapua.service.device.management.configuration.internal.DeviceComponentConfigurationImpl;
import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationImpl;
@@ -38,6 +37,7 @@
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
@@ -48,16 +48,15 @@
*/
public class TranslatorAppConfigurationKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final String CHAR_ENCODING = DeviceManagementSetting.getInstance().getString(DeviceManagementSettingKey.CHAR_ENCODING);
-
- public TranslatorAppConfigurationKuraKapua() {
- super(ConfigurationResponseMessage.class, ConfigurationResponsePayload.class);
+ @Inject
+ public TranslatorAppConfigurationKuraKapua(DeviceManagementSetting deviceManagementSetting) {
+ super(deviceManagementSetting, ConfigurationResponseMessage.class, ConfigurationResponsePayload.class);
}
@Override
protected ConfigurationResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, ConfigurationMetrics.APP_ID, ConfigurationMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, ConfigurationMetrics.APP_ID, ConfigurationMetrics.APP_VERSION);
return new ConfigurationResponseChannel();
} catch (Exception e) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppNotifyKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppNotifyKuraKapua.java
index 9ce023ca391..5d25fcb4216 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppNotifyKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppNotifyKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaIdFactory;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.account.AccountService;
@@ -46,6 +45,7 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
@@ -57,32 +57,34 @@
*/
public class TranslatorAppNotifyKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
-
- private static final KapuaIdFactory KAPUA_ID_FACTORY = LOCATOR.getFactory(KapuaIdFactory.class);
-
- private static final Map APP_NAME_DICTIONARY;
- private static final Map APP_VERSION_DICTIONARY;
-
- static {
- APP_NAME_DICTIONARY = new HashMap<>();
-
- APP_NAME_DICTIONARY.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_NAME);
-
- APP_VERSION_DICTIONARY = new HashMap<>();
-
- APP_VERSION_DICTIONARY.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_VERSION);
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private KapuaIdFactory kapuaIdFactory;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
+
+ private final Map appNameDictionary;
+ private final Map appVersionDictionary;
+
+ public TranslatorAppNotifyKuraKapua() {
+ appNameDictionary = new HashMap<>();
+
+ appNameDictionary.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_NAME);
+ appNameDictionary.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_NAME);
+ appNameDictionary.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_NAME);
+ appNameDictionary.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_NAME);
+ appNameDictionary.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_NAME);
+
+ appVersionDictionary = new HashMap<>();
+
+ appVersionDictionary.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_VERSION);
+ appVersionDictionary.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_VERSION);
+ appVersionDictionary.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_VERSION);
+ appVersionDictionary.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_VERSION);
+ appVersionDictionary.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_VERSION);
}
@Override
@@ -93,12 +95,12 @@ public KapuaNotifyMessage translate(KuraNotifyMessage kuraNotifyMessage) throws
kapuaNotifyMessage.setChannel(translate(kuraNotifyMessage.getChannel()));
kapuaNotifyMessage.setPayload(translate(kuraNotifyMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraNotifyMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraNotifyMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraNotifyMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraNotifyMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraNotifyMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.class.toString(), kuraNotifyMessage.getChannel().getClientId());
}
@@ -108,7 +110,7 @@ public KapuaNotifyMessage translate(KuraNotifyMessage kuraNotifyMessage) throws
kapuaNotifyMessage.setCapturedOn(kuraNotifyMessage.getPayload().getTimestamp());
kapuaNotifyMessage.setSentOn(kuraNotifyMessage.getPayload().getTimestamp());
kapuaNotifyMessage.setReceivedOn(kuraNotifyMessage.getTimestamp());
- kapuaNotifyMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraNotifyMessage.getPayload().getPosition()));
+ kapuaNotifyMessage.setPosition(translatorKuraKapuaUtils.translate(kuraNotifyMessage.getPayload().getPosition()));
return kapuaNotifyMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
@@ -124,8 +126,8 @@ private KapuaNotifyChannel translate(KuraNotifyChannel kuraNotifyChannel) throws
String kuraAppIdVersion = kuraNotifyChannel.getAppId().split("-")[1];
KapuaNotifyChannel kapuaNotifyChannel = new KapuaNotifyChannelImpl();
- kapuaNotifyChannel.setAppName(APP_NAME_DICTIONARY.get(kuraAppIdName));
- kapuaNotifyChannel.setVersion(APP_VERSION_DICTIONARY.get(kuraAppIdVersion));
+ kapuaNotifyChannel.setAppName(appNameDictionary.get(kuraAppIdName));
+ kapuaNotifyChannel.setVersion(appVersionDictionary.get(kuraAppIdVersion));
kapuaNotifyChannel.setResources(kuraNotifyChannel.getResources());
return kapuaNotifyChannel;
@@ -138,7 +140,7 @@ private KapuaNotifyPayload translate(KuraNotifyPayload kuraNotifyPayload) throws
try {
KapuaNotifyPayload kapuaNotifyPayload = new KapuaNotifyPayloadImpl();
- kapuaNotifyPayload.setOperationId(KAPUA_ID_FACTORY.newKapuaId(new BigInteger(kuraNotifyPayload.getOperationId().toString())));
+ kapuaNotifyPayload.setOperationId(kapuaIdFactory.newKapuaId(new BigInteger(kuraNotifyPayload.getOperationId().toString())));
kapuaNotifyPayload.setResource(kuraNotifyPayload.getResource());
kapuaNotifyPayload.setProgress(kuraNotifyPayload.getProgress());
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java
index cc660cef3a5..10d46a278a8 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java
@@ -14,7 +14,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.commons.model.id.KapuaEid;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraBundleInfo;
import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraDeploymentPackage;
import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraDeploymentPackages;
@@ -23,6 +22,7 @@
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseCode;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory;
import org.eclipse.kapua.service.device.management.packages.message.internal.PackageResponseChannel;
import org.eclipse.kapua.service.device.management.packages.message.internal.PackageResponseMessage;
@@ -37,6 +37,7 @@
import org.eclipse.kapua.translator.exception.TranslatorErrorCodes;
import org.eclipse.kapua.translator.exception.TranslatorException;
+import javax.inject.Inject;
import java.math.BigInteger;
import java.util.Map;
@@ -47,16 +48,18 @@
*/
public class TranslatorAppPackageKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DevicePackageFactory devicePackageFactory;
- public TranslatorAppPackageKuraKapua() {
- super(PackageResponseMessage.class, PackageResponsePayload.class);
+ @Inject
+ public TranslatorAppPackageKuraKapua(DeviceManagementSetting deviceManagementSetting, DevicePackageFactory devicePackageFactory) {
+ super(deviceManagementSetting, PackageResponseMessage.class, PackageResponsePayload.class);
+ this.devicePackageFactory = devicePackageFactory;
}
@Override
protected PackageResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, PackageMetrics.APP_ID, PackageMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, PackageMetrics.APP_ID, PackageMetrics.APP_VERSION);
return new PackageResponseChannel();
} catch (Exception e) {
@@ -126,7 +129,6 @@ protected PackageResponsePayload translatePayload(KuraResponsePayload kuraRespon
}
private DevicePackages translate(KuraDeploymentPackages kuraDeploymentPackages) {
- DevicePackageFactory devicePackageFactory = LOCATOR.getFactory(DevicePackageFactory.class);
DevicePackages deviceDeploymentPackages = devicePackageFactory.newDeviceDeploymentPackages();
KuraDeploymentPackage[] deploymentPackageArray = kuraDeploymentPackages.getDeploymentPackages();
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppResponseKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppResponseKuraKapua.java
index 56ab65288b2..834e91e573d 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppResponseKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppResponseKuraKapua.java
@@ -12,9 +12,9 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.request.GenericRequestFactory;
import org.eclipse.kapua.service.device.management.request.internal.GenericAppProperties;
import org.eclipse.kapua.service.device.management.request.message.response.GenericResponseChannel;
@@ -25,6 +25,8 @@
import org.eclipse.kapua.translator.exception.TranslatorErrorCodes;
import org.eclipse.kapua.translator.exception.TranslatorException;
+import javax.inject.Inject;
+
/**
* {@link org.eclipse.kapua.translator.Translator} implementation from {@link org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage} to {@link GenericResponseMessage}
*
@@ -32,17 +34,17 @@
*/
public class TranslatorAppResponseKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final GenericRequestFactory genericRequestFactory;
- public TranslatorAppResponseKuraKapua() {
- super(GenericResponseMessage.class, GenericResponsePayload.class);
+ @Inject
+ public TranslatorAppResponseKuraKapua(DeviceManagementSetting deviceManagementSetting, GenericRequestFactory genericRequestFactory) {
+ super(deviceManagementSetting, GenericResponseMessage.class, GenericResponsePayload.class);
+ this.genericRequestFactory = genericRequestFactory;
}
@Override
protected GenericResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- GenericRequestFactory genericRequestFactory = LOCATOR.getFactory(GenericRequestFactory.class);
-
if (!getControlMessageClassifier().equals(kuraResponseChannel.getMessageClassification())) {
throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_CLASSIFIER, null, kuraResponseChannel.getMessageClassification());
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppSnapshotKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppSnapshotKuraKapua.java
index 244ea47057f..6bdeca35a38 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppSnapshotKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppSnapshotKuraKapua.java
@@ -13,12 +13,12 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.snapshot.KuraSnapshotIds;
import org.eclipse.kapua.service.device.call.kura.model.snapshot.SnapshotMetrics;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshot;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory;
import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshots;
@@ -29,6 +29,7 @@
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
import java.util.List;
/**
@@ -38,16 +39,18 @@
*/
public class TranslatorAppSnapshotKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceSnapshotFactory deviceSnapshotFactory;
- public TranslatorAppSnapshotKuraKapua() {
- super(SnapshotResponseMessage.class, SnapshotResponsePayload.class);
+ @Inject
+ public TranslatorAppSnapshotKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceSnapshotFactory deviceSnapshotFactory) {
+ super(deviceManagementSetting, SnapshotResponseMessage.class, SnapshotResponsePayload.class);
+ this.deviceSnapshotFactory = deviceSnapshotFactory;
}
@Override
protected SnapshotResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, SnapshotMetrics.APP_ID, SnapshotMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, SnapshotMetrics.APP_ID, SnapshotMetrics.APP_VERSION);
return new SnapshotResponseChannel();
} catch (Exception e) {
@@ -82,7 +85,6 @@ protected SnapshotResponsePayload translatePayload(KuraResponsePayload kuraRespo
* @since 1.0.0
*/
private DeviceSnapshots translate(KuraSnapshotIds kuraSnapshotIdResult) {
- DeviceSnapshotFactory deviceSnapshotFactory = LOCATOR.getFactory(DeviceSnapshotFactory.class);
DeviceSnapshots deviceSnapshots = deviceSnapshotFactory.newDeviceSnapshots();
List snapshotIds = kuraSnapshotIdResult.getSnapshotIds();
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorDataKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorDataKuraKapua.java
index 6cc4ceb8bc5..2b2145c2105 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorDataKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorDataKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.data.KapuaDataChannel;
import org.eclipse.kapua.message.device.data.KapuaDataMessage;
import org.eclipse.kapua.message.device.data.KapuaDataMessageFactory;
@@ -31,6 +30,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraDataMessage} to {@link KapuaDataMessage}
*
@@ -38,12 +39,14 @@
*/
public class TranslatorDataKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
-
- private static final KapuaDataMessageFactory DATA_MESSAGE_FACTORY = LOCATOR.getFactory(KapuaDataMessageFactory.class);
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private KapuaDataMessageFactory kapuaDataMessageFactory;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
public KapuaDataMessage translate(KuraDataMessage kuraMessage) throws TranslateException {
@@ -53,15 +56,15 @@ public KapuaDataMessage translate(KuraDataMessage kuraMessage) throws TranslateE
// Kapua payload
KapuaDataPayload kapuaDataPayload = translate(kuraMessage.getPayload());
// Kapua message
- Account account = ACCOUNT_SERVICE.findByName(kuraMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraMessage.getChannel().getClientId());
- KapuaDataMessage kapuaDataMessage = DATA_MESSAGE_FACTORY.newKapuaDataMessage();
+ KapuaDataMessage kapuaDataMessage = kapuaDataMessageFactory.newKapuaDataMessage();
kapuaDataMessage.setScopeId(account.getId());
kapuaDataMessage.setDeviceId(device != null ? device.getId() : null);
kapuaDataMessage.setClientId(kuraMessage.getChannel().getClientId());
@@ -70,7 +73,7 @@ public KapuaDataMessage translate(KuraDataMessage kuraMessage) throws TranslateE
kapuaDataMessage.setCapturedOn(kuraMessage.getPayload().getTimestamp());
kapuaDataMessage.setSentOn(kuraMessage.getPayload().getTimestamp());
kapuaDataMessage.setReceivedOn(kuraMessage.getTimestamp());
- kapuaDataMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraMessage.getPayload().getPosition()));
+ kapuaDataMessage.setPosition(translatorKuraKapuaUtils.translate(kuraMessage.getPayload().getPosition()));
// Return Kapua Message
return kapuaDataMessage;
@@ -82,7 +85,7 @@ public KapuaDataMessage translate(KuraDataMessage kuraMessage) throws TranslateE
}
private KapuaDataChannel translate(KuraDataChannel kuraChannel) {
- KapuaDataChannel kapuaChannel = DATA_MESSAGE_FACTORY.newKapuaDataChannel();
+ KapuaDataChannel kapuaChannel = kapuaDataMessageFactory.newKapuaDataChannel();
kapuaChannel.setSemanticParts(kuraChannel.getSemanticParts());
// Return Kapua Channel
@@ -90,7 +93,7 @@ private KapuaDataChannel translate(KuraDataChannel kuraChannel) {
}
private KapuaDataPayload translate(KuraDataPayload kuraPayload) {
- KapuaDataPayload kapuaPayload = DATA_MESSAGE_FACTORY.newKapuaDataPayload();
+ KapuaDataPayload kapuaPayload = kapuaDataMessageFactory.newKapuaDataPayload();
if (!kuraPayload.getMetrics().isEmpty()) {
kapuaPayload.setMetrics(kuraPayload.getMetrics());
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtils.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtils.java
index 1919a376d78..008d1aec18e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtils.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtils.java
@@ -8,134 +8,24 @@
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
- * Eurotech - initial API and implementation
- * Red Hat Inc
+ * Red Hat
+ * Eurotech
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaException;
-import org.eclipse.kapua.commons.setting.system.SystemSetting;
-import org.eclipse.kapua.locator.KapuaLocator;
-import org.eclipse.kapua.message.KapuaMessageFactory;
import org.eclipse.kapua.message.KapuaPosition;
import org.eclipse.kapua.service.device.call.message.DevicePosition;
import org.eclipse.kapua.service.device.call.message.app.DeviceAppMetrics;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseCode;
import org.eclipse.kapua.service.device.management.message.response.KapuaResponseCode;
-import org.eclipse.kapua.translator.exception.TranslatorErrorCodes;
import org.eclipse.kapua.translator.exception.TranslatorException;
-/**
- * {@link org.eclipse.kapua.translator.Translator} utilities.
- * It provides helpful methods for translate {@link DevicePosition} and {@link KuraResponseCode}.
- *
- * @since 1.0.0
- */
-public final class TranslatorKuraKapuaUtils {
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
- private static final KapuaMessageFactory KAPUA_MESSAGE_FACTORY = LOCATOR.getFactory(KapuaMessageFactory.class);
-
- private static final String CONTROL_MESSAGE_CLASSIFIER = SystemSetting.getInstance().getMessageClassifier();
-
- private TranslatorKuraKapuaUtils() {
- }
-
- /**
- * Validates the given {@link KuraResponseChannel}.
- *
- * Checks that:
- *
- * - the {@link KuraResponseChannel#getMessageClassification()} matches the configured {@link SystemSetting#getMessageClassifier()}
- * - the {@link KuraResponseChannel#getAppId()} is formatted as {@code appId-appVersion}
- * - the {@link KuraResponseChannel#getAppId()} first token matches the given application name
- * - the {@link KuraResponseChannel#getAppId()} second token matches the given application version
- *
- *
- * @param kuraResponseChannel the {@link KuraResponseChannel} to check.
- * @param appName the application name.
- * @param appVersion the application version.
- * @throws TranslatorException The any of the constraints fails.
- * @since 1.2.0
- */
- public static void validateKuraResponseChannel(KuraResponseChannel kuraResponseChannel, DeviceAppMetrics appName, DeviceAppMetrics appVersion) throws TranslatorException {
- if (!CONTROL_MESSAGE_CLASSIFIER.equals(kuraResponseChannel.getMessageClassification())) {
- throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_CLASSIFIER, null, kuraResponseChannel.getMessageClassification());
- }
-
- String[] appIdTokens = kuraResponseChannel.getAppId().split("-");
-
- if (appIdTokens.length < 2) {
- throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_NAME, null, (Object) appIdTokens);
- }
-
- if (!appName.getName().equals(appIdTokens[0])) {
- throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_NAME, null, appIdTokens[0]);
- }
-
- if (!appVersion.getName().equals(appIdTokens[1])) {
- throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_VERSION, null, appIdTokens[1]);
- }
- }
-
- /**
- * Translates {@link DevicePosition} to {@link KapuaPosition}
- *
- * @param devicePosition The {@link DevicePosition} to translate.
- * @return The translated {@link KapuaPosition}.
- * @since 1.0.0
- */
- public static KapuaPosition translate(DevicePosition devicePosition) {
- KapuaPosition kapuaPosition = null;
-
- if (devicePosition != null) {
- kapuaPosition = KAPUA_MESSAGE_FACTORY.newPosition();
-
- kapuaPosition.setAltitude(devicePosition.getAltitude());
- kapuaPosition.setHeading(devicePosition.getHeading());
- kapuaPosition.setLatitude(devicePosition.getLatitude());
- kapuaPosition.setLongitude(devicePosition.getLongitude());
- kapuaPosition.setPrecision(devicePosition.getPrecision());
- kapuaPosition.setSatellites(devicePosition.getSatellites());
- kapuaPosition.setSpeed(devicePosition.getSpeed());
- kapuaPosition.setStatus(devicePosition.getStatus());
- kapuaPosition.setTimestamp(devicePosition.getTimestamp());
- }
-
- return kapuaPosition;
- }
-
- /**
- * Translate {@link KuraResponseCode} to {@link KapuaResponseCode}
- *
- * @param kuraResponseCode The {@link KuraResponseCode} to translate.
- * @return The translated {@link KapuaResponseCode}
- * @since 1.0.0
- */
- public static KapuaResponseCode translate(KuraResponseCode kuraResponseCode) throws KapuaException {
- if (kuraResponseCode == null) {
- return null;
- }
+public interface TranslatorKuraKapuaUtils {
+ void validateKuraResponseChannel(KuraResponseChannel kuraResponseChannel, DeviceAppMetrics appName, DeviceAppMetrics appVersion) throws TranslatorException;
- KapuaResponseCode responseCode;
- switch (kuraResponseCode) {
- case ACCEPTED:
- responseCode = KapuaResponseCode.ACCEPTED;
- break;
- case BAD_REQUEST:
- responseCode = KapuaResponseCode.BAD_REQUEST;
- break;
- case NOT_FOUND:
- responseCode = KapuaResponseCode.NOT_FOUND;
- break;
- case INTERNAL_ERROR:
- responseCode = KapuaResponseCode.INTERNAL_ERROR;
- break;
- default:
- throw KapuaException.internalError("Kura Response code not mapped");
- }
+ KapuaPosition translate(DevicePosition devicePosition);
- return responseCode;
- }
+ KapuaResponseCode translate(KuraResponseCode kuraResponseCode) throws KapuaException;
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtilsImpl.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtilsImpl.java
new file mode 100644
index 00000000000..8669d7c5df6
--- /dev/null
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorKuraKapuaUtilsImpl.java
@@ -0,0 +1,143 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator.kura.kapua;
+
+import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
+import org.eclipse.kapua.message.KapuaMessageFactory;
+import org.eclipse.kapua.message.KapuaPosition;
+import org.eclipse.kapua.service.device.call.message.DevicePosition;
+import org.eclipse.kapua.service.device.call.message.app.DeviceAppMetrics;
+import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
+import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseCode;
+import org.eclipse.kapua.service.device.management.message.response.KapuaResponseCode;
+import org.eclipse.kapua.translator.exception.TranslatorErrorCodes;
+import org.eclipse.kapua.translator.exception.TranslatorException;
+
+/**
+ * {@link org.eclipse.kapua.translator.Translator} utilities.
+ * It provides helpful methods for translate {@link DevicePosition} and {@link KuraResponseCode}.
+ *
+ * @since 1.0.0
+ */
+public final class TranslatorKuraKapuaUtilsImpl implements TranslatorKuraKapuaUtils {
+
+ private final KapuaMessageFactory kapuaMessageFactory;
+ private final String controlMessageClassifier;
+
+ public TranslatorKuraKapuaUtilsImpl(KapuaMessageFactory kapuaMessageFactory, String controlMessageClassifier) {
+ this.kapuaMessageFactory = kapuaMessageFactory;
+ this.controlMessageClassifier = controlMessageClassifier;
+ }
+
+ /**
+ * Validates the given {@link KuraResponseChannel}.
+ *
+ * Checks that:
+ *
+ * - the {@link KuraResponseChannel#getMessageClassification()} matches the configured {@link SystemSetting#getMessageClassifier()}
+ * - the {@link KuraResponseChannel#getAppId()} is formatted as {@code appId-appVersion}
+ * - the {@link KuraResponseChannel#getAppId()} first token matches the given application name
+ * - the {@link KuraResponseChannel#getAppId()} second token matches the given application version
+ *
+ *
+ * @param kuraResponseChannel the {@link KuraResponseChannel} to check.
+ * @param appName the application name.
+ * @param appVersion the application version.
+ * @throws TranslatorException The any of the constraints fails.
+ * @since 1.2.0
+ */
+ @Override
+ public void validateKuraResponseChannel(KuraResponseChannel kuraResponseChannel, DeviceAppMetrics appName, DeviceAppMetrics appVersion) throws TranslatorException {
+ if (!controlMessageClassifier.equals(kuraResponseChannel.getMessageClassification())) {
+ throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_CLASSIFIER, null, kuraResponseChannel.getMessageClassification());
+ }
+
+ String[] appIdTokens = kuraResponseChannel.getAppId().split("-");
+
+ if (appIdTokens.length < 2) {
+ throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_NAME, null, (Object) appIdTokens);
+ }
+
+ if (!appName.getName().equals(appIdTokens[0])) {
+ throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_NAME, null, appIdTokens[0]);
+ }
+
+ if (!appVersion.getName().equals(appIdTokens[1])) {
+ throw new TranslatorException(TranslatorErrorCodes.INVALID_CHANNEL_APP_VERSION, null, appIdTokens[1]);
+ }
+ }
+
+ /**
+ * Translates {@link DevicePosition} to {@link KapuaPosition}
+ *
+ * @param devicePosition The {@link DevicePosition} to translate.
+ * @return The translated {@link KapuaPosition}.
+ * @since 1.0.0
+ */
+ @Override
+ public KapuaPosition translate(DevicePosition devicePosition) {
+ KapuaPosition kapuaPosition = null;
+
+ if (devicePosition != null) {
+ kapuaPosition = kapuaMessageFactory.newPosition();
+
+ kapuaPosition.setAltitude(devicePosition.getAltitude());
+ kapuaPosition.setHeading(devicePosition.getHeading());
+ kapuaPosition.setLatitude(devicePosition.getLatitude());
+ kapuaPosition.setLongitude(devicePosition.getLongitude());
+ kapuaPosition.setPrecision(devicePosition.getPrecision());
+ kapuaPosition.setSatellites(devicePosition.getSatellites());
+ kapuaPosition.setSpeed(devicePosition.getSpeed());
+ kapuaPosition.setStatus(devicePosition.getStatus());
+ kapuaPosition.setTimestamp(devicePosition.getTimestamp());
+ }
+
+ return kapuaPosition;
+ }
+
+ /**
+ * Translate {@link KuraResponseCode} to {@link KapuaResponseCode}
+ *
+ * @param kuraResponseCode The {@link KuraResponseCode} to translate.
+ * @return The translated {@link KapuaResponseCode}
+ * @since 1.0.0
+ */
+ @Override
+ public KapuaResponseCode translate(KuraResponseCode kuraResponseCode) throws KapuaException {
+ if (kuraResponseCode == null) {
+ return null;
+ }
+
+ KapuaResponseCode responseCode;
+ switch (kuraResponseCode) {
+ case ACCEPTED:
+ responseCode = KapuaResponseCode.ACCEPTED;
+ break;
+ case BAD_REQUEST:
+ responseCode = KapuaResponseCode.BAD_REQUEST;
+ break;
+ case NOT_FOUND:
+ responseCode = KapuaResponseCode.NOT_FOUND;
+ break;
+ case INTERNAL_ERROR:
+ responseCode = KapuaResponseCode.INTERNAL_ERROR;
+ break;
+ default:
+ throw KapuaException.internalError("Kura Response code not mapped");
+ }
+
+ return responseCode;
+ }
+}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeAppsKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeAppsKuraKapua.java
index 5b0d144adb5..c8b93186128 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeAppsKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeAppsKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.lifecycle.KapuaAppsChannel;
import org.eclipse.kapua.message.device.lifecycle.KapuaAppsMessage;
import org.eclipse.kapua.message.device.lifecycle.KapuaAppsPayload;
@@ -33,6 +32,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraAppsMessage} to {@link KapuaAppsMessage}
*
@@ -40,10 +41,12 @@
*/
public class TranslatorLifeAppsKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
public KapuaAppsMessage translate(KuraAppsMessage kuraAppsMessage) throws TranslateException {
@@ -52,12 +55,12 @@ public KapuaAppsMessage translate(KuraAppsMessage kuraAppsMessage) throws Transl
kapuaAppsMessage.setChannel(translate(kuraAppsMessage.getChannel()));
kapuaAppsMessage.setPayload(translate(kuraAppsMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraAppsMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraAppsMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraAppsMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraAppsMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraAppsMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.class.toString(), kuraAppsMessage.getChannel().getClientId());
}
@@ -67,7 +70,7 @@ public KapuaAppsMessage translate(KuraAppsMessage kuraAppsMessage) throws Transl
kapuaAppsMessage.setCapturedOn(kuraAppsMessage.getPayload().getTimestamp());
kapuaAppsMessage.setSentOn(kuraAppsMessage.getPayload().getTimestamp());
kapuaAppsMessage.setReceivedOn(kuraAppsMessage.getTimestamp());
- kapuaAppsMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraAppsMessage.getPayload().getPosition()));
+ kapuaAppsMessage.setPosition(translatorKuraKapuaUtils.translate(kuraAppsMessage.getPayload().getPosition()));
return kapuaAppsMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeBirthKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeBirthKuraKapua.java
index 7cc3c7cdc18..7ddb374b609 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeBirthKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeBirthKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.lifecycle.KapuaBirthChannel;
import org.eclipse.kapua.message.device.lifecycle.KapuaBirthMessage;
import org.eclipse.kapua.message.device.lifecycle.KapuaBirthPayload;
@@ -33,6 +32,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraBirthMessage} to {@link KapuaBirthMessage}
*
@@ -40,10 +41,12 @@
*/
public class TranslatorLifeBirthKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
public KapuaBirthMessage translate(KuraBirthMessage kuraBirthMessage) throws TranslateException {
@@ -52,13 +55,13 @@ public KapuaBirthMessage translate(KuraBirthMessage kuraBirthMessage) throws Tra
kapuaBirthMessage.setChannel(translate(kuraBirthMessage.getChannel()));
kapuaBirthMessage.setPayload(translate(kuraBirthMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraBirthMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraBirthMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraBirthMessage.getChannel().getScope());
}
kapuaBirthMessage.setScopeId(account.getId());
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraBirthMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraBirthMessage.getChannel().getClientId());
if (device != null) {
kapuaBirthMessage.setDeviceId(device.getId());
} else {
@@ -68,7 +71,7 @@ public KapuaBirthMessage translate(KuraBirthMessage kuraBirthMessage) throws Tra
kapuaBirthMessage.setCapturedOn(kuraBirthMessage.getPayload().getTimestamp());
kapuaBirthMessage.setSentOn(kuraBirthMessage.getPayload().getTimestamp());
kapuaBirthMessage.setReceivedOn(kuraBirthMessage.getTimestamp());
- kapuaBirthMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraBirthMessage.getPayload().getPosition()));
+ kapuaBirthMessage.setPosition(translatorKuraKapuaUtils.translate(kuraBirthMessage.getPayload().getPosition()));
return kapuaBirthMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeDisconnectKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeDisconnectKuraKapua.java
index 4754d6589dd..35eefc437a3 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeDisconnectKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeDisconnectKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.lifecycle.KapuaDisconnectChannel;
import org.eclipse.kapua.message.device.lifecycle.KapuaDisconnectMessage;
import org.eclipse.kapua.message.device.lifecycle.KapuaDisconnectPayload;
@@ -33,6 +32,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraDisconnectMessage} to {@link KapuaDisconnectMessage}
*
@@ -40,10 +41,12 @@
*/
public class TranslatorLifeDisconnectKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
public KapuaDisconnectMessage translate(KuraDisconnectMessage kuraDisconnectMessage) throws TranslateException {
@@ -52,12 +55,12 @@ public KapuaDisconnectMessage translate(KuraDisconnectMessage kuraDisconnectMess
kapuaDisconnectMessage.setChannel(translate(kuraDisconnectMessage.getChannel()));
kapuaDisconnectMessage.setPayload(translate(kuraDisconnectMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraDisconnectMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraDisconnectMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraDisconnectMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraDisconnectMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraDisconnectMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.class.toString(), kuraDisconnectMessage.getChannel().getClientId());
}
@@ -67,7 +70,7 @@ public KapuaDisconnectMessage translate(KuraDisconnectMessage kuraDisconnectMess
kapuaDisconnectMessage.setCapturedOn(kuraDisconnectMessage.getPayload().getTimestamp());
kapuaDisconnectMessage.setSentOn(kuraDisconnectMessage.getPayload().getTimestamp());
kapuaDisconnectMessage.setReceivedOn(kuraDisconnectMessage.getTimestamp());
- kapuaDisconnectMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraDisconnectMessage.getPayload().getPosition()));
+ kapuaDisconnectMessage.setPosition(translatorKuraKapuaUtils.translate(kuraDisconnectMessage.getPayload().getPosition()));
return kapuaDisconnectMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeMissingKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeMissingKuraKapua.java
index 2d4932c2546..4cbbedc3055 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeMissingKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorLifeMissingKuraKapua.java
@@ -13,7 +13,6 @@
package org.eclipse.kapua.translator.kura.kapua;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.message.device.lifecycle.KapuaMissingChannel;
import org.eclipse.kapua.message.device.lifecycle.KapuaMissingMessage;
import org.eclipse.kapua.message.device.lifecycle.KapuaMissingPayload;
@@ -33,6 +32,8 @@
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
import org.eclipse.kapua.translator.exception.TranslateException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraMissingMessage} to {@link KapuaMissingMessage}
*
@@ -40,10 +41,12 @@
*/
public class TranslatorLifeMissingKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
-
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
@Override
public KapuaMissingMessage translate(KuraMissingMessage kuraMissingMessage) throws TranslateException {
@@ -52,12 +55,12 @@ public KapuaMissingMessage translate(KuraMissingMessage kuraMissingMessage) thro
kapuaMissingMessage.setChannel(translate(kuraMissingMessage.getChannel()));
kapuaMissingMessage.setPayload(translate(kuraMissingMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraMissingMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraMissingMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraMissingMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraMissingMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraMissingMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.class.toString(), kuraMissingMessage.getChannel().getClientId());
}
@@ -67,7 +70,7 @@ public KapuaMissingMessage translate(KuraMissingMessage kuraMissingMessage) thro
kapuaMissingMessage.setCapturedOn(kuraMissingMessage.getPayload().getTimestamp());
kapuaMissingMessage.setSentOn(kuraMissingMessage.getPayload().getTimestamp());
kapuaMissingMessage.setReceivedOn(kuraMissingMessage.getTimestamp());
- kapuaMissingMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraMissingMessage.getPayload().getPosition()));
+ kapuaMissingMessage.setPosition(translatorKuraKapuaUtils.translate(kuraMissingMessage.getPayload().getPosition()));
return kapuaMissingMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java
index 291a19871ef..83784fed2af 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java
@@ -15,7 +15,6 @@
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.kapua.KapuaEntityNotFoundException;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.device.call.kura.model.asset.AssetMetrics;
@@ -31,6 +30,7 @@
import org.eclipse.kapua.service.device.management.bundle.internal.DeviceBundleAppProperties;
import org.eclipse.kapua.service.device.management.command.internal.CommandAppProperties;
import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration;
+import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration;
import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationAppProperties;
import org.eclipse.kapua.service.device.management.configuration.message.event.DeviceConfigurationEventMessage;
@@ -51,6 +51,7 @@
import org.eclipse.kapua.translator.exception.TranslateException;
import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtils;
+import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
@@ -65,48 +66,48 @@
*/
public class TranslatorEventConfigurationKuraKapua extends Translator {
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ @Inject
+ private AccountService accountService;
+ @Inject
+ private DeviceRegistryService deviceRegistryService;
+ @Inject
+ private DeviceConfigurationFactory deviceConfigurationFactory;
+ @Inject
+ private TranslatorKuraKapuaUtils translatorKuraKapuaUtils;
+
+ private final Map appNameDictionary;
+ private final Map appVersionDictionary;
+
+ public TranslatorEventConfigurationKuraKapua() {
+ appNameDictionary = new HashMap<>();
+ appNameDictionary.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_NAME);
+ appNameDictionary.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_NAME);
+ appNameDictionary.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_NAME);
+ appNameDictionary.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_NAME);
+ appNameDictionary.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_NAME);
+
+ appVersionDictionary = new HashMap<>();
+ appVersionDictionary.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_VERSION);
+ appVersionDictionary.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_VERSION);
+ appVersionDictionary.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_VERSION);
+ appVersionDictionary.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_VERSION);
+ appVersionDictionary.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_VERSION);
- private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class);
- private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class);
-
- private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = LOCATOR.getFactory(DeviceConfigurationFactory.class);
-
- private static final Map APP_NAME_DICTIONARY;
- private static final Map APP_VERSION_DICTIONARY;
-
- static {
- APP_NAME_DICTIONARY = new HashMap<>();
-
- APP_NAME_DICTIONARY.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_NAME);
- APP_NAME_DICTIONARY.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_NAME);
-
- APP_VERSION_DICTIONARY = new HashMap<>();
-
- APP_VERSION_DICTIONARY.put(AssetMetrics.APP_ID.getName(), DeviceAssetAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(BundleMetrics.APP_ID.getName(), DeviceBundleAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(CommandMetrics.APP_ID.getName(), CommandAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(ConfigurationMetrics.APP_ID.getName(), DeviceConfigurationAppProperties.APP_VERSION);
- APP_VERSION_DICTIONARY.put(PackageMetrics.APP_ID.getName(), PackageAppProperties.APP_VERSION);
}
@Override
public DeviceConfigurationEventMessage translate(KuraConfigurationEventMessage kuraNotifyMessage) throws TranslateException {
-
try {
DeviceConfigurationEventMessage deviceConfigurationEventMessage = new DeviceConfigurationEventMessageImpl();
deviceConfigurationEventMessage.setChannel(translate(kuraNotifyMessage.getChannel()));
deviceConfigurationEventMessage.setPayload(translate(kuraNotifyMessage.getPayload()));
- Account account = ACCOUNT_SERVICE.findByName(kuraNotifyMessage.getChannel().getScope());
+ Account account = accountService.findByName(kuraNotifyMessage.getChannel().getScope());
if (account == null) {
throw new KapuaEntityNotFoundException(Account.TYPE, kuraNotifyMessage.getChannel().getScope());
}
- Device device = DEVICE_REGISTRY_SERVICE.findByClientId(account.getId(), kuraNotifyMessage.getChannel().getClientId());
+ Device device = deviceRegistryService.findByClientId(account.getId(), kuraNotifyMessage.getChannel().getClientId());
if (device == null) {
throw new KapuaEntityNotFoundException(Device.class.toString(), kuraNotifyMessage.getChannel().getClientId());
}
@@ -116,7 +117,7 @@ public DeviceConfigurationEventMessage translate(KuraConfigurationEventMessage k
deviceConfigurationEventMessage.setCapturedOn(kuraNotifyMessage.getPayload().getTimestamp());
deviceConfigurationEventMessage.setSentOn(kuraNotifyMessage.getPayload().getTimestamp());
deviceConfigurationEventMessage.setReceivedOn(kuraNotifyMessage.getTimestamp());
- deviceConfigurationEventMessage.setPosition(TranslatorKuraKapuaUtils.translate(kuraNotifyMessage.getPayload().getPosition()));
+ deviceConfigurationEventMessage.setPosition(translatorKuraKapuaUtils.translate(kuraNotifyMessage.getPayload().getPosition()));
return deviceConfigurationEventMessage;
} catch (InvalidChannelException | InvalidPayloadException te) {
@@ -154,7 +155,9 @@ private DeviceConfigurationEventPayloadImpl translate(KuraConfigurationEventPayl
deviceComponentConfigurations.add(translate(kuraDeviceComponentConfiguration));
}
- configurationEventPayload.setDeviceComponentConfigurations(deviceComponentConfigurations);
+ final DeviceConfiguration deviceConfiguration = deviceConfigurationFactory.newConfigurationInstance();
+ deviceConfiguration.setComponentConfigurations(deviceComponentConfigurations);
+ configurationEventPayload.setDeviceComponentConfigurations(deviceConfiguration);
}
return configurationEventPayload;
@@ -173,7 +176,7 @@ private DeviceConfigurationEventPayloadImpl translate(KuraConfigurationEventPayl
* @since 2.0.0
*/
private DeviceComponentConfiguration translate(KuraDeviceComponentConfiguration kuraDeviceComponentConfiguration) {
- return DEVICE_CONFIGURATION_FACTORY.newComponentConfigurationInstance(kuraDeviceComponentConfiguration.getComponentId());
+ return deviceConfigurationFactory.newComponentConfigurationInstance(kuraDeviceComponentConfiguration.getComponentId());
}
@Override
@@ -187,6 +190,7 @@ public Class getClassTo() {
}
// Things copied from AbstractSimpleTranslatorResponseKuraKapua than need to be refactored
+ //TODO: FIXME: promote following methods as an external, injectable collaborator
private static final ObjectMapper JSON_MAPPER = new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java
index deea4df3e95..8f507290c63 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java
@@ -12,7 +12,6 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua.inventory;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.inventory.InventoryMetrics;
import org.eclipse.kapua.service.device.call.kura.model.inventory.KuraInventoryItems;
import org.eclipse.kapua.service.device.call.kura.model.inventory.bundles.KuraInventoryBundles;
@@ -21,6 +20,7 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackages;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponseChannel;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponseMessage;
@@ -39,10 +39,11 @@
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.kura.kapua.AbstractSimpleTranslatorResponseKuraKapua;
-import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
+
/**
* {@link Translator} {@code abstract} implementation from {@link KuraResponseMessage} to {@link InventoryResponseMessage}
*
@@ -51,23 +52,25 @@
public class AbstractTranslatorAppInventoryKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua {
private static final Logger LOG = LoggerFactory.getLogger(AbstractTranslatorAppInventoryKuraKapua.class);
-
- private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
+ private final DeviceInventoryManagementFactory deviceInventoryFactory;
/**
* Constructor.
*
- * @param responseMessageClass The type of the {@link InventoryResponseMessage}.
+ * @param deviceInventoryFactory
+ * @param responseMessageClass The type of the {@link InventoryResponseMessage}.
* @since 1.5.0
*/
- public AbstractTranslatorAppInventoryKuraKapua(Class responseMessageClass) {
- super(responseMessageClass, InventoryResponsePayload.class);
+ @Inject
+ public AbstractTranslatorAppInventoryKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryFactory, Class responseMessageClass) {
+ super(deviceManagementSetting, responseMessageClass, InventoryResponsePayload.class);
+ this.deviceInventoryFactory = deviceInventoryFactory;
}
@Override
protected InventoryResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, InventoryMetrics.APP_ID, InventoryMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, InventoryMetrics.APP_ID, InventoryMetrics.APP_VERSION);
return new InventoryResponseChannel();
} catch (Exception e) {
@@ -83,7 +86,6 @@ protected InventoryResponseChannel translateChannel(KuraResponseChannel kuraResp
* @since 1.5.0
*/
protected DeviceInventory translate(KuraInventoryItems kuraInventoryItems) {
- DeviceInventoryManagementFactory deviceInventoryFactory = LOCATOR.getFactory(DeviceInventoryManagementFactory.class);
DeviceInventory deviceInventory = deviceInventoryFactory.newDeviceInventory();
kuraInventoryItems.getInventoryItems().forEach(kuraInventoryItem -> {
@@ -106,7 +108,6 @@ protected DeviceInventory translate(KuraInventoryItems kuraInventoryItems) {
* @since 1.5.0
*/
protected DeviceInventoryBundles translate(KuraInventoryBundles kuraInventoryBundles) {
- DeviceInventoryManagementFactory deviceInventoryFactory = LOCATOR.getFactory(DeviceInventoryManagementFactory.class);
DeviceInventoryBundles deviceInventoryBundles = deviceInventoryFactory.newDeviceInventoryBundles();
kuraInventoryBundles.getInventoryBundles().forEach(kuraInventoryBundle -> {
@@ -131,7 +132,6 @@ protected DeviceInventoryBundles translate(KuraInventoryBundles kuraInventoryBun
* @since 2.0.0
*/
protected DeviceInventoryContainers translate(KuraInventoryContainers kuraInventoryContainers) {
- DeviceInventoryManagementFactory deviceInventoryFactory = LOCATOR.getFactory(DeviceInventoryManagementFactory.class);
DeviceInventoryContainers deviceInventoryContainers = deviceInventoryFactory.newDeviceInventoryContainers();
kuraInventoryContainers.getInventoryContainers().forEach(kuraInventoryContainer -> {
@@ -166,7 +166,6 @@ protected DeviceInventoryContainers translate(KuraInventoryContainers kuraInvent
* @since 1.5.0
*/
protected DeviceInventorySystemPackages translate(KuraInventorySystemPackages kuraInventorySystemPackages) {
- DeviceInventoryManagementFactory deviceInventoryFactory = LOCATOR.getFactory(DeviceInventoryManagementFactory.class);
DeviceInventorySystemPackages deviceInventorySystemPackages = deviceInventoryFactory.newDeviceInventorySystemPackages();
kuraInventorySystemPackages.getSystemPackages().forEach(kuraInventorySystemPackage -> {
@@ -189,7 +188,6 @@ protected DeviceInventorySystemPackages translate(KuraInventorySystemPackages ku
* @since 1.5.0
*/
protected DeviceInventoryPackages translate(KuraInventoryPackages kuraInventoryPackages) {
- DeviceInventoryManagementFactory deviceInventoryFactory = LOCATOR.getFactory(DeviceInventoryManagementFactory.class);
DeviceInventoryPackages deviceInventoryPackages = deviceInventoryFactory.newDeviceInventoryPackages();
kuraInventoryPackages.getPackages().forEach(kuraInventoryPackage -> {
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java
index 2b8c3577bf2..4a926af1d2e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.bundles.KuraInventoryBundles;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundlesResponseMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryBundlesResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppInventoryBundlesKuraKapua extends AbstractTranslatorAp
*
* @since 1.5.0
*/
- public TranslatorAppInventoryBundlesKuraKapua() {
- super(InventoryBundlesResponseMessage.class);
+ @Inject
+ public TranslatorAppInventoryBundlesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryBundlesResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java
index bf962a457cc..8cc60cfc187 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.containers.KuraInventoryContainers;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryContainersResponseMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryContainersResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppInventoryContainersKuraKapua extends AbstractTranslato
*
* @since 2.0.0
*/
- public TranslatorAppInventoryContainersKuraKapua() {
- super(InventoryContainersResponseMessage.class);
+ @Inject
+ public TranslatorAppInventoryContainersKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryContainersResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java
index aa227c1b922..24e44589340 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.KuraInventoryItems;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryListResponseMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryListResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppInventoryListKuraKapua extends AbstractTranslatorAppIn
*
* @since 1.5.0
*/
- public TranslatorAppInventoryListKuraKapua() {
- super(InventoryListResponseMessage.class);
+ @Inject
+ public TranslatorAppInventoryListKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryListResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java
index 6afb6b7bdaa..e24fb9263d0 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java
@@ -13,9 +13,13 @@
package org.eclipse.kapua.translator.kura.kapua.inventory;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryNoContentResponseMessage;
import org.eclipse.kapua.translator.Translator;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryNoContentResponseMessage}
*
@@ -28,7 +32,8 @@ public class TranslatorAppInventoryNoContentKuraKapua extends AbstractTranslator
*
* @since 1.5.0
*/
- public TranslatorAppInventoryNoContentKuraKapua() {
- super(InventoryNoContentResponseMessage.class);
+ @Inject
+ public TranslatorAppInventoryNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryNoContentResponseMessage.class);
}
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java
index abc6516da50..443b29fa49e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.packages.KuraInventoryPackages;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryPackagesResponseMessage;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryPackagesResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppInventoryPackagesKuraKapua extends AbstractTranslatorA
*
* @since 1.5.0
*/
- public TranslatorAppInventoryPackagesKuraKapua() {
- super(InventoryPackagesResponseMessage.class);
+ @Inject
+ public TranslatorAppInventoryPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryPackagesResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java
index 146890c7fb7..9f52c5be199 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackages;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload;
import org.eclipse.kapua.service.device.management.inventory.internal.message.InventorySystemPackagesResponseMessage;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventorySystemPackagesResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppInventorySystemPackagesKuraKapua extends AbstractTrans
*
* @since 1.5.0
*/
- public TranslatorAppInventorySystemPackagesKuraKapua() {
- super(InventorySystemPackagesResponseMessage.class);
+ @Inject
+ public TranslatorAppInventorySystemPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) {
+ super(deviceManagementSetting, deviceInventoryManagementFactory, InventorySystemPackagesResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java
index c537427fd05..f7c956b4a1e 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java
@@ -12,13 +12,13 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.kapua.keystore;
-import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.service.device.call.kura.model.keystore.KeystoreMetrics;
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystore;
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCSR;
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItem;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponseChannel;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponseMessage;
@@ -32,7 +32,6 @@
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidChannelException;
import org.eclipse.kapua.translator.kura.kapua.AbstractSimpleTranslatorResponseKuraKapua;
-import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,25 +49,25 @@ public abstract class AbstractTranslatorAppKeystoreKuraKapua responseMessageClass) {
- super(responseMessageClass, KeystoreResponsePayload.class);
+ @Inject
+ public AbstractTranslatorAppKeystoreKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory, Class responseMessageClass) {
+ super(deviceManagementSetting, responseMessageClass, KeystoreResponsePayload.class);
+ this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory;
}
@Override
protected KeystoreResponseChannel translateChannel(KuraResponseChannel kuraResponseChannel) throws InvalidChannelException {
try {
- TranslatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, KeystoreMetrics.APP_ID, KeystoreMetrics.APP_VERSION);
+ translatorKuraKapuaUtils.validateKuraResponseChannel(kuraResponseChannel, KeystoreMetrics.APP_ID, KeystoreMetrics.APP_VERSION);
return new KeystoreResponseChannel();
} catch (Exception e) {
@@ -85,11 +84,11 @@ protected KeystoreResponseChannel translateChannel(KuraResponseChannel kuraRespo
*/
protected DeviceKeystores translate(KuraKeystore[] kuraKeystoreArray) {
- DeviceKeystores deviceKeystores = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystores();
+ DeviceKeystores deviceKeystores = deviceKeystoreManagementFactory.newDeviceKeystores();
deviceKeystores.setKeystores(
Arrays.stream(kuraKeystoreArray).map(kuraKeystore -> {
- DeviceKeystore deviceKeystore = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystore();
+ DeviceKeystore deviceKeystore = deviceKeystoreManagementFactory.newDeviceKeystore();
deviceKeystore.setId(kuraKeystore.getKeystoreServicePid());
deviceKeystore.setKeystoreType(kuraKeystore.getType());
@@ -111,7 +110,7 @@ protected DeviceKeystores translate(KuraKeystore[] kuraKeystoreArray) {
*/
protected DeviceKeystoreItems translate(KuraKeystoreItem[] kuraKeystoreItemArray) {
- DeviceKeystoreItems deviceKeystoreItems = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItems();
+ DeviceKeystoreItems deviceKeystoreItems = deviceKeystoreManagementFactory.newDeviceKeystoreItems();
deviceKeystoreItems.setKeystoreItems(
Arrays.stream(kuraKeystoreItemArray)
@@ -131,7 +130,7 @@ protected DeviceKeystoreItems translate(KuraKeystoreItem[] kuraKeystoreItemArray
*/
protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) {
- DeviceKeystoreItem deviceKeystore = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItem();
+ DeviceKeystoreItem deviceKeystore = deviceKeystoreManagementFactory.newDeviceKeystoreItem();
deviceKeystore.setKeystoreId(kuraKeystoreItem.getKeystoreServicePid());
deviceKeystore.setItemType(kuraKeystoreItem.getType());
@@ -144,7 +143,7 @@ protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) {
deviceKeystore.setCertificateChain(kuraKeystoreItem.getCertificateChain());
for (String[] kuraSubjectAN : kuraKeystoreItem.getSubjectAN()) {
- DeviceKeystoreSubjectAN deviceSubjectAN = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreSubjectAN();
+ DeviceKeystoreSubjectAN deviceSubjectAN = deviceKeystoreManagementFactory.newDeviceKeystoreSubjectAN();
if (kuraSubjectAN == null || kuraSubjectAN.length != 2) {
LOG.warn("Invalid Subject Alternative Names provided from the device: {}", (Object) kuraSubjectAN);
@@ -176,7 +175,7 @@ protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) {
* @since 1.5.0
*/
protected DeviceKeystoreCSR translate(KuraKeystoreCSR kuraKeystoreCSR) {
- DeviceKeystoreCSR deviceKeystoreCSR = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCSR();
+ DeviceKeystoreCSR deviceKeystoreCSR = deviceKeystoreManagementFactory.newDeviceKeystoreCSR();
deviceKeystoreCSR.setSigningRequest(kuraKeystoreCSR.getSigningRequest());
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java
index aa1aedd037b..efee19b7fd4 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java
@@ -14,6 +14,8 @@
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCSR;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreCsrResponseMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload;
import org.eclipse.kapua.translator.Translator;
@@ -21,6 +23,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KeystoreCsrResponseMessage} to {@link KeystoreCsrResponseMessage}
*
@@ -35,8 +39,9 @@ public class TranslatorAppKeystoreCsrKuraKapua extends AbstractTranslatorAppKeys
*
* @since 1.5.0
*/
- public TranslatorAppKeystoreCsrKuraKapua() {
- super(KeystoreCsrResponseMessage.class);
+ @Inject
+ public TranslatorAppKeystoreCsrKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreCsrResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java
index 82d252496b8..8cf230b7fc2 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItem;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreItemResponseMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreItemResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppKeystoreItemKuraKapua extends AbstractTranslatorAppKey
*
* @since 1.5.0
*/
- public TranslatorAppKeystoreItemKuraKapua() {
- super(KeystoreItemResponseMessage.class);
+ @Inject
+ public TranslatorAppKeystoreItemKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreItemResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java
index ad67118ed58..16c31625c12 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItem;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreItemsResponseMessage;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreItemsResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppKeystoreItemsKuraKapua extends AbstractTranslatorAppKe
*
* @since 1.5.0
*/
- public TranslatorAppKeystoreItemsKuraKapua() {
- super(KeystoreItemsResponseMessage.class);
+ @Inject
+ public TranslatorAppKeystoreItemsKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreItemsResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java
index 39c33ade93e..4f72434d751 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java
@@ -13,9 +13,13 @@
package org.eclipse.kapua.translator.kura.kapua.keystore;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreNoContentResponseMessage;
import org.eclipse.kapua.translator.Translator;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreNoContentResponseMessage}
*
@@ -28,7 +32,8 @@ public class TranslatorAppKeystoreNoContentKuraKapua extends AbstractTranslatorA
*
* @since 1.5.0
*/
- public TranslatorAppKeystoreNoContentKuraKapua() {
- super(KeystoreNoContentResponseMessage.class);
+ @Inject
+ public TranslatorAppKeystoreNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreNoContentResponseMessage.class);
}
}
diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java
index b3e17c1f0ee..d4dd476772a 100644
--- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java
+++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java
@@ -15,11 +15,15 @@
import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystore;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage;
import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload;
+import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload;
import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoresResponseMessage;
import org.eclipse.kapua.translator.Translator;
import org.eclipse.kapua.translator.exception.InvalidPayloadException;
+import javax.inject.Inject;
+
/**
* {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoresResponseMessage}
*
@@ -32,8 +36,9 @@ public class TranslatorAppKeystoresKuraKapua extends AbstractTranslatorAppKeysto
*
* @since 1.5.0
*/
- public TranslatorAppKeystoresKuraKapua() {
- super(KeystoresResponseMessage.class);
+ @Inject
+ public TranslatorAppKeystoresKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) {
+ super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoresResponseMessage.class);
}
@Override
diff --git a/translator/kapua/kura/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator b/translator/kapua/kura/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
deleted file mode 100644
index 32bbf7b4952..00000000000
--- a/translator/kapua/kura/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
+++ /dev/null
@@ -1,43 +0,0 @@
-# From Kapua to Kura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppAssetKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppBundleKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppCommandKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppConfigurationKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppPackageKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppRequestKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorAppSnapshotKapuaKura
-org.eclipse.kapua.translator.kapua.kura.TranslatorDataKapuaKura
-org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryBundleExecKapuaKura
-org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryContainerExecKapuaKura
-org.eclipse.kapua.translator.kapua.kura.inventory.TranslatorAppInventoryEmptyKapuaKura
-org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreCertificateKapuaKura
-org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreCsrKapuaKura
-org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreKeypairKapuaKura
-org.eclipse.kapua.translator.kapua.kura.keystore.TranslatorAppKeystoreQueryKapuaKura
-
-# From Kura to Kapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppAssetKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppBundleKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppCommandKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppConfigurationKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppPackageKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppResponseKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppSnapshotKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorDataKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorLifeAppsKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorLifeBirthKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorLifeDisconnectKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorLifeMissingKuraKapua
-org.eclipse.kapua.translator.kura.kapua.TranslatorAppNotifyKuraKapua
-org.eclipse.kapua.translator.kura.kapua.event.TranslatorEventConfigurationKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryBundlesKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryContainersKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryListKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryNoContentKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventoryPackagesKuraKapua
-org.eclipse.kapua.translator.kura.kapua.inventory.TranslatorAppInventorySystemPackagesKuraKapua
-org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreItemKuraKapua
-org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreItemsKuraKapua
-org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreNoContentKuraKapua
-org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoreCsrKuraKapua
-org.eclipse.kapua.translator.kura.kapua.keystore.TranslatorAppKeystoresKuraKapua
diff --git a/translator/kura/jms/src/main/java/org/eclipse/kapua/translator/jms/kura/JmsKuraTranslatorsModule.java b/translator/kura/jms/src/main/java/org/eclipse/kapua/translator/jms/kura/JmsKuraTranslatorsModule.java
new file mode 100644
index 00000000000..ea4000c60cf
--- /dev/null
+++ b/translator/kura/jms/src/main/java/org/eclipse/kapua/translator/jms/kura/JmsKuraTranslatorsModule.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator.jms.kura;
+
+import com.google.inject.multibindings.Multibinder;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.jms.kura.data.TranslatorDataJmsKura;
+import org.eclipse.kapua.translator.jms.kura.event.TranslatorEventConfigurationManagementJmsKura;
+import org.eclipse.kapua.translator.jms.kura.lifecycle.TranslatorLifeAppsJmsKura;
+import org.eclipse.kapua.translator.jms.kura.lifecycle.TranslatorLifeBirthJmsKura;
+import org.eclipse.kapua.translator.jms.kura.lifecycle.TranslatorLifeDisconnectJmsKura;
+import org.eclipse.kapua.translator.jms.kura.lifecycle.TranslatorLifeMissingJmsKura;
+import org.eclipse.kapua.translator.jms.kura.notify.TranslatorLifeNotifyJmsKura;
+import org.eclipse.kapua.translator.kura.jms.data.TranslatorDataKuraJms;
+
+public class JmsKuraTranslatorsModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ final Multibinder translatorMultibinder = Multibinder.newSetBinder(binder(), Translator.class);
+ //org.eclipse.kapua.translator.jms.kura.data
+ translatorMultibinder.addBinding().to(TranslatorDataJmsKura.class);
+ //org.eclipse.kapua.translator.jms.kura.event
+ translatorMultibinder.addBinding().to(TranslatorEventConfigurationManagementJmsKura.class);
+ //org.eclipse.kapua.translator.jms.kura.lifecycle
+ translatorMultibinder.addBinding().to(TranslatorLifeAppsJmsKura.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeBirthJmsKura.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeDisconnectJmsKura.class);
+ translatorMultibinder.addBinding().to(TranslatorLifeMissingJmsKura.class);
+ //org.eclipse.kapua.translator.jms.kura.notify
+ translatorMultibinder.addBinding().to(TranslatorLifeNotifyJmsKura.class);
+ //org.eclipse.kapua.translator.kura.jms.data
+ translatorMultibinder.addBinding().to(TranslatorDataKuraJms.class);
+ }
+}
diff --git a/translator/kura/jms/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator b/translator/kura/jms/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
index 4b77fd700f3..bd00aca9941 100644
--- a/translator/kura/jms/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
+++ b/translator/kura/jms/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
@@ -1,3 +1,5 @@
+#Deprecated! Use dependency injection instead (JmsKuraTranslatorsModule)
+
org.eclipse.kapua.translator.jms.kura.data.TranslatorDataJmsKura
org.eclipse.kapua.translator.jms.kura.event.TranslatorEventConfigurationManagementJmsKura
org.eclipse.kapua.translator.jms.kura.lifecycle.TranslatorLifeAppsJmsKura
diff --git a/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/KuraMqttTranslatorsModule.java b/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/KuraMqttTranslatorsModule.java
new file mode 100644
index 00000000000..361d30d5739
--- /dev/null
+++ b/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/KuraMqttTranslatorsModule.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ * Red Hat Inc
+ *******************************************************************************/
+package org.eclipse.kapua.translator;
+
+import com.google.inject.multibindings.Multibinder;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.translator.kura.mqtt.TranslatorDataKuraMqtt;
+import org.eclipse.kapua.translator.kura.mqtt.TranslatorRequestKuraMqtt;
+import org.eclipse.kapua.translator.mqtt.kura.TranslatorDataMqttKura;
+import org.eclipse.kapua.translator.mqtt.kura.TranslatorResponseMqttKura;
+
+public class KuraMqttTranslatorsModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ final Multibinder translatorMultibinder = Multibinder.newSetBinder(binder(), Translator.class);
+ //org.eclipse.kapua.translator.kura.mqtt
+ translatorMultibinder.addBinding().to(TranslatorDataKuraMqtt.class);
+ translatorMultibinder.addBinding().to(TranslatorRequestKuraMqtt.class);
+ //org.eclipse.kapua.translator.mqtt.kura
+ translatorMultibinder.addBinding().to(TranslatorDataMqttKura.class);
+ translatorMultibinder.addBinding().to(TranslatorResponseMqttKura.class);
+ }
+}
diff --git a/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/kura/mqtt/TranslatorRequestKuraMqtt.java b/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/kura/mqtt/TranslatorRequestKuraMqtt.java
index b10dc3cbb24..ef33a160bba 100644
--- a/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/kura/mqtt/TranslatorRequestKuraMqtt.java
+++ b/translator/kura/mqtt/src/main/java/org/eclipse/kapua/translator/kura/mqtt/TranslatorRequestKuraMqtt.java
@@ -12,6 +12,7 @@
*******************************************************************************/
package org.eclipse.kapua.translator.kura.mqtt;
+import com.google.inject.Inject;
import org.eclipse.kapua.service.device.call.message.kura.KuraPayload;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestChannel;
import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage;
@@ -38,7 +39,12 @@
*/
public class TranslatorRequestKuraMqtt extends Translator {
- private static final String REPLY_PART = DeviceCallSettings.getInstance().getString(DeviceCallSettingKeys.DESTINATION_REPLY_PART);
+ private final String replyPart;
+
+ @Inject
+ public TranslatorRequestKuraMqtt(DeviceCallSettings deviceCallSettings) {
+ replyPart = deviceCallSettings.getString(DeviceCallSettingKeys.DESTINATION_REPLY_PART);
+ }
@Override
public MqttMessage translate(KuraRequestMessage kuraRequestMessage) throws TranslateException {
@@ -110,7 +116,7 @@ public MqttTopic generateResponseTopic(KuraRequestChannel kuraRequestChannel) th
topicTokens.add(kuraRequestChannel.getScope());
topicTokens.add(kuraRequestChannel.getRequesterClientId());
topicTokens.add(kuraRequestChannel.getAppId());
- topicTokens.add(REPLY_PART);
+ topicTokens.add(replyPart);
topicTokens.add(kuraRequestChannel.getRequestId());
return new MqttTopic(topicTokens.toArray(new String[0]));
diff --git a/translator/kura/mqtt/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator b/translator/kura/mqtt/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
index e18339c356e..db3b3932e2e 100644
--- a/translator/kura/mqtt/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
+++ b/translator/kura/mqtt/src/main/resources/META-INF/services/org.eclipse.kapua.translator.Translator
@@ -1,3 +1,5 @@
+#Deprecated! Use dependency injection instead (KuraMqttTranslatorsModule)
+
org.eclipse.kapua.translator.kura.mqtt.TranslatorDataKuraMqtt
org.eclipse.kapua.translator.kura.mqtt.TranslatorRequestKuraMqtt
diff --git a/translator/test-steps/src/main/java/org/eclipse/kapua/translator/test/steps/TranslatorSteps.java b/translator/test-steps/src/main/java/org/eclipse/kapua/translator/test/steps/TranslatorSteps.java
index e26849a03d6..973ccd6e23d 100644
--- a/translator/test-steps/src/main/java/org/eclipse/kapua/translator/test/steps/TranslatorSteps.java
+++ b/translator/test-steps/src/main/java/org/eclipse/kapua/translator/test/steps/TranslatorSteps.java
@@ -12,7 +12,15 @@
*******************************************************************************/
package org.eclipse.kapua.translator.test.steps;
+import com.google.inject.Singleton;
+import io.cucumber.java.Before;
+import io.cucumber.java.Scenario;
+import io.cucumber.java.en.And;
+import io.cucumber.java.en.Given;
+import io.cucumber.java.en.Then;
+import io.cucumber.java.en.When;
import org.eclipse.kapua.KapuaException;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.qa.common.StepData;
import org.eclipse.kapua.qa.common.TestBase;
import org.eclipse.kapua.service.device.call.message.kura.KuraPayload;
@@ -21,6 +29,7 @@
import org.eclipse.kapua.service.device.call.message.kura.data.KuraDataMessage;
import org.eclipse.kapua.service.device.call.message.kura.data.KuraDataPayload;
import org.eclipse.kapua.translator.Translator;
+import org.eclipse.kapua.translator.TranslatorHub;
import org.eclipse.kapua.translator.jms.kura.data.TranslatorDataJmsKura;
import org.eclipse.kapua.translator.kura.jms.data.TranslatorDataKuraJms;
import org.eclipse.kapua.translator.kura.mqtt.TranslatorDataKuraMqtt;
@@ -34,15 +43,6 @@
import org.eclipse.kapua.transport.message.mqtt.MqttTopic;
import org.junit.Assert;
-import com.google.inject.Singleton;
-
-import io.cucumber.java.Before;
-import io.cucumber.java.Scenario;
-import io.cucumber.java.en.And;
-import io.cucumber.java.en.Given;
-import io.cucumber.java.en.Then;
-import io.cucumber.java.en.When;
-
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
@@ -53,16 +53,18 @@
@Singleton
public class TranslatorSteps extends TestBase {
- private ExampleTranslator exampleTranslator;
- private TranslatorDataMqttKura translatorDataMqttKura;
- private TranslatorResponseMqttKura translatorResponseMqttKura;
- private TranslatorDataKuraMqtt translatorDataKuraMqtt;
- private TranslatorDataJmsKura translatorDataJmsKura;
- private TranslatorDataKuraJms translatorDataKuraJms;
+ private final ExampleTranslator exampleTranslator;
+ private final TranslatorDataMqttKura translatorDataMqttKura;
+ private final TranslatorResponseMqttKura translatorResponseMqttKura;
+ private final TranslatorDataKuraMqtt translatorDataKuraMqtt;
+ private final TranslatorDataJmsKura translatorDataJmsKura;
+ private final TranslatorDataKuraJms translatorDataKuraJms;
+ private final TranslatorHub translatorHub;
@Inject
public TranslatorSteps(StepData stepData) {
super(stepData);
+ translatorHub = KapuaLocator.getInstance().getComponent(TranslatorHub.class);
exampleTranslator = new ExampleTranslator();
translatorDataMqttKura = new TranslatorDataMqttKura();
translatorResponseMqttKura = new TranslatorResponseMqttKura();
@@ -92,7 +94,7 @@ public void iFindTranslator(String from, String to) throws Exception {
fromClass = null;
toClass = null;
}
- Translator translator = Translator.getTranslatorFor(exampleTranslator.getClass(fromClass), exampleTranslator.getClass(toClass));
+ Translator translator = translatorHub.getTranslatorFor(exampleTranslator.getClass(fromClass), exampleTranslator.getClass(toClass));
stepData.put("Translator", translator);
} catch (Exception ex) {
verifyException(ex);
@@ -106,7 +108,7 @@ public void translatorIsFound(String translatorName) {
}
@Given("I create mqtt message with (valid/invalid/empty) payload {string} and (valid/invalid) topic {string}")
- public void creatingMqttMessage(String payload, String topic) throws Exception{
+ public void creatingMqttMessage(String payload, String topic) throws Exception {
try {
Date date = new Date();
MqttTopic mqttTopic = new MqttTopic(topic);
@@ -119,7 +121,7 @@ public void creatingMqttMessage(String payload, String topic) throws Exception{
MqttPayload mqttPayload = new MqttPayload(kuraPayload.toByteArray());
MqttMessage mqttMessage = new MqttMessage(mqttTopic, date, mqttPayload);
stepData.put("MqttMessage", mqttMessage);
- } catch (Exception ex){
+ } catch (Exception ex) {
verifyException(ex);
}
}
@@ -328,7 +330,7 @@ public void iTryToTranslateMqttNullMessageToKuraDataMessage() throws Exception {
MqttMessage mqttMessage = (MqttMessage) stepData.get("MqttMessage");
KuraDataMessage kuraDataMessage = translatorDataMqttKura.translate((MqttMessage) null);
stepData.put("KuraDataMessage", kuraDataMessage);
- } catch (Exception ex){
+ } catch (Exception ex) {
verifyException(ex);
}
}
@@ -363,7 +365,7 @@ public void iTryToTranslateInvalidKuraDataMessageToMqttMessage() throws Exceptio
}
@When("I try to translate invalid jms message to kura data message")
- public void iTryToTranslateInvalidJmsMessageToKuraDataMessage() throws Exception{
+ public void iTryToTranslateInvalidJmsMessageToKuraDataMessage() throws Exception {
try {
KuraDataMessage kuraDataMessage = translatorDataJmsKura.translate((JmsMessage) null);
stepData.put("KuraDataMessage", kuraDataMessage);
@@ -377,7 +379,7 @@ public void iTryToTranslateInvalidKuraDataMessageToJmsMessage() throws Exception
try {
JmsMessage jmsMessage = translatorDataKuraJms.translate((KuraDataMessage) null);
stepData.put("JmsMessage", jmsMessage);
- } catch (Exception ex){
+ } catch (Exception ex) {
verifyException(ex);
}
}
diff --git a/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java b/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java
index 162b21ab491..9a535a643a3 100644
--- a/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java
+++ b/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java
@@ -12,20 +12,52 @@
*******************************************************************************/
package org.eclipse.kapua.translator.test;
+import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
+import com.google.inject.name.Names;
import io.cucumber.java.Before;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.configuration.metatype.KapuaMetatypeFactoryImpl;
+import org.eclipse.kapua.commons.crypto.CryptoUtil;
+import org.eclipse.kapua.commons.crypto.CryptoUtilImpl;
+import org.eclipse.kapua.commons.crypto.setting.CryptoSettings;
import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration;
+import org.eclipse.kapua.commons.metric.CommonsMetric;
+import org.eclipse.kapua.commons.metric.MetricsService;
+import org.eclipse.kapua.commons.metric.MetricsServiceImpl;
+import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider;
+import org.eclipse.kapua.commons.setting.system.SystemSetting;
import org.eclipse.kapua.locator.KapuaLocator;
+import org.eclipse.kapua.message.KapuaMessageFactory;
+import org.eclipse.kapua.message.device.data.KapuaDataMessageFactory;
+import org.eclipse.kapua.message.internal.KapuaMessageFactoryImpl;
import org.eclipse.kapua.model.config.metatype.KapuaMetatypeFactory;
+import org.eclipse.kapua.model.id.KapuaIdFactory;
import org.eclipse.kapua.qa.common.MockedLocator;
+import org.eclipse.kapua.service.account.AccountService;
+import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator;
+import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl;
+import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting;
import org.eclipse.kapua.service.authorization.AuthorizationService;
+import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
import org.eclipse.kapua.service.authorization.permission.Permission;
import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
+import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory;
+import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory;
+import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory;
+import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory;
+import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory;
+import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory;
+import org.eclipse.kapua.service.device.management.request.GenericRequestFactory;
+import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory;
+import org.eclipse.kapua.service.device.registry.DeviceRegistryService;
+import org.eclipse.kapua.translator.KapuaKuraTranslatorsModule;
+import org.eclipse.kapua.translator.KuraMqttTranslatorsModule;
+import org.eclipse.kapua.translator.TranslatorHubModule;
+import org.eclipse.kapua.translator.jms.kura.JmsKuraTranslatorsModule;
import org.mockito.Matchers;
import org.mockito.Mockito;
@@ -45,7 +77,18 @@ public void setupDI() {
@Override
protected void configure() {
-
+ bind(CommonsMetric.class).toInstance(Mockito.mock(CommonsMetric.class));
+ bind(SystemSetting.class).toInstance(SystemSetting.getInstance());
+ bind(DomainRegistryService.class).toInstance(Mockito.mock(DomainRegistryService.class));
+ final CacheManagerProvider cacheManagerProvider;
+ cacheManagerProvider = new CacheManagerProvider(Mockito.mock(CommonsMetric.class), SystemSetting.getInstance());
+ bind(javax.cache.CacheManager.class).toInstance(cacheManagerProvider.get());
+ bind(MfaAuthenticator.class).toInstance(new MfaAuthenticatorImpl(new KapuaAuthenticationSetting()));
+ bind(CryptoUtil.class).toInstance(new CryptoUtilImpl(new CryptoSettings()));
+ bind(String.class).annotatedWith(Names.named("metricModuleName")).toInstance("tests");
+ bind(MetricRegistry.class).toInstance(new MetricRegistry());
+ bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class);
+ bind(KapuaMessageFactory.class).to(KapuaMessageFactoryImpl.class).in(Singleton.class);
// Inject mocked Authorization Service method checkPermission
AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class);
bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration());
@@ -58,12 +101,24 @@ protected void configure() {
bind(AuthorizationService.class).toInstance(mockedAuthorization);
// Inject mocked Permission Factory
bind(PermissionFactory.class).toInstance(Mockito.mock(PermissionFactory.class));
+ bind(AccountService.class).toInstance(Mockito.mock(AccountService.class));
+ bind(DeviceRegistryService.class).toInstance(Mockito.mock(DeviceRegistryService.class));
+ bind(GenericRequestFactory.class).toInstance(Mockito.mock(GenericRequestFactory.class));
+ bind(DeviceAssetFactory.class).toInstance(Mockito.mock(DeviceAssetFactory.class));
+ bind(DeviceBundleFactory.class).toInstance(Mockito.mock(DeviceBundleFactory.class));
+ bind(KapuaIdFactory.class).toInstance(Mockito.mock(KapuaIdFactory.class));
+ bind(DevicePackageFactory.class).toInstance(Mockito.mock(DevicePackageFactory.class));
+ bind(DeviceSnapshotFactory.class).toInstance(Mockito.mock(DeviceSnapshotFactory.class));
+ bind(KapuaDataMessageFactory.class).toInstance(Mockito.mock(KapuaDataMessageFactory.class));
+ bind(DeviceConfigurationFactory.class).toInstance(Mockito.mock(DeviceConfigurationFactory.class));
+ bind(DeviceInventoryManagementFactory.class).toInstance(Mockito.mock(DeviceInventoryManagementFactory.class));
+ bind(DeviceKeystoreManagementFactory.class).toInstance(Mockito.mock(DeviceKeystoreManagementFactory.class));
// Set KapuaMetatypeFactory for Metatype configuration
bind(KapuaMetatypeFactory.class).toInstance(new KapuaMetatypeFactoryImpl());
}
};
- Injector injector = Guice.createInjector(module);
+ Injector injector = Guice.createInjector(module, new TranslatorHubModule(), new KapuaKuraTranslatorsModule(), new KuraMqttTranslatorsModule(), new JmsKuraTranslatorsModule());
mockedLocator.setInjector(injector);
}
}
diff --git a/translator/test/src/test/resources/features/TranslatorUnitTests.feature b/translator/test/src/test/resources/features/TranslatorUnitTests.feature
index 74a22293a37..3a8af787a90 100644
--- a/translator/test/src/test/resources/features/TranslatorUnitTests.feature
+++ b/translator/test/src/test/resources/features/TranslatorUnitTests.feature
@@ -18,8 +18,8 @@ Feature: Translator Service
#KapuaTranslatorApi
-@setup
-@KapuaProperties("locator.class.impl=org.eclipse.kapua.qa.common.MockedLocator")
+ @setup
+ @KapuaProperties("locator.class.impl=org.eclipse.kapua.qa.common.MockedLocator")
Scenario: Initialize test environment
Given Init Jaxb Context
And Init Security Context
@@ -35,7 +35,7 @@ Feature: Translator Service
Trying to make translation from CommandRequestMessage to null message.
NullPointerException should be thrown.
- Given I expect the exception "NullPointerException" with the text "*"
+ Given I expect the exception "TranslatorNotFoundException" with the text "*"
When I try to translate from "org.eclipse.kapua.service.device.management.command.message.internal.CommandRequestMessage" to ""
Then An exception was thrown
@@ -43,14 +43,14 @@ Feature: Translator Service
Trying to make translation from null to KuraRequestMessage message.
NullPointerException should be thrown.
- Given I expect the exception "NullPointerException" with the text "*"
+ Given I expect the exception "TranslatorNotFoundException" with the text "*"
When I try to translate from "" to "org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage"
Then An exception was thrown
Scenario: Translating empty message to empty message
Trying to do translation without messages. NPE exception should be thrown.
- Given I expect the exception "NullPointerException" with the text "*"
+ Given I expect the exception "TranslatorNotFoundException" with the text "*"
And I try to translate from "" to ""
Then An exception was thrown
@@ -221,9 +221,9 @@ Feature: Translator Service
Given I create jms message with invalid payload "invalidPayload" and valid topic "kapua-sys/rpione3/DEPLOY-V2/GET/packages"
When I try to translate jms message to kura data message
Then I got kura data message channel with "kapua-sys" scope, "rpione3" client id and proper semanticPart
- | DEPLOY-V2 |
- | GET |
- | packages |
+ | DEPLOY-V2 |
+ | GET |
+ | packages |
And I got kura data message with "byte[]" payload body
And No exception was thrown
@@ -234,9 +234,9 @@ Feature: Translator Service
Given I create jms message with valid payload "response.code" and valid topic "kapua-sys/rpione3/DEPLOY-V2/GET/packages"
When I try to translate jms message to kura data message
Then I got kura data message channel with "kapua-sys" scope, "rpione3" client id and proper semanticPart
- | DEPLOY-V2 |
- | GET |
- | packages |
+ | DEPLOY-V2 |
+ | GET |
+ | packages |
And I got kura data message with proper payload metrics response code 200
And No exception was thrown
@@ -247,9 +247,9 @@ Feature: Translator Service
Given I create jms message with empty payload "" and valid topic "kapua-sys/rpione3/DEPLOY-V2/GET/packages"
And I try to translate jms message to kura data message
And I got kura data message channel with "kapua-sys" scope, "rpione3" client id and proper semanticPart
- | DEPLOY-V2 |
- | GET |
- | packages |
+ | DEPLOY-V2 |
+ | GET |
+ | packages |
Then I got kura data message with empty payload
And No exception was thrown
@@ -328,7 +328,7 @@ Feature: Translator Service
When I try to translate invalid kura data message to jms message
Then An exception was thrown
-@teardown
+ @teardown
Scenario: Reset Security Context for all scenarios
Given Reset Security Context
And An exception was thrown
diff --git a/transport/api/src/main/java/org/eclipse/kapua/transport/TransportModule.java b/transport/api/src/main/java/org/eclipse/kapua/transport/TransportModule.java
new file mode 100644
index 00000000000..27a1c3f989e
--- /dev/null
+++ b/transport/api/src/main/java/org/eclipse/kapua/transport/TransportModule.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
+ *
+ * This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License 2.0
+ * which is available at https://www.eclipse.org/legal/epl-2.0/
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *
+ * Contributors:
+ * Eurotech - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.kapua.transport;
+
+import com.google.inject.Provides;
+import org.eclipse.kapua.commons.core.AbstractKapuaModule;
+import org.eclipse.kapua.commons.util.RandomUtils;
+import org.eclipse.kapua.transport.utils.ClientIdGenerator;
+
+import javax.inject.Singleton;
+
+public class TransportModule extends AbstractKapuaModule {
+ @Override
+ protected void configureModule() {
+ }
+
+ @Provides
+ @Singleton
+ ClientIdGenerator clientIdGenerator() {
+ return new ClientIdGenerator(RandomUtils.getInstance());
+ }
+}
diff --git a/transport/api/src/main/java/org/eclipse/kapua/transport/utils/ClientIdGenerator.java b/transport/api/src/main/java/org/eclipse/kapua/transport/utils/ClientIdGenerator.java
index 53db425a15a..eb1bf62030d 100644
--- a/transport/api/src/main/java/org/eclipse/kapua/transport/utils/ClientIdGenerator.java
+++ b/transport/api/src/main/java/org/eclipse/kapua/transport/utils/ClientIdGenerator.java
@@ -13,8 +13,7 @@
package org.eclipse.kapua.transport.utils;
-import org.eclipse.kapua.commons.util.RandomUtils;
-
+import javax.inject.Inject;
import java.util.Random;
/**
@@ -37,31 +36,16 @@ public class ClientIdGenerator {
*
* @since 1.2.0
*/
- private static final Random RANDOM = RandomUtils.getInstance();
-
- /**
- * {@code static} instance singleton reference
- *
- * @since 1.0.0
- */
- private static final ClientIdGenerator INSTANCE = new ClientIdGenerator();
-
- /**
- * Private default constructor. To obtain an instance of {@link ClientIdGenerator} use {@link ClientIdGenerator#getInstance()}.
- *
- * @since 1.0.0
- */
- private ClientIdGenerator() {
- }
+ private final Random random;
/**
- * Returns a {@code static} instance of the {@link ClientIdGenerator}.
+ * Default constructor.
*
- * @return The singleton instance of {@link ClientIdGenerator}
* @since 1.0.0
*/
- public static ClientIdGenerator getInstance() {
- return INSTANCE;
+ @Inject
+ public ClientIdGenerator(Random random) {
+ this.random = random;
}
/**
@@ -86,7 +70,7 @@ public String next() {
*/
public String next(String prefix) {
long timestamp = System.currentTimeMillis();
- long randomNumber = RANDOM.nextLong();
+ long randomNumber = random.nextLong();
return String.format(GENERATED_ID_STRING_FORMAT,
prefix,
diff --git a/transport/api/src/test/java/org/eclipse/kapua/transport/utils/ClientIdGeneratorTest.java b/transport/api/src/test/java/org/eclipse/kapua/transport/utils/ClientIdGeneratorTest.java
index c71e874fe0d..f70cca82d96 100644
--- a/transport/api/src/test/java/org/eclipse/kapua/transport/utils/ClientIdGeneratorTest.java
+++ b/transport/api/src/test/java/org/eclipse/kapua/transport/utils/ClientIdGeneratorTest.java
@@ -20,7 +20,10 @@
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Random;
+import java.util.Set;
/**
* {@link ClientIdGenerator} tests.
@@ -32,20 +35,9 @@ public class ClientIdGeneratorTest {
private static final Logger LOG = LoggerFactory.getLogger(ClientIdGeneratorTest.class);
- @Test
- public void getInstanceTest() {
- ClientIdGenerator clientIdGenerator1 = ClientIdGenerator.getInstance();
- Assert.assertNotNull(clientIdGenerator1);
-
- ClientIdGenerator clientIdGenerator2 = ClientIdGenerator.getInstance();
- Assert.assertNotNull(clientIdGenerator2);
-
- Assert.assertEquals(clientIdGenerator1, clientIdGenerator2);
- }
-
@Test
public void nextTest() {
- ClientIdGenerator clientIdGenerator = ClientIdGenerator.getInstance();
+ ClientIdGenerator clientIdGenerator = new ClientIdGenerator(new Random());
String nextId = clientIdGenerator.next();
@@ -56,9 +48,9 @@ public void nextTest() {
@Test
public void nextGenerationTest() {
- ClientIdGenerator clientIdGenerator = ClientIdGenerator.getInstance();
+ ClientIdGenerator clientIdGenerator = new ClientIdGenerator(new Random());
- List generatedIds = new ArrayList<>();
+ Set generatedIds = new HashSet<>();
for (int i = 0; i < 10000; i++) {
String nextId = clientIdGenerator.next();
LOG.trace("Generated Id: {}", nextId);
@@ -72,7 +64,7 @@ public void nextGenerationTest() {
@Test
public void nextWithPrefixTest() {
- ClientIdGenerator clientIdGenerator = ClientIdGenerator.getInstance();
+ ClientIdGenerator clientIdGenerator = new ClientIdGenerator(new Random());
String nextId = clientIdGenerator.next("MyPrefix");
@@ -83,7 +75,7 @@ public void nextWithPrefixTest() {
@Test
public void nextWithPrefixGenerationTest() {
- ClientIdGenerator clientIdGenerator = ClientIdGenerator.getInstance();
+ ClientIdGenerator clientIdGenerator = new ClientIdGenerator(new Random());
List generatedIds = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
diff --git a/transport/jms/src/main/java/org/eclipse/kapua/transport/jms/setting/JmsClientSetting.java b/transport/jms/src/main/java/org/eclipse/kapua/transport/jms/setting/JmsClientSetting.java
index 4f94feac517..69808b0f712 100644
--- a/transport/jms/src/main/java/org/eclipse/kapua/transport/jms/setting/JmsClientSetting.java
+++ b/transport/jms/src/main/java/org/eclipse/kapua/transport/jms/setting/JmsClientSetting.java
@@ -19,6 +19,7 @@
*
* @since 1.0.0
*/
+//TODO: FIXME: singletons should not be handled manually, we have DI for that
public class JmsClientSetting extends AbstractKapuaSetting {
/**
diff --git a/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsPayload.java b/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsPayload.java
index 957834854a3..32eddfa15cb 100644
--- a/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsPayload.java
+++ b/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsPayload.java
@@ -27,6 +27,7 @@
*/
public class JmsPayload implements TransportPayload {
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
private static final int BODY_TOSTRING_LENGTH = JmsClientSetting.getInstance().getInt(JmsClientSettingKeys.PAYLOAD_TOSTRING_LENGTH, 64);
/**
diff --git a/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsTopic.java b/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsTopic.java
index eff013db573..9bb53de97d6 100644
--- a/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsTopic.java
+++ b/transport/jms/src/main/java/org/eclipse/kapua/transport/message/jms/JmsTopic.java
@@ -32,6 +32,7 @@ public class JmsTopic implements TransportChannel {
*
* @since 1.0.0
*/
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
private static final String TOPIC_SEPARATOR = JmsClientSetting.getInstance().getString(JmsClientSettingKeys.TRANSPORT_TOPIC_SEPARATOR);
/**
diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttPayload.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttPayload.java
index 436c25b59d6..696460680a7 100644
--- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttPayload.java
+++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttPayload.java
@@ -27,6 +27,7 @@
*/
public class MqttPayload implements TransportPayload {
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
private static final int BODY_TOSTRING_LENGTH = MqttClientSetting.getInstance().getInt(MqttClientSettingKeys.PAYLOAD_TOSTRING_LENGTH, 64);
/**
diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttTopic.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttTopic.java
index 8df8e0df36f..3ed2084ae65 100644
--- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttTopic.java
+++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/message/mqtt/MqttTopic.java
@@ -32,6 +32,7 @@ public class MqttTopic implements TransportChannel {
*
* @since 1.0.0
*/
+ //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class!
private static final String TOPIC_SEPARATOR = MqttClientSetting.getInstance().getString(MqttClientSettingKeys.TRANSPORT_TOPIC_SEPARATOR, "/");
/**
diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/PooledMqttClientFactory.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/PooledMqttClientFactory.java
index 241c0a75bf2..95b2d071e8f 100644
--- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/PooledMqttClientFactory.java
+++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/PooledMqttClientFactory.java
@@ -15,6 +15,7 @@
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
+import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.transport.mqtt.MqttClient;
import org.eclipse.kapua.transport.mqtt.MqttClientConnectionOptions;
import org.eclipse.kapua.transport.mqtt.exception.MqttClientException;
@@ -37,7 +38,8 @@
public class PooledMqttClientFactory extends BasePooledObjectFactory {
private static final Logger LOG = LoggerFactory.getLogger(PooledMqttClientFactory.class);
- private static final ClientIdGenerator CLIENT_ID_GENERATOR = ClientIdGenerator.getInstance();
+ //TODO: Inject if possible
+ private final ClientIdGenerator clientIdGenerator = KapuaLocator.getInstance().getComponent(ClientIdGenerator.class);
private final String serverURI;
@@ -63,7 +65,7 @@ public MqttClient create() throws Exception {
String username = mqttClientSettings.getString(MqttClientSettingKeys.TRANSPORT_CREDENTIAL_USERNAME);
char[] password = mqttClientSettings.getString(MqttClientSettingKeys.TRANSPORT_CREDENTIAL_PASSWORD).toCharArray();
- String clientId = CLIENT_ID_GENERATOR.next(mqttClientPoolSettings.getString(MqttClientPoolSettingKeys.CLIENT_POOL_CLIENT_ID_PREFIX));
+ String clientId = clientIdGenerator.next(mqttClientPoolSettings.getString(MqttClientPoolSettingKeys.CLIENT_POOL_CLIENT_ID_PREFIX));
// Get new client and connection options
MqttClientConnectionOptions connectionOptions = new MqttClientConnectionOptions();
connectionOptions.setClientId(clientId);
diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/setting/MqttClientPoolSetting.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/setting/MqttClientPoolSetting.java
index 68182fec51b..dafbc0f2643 100644
--- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/setting/MqttClientPoolSetting.java
+++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/pooling/setting/MqttClientPoolSetting.java
@@ -19,6 +19,7 @@
*
* @since 1.0.0
*/
+//TODO: FIXME: singletons should not be handled manually, we have DI for that
public class MqttClientPoolSetting extends AbstractKapuaSetting {
/**
diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/setting/MqttClientSetting.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/setting/MqttClientSetting.java
index 6a985f07d13..38a4e6d40df 100644
--- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/setting/MqttClientSetting.java
+++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/setting/MqttClientSetting.java
@@ -19,6 +19,7 @@
*
* @since 1.0.0
*/
+//TODO: FIXME: singletons should not be handled manually, we have DI for that
public class MqttClientSetting extends AbstractKapuaSetting {
/**