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;
}
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);
}
}
}
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());
}
}
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();
}
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;
}
Aggregations