Search in sources :

Example 1 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class DWHQueryBean method cypherResults.

private List<Object> cypherResults(MeasurableQuantity mq) throws BusinessException {
    // List of query results
    List<Object> results = new ArrayList<>();
    // Cypher query template to execute
    String cypherQuery = formatQuery(mq, mq.getCypherQuery());
    log.debug("resolve query:{}, nextMeasureDate={}, lastMeasureDate={}", mq.getCypherQuery(), mq.getNextMeasureDate(), mq.getLastMeasureDate());
    log.debug("execute query:{}", cypherQuery);
    /* Start transaction */
    String neo4jUrl = ParamBean.getInstance().getProperty("neo4j.host", "localhost");
    String neo4jLogin = ParamBean.getInstance().getProperty("neo4j.login", "neo4j");
    String neo4jPassword = ParamBean.getInstance().getProperty("neo4j.password", "meveo");
    Driver driver = GraphDatabase.driver("bolt://" + neo4jUrl, AuthTokens.basic(neo4jLogin, neo4jPassword));
    Session session = driver.session();
    Transaction transaction = session.beginTransaction();
    try {
        // Execute query
        final StatementResult statementResult = transaction.run(cypherQuery);
        List<Record> recordList = statementResult.list();
        recordList.forEach(record -> {
            Object[] recordObject = { // Date or Value
            record.get(0), // Value or Dimension 1
            record.get(1), // Dimension 1 or 2 or null
            record.get(2), // Dimension 2 or 3 or null
            record.get(3), // Dimension 3 or 4 or null
            record.get(4), // Dimension 4 or null
            record.get(5) };
            results.add(recordObject);
        });
        transaction.success();
    } catch (Exception e) {
        throw new BusinessException(e);
    } finally {
        session.close();
        transaction.close();
    }
    return results;
}
Also used : StatementResult(org.neo4j.driver.v1.StatementResult) ArrayList(java.util.ArrayList) Driver(org.neo4j.driver.v1.Driver) BusinessException(org.meveo.admin.exception.BusinessException) BusinessException(org.meveo.admin.exception.BusinessException) Transaction(org.neo4j.driver.v1.Transaction) Record(org.neo4j.driver.v1.Record) Session(org.neo4j.driver.v1.Session)

Example 2 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class StartupListener method init.

