Search in sources :

Example 1 with CustomFieldTemplate

use of org.meveo.model.crm.CustomFieldTemplate in project meveo by meveo-org.

the class WorkflowJob method getCustomFields.

@Override
public Map<String, CustomFieldTemplate> getCustomFields() {
    Map<String, CustomFieldTemplate> result = new HashMap<String, CustomFieldTemplate>();
    CustomFieldTemplate filterCF = new CustomFieldTemplate();
    filterCF.setCode("wfJob_filter");
    filterCF.setAppliesTo("JOB_WorkflowJob");
    filterCF.setActive(true);
    filterCF.setDescription("Filter");
    filterCF.setFieldType(CustomFieldTypeEnum.ENTITY);
    filterCF.setEntityClazz(Filter.class.getName());
    filterCF.setValueRequired(true);
    result.put("wfJob_filter", filterCF);
    CustomFieldTemplate worklowCF = new CustomFieldTemplate();
    worklowCF.setCode("wfJob_workflow");
    worklowCF.setAppliesTo("JOB_WorkflowJob");
    worklowCF.setActive(true);
    worklowCF.setDescription("Workflow");
    worklowCF.setFieldType(CustomFieldTypeEnum.ENTITY);
    worklowCF.setEntityClazz(Workflow.class.getName());
    worklowCF.setValueRequired(true);
    result.put("wfJob_workflow", worklowCF);
    CustomFieldTemplate nbRuns = new CustomFieldTemplate();
    nbRuns.setCode("wfJob_nbRuns");
    nbRuns.setAppliesTo("JOB_WorkflowJob");
    nbRuns.setActive(true);
    nbRuns.setDescription(resourceMessages.getString("jobExecution.nbRuns"));
    nbRuns.setFieldType(CustomFieldTypeEnum.LONG);
    nbRuns.setValueRequired(false);
    nbRuns.setDefaultValue("1");
    result.put("wfJob_nbRuns", nbRuns);
    CustomFieldTemplate waitingMillis = new CustomFieldTemplate();
    waitingMillis.setCode("wfJob_waitingMillis");
    waitingMillis.setAppliesTo("JOB_WorkflowJob");
    waitingMillis.setActive(true);
    waitingMillis.setDescription(resourceMessages.getString("jobExecution.waitingMillis"));
    waitingMillis.setFieldType(CustomFieldTypeEnum.LONG);
    waitingMillis.setValueRequired(false);
    waitingMillis.setDefaultValue("0");
    result.put("wfJob_waitingMillis", waitingMillis);
    return result;
}
Also used : HashMap(java.util.HashMap) Filter(org.meveo.model.filter.Filter) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) Workflow(org.meveo.model.wf.Workflow)

Example 2 with CustomFieldTemplate

use of org.meveo.model.crm.CustomFieldTemplate in project meveo by meveo-org.

the class CETUtils method initCustomFieldValues.

/**
 * Init a {@link CustomFieldValues} container from values map and fields definitions
 *
 * @param valuesMap	Values map
 * @param fields	Fields definition
 * @return instance of {@link CustomFieldValues}
 */
public static CustomFieldValues initCustomFieldValues(Map<String, Object> valuesMap, Collection<CustomFieldTemplate> fields) {
    CustomFieldValues values = new CustomFieldValues();
    valuesMap.forEach((k, v) -> {
        values.setValue(k, v);
    });
    fields.stream().filter(f -> CustomFieldStorageTypeEnum.LIST.equals(f.getStorageType())).filter(f -> valuesMap.get(f.getDbFieldname()) == null).forEach(f -> values.setValue(f.getDbFieldname(), f.getNewListValue(), f.getFieldType().getDataClass()));
    return values;
}
Also used : Date(java.util.Date) BasicAuthentication(org.jboss.resteasy.client.jaxrs.BasicAuthentication) LoggerFactory(org.slf4j.LoggerFactory) SimpleDateFormat(java.text.SimpleDateFormat) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) CustomFieldValues(org.meveo.model.crm.custom.CustomFieldValues) HttpMethod(javax.ws.rs.HttpMethod) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) MediaType(javax.ws.rs.core.MediaType) Calendar(java.util.Calendar) Matcher(java.util.regex.Matcher) Map(java.util.Map) ParamBean(org.meveo.commons.utils.ParamBean) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) Logger(org.slf4j.Logger) Collection(java.util.Collection) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) IOException(java.io.IOException) Entity(javax.ws.rs.client.Entity) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) BusinessException(org.meveo.admin.exception.BusinessException) List(java.util.List) Response(javax.ws.rs.core.Response) CustomFieldStorageTypeEnum(org.meveo.model.crm.custom.CustomFieldStorageTypeEnum) HttpURLConnection(org.apache.commons.httpclient.util.HttpURLConnection) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Pattern(java.util.regex.Pattern) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) CustomFieldValues(org.meveo.model.crm.custom.CustomFieldValues)

