Search in sources :

Example 1 with AssetDescriptor

use of org.openremote.model.asset.AssetDescriptor in project openremote by openremote.

the class PersistenceService method init.

@Override
public void init(Container container) throws Exception {
    this.messageBrokerService = container.hasService(MessageBrokerService.class) ? container.getService(MessageBrokerService.class) : null;
    String dbVendor = getString(container.getConfig(), DB_VENDOR, DB_VENDOR_DEFAULT).toUpperCase(Locale.ROOT);
    LOG.info("Preparing persistence service for database: " + dbVendor);
    try {
        database = Database.Product.valueOf(dbVendor);
    } catch (Exception e) {
        LOG.severe("Requested DB_VENDOR is not supported: " + dbVendor);
        throw new UnsupportedOperationException("Requested DB_VENDOR is not supported: " + dbVendor);
    }
    String dbHost = getString(container.getConfig(), DB_HOST, DB_HOST_DEFAULT);
    int dbPort = getInteger(container.getConfig(), DB_PORT, DB_PORT_DEFAULT);
    String dbName = getString(container.getConfig(), DB_NAME, DB_NAME_DEFAULT);
    String dbSchema = getString(container.getConfig(), DB_SCHEMA, DB_SCHEMA_DEFAULT);
    String dbUsername = getString(container.getConfig(), DB_USERNAME, DB_USERNAME_DEFAULT);
    String dbPassword = getString(container.getConfig(), DB_PASSWORD, DB_PASSWORD_DEFAULT);
    String connectionUrl = "jdbc:" + database.getConnectorName() + "://" + dbHost + ":" + dbPort + "/" + dbName;
    connectionUrl = UriBuilder.fromUri(connectionUrl).replaceQueryParam("currentSchema", dbSchema).build().toString();
    persistenceUnitProperties = database.createProperties();
    if (messageBrokerService != null) {
        persistenceUnitProperties.put(AvailableSettings.SESSION_SCOPED_INTERCEPTOR, PersistenceEventInterceptor.class.getName());
    }
    persistenceUnitProperties.put(AvailableSettings.DEFAULT_SCHEMA, dbSchema);
    // Add custom integrator so we can register a custom flush entity event listener
    persistenceUnitProperties.put(EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, IntegratorProvider.class.getName());
    persistenceUnitName = getString(container.getConfig(), PERSISTENCE_UNIT_NAME, PERSISTENCE_UNIT_NAME_DEFAULT);
    forceClean = getBoolean(container.getConfig(), SETUP_WIPE_CLEAN_INSTALL, container.isDevMode());
    openDatabase(container, database, dbUsername, dbPassword, connectionUrl);
    prepareSchema(connectionUrl, dbUsername, dbPassword, dbSchema);
    // Register standard entity classes and also any Entity ClassProviders
    List<String> entityClasses = new ArrayList<>(50);
    entityClasses.add(Asset.class.getName());
    entityClasses.add(UserAssetLink.class.getName());
    entityClasses.add(AssetDatapoint.class.getName());
    entityClasses.add(SentNotification.class.getName());
    entityClasses.add(AssetPredictedDatapoint.class.getName());
    entityClasses.add(Tenant.class.getName());
    entityClasses.add(User.class.getName());
    entityClasses.add(UserAttribute.class.getName());
    entityClasses.add(RealmRole.class.getName());
    entityClasses.add(GlobalRuleset.class.getName());
    entityClasses.add(AssetRuleset.class.getName());
    entityClasses.add(TenantRuleset.class.getName());
    entityClasses.add(SyslogEvent.class.getName());
    entityClasses.add(GatewayConnection.class.getName());
    entityClasses.add(ConsoleAppConfig.class.getName());
    entityClasses.add(ProvisioningConfig.class.getName());
    entityClasses.add(X509ProvisioningConfig.class.getName());
    // Add packages with package-info (don't think this is JPA spec but hibernate specific)
    entityClasses.add("org.openremote.container.persistence");
    entityClasses.add("org.openremote.container.util");
    // Get asset sub type entities from asset model
    Arrays.stream(ValueUtil.getAssetDescriptors(null)).map(AssetDescriptor::getType).filter(assetClass -> assetClass.getAnnotation(Entity.class) != null).map(Class::getName).forEach(entityClasses::add);
    // Get any entity class providers from the service loader
    ServiceLoader<EntityClassProvider> entityClassProviders = ServiceLoader.load(EntityClassProvider.class);
    entityClassProviders.forEach(entityClassProvider -> entityClassProvider.getEntityClasses().stream().filter(entityClass -> entityClass.getAnnotation(Entity.class) != null).map(Class::getName).forEach(entityClasses::add));
    this.entityManagerFactory = getEntityManagerFactory(persistenceUnitProperties, entityClasses);
// Persistence.createEntityManagerFactory(persistenceUnitName, persistenceUnitProperties);
}
Also used : Tenant(org.openremote.model.security.Tenant) IntStream(java.util.stream.IntStream) MigrateResult(org.flywaydb.core.api.output.MigrateResult) UserAssetLink(org.openremote.model.asset.UserAssetLink) java.util(java.util) javax.persistence(javax.persistence) GatewayConnection(org.openremote.model.gateway.GatewayConnection) AssetDescriptor(org.openremote.model.asset.AssetDescriptor) AvailableSettings(org.hibernate.cfg.AvailableSettings) SentNotification(org.openremote.model.notification.SentNotification) URL(java.net.URL) Session(org.hibernate.Session) ValueUtil(org.openremote.model.util.ValueUtil) Function(java.util.function.Function) Level(java.util.logging.Level) ProvisioningConfig(org.openremote.model.provisioning.ProvisioningConfig) Predicate(org.apache.camel.Predicate) ClassTransformer(javax.persistence.spi.ClassTransformer) RealmRole(org.openremote.model.security.RealmRole) AssetRuleset(org.openremote.model.rules.AssetRuleset) DataSource(javax.sql.DataSource) ProducerTemplate(org.apache.camel.ProducerTemplate) X509ProvisioningConfig(org.openremote.model.provisioning.X509ProvisioningConfig) UriBuilder(javax.ws.rs.core.UriBuilder) MigrationInfo(org.flywaydb.core.api.MigrationInfo) ExchangePattern(org.apache.camel.ExchangePattern) ConsoleAppConfig(org.openremote.model.apps.ConsoleAppConfig) MessageBrokerService(org.openremote.container.message.MessageBrokerService) User(org.openremote.model.security.User) GlobalRuleset(org.openremote.model.rules.GlobalRuleset) Asset(org.openremote.model.asset.Asset) PersistenceUnitInfoDescriptor(org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor) PersistenceUnitTransactionType(javax.persistence.spi.PersistenceUnitTransactionType) AssetDatapoint(org.openremote.model.datapoint.AssetDatapoint) Field(java.lang.reflect.Field) Logger(java.util.logging.Logger) Consumer(java.util.function.Consumer) SyslogEvent(org.openremote.model.syslog.SyslogEvent) MapAccess(org.openremote.container.util.MapAccess) org.openremote.model(org.openremote.model) AssetPredictedDatapoint(org.openremote.model.datapoint.AssetPredictedDatapoint) EntityManagerFactoryBuilder(org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder) UserAttribute(org.openremote.model.security.UserAttribute) EntityManagerFactoryBuilderImpl(org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl) Flyway(org.flywaydb.core.Flyway) TenantRuleset(org.openremote.model.rules.TenantRuleset) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) User(org.openremote.model.security.User) UserAttribute(org.openremote.model.security.UserAttribute) AssetDatapoint(org.openremote.model.datapoint.AssetDatapoint) UserAssetLink(org.openremote.model.asset.UserAssetLink) SentNotification(org.openremote.model.notification.SentNotification) AssetPredictedDatapoint(org.openremote.model.datapoint.AssetPredictedDatapoint) SyslogEvent(org.openremote.model.syslog.SyslogEvent) AssetRuleset(org.openremote.model.rules.AssetRuleset) Tenant(org.openremote.model.security.Tenant) GatewayConnection(org.openremote.model.gateway.GatewayConnection) TenantRuleset(org.openremote.model.rules.TenantRuleset) Asset(org.openremote.model.asset.Asset) X509ProvisioningConfig(org.openremote.model.provisioning.X509ProvisioningConfig) GlobalRuleset(org.openremote.model.rules.GlobalRuleset) AssetDatapoint(org.openremote.model.datapoint.AssetDatapoint) AssetPredictedDatapoint(org.openremote.model.datapoint.AssetPredictedDatapoint) ProvisioningConfig(org.openremote.model.provisioning.ProvisioningConfig) X509ProvisioningConfig(org.openremote.model.provisioning.X509ProvisioningConfig) RealmRole(org.openremote.model.security.RealmRole) ConsoleAppConfig(org.openremote.model.apps.ConsoleAppConfig)