@SuppressWarnings("unchecked")
@PostConstruct
@Transactional(Transactional.TxType.REQUIRES_NEW)
public void init() {
    entityManagerWrapper.getEntityManager().joinTransaction();
    Session session = entityManagerWrapper.getEntityManager().unwrap(Session.class);
    session.doWork(connection -> {
        applicationInitializer.init();
        // A default Repository and SQL Configuration should be genarated/updated at Meveo first initialization
        try {
            // defaultSqlConfiguration
            SqlConfiguration defaultSqlConfiguration;
            defaultSqlConfiguration = sqlConfigurationService.findByCode(SqlConfiguration.DEFAULT_SQL_CONNECTION);
            if (defaultSqlConfiguration == null) {
                defaultSqlConfiguration = new SqlConfiguration();
                defaultSqlConfiguration.setCode(SqlConfiguration.DEFAULT_SQL_CONNECTION);
                setSqlConfiguration(defaultSqlConfiguration);
                sqlConfigurationService.create(defaultSqlConfiguration);
            } else {
                setSqlConfiguration(defaultSqlConfiguration);
                sqlConfigurationService.update(defaultSqlConfiguration);
            }
            // defaultNeo4jConfiguration
            Neo4JConfiguration defaultNeo4jConfiguration = neo4jConfigurationService.findByCode(Neo4JConfiguration.DEFAULT_NEO4J_CONNECTION);
            if (defaultNeo4jConfiguration == null) {
                defaultNeo4jConfiguration = neo4jConnectionProvider.getDefaultConfiguration();
                if (defaultNeo4jConfiguration != null) {
                    neo4jConfigurationService.create(defaultNeo4jConfiguration);
                }
            }
            Repository defaultRepository = repositoryService.findByCode(Repository.DEFAULT_REPOSITORY);
            if (defaultRepository == null) {
                defaultRepository = new Repository();
                defaultRepository.setCode(Repository.DEFAULT_REPOSITORY);
                defaultRepository.setSqlConfiguration(defaultSqlConfiguration);
                defaultRepository.setNeo4jConfiguration(defaultNeo4jConfiguration);
                repositoryService.create(defaultRepository);
                log.info("Created default repository");
            } else if (defaultNeo4jConfiguration != null && defaultRepository.getNeo4jConfiguration() == null) {
                defaultRepository.setNeo4jConfiguration(defaultNeo4jConfiguration);
                repositoryService.update(defaultRepository);
                log.info("Updated default repository");
            }
        } catch (BusinessException e) {
            log.error("Cannot create default repository", e);
        }
        // Create Meveo git repository
        GitRepository meveoRepo = gitRepositoryService.findByCode("Meveo");
        if (meveoRepo == null) {
            try {
                meveoRepo = gitRepositoryService.create(GitRepositoryService.MEVEO_DIR, false, GitRepositoryService.MEVEO_DIR.getDefaultRemoteUsername(), GitRepositoryService.MEVEO_DIR.getClearDefaultRemotePassword());
                log.info("Created Meveo GIT repository");
            } catch (BusinessException e) {
                log.error("Cannot create Meveo GIT repository", e);
            }
        } else {
            log.info("Meveo GIT repository already created");
            try {
                GitRepositoryService.MEVEO_DIR = meveoRepo;
                // 
                gitClient.create(// 
                GitRepositoryService.MEVEO_DIR, // 
                false, // 
                GitRepositoryService.MEVEO_DIR.getDefaultRemoteUsername(), GitRepositoryService.MEVEO_DIR.getDefaultRemotePassword());
            } catch (BusinessException e) {
                log.error("Cannot create Meveo Git folder", e);
            }
        }
        try {
            createMeveoModule(meveoRepo);
        } catch (BusinessException e2) {
            log.error("Failed to create main Meveo module");
        }
        // Generate .gitignore file
        List<String> ignoredFiles = List.of(".classpath", ".project", ".settings/*", ".vscode/*", "target/*");
        File gitRepo = GitHelper.getRepositoryDir(appInitUser.get(), meveoRepo.getCode());
        File gitIgnoreFile = new File(gitRepo, ".gitignore");
        try {
            List<String> actualIgnoredFiles = gitIgnoreFile.exists() ? Files.readAllLines(gitIgnoreFile.toPath()) : List.of();
            Collection<String> missingEntries = CollectionUtils.subtract(ignoredFiles, actualIgnoredFiles);
            try (FileWriter fw = new FileWriter(gitIgnoreFile, true);
                BufferedWriter output = new BufferedWriter(fw)) {
                for (String missingEntry : missingEntries) {
                    output.append(missingEntry);
                    output.newLine();
                }
            }
            gitClient.commitFiles(meveoRepo, List.of(gitIgnoreFile), "Update .gitignore");
        } catch (IOException e1) {
            log.error("Can't read / write .gitignore file");
        } catch (BusinessException e) {
            log.error("Can't commit .gitignore file", e);
        } catch (JGitInternalException e) {
            log.error("Can't commit .gitignore file, it is probably corrupted, you might want to delete it and restart meveo", e);
        }
        // Create default pom file
        mavenConfigurationService.createDefaultPomFile(meveoRepo.getCode());
        try {
            // Create default maven repository
            RemoteRepository remoteRepository = remoteRepositoryService.findByCode("maven central");
            if (remoteRepository == null) {
                remoteRepository = new RemoteRepository();
                remoteRepository.setCode("maven central");
                remoteRepository.setUrl("https://repo1.maven.org/maven2/");
                remoteRepositoryService.create(remoteRepository);
                log.info("Created default maven repository");
            }
        } catch (BusinessException e) {
            log.error("Cannot create default maven repository", e);
        }
        log.info("Thank you for running Meveo Community code.");
    });
    session.flush();
    try {
        // Set-up secret key
        String secret = System.getProperty("meveo.security.secret");
        if (secret == null) {
            var paramBean = ParamBean.getInstance("meveo-security.properties");
            secret = paramBean.getProperty("meveo.security.secret", null);
            if (secret == null) {
                KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
                SecureRandom secureRandom = new SecureRandom();
                int keyBitSize = 256;
                keyGenerator.init(keyBitSize, secureRandom);
                SecretKey secretKey = keyGenerator.generateKey();
                byte[] encodedKey = Base64.getEncoder().encode(secretKey.getEncoded());
                var randomSecret = new String(encodedKey, StandardCharsets.UTF_8);
                paramBean.setProperty("meveo.security.secret", randomSecret);
                paramBean.saveProperties();
                secret = randomSecret;
            }
            System.setProperty("meveo.security.secret", secret);
        }
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }
    // Test neo4j connections
    var neo4jConfs = neo4jConfigurationService.listActive();
    for (var neo4jConf : neo4jConfs) {
        try {
            var neo4jSession = neo4jConnectionProvider.getSession(neo4jConf.getCode());
            neo4jSession.close();
        } catch (Exception e) {
            try {
                neo4jConfigurationService.disable(neo4jConf.getId());
            } catch (BusinessException e1) {
                log.error("Failed to disable {}", neo4jConf, e1);
            }
        }
    }
    for (MeveoInitializer initializer : initializers) {
        try {
            initializer.init();
        } catch (Exception e) {
            log.error("Error during execution of {}", initializer.getClass(), e);
        }
    }
}
Also used : FileWriter(java.io.FileWriter) RemoteRepository(org.meveo.model.storage.RemoteRepository) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BufferedWriter(java.io.BufferedWriter) BusinessException(org.meveo.admin.exception.BusinessException) KeyGenerator(javax.crypto.KeyGenerator) SqlConfiguration(org.meveo.model.sql.SqlConfiguration) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) IOException(java.io.IOException) BusinessException(org.meveo.admin.exception.BusinessException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) GitRepository(org.meveo.model.git.GitRepository) RemoteRepository(org.meveo.model.storage.RemoteRepository) Repository(org.meveo.model.storage.Repository) GitRepository(org.meveo.model.git.GitRepository) SecretKey(javax.crypto.SecretKey) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) File(java.io.File) Session(org.hibernate.Session) Neo4JConfiguration(org.meveo.model.neo4j.Neo4JConfiguration) PostConstruct(javax.annotation.PostConstruct) Transactional(javax.transaction.Transactional)