Example 3 with CustomFieldTemplate

use of org.meveo.model.crm.CustomFieldTemplate in project meveo by meveo-org.

the class SwaggerHelperService method convertCftsToProperties.

public Map<String, Property> convertCftsToProperties(Map<String, CustomFieldTemplate> cfts) {
    Map<String, Property> result = new HashMap<>();
    if (!cfts.isEmpty()) {
        for (Entry<String, CustomFieldTemplate> entry : cfts.entrySet()) {
            Property property = convertToProperty(entry.getValue());
            result.put(entry.getKey(), property);
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) StringProperty(io.swagger.models.properties.StringProperty) BinaryProperty(io.swagger.models.properties.BinaryProperty) LongProperty(io.swagger.models.properties.LongProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) MapProperty(io.swagger.models.properties.MapProperty) DateProperty(io.swagger.models.properties.DateProperty) ObjectProperty(io.swagger.models.properties.ObjectProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty)

Example 4 with CustomFieldTemplate

use of org.meveo.model.crm.CustomFieldTemplate in project meveo by meveo-org.

the class CustomTableCreatorService method addField.

@AccessTimeout(value = 1L, unit = TimeUnit.MINUTES)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void addField(String sqlConnectionCode, String dbTableName, CustomFieldTemplate cft, boolean checkStorage) {
    // Don't add field if not stored in sql
    if (checkStorage && !cft.getStoragesNullSafe().contains(DBStorageType.SQL)) {
        return;
    }
    String dbFieldname = cft.getDbFieldname();
    if ((cft.getFieldType() == CustomFieldTypeEnum.STRING || cft.getFieldType() == CustomFieldTypeEnum.SECRET) && (cft.getMaxValue() == null || cft.getMaxValue() < 1)) {
        cft.setMaxValue(CustomFieldTemplate.DEFAULT_MAX_LENGTH_STRING);
    }
    DatabaseChangeLog dbLog = new DatabaseChangeLog("path");
    ChangeSet changeSet = new ChangeSet(dbTableName + "_CT_" + dbFieldname + "_AF_" + System.currentTimeMillis(), "Meveo", false, false, "meveo", "", "", dbLog);
    String columnType;
    try {
        columnType = getColumnType(cft);
    } catch (ClassNotFoundException e1) {
        throw new IllegalArgumentException("Cannot get field type for entity with class or code " + cft.getEntityClazzCetCode(), e1);
    }
    AddColumnConfig column = new AddColumnConfig();
    // Check if column type is handled
    if (columnType != null) {
        AddColumnChange addColumnChange = new AddColumnChange();
        addColumnChange.setTableName(dbTableName);
        column.setName(dbFieldname);
        setDefaultValue(cft, column);
        column.setType(columnType);
        ConstraintsConfig constraints = new ConstraintsConfig();
        column.setConstraints(constraints);
        if (cft.isValueRequired()) {
            constraints.setNullable(false);
        }
        if (cft.isUnique()) {
            constraints.setUnique(true);
            constraints.setUniqueConstraintName(getUniqueConstraintName(dbTableName, dbFieldname));
        }
        addColumnChange.setColumns(Collections.singletonList(column));
        changeSet.addChange(addColumnChange);
    }
    // entity reference
    if (cft.getFieldType() == CustomFieldTypeEnum.ENTITY && cft.getStorageType().equals(CustomFieldStorageTypeEnum.SINGLE)) {
        addForeignKey(sqlConnectionCode, changeSet, cft, dbTableName, dbFieldname);
    }
    if (!changeSet.getChanges().isEmpty()) {
        dbLog.addChangeSet(changeSet);
        try (Session hibernateSession = sqlConnectionProvider.getSession(sqlConnectionCode)) {
            try {
                CompletableFuture.runAsync(() -> {
                    hibernateSession.doWork(connection -> {
                        Database database;
                        try {
                            database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
                            setSchemaName(database);
                            var meta = connection.getMetaData();
                            // Check if field already exist in table
                            try (ResultSet res = meta.getColumns(null, database.getDefaultSchemaName(), dbTableName, dbFieldname)) {
                                if (res.next()) {
                                    checkTypeMatches(dbTableName, cft, column, res.getString("TYPE_NAME"), res.getInt("COLUMN_SIZE"));
                                } else {
                                    // Create the field
                                    Liquibase liquibase = new Liquibase(dbLog, new ClassLoaderResourceAccessor(), database);
                                    liquibase.update(new Contexts(), new LabelExpression());
                                    liquibase.forceReleaseLocks();
                                }
                            }
                        } catch (Exception e) {
                            log.error("Failed to add field {} to custom table {}", dbFieldname, dbTableName, e);
                            throw new SQLException(String.format("Failed to add field %s to custom table %s : ", dbFieldname, dbTableName) + e.getMessage(), e);
                        }
                    });
                }).get(1, TimeUnit.MINUTES);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                log.error("Failed to add field {} to custom table {} within 1 minute", dbFieldname, dbTableName, e);
                throw new RuntimeException(e);
            }
        }
    }
}
Also used : Connection(java.sql.Connection) NotPrecondition(liquibase.precondition.core.NotPrecondition) DropColumnChange(liquibase.change.core.DropColumnChange) DatabaseFactory(liquibase.database.DatabaseFactory) TimeoutException(java.util.concurrent.TimeoutException) AddForeignKeyConstraintChange(liquibase.change.core.AddForeignKeyConstraintChange) ModifyDataTypeChange(liquibase.change.core.ModifyDataTypeChange) StringUtils(org.meveo.commons.utils.StringUtils) MigrationFailedException(liquibase.exception.MigrationFailedException) ErrorOption(liquibase.precondition.core.PreconditionContainer.ErrorOption) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) Repository(org.meveo.model.storage.Repository) Matcher(java.util.regex.Matcher) TransactionAttributeType(javax.ejb.TransactionAttributeType) SQLStorageConfiguration(org.meveo.model.persistence.sql.SQLStorageConfiguration) ResultSet(java.sql.ResultSet) ConstraintsConfig(liquibase.change.ConstraintsConfig) AccessTimeout(javax.ejb.AccessTimeout) ModuleInstallationContext(org.meveo.service.admin.impl.ModuleInstallationContext) SqlConfiguration(org.meveo.model.sql.SqlConfiguration) DropSequenceChange(liquibase.change.core.DropSequenceChange) Collection(java.util.Collection) DatabaseFunction(liquibase.statement.DatabaseFunction) LabelExpression(liquibase.LabelExpression) AddColumnConfig(liquibase.change.AddColumnConfig) PreconditionContainer(liquibase.precondition.core.PreconditionContainer) PreparedStatement(java.sql.PreparedStatement) AddNotNullConstraintChange(liquibase.change.core.AddNotNullConstraintChange) Collectors(java.util.stream.Collectors) AddColumnChange(liquibase.change.core.AddColumnChange) BusinessException(org.meveo.admin.exception.BusinessException) Liquibase(liquibase.Liquibase) Serializable(java.io.Serializable) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) DropTableChange(liquibase.change.core.DropTableChange) List(java.util.List) Query(javax.persistence.Query) TableExistsPrecondition(liquibase.precondition.core.TableExistsPrecondition) CustomFieldStorageTypeEnum(org.meveo.model.crm.custom.CustomFieldStorageTypeEnum) Singleton(javax.ejb.Singleton) CustomFieldsCacheContainerProvider(org.meveo.cache.CustomFieldsCacheContainerProvider) JdbcConnection(liquibase.database.jvm.JdbcConnection) Pattern(java.util.regex.Pattern) HibernateException(org.hibernate.HibernateException) CreateTableChange(liquibase.change.core.CreateTableChange) DropForeignKeyConstraintChange(liquibase.change.core.DropForeignKeyConstraintChange) ColumnConfig(liquibase.change.ColumnConfig) Lock(javax.ejb.Lock) Contexts(liquibase.Contexts) AddUniqueConstraintChange(liquibase.change.core.AddUniqueConstraintChange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Session(org.hibernate.Session) DatabaseMetaData(java.sql.DatabaseMetaData) CompletableFuture(java.util.concurrent.CompletableFuture) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) Change(liquibase.change.Change) ArrayList(java.util.ArrayList) DropNotNullConstraintChange(liquibase.change.core.DropNotNullConstraintChange) ChangeSet(liquibase.changelog.ChangeSet) Inject(javax.inject.Inject) SQLException(java.sql.SQLException) FailOption(liquibase.precondition.core.PreconditionContainer.FailOption) TransactionAttribute(javax.ejb.TransactionAttribute) CustomModelObject(org.meveo.model.customEntities.CustomModelObject) EntityManagerProvider(org.meveo.jpa.EntityManagerProvider) TransactionManagement(javax.ejb.TransactionManagement) RawSQLChange(liquibase.change.core.RawSQLChange) Logger(org.slf4j.Logger) DBStorageType(org.meveo.model.persistence.DBStorageType) DatabaseException(liquibase.exception.DatabaseException) EntityManager(javax.persistence.EntityManager) Database(liquibase.database.Database) DropDefaultValueChange(liquibase.change.core.DropDefaultValueChange) LockType(javax.ejb.LockType) CustomFieldTypeEnum(org.meveo.model.crm.custom.CustomFieldTypeEnum) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) SQLConnectionProvider(org.meveo.persistence.sql.SQLConnectionProvider) Collections(java.util.Collections) SqlConfigurationService(org.meveo.persistence.sql.SqlConfigurationService) AddPrimaryKeyChange(liquibase.change.core.AddPrimaryKeyChange) TransactionManagementType(javax.ejb.TransactionManagementType) PersistenceUtils(org.meveo.util.PersistenceUtils) AddDefaultValueChange(liquibase.change.core.AddDefaultValueChange) SQLException(java.sql.SQLException) JdbcConnection(liquibase.database.jvm.JdbcConnection) Contexts(liquibase.Contexts) ConstraintsConfig(liquibase.change.ConstraintsConfig) Database(liquibase.database.Database) ResultSet(java.sql.ResultSet) ExecutionException(java.util.concurrent.ExecutionException) ChangeSet(liquibase.changelog.ChangeSet) TimeoutException(java.util.concurrent.TimeoutException) 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) LabelExpression(liquibase.LabelExpression) AddColumnConfig(liquibase.change.AddColumnConfig) AddColumnChange(liquibase.change.core.AddColumnChange) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) Session(org.hibernate.Session) AccessTimeout(javax.ejb.AccessTimeout) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 5 with CustomFieldTemplate