Example 2 with AssetDescriptor

use of org.openremote.model.asset.AssetDescriptor in project openremote by openremote.

the class ValueUtil method doInitialise.

/**
 * Initialise the asset model and throw an {@link IllegalStateException} exception if a problem is detected; this
 * can be called by applications at startup to fail hard and fast if the asset model is un-usable
 */
protected static void doInitialise() throws IllegalStateException {
    assetInfoMap = new HashMap<>();
    assetTypeMap = new HashMap<>();
    agentLinkMap = new HashMap<>();
    metaItemDescriptors = new ArrayList<>();
    valueDescriptors = new ArrayList<>();
    generator = null;
    // Provide basic Object Mapper and enhance once asset model is initialised
    JSON = configureObjectMapper(new ObjectMapper());
    LOG.info("Initialising asset model...");
    Map<Class<? extends Asset<?>>, List<NameHolder>> assetDescriptorProviders = new TreeMap<>(new ClassHierarchyComparator());
    // noinspection RedundantCast
    assetDescriptorProviders.put((Class<? extends Asset<?>>) (Class<?>) Asset.class, new ArrayList<>(getDescriptorFields(Asset.class)));
    getModelProviders().forEach(assetModelProvider -> {
        LOG.fine("Processing asset model provider: " + assetModelProvider.getClass().getSimpleName());
        LOG.fine("Auto scan = " + assetModelProvider.useAutoScan());
        if (assetModelProvider.useAutoScan()) {
            Set<Class<? extends Asset<?>>> assetClasses = getAssetClasses(assetModelProvider);
            LOG.fine("Found " + assetClasses.size() + " asset class(es)");
            assetClasses.forEach(assetClass -> assetDescriptorProviders.computeIfAbsent(assetClass, aClass -> new ArrayList<>(getDescriptorFields(aClass))));
            ModelDescriptors modelDescriptors = assetModelProvider.getClass().getAnnotation(ModelDescriptors.class);
            if (modelDescriptors != null) {
                for (ModelDescriptor modelDescriptor : modelDescriptors.value()) {
                    Class<? extends Asset<?>> assetClass = (Class<? extends Asset<?>>) modelDescriptor.assetType();
                    assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                        if (list == null) {
                            list = new ArrayList<>();
                        }
                        list.addAll(getDescriptorFields(modelDescriptor.provider()));
                        return list;
                    });
                }
            }
        }
        if (assetModelProvider.getAssetDescriptors() != null) {
            for (AssetDescriptor<?> assetDescriptor : assetModelProvider.getAssetDescriptors()) {
                Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
                assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(assetDescriptor);
                    return list;
                });
            }
        }
        if (assetModelProvider.getAttributeDescriptors() != null) {
            assetModelProvider.getAttributeDescriptors().forEach((assetClass, attributeDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(attributeDescriptors);
                return list;
            }));
        }
        if (assetModelProvider.getMetaItemDescriptors() != null) {
            assetModelProvider.getMetaItemDescriptors().forEach((assetClass, metaDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(metaDescriptors);
                return list;
            }));
        }
        if (assetModelProvider.getValueDescriptors() != null) {
            assetModelProvider.getValueDescriptors().forEach((assetClass, valueDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(valueDescriptors);
                return list;
            }));
        }
    });
    // Build each asset info checking that no conflicts occur
    Map<Class<? extends Asset<?>>, List<NameHolder>> copy = new HashMap<>(assetDescriptorProviders);
    assetDescriptorProviders.forEach((assetClass, descriptors) -> {
        // Skip abstract classes as a start point - they should be in the class hierarchy of concrete class
        if (!Modifier.isAbstract(assetClass.getModifiers())) {
            AssetTypeInfo assetInfo = buildAssetInfo(assetClass, copy);
            assetInfoMap.put(assetClass, assetInfo);
            assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
            if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor) {
                AgentDescriptor<?, ?, ?> agentDescriptor = (AgentDescriptor<?, ?, ?>) assetInfo.getAssetDescriptor();
                String agentLinkName = agentDescriptor.getAgentLinkClass().getSimpleName();
                if (agentLinkMap.containsKey(agentLinkName) && agentLinkMap.get(agentLinkName) != agentDescriptor.getAgentLinkClass()) {
                    throw new IllegalStateException("AgentLink simple class name must be unique, duplicate found for: " + agentDescriptor.getAgentLinkClass());
                }
                agentLinkMap.put(agentLinkName, agentDescriptor.getAgentLinkClass());
            }
        }
    });
    // Check each value type implements serializable interface
    List<ValueDescriptor<?>> nonSerializableValueDescriptors = new ArrayList<>();
    valueDescriptors.forEach(vd -> {
        if (!Serializable.class.isAssignableFrom(vd.getType())) {
            nonSerializableValueDescriptors.add(vd);
        }
    });
    if (!nonSerializableValueDescriptors.isEmpty()) {
        String vds = nonSerializableValueDescriptors.stream().map(ValueDescriptor::toString).collect(Collectors.joining(",\n"));
        throw new IllegalStateException("One or more value types do not implement java.io.Serializable: " + vds);
    }
    // Call on finished on each provider
    assetModelProviders.forEach(AssetModelProvider::onAssetModelFinished);
    // Add agent link sub types to object mapper (need to avoid circular dependency)
    NamedType[] agentLinkSubTypes = Arrays.stream(getAgentLinkClasses()).map(agentLinkClass -> new NamedType(agentLinkClass, agentLinkClass.getSimpleName())).toArray(NamedType[]::new);
    JSON.registerSubtypes(agentLinkSubTypes);
    doSchemaInit();
}
Also used : Reflections(org.reflections.Reflections) ModelDescriptor(org.openremote.model.ModelDescriptor) com.fasterxml.jackson.databind.node(com.fasterxml.jackson.databind.node) AgentLink(org.openremote.model.asset.agent.AgentLink) BigDecimal(java.math.BigDecimal) AgentDescriptor(org.openremote.model.asset.agent.AgentDescriptor) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) BigInteger(java.math.BigInteger) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ConstraintViolation(javax.validation.ConstraintViolation) java.lang.reflect(java.lang.reflect) Entity(javax.persistence.Entity) ConstructorDetector(com.fasterxml.jackson.databind.cfg.ConstructorDetector) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo) Validator(javax.validation.Validator) JsonAutoDetect(com.fasterxml.jackson.annotation.JsonAutoDetect) NotNull(javax.validation.constraints.NotNull) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) ClasspathHelper(org.reflections.util.ClasspathHelper) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Serializable(java.io.Serializable) ModelDescriptors(org.openremote.model.ModelDescriptors) JsonSchemaGenerator(com.kjetland.jackson.jsonSchema.JsonSchemaGenerator) Agent(org.openremote.model.asset.agent.Agent) IntStream(java.util.stream.IntStream) java.util(java.util) AssetDescriptor(org.openremote.model.asset.AssetDescriptor) Modifier.isStatic(java.lang.reflect.Modifier.isStatic) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Level(java.util.logging.Level) Attribute(org.openremote.model.attribute.Attribute) Validation(javax.validation.Validation) PropertyAccessor(com.fasterxml.jackson.annotation.PropertyAccessor) AssetModelProvider(org.openremote.model.AssetModelProvider) com.fasterxml.jackson.databind(com.fasterxml.jackson.databind) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) Asset(org.openremote.model.asset.Asset) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SerializationHelper(org.hibernate.internal.util.SerializationHelper) ParameterNamesModule(com.fasterxml.jackson.module.paramnames.ParameterNamesModule) SubTypesScanner(org.reflections.scanners.SubTypesScanner) org.openremote.model.value(org.openremote.model.value) Modifier.isPublic(java.lang.reflect.Modifier.isPublic) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) StandardModelProvider(org.openremote.model.StandardModelProvider) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) MODEL_AND_VALUES(org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES) Serializable(java.io.Serializable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AssetModelProvider(org.openremote.model.AssetModelProvider) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) Asset(org.openremote.model.asset.Asset) AgentDescriptor(org.openremote.model.asset.agent.AgentDescriptor) ModelDescriptors(org.openremote.model.ModelDescriptors) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo) ModelDescriptor(org.openremote.model.ModelDescriptor)

Aggregations

java.util (java.util)2 Function (java.util.function.Function)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 IntStream (java.util.stream.IntStream)2 Asset (org.openremote.model.asset.Asset)2 AssetDescriptor (org.openremote.model.asset.AssetDescriptor)2 JsonAutoDetect (com.fasterxml.jackson.annotation.JsonAutoDetect)1 JsonCreator (com.fasterxml.jackson.annotation.JsonCreator)1 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1 PropertyAccessor (com.fasterxml.jackson.annotation.PropertyAccessor)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 com.fasterxml.jackson.databind (com.fasterxml.jackson.databind)1 ConstructorDetector (com.fasterxml.jackson.databind.cfg.ConstructorDetector)1 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)1 com.fasterxml.jackson.databind.node (com.fasterxml.jackson.databind.node)1 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)1 Jdk8Module (com.fasterxml.jackson.datatype.jdk8.Jdk8Module)1 JavaTimeModule (com.fasterxml.jackson.datatype.jsr310.JavaTimeModule)1