Example 3 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class CETUtils method callMeveoApi.

public Response callMeveoApi(String url, String body, String httpMethod) throws BusinessException {
    log.info("callMeveoApi url:{},body:{}", url, body);
    try {
        ParamBean paramBean = ParamBean.getInstance();
        String baseurl = paramBean.getProperty("meveo.admin.baseUrl", "http://localhost:8080/meveo/");
        String username = paramBean.getProperty("meveo.admin.login", "meveo.admin");
        String password = paramBean.getProperty("meveo.admin.password", "meveo.admin");
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target(baseurl + url);
        log.debug("call {} with body:{}", baseurl + url, body);
        BasicAuthentication basicAuthentication = new BasicAuthentication(username, password);
        target.register(basicAuthentication);
        Response response = null;
        if (HttpMethod.POST.equals(httpMethod)) {
            response = target.request().post(Entity.entity(body, MediaType.APPLICATION_JSON));
        } else if (HttpMethod.GET.equals(httpMethod)) {
            response = target.request().get();
        }
        if (response.getStatus() != HttpURLConnection.HTTP_OK) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED || response.getStatus() == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new RemoteAuthenticationException("Http status " + response.getStatus() + ", info " + response.getStatusInfo().getReasonPhrase());
            } else {
                throw new BusinessException("Http status " + response.getStatus() + ", info " + response.getStatusInfo().getReasonPhrase());
            }
        }
        return response;
    } catch (Exception e) {
        log.error("Failed to communicate {}. Reason {}", url, (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()), e);
        throw new BusinessException("Failed to communicate " + url + ". Error " + e.getMessage());
    }
}
Also used : Response(javax.ws.rs.core.Response) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) BusinessException(org.meveo.admin.exception.BusinessException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) BasicAuthentication(org.jboss.resteasy.client.jaxrs.BasicAuthentication) ParamBean(org.meveo.commons.utils.ParamBean) IOException(java.io.IOException) BusinessException(org.meveo.admin.exception.BusinessException) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException)