use of org.meveo.model.crm.CustomFieldTemplate in project meveo by meveo-org.

the class CustomEntityTemplateService method remove.

@Override
public void remove(CustomEntityTemplate cet) throws BusinessException {
    Map<String, CustomFieldTemplate> fields = customFieldTemplateService.findByAppliesToNoCache(cet.getAppliesTo());
    Map<String, EntityCustomAction> customActionMap = entityCustomActionService.findByAppliesTo(cet.getAppliesTo());
    for (CustomFieldTemplate cft : fields.values()) {
        // Don't remove super-template cfts
        if (cft.getAppliesTo().equals(cet.getAppliesTo())) {
            customFieldTemplateService.remove(cft);
        }
    }
    for (EntityCustomAction entityCustomAction : customActionMap.values()) {
        entityCustomActionService.remove(entityCustomAction.getId());
    }
    customFieldsCache.removeCustomEntityTemplate(cet);
    // Remove permissions
    permissionService.removeIfPresent(cet.getModifyPermission());
    permissionService.removeIfPresent(cet.getDecrpytPermission());
    permissionService.removeIfPresent(cet.getReadPermission());
    super.remove(cet);
}
Also used : CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) EntityCustomAction(org.meveo.model.crm.custom.EntityCustomAction)

Aggregations

CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)176 HashMap (java.util.HashMap)61 ArrayList (java.util.ArrayList)60 CustomEntityTemplate (org.meveo.model.customEntities.CustomEntityTemplate)56 BusinessException (org.meveo.admin.exception.BusinessException)50 Map (java.util.Map)46 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)38 List (java.util.List)37 CustomEntityInstance (org.meveo.model.customEntities.CustomEntityInstance)31 IOException (java.io.IOException)28 Collection (java.util.Collection)25 CustomModelObject (org.meveo.model.customEntities.CustomModelObject)23 Inject (javax.inject.Inject)22 Provider (org.meveo.model.crm.Provider)22 CustomRelationshipTemplate (org.meveo.model.customEntities.CustomRelationshipTemplate)21 DBStorageType (org.meveo.model.persistence.DBStorageType)21 CustomFieldTypeEnum (org.meveo.model.crm.custom.CustomFieldTypeEnum)20 CustomFieldTemplateService (org.meveo.service.crm.impl.CustomFieldTemplateService)20 Collectors (java.util.stream.Collectors)19 PaginationConfiguration (org.meveo.admin.util.pagination.PaginationConfiguration)19