Example 4 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class CustomTableCreatorService method createCrtTable.

/**
 * Create a table with two columns referencing source and target custom tables
 *
 * @param crt {@link CustomRelationshipTemplate} to create table for
 * @throws BusinessException if the {@link CustomRelationshipTemplate} is not
 *                           configured to be stored in a custom table
 */
public boolean createCrtTable(String sqlConnectionCode, CustomRelationshipTemplate crt) throws BusinessException {
    if (crt.getAvailableStorages() == null || !crt.getAvailableStorages().contains(DBStorageType.SQL)) {
        throw new BusinessException("CustomRelationshipTemplate " + crt.getCode() + " is not configured to be stored in a custom table");
    }
    String tableName = SQLStorageConfiguration.getDbTablename(crt);
    DatabaseChangeLog dbLog = new DatabaseChangeLog("path");
    List<Change> changeset = new ArrayList<>();
    // Source column
    ColumnConfig sourceColumn = new ColumnConfig();
    sourceColumn.setName(SQLStorageConfiguration.getSourceColumnName(crt));
    sourceColumn.setType("varchar(255)");
    // Target column
    ColumnConfig targetColumn = new ColumnConfig();
    targetColumn.setName(SQLStorageConfiguration.getTargetColumnName(crt));
    targetColumn.setType("varchar(255)");
    // UUID column
    ColumnConfig uuidColumn = new ColumnConfig();
    uuidColumn.setName(UUID);
    uuidColumn.setType("varchar(255)");
    uuidColumn.setDefaultValueComputed(new DatabaseFunction("uuid_generate_v4()"));
    // Table creation
    CreateTableChange createTableChange = new CreateTableChange();
    createTableChange.setTableName(tableName);
    createTableChange.addColumn(sourceColumn);
    createTableChange.addColumn(targetColumn);
    createTableChange.addColumn(uuidColumn);
    changeset.add(createTableChange);
    AtomicBoolean created = new AtomicBoolean();
    created.set(true);
    try (Session hibernateSession = sqlConnectionProvider.getSession(sqlConnectionCode)) {
        hibernateSession.doWork(connection -> {
            DatabaseMetaData meta = connection.getMetaData();
            Database database;
            try {
                database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
                setSchemaName(database);
                boolean sourceOrTargetColDidNotExist = false;
                // Check table does not exists
                try (var res = meta.getTables(null, database.getDefaultSchemaName(), tableName, new String[] { "TABLE" })) {
                    if (res.next()) {
                        changeset.remove(createTableChange);
                        // if uuid field does not exists, add it
                        try (ResultSet res2 = meta.getColumns(null, database.getDefaultSchemaName(), tableName, "uuid")) {
                            if (!res2.next()) {
                                AddColumnConfig addUuidCol = new AddColumnConfig();
                                addUuidCol.setName(uuidColumn.getName());
                                addUuidCol.setType(uuidColumn.getType());
                                AddColumnChange pgUuidColChange = new AddColumnChange();
                                pgUuidColChange.setTableName(tableName);
                                pgUuidColChange.setColumns(List.of((addUuidCol)));
                                changeset.add(pgUuidColChange);
                            }
                        }
                        // if source field does not exists, add it
                        try (ResultSet res2 = meta.getColumns(null, database.getDefaultSchemaName(), tableName, sourceColumn.getName())) {
                            if (!res2.next()) {
                                sourceOrTargetColDidNotExist = true;
                                AddColumnConfig addSourceField = new AddColumnConfig();
                                addSourceField.setName(sourceColumn.getName());
                                addSourceField.setType(sourceColumn.getType());
                                AddColumnChange addSourceFieldChange = new AddColumnChange();
                                addSourceFieldChange.setTableName(tableName);
                                addSourceFieldChange.setColumns(List.of((addSourceField)));
                                changeset.add(addSourceFieldChange);
                            }
                        }
                        // if target field does not exists, add it
                        try (ResultSet res2 = meta.getColumns(null, database.getDefaultSchemaName(), tableName, targetColumn.getName())) {
                            if (!res2.next()) {
                                sourceOrTargetColDidNotExist = true;
                                AddColumnConfig addTargetField = new AddColumnConfig();
                                addTargetField.setName(targetColumn.getName());
                                addTargetField.setType(targetColumn.getType());
                                addTargetField.setDefaultValueComputed(targetColumn.getDefaultValueComputed());
                                AddColumnChange addTargetFieldChange = new AddColumnChange();
                                addTargetFieldChange.setTableName(tableName);
                                addTargetFieldChange.setColumns(List.of((addTargetField)));
                                changeset.add(addTargetFieldChange);
                            }
                        }
                    }
                }
                if (sourceOrTargetColDidNotExist) {
                    // Primary key constraint addition
                    AddPrimaryKeyChange addPrimaryKeyChange = new AddPrimaryKeyChange();
                    addPrimaryKeyChange.setColumnNames(uuidColumn.getName());
                    addPrimaryKeyChange.setTableName(tableName);
                    changeset.add(addPrimaryKeyChange);
                }
                // Unique constraint if CRT is unique
                if (crt.isUnique() && sourceOrTargetColDidNotExist) {
                    AddUniqueConstraintChange uniqueConstraint = new AddUniqueConstraintChange();
                    uniqueConstraint.setColumnNames(sourceColumn.getName() + ", " + targetColumn.getName());
                    uniqueConstraint.setTableName(tableName);
                    uniqueConstraint.setConstraintName("uk_" + tableName);
                    changeset.add(uniqueConstraint);
                }
                // Source foreign key if source cet is a custom table
                if (sourceOrTargetColDidNotExist && crt.getStartNode().getSqlStorageConfiguration() != null && crt.getStartNode().getSqlStorageConfiguration().isStoreAsTable()) {
                    AddForeignKeyConstraintChange sourceFkChange = new AddForeignKeyConstraintChange();
                    sourceFkChange.setBaseColumnNames(sourceColumn.getName());
                    sourceFkChange.setConstraintName(sourceColumn.getName() + "_fk");
                    sourceFkChange.setReferencedColumnNames(UUID);
                    sourceFkChange.setBaseTableName(tableName);
                    sourceFkChange.setReferencedTableName(SQLStorageConfiguration.getDbTablename(crt.getStartNode()));
                    changeset.add(sourceFkChange);
                }
                // Target foreign key if target cet is a custom table
                if (sourceOrTargetColDidNotExist && crt.getEndNode().getSqlStorageConfiguration() != null && crt.getEndNode().getSqlStorageConfiguration().isStoreAsTable()) {
                    AddForeignKeyConstraintChange targetFkChange = new AddForeignKeyConstraintChange();
                    targetFkChange.setConstraintName(targetColumn.getName() + "_fk");
                    targetFkChange.setBaseColumnNames(targetColumn.getName());
                    targetFkChange.setReferencedColumnNames(UUID);
                    targetFkChange.setBaseTableName(tableName);
                    targetFkChange.setReferencedTableName(SQLStorageConfiguration.getDbTablename(crt.getEndNode()));
                    changeset.add(targetFkChange);
                }
                ChangeSet liquibaseChangeset = new ChangeSet(tableName + "_CT_CP_" + System.currentTimeMillis(), "Meveo", false, false, "meveo", "", "", dbLog);
                changeset.forEach(liquibaseChangeset::addChange);
                dbLog.addChangeSet(liquibaseChangeset);
                Liquibase liquibase = new Liquibase(dbLog, new ClassLoaderResourceAccessor(), database);
                liquibase.update(new Contexts(), new LabelExpression());
            } catch (MigrationFailedException e) {
                if (e.getMessage().toLowerCase().contains("precondition")) {
                    created.set(false);
                } else {
                    throw new HibernateException(e);
                }
            } catch (Exception e) {
                log.error("Failed to create a custom table {}", tableName, e);
                throw new SQLException(e);
            }
        });
    }
    return created.get();
}
Also used : AddColumnConfig(liquibase.change.AddColumnConfig) ColumnConfig(liquibase.change.ColumnConfig) DatabaseFunction(liquibase.statement.DatabaseFunction) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) JdbcConnection(liquibase.database.jvm.JdbcConnection) Contexts(liquibase.Contexts) BusinessException(org.meveo.admin.exception.BusinessException) AddUniqueConstraintChange(liquibase.change.core.AddUniqueConstraintChange) MigrationFailedException(liquibase.exception.MigrationFailedException) Database(liquibase.database.Database) ResultSet(java.sql.ResultSet) AddPrimaryKeyChange(liquibase.change.core.AddPrimaryKeyChange) ChangeSet(liquibase.changelog.ChangeSet) HibernateException(org.hibernate.HibernateException) AddForeignKeyConstraintChange(liquibase.change.core.AddForeignKeyConstraintChange) DropColumnChange(liquibase.change.core.DropColumnChange) AddForeignKeyConstraintChange(liquibase.change.core.AddForeignKeyConstraintChange) ModifyDataTypeChange(liquibase.change.core.ModifyDataTypeChange) DropSequenceChange(liquibase.change.core.DropSequenceChange) AddNotNullConstraintChange(liquibase.change.core.AddNotNullConstraintChange) AddColumnChange(liquibase.change.core.AddColumnChange) DropTableChange(liquibase.change.core.DropTableChange) CreateTableChange(liquibase.change.core.CreateTableChange) DropForeignKeyConstraintChange(liquibase.change.core.DropForeignKeyConstraintChange) AddUniqueConstraintChange(liquibase.change.core.AddUniqueConstraintChange) Change(liquibase.change.Change) DropNotNullConstraintChange(liquibase.change.core.DropNotNullConstraintChange) RawSQLChange(liquibase.change.core.RawSQLChange) DropDefaultValueChange(liquibase.change.core.DropDefaultValueChange) AddPrimaryKeyChange(liquibase.change.core.AddPrimaryKeyChange) AddDefaultValueChange(liquibase.change.core.AddDefaultValueChange) DatabaseMetaData(java.sql.DatabaseMetaData) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) TimeoutException(java.util.concurrent.TimeoutException) MigrationFailedException(liquibase.exception.MigrationFailedException) BusinessException(org.meveo.admin.exception.BusinessException) HibernateException(org.hibernate.HibernateException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) ExecutionException(java.util.concurrent.ExecutionException) Liquibase(liquibase.Liquibase) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CreateTableChange(liquibase.change.core.CreateTableChange) LabelExpression(liquibase.LabelExpression) AddColumnConfig(liquibase.change.AddColumnConfig) AddColumnChange(liquibase.change.core.AddColumnChange) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) Session(org.hibernate.Session)

Example 5 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class CustomEntityTemplateService method update.

@Override
public CustomEntityTemplate update(CustomEntityTemplate cet) throws BusinessException {
    CustomEntityTemplate oldValue = customFieldsCache.getCustomEntityTemplate(cet.getCode());
    if (!EntityCustomizationUtils.validateOntologyCode(cet.getCode())) {
        throw new IllegalArgumentException("The code of ontology elements must not contain numbers");
    }
    checkCrudEventListenerScript(cet);
    ParamBean paramBean = paramBeanFactory.getInstance();
    if (cet.getCustomEntityCategory() != null && !cet.getCustomEntityCategory().isTransient()) {
        CustomEntityCategory cec = customEntityCategoryService.reattach(cet.getCustomEntityCategory());
        cet.setCustomEntityCategory(cec);
    }
    CustomEntityTemplate cetUpdated = super.update(cet);
    customFieldsCache.addUpdateCustomEntityTemplate(cet);
    try {
        permissionService.createIfAbsent(cet.getModifyPermission(), paramBean.getProperty("role.modifyAllCE", "ModifyAllCE"));
        permissionService.createIfAbsent(cet.getReadPermission(), paramBean.getProperty("role.readAllCE", "ReadAllCE"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    flush();
    // Synchronize custom fields storages with CET available storages
    for (CustomFieldTemplate cft : customFieldTemplateService.findByAppliesToNoCache(cet.getAppliesTo()).values()) {
        cft.setHasReferenceJpaEntity(cet.hasReferenceJpaEntity());
        if (cft.getStoragesNullSafe() != null) {
            for (DBStorageType storage : new ArrayList<>(cft.getStoragesNullSafe())) {
                if (!cet.getAvailableStorages().contains(storage)) {
                    log.info("Remove storage '{}' from CFT '{}' of CET '{}'", storage, cft.getCode(), cet.getCode());
                    cft.getStoragesNullSafe().remove(storage);
                    customFieldTemplateService.update(cft);
                }
            }
        }
    }
    // Synchronize neoj4 indexes
    if (cet.getAvailableStorages() != null && cet.getAvailableStorages().contains(DBStorageType.NEO4J)) {
        neo4jService.addUUIDIndexes(cet);
    } else {
        neo4jService.removeUUIDIndexes(cet);
    }
    var sqlConfs = sqlConfigurationService.listActiveAndInitialized();
    // Handle SQL inheritance
    if (cet.storedIn(DBStorageType.SQL)) {
        if (oldValue.getSuperTemplate() != null && cet.getSuperTemplate() == null) {
            // Inheritance removed
            sqlConfs.forEach(sc -> customTableCreatorService.removeInheritance(sc.getCode(), cet));
        } else if (oldValue.getSuperTemplate() == null && cet.getSuperTemplate() != null) {
            // Inheritance added
            sqlConfs.forEach(sc -> customTableCreatorService.addInheritance(sc.getCode(), cet));
        }
    }
    return cetUpdated;
}
Also used : JSONSchemaGenerator(org.meveo.service.crm.impl.JSONSchemaGenerator) NoResultException(javax.persistence.NoResultException) CustomEntityTemplateDto(org.meveo.api.dto.CustomEntityTemplateDto) MeveoRepository(org.meveo.service.git.MeveoRepository) ICustomFieldEntity(org.meveo.model.ICustomFieldEntity) ScriptInstanceService(org.meveo.service.script.ScriptInstanceService) CustomEntity(org.meveo.model.CustomEntity) Repository(org.meveo.model.storage.Repository) TransactionAttributeType(javax.ejb.TransactionAttributeType) SQLStorageConfiguration(org.meveo.model.persistence.sql.SQLStorageConfiguration) Asynchronous(javax.ejb.Asynchronous) Map(java.util.Map) Observes(javax.enterprise.event.Observes) MeveoUser(org.meveo.security.MeveoUser) CustomEntityCategory(org.meveo.model.customEntities.CustomEntityCategory) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Stateless(javax.ejb.Stateless) TxType(javax.transaction.Transactional.TxType) Transactional(javax.transaction.Transactional) MeveoModule(org.meveo.model.module.MeveoModule) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) ElasticClient(org.meveo.service.index.ElasticClient) MeveoModuleHelper(org.meveo.service.admin.impl.MeveoModuleHelper) List(java.util.List) EntityCustomizationUtils(org.meveo.util.EntityCustomizationUtils) ModuleUninstall(org.meveo.service.admin.impl.ModuleUninstall) Entry(java.util.Map.Entry) PostConstruct(javax.annotation.PostConstruct) CustomFieldsCacheContainerProvider(org.meveo.cache.CustomFieldsCacheContainerProvider) Optional(java.util.Optional) GitRepository(org.meveo.model.git.GitRepository) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration) EntityCustomAction(org.meveo.model.crm.custom.EntityCustomAction) MeveoModuleItem(org.meveo.model.module.MeveoModuleItem) HashMap(java.util.HashMap) ModulePostUninstall(org.meveo.model.ModulePostUninstall) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) PermissionService(org.meveo.service.admin.impl.PermissionService) TypedQuery(javax.persistence.TypedQuery) MeveoFileUtils(org.meveo.commons.utils.MeveoFileUtils) BusinessService(org.meveo.service.base.BusinessService) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Inject(javax.inject.Inject) PrimitiveTypeEnum(org.meveo.model.crm.custom.PrimitiveTypeEnum) JacksonUtil(org.meveo.model.persistence.JacksonUtil) Lists(com.google.common.collect.Lists) CustomFieldTemplateService(org.meveo.service.crm.impl.CustomFieldTemplateService) ImmutableList(com.google.common.collect.ImmutableList) TransactionAttribute(javax.ejb.TransactionAttribute) ParamBean(org.meveo.commons.utils.ParamBean) LinkedList(java.util.LinkedList) Neo4jService(org.meveo.persistence.neo4j.service.Neo4jService) MapUtils(org.apache.commons.collections4.MapUtils) QueryBuilder(org.meveo.commons.utils.QueryBuilder) CrudEventListenerScript(org.meveo.model.customEntities.CrudEventListenerScript) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) Files(java.nio.file.Files) DBStorageType(org.meveo.model.persistence.DBStorageType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) GitHelper(org.meveo.service.git.GitHelper) ParamBeanFactory(org.meveo.commons.utils.ParamBeanFactory) File(java.io.File) CustomFieldTypeEnum(org.meveo.model.crm.custom.CustomFieldTypeEnum) GitClient(org.meveo.service.git.GitClient) JSONSchemaIntoJavaClassParser(org.meveo.service.crm.impl.JSONSchemaIntoJavaClassParser) Collections(java.util.Collections) SqlConfigurationService(org.meveo.persistence.sql.SqlConfigurationService) CustomEntityCategory(org.meveo.model.customEntities.CustomEntityCategory) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) DBStorageType(org.meveo.model.persistence.DBStorageType) ArrayList(java.util.ArrayList) ParamBean(org.meveo.commons.utils.ParamBean) NoResultException(javax.persistence.NoResultException) BusinessException(org.meveo.admin.exception.BusinessException) IOException(java.io.IOException)

Aggregations

BusinessException (org.meveo.admin.exception.BusinessException)229 IOException (java.io.IOException)97 File (java.io.File)59 HashMap (java.util.HashMap)50 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)50 ArrayList (java.util.ArrayList)48 MeveoApiException (org.meveo.api.exception.MeveoApiException)39 ELException (org.meveo.elresolver.ELException)39 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)38 CustomEntityTemplate (org.meveo.model.customEntities.CustomEntityTemplate)37 Map (java.util.Map)34 BundleKey (org.jboss.seam.international.status.builder.BundleKey)30 TransactionAttribute (javax.ejb.TransactionAttribute)28 CustomEntityInstance (org.meveo.model.customEntities.CustomEntityInstance)27 List (java.util.List)25 MeveoModule (org.meveo.model.module.MeveoModule)25 NoResultException (javax.persistence.NoResultException)24 HashSet (java.util.HashSet)22 Response (javax.ws.rs.core.Response)22 Collection (java.util.Collection)20