Search in sources :

Example 11 with MetaModel

use of com.axelor.meta.db.MetaModel in project axelor-open-suite by axelor.

the class DataBackupCreateService method writeCSVData.

protected CSVInput writeCSVData(MetaModel metaModel, CSVWriter csvWriter, DataBackup dataBackup, long totalRecord, List<String> subClasses, String dirPath) {
    CSVInput csvInput = new CSVInput();
    boolean headerFlag = true;
    List<String> dataArr;
    List<String> headerArr = new ArrayList<>();
    List<Model> dataList;
    try {
        Mapper metaModelMapper = Mapper.of(Class.forName(metaModel.getFullName()));
        Property[] pro = metaModelMapper.getProperties();
        Integer fetchLimit = dataBackup.getFetchLimit();
        boolean isRelativeDate = dataBackup.getIsRelativeDate();
        boolean updateImportId = dataBackup.getUpdateImportId();
        csvInput.setFileName(metaModel.getName() + ".csv");
        csvInput.setTypeName(metaModel.getFullName());
        csvInput.setBindings(new ArrayList<>());
        for (int i = 0; i < totalRecord; i = i + fetchLimit) {
            dataList = getMetaModelDataList(metaModel, i, fetchLimit, subClasses);
            if (dataList != null && !dataList.isEmpty()) {
                for (Object dataObject : dataList) {
                    dataArr = new ArrayList<>();
                    for (Property property : pro) {
                        if (isPropertyExportable(property)) {
                            if (headerFlag) {
                                String headerStr = getMetaModelHeader(property, csvInput, isRelativeDate);
                                headerArr.add(headerStr);
                            }
                            dataArr.add(getMetaModelData(metaModel.getName(), metaModelMapper, property, dataObject, dirPath, isRelativeDate, updateImportId));
                        }
                    }
                    if (headerFlag) {
                        if (byteArrFieldFlag) {
                            csvInput.setCallable("com.axelor.apps.base.service.app.DataBackupRestoreService:importObjectWithByteArray");
                            byteArrFieldFlag = false;
                        }
                        csvWriter.writeNext(headerArr.toArray(new String[headerArr.size()]), true);
                        headerFlag = false;
                    }
                    csvWriter.writeNext(dataArr.toArray(new String[dataArr.size()]), true);
                }
            }
        }
        if (AutoImportModelMap.containsKey(csvInput.getTypeName())) {
            csvInput.setSearch(AutoImportModelMap.get(csvInput.getTypeName()).toString());
        } else if (Class.forName(metaModel.getFullName()).getSuperclass() == App.class) {
            csvInput.setSearch("self.code = :code");
        } else {
            csvInput.setSearch("self.importId = :importId");
        }
    } catch (ClassNotFoundException e) {
    }
    return csvInput;
}
Also used : App(com.axelor.apps.base.db.App) ArrayList(java.util.ArrayList) CSVInput(com.axelor.data.csv.CSVInput) Mapper(com.axelor.db.mapper.Mapper) MetaModel(com.axelor.meta.db.MetaModel) AuditableModel(com.axelor.auth.db.AuditableModel) Model(com.axelor.db.Model) Property(com.axelor.db.mapper.Property)

Example 12 with MetaModel

use of com.axelor.meta.db.MetaModel in project axelor-open-suite by axelor.

the class DataBackupCreateService method getQuery.

protected Query<Model> getQuery(MetaModel metaModel, List<String> subClasses) throws ClassNotFoundException {
    StringBuilder whereStr = new StringBuilder();
    if (subClasses != null && !subClasses.isEmpty()) {
        for (String subClassName : subClasses) {
            whereStr.append(whereStr.length() > 0 ? " AND " : "");
            whereStr.append("id NOT IN (select id from ").append(subClassName).append(")");
        }
    }
    @SuppressWarnings("unchecked") Class<Model> klass = (Class<Model>) Class.forName(metaModel.getFullName());
    JpaRepository<Model> model = null;
    Query<Model> query = null;
    try {
        model = JpaRepository.of(klass);
    } catch (Exception e) {
        TraceBackService.trace(e, DataBackupService.class.getName());
    }
    if (model != null) {
        query = JpaRepository.of(klass).all();
        if (StringUtils.notEmpty(whereStr.toString())) {
            query.filter(whereStr.toString());
        }
        try {
            Connection connection = DBHelper.getConnection();
            DatabaseMetaData dbmd = connection.getMetaData();
            List<Property> properties = model.fields();
            for (Property property : properties) {
                if (property.isRequired()) {
                    ResultSet res = dbmd.getColumns(null, null, metaModel.getTableName().toLowerCase(), property.getName().replaceAll("([^_A-Z])([A-Z])", "$1_$2").toLowerCase());
                    while (res.next()) {
                        if (res.getInt("NULLABLE") == 1) {
                            String strErr = "Required field issue in table: ";
                            sb.append(strErr).append("Model: " + metaModel.getName() + ", Field: " + property.getName() + "-----------------------------------------\n");
                            query = null;
                        }
                    }
                }
            }
            connection.close();
        } catch (SQLException | NamingException e) {
            e.printStackTrace();
        }
    }
    return query;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) IOException(java.io.IOException) MetaModel(com.axelor.meta.db.MetaModel) AuditableModel(com.axelor.auth.db.AuditableModel) Model(com.axelor.db.Model) ResultSet(java.sql.ResultSet) NamingException(javax.naming.NamingException) Property(com.axelor.db.mapper.Property)

Example 13 with MetaModel

use of com.axelor.meta.db.MetaModel in project axelor-open-suite by axelor.

the class PermissionAssistantService method writeObject.

private void writeObject(CSVWriter csvWriter, PermissionAssistant assistant, Integer size, ResourceBundle bundle) {
    MetaField userField = assistant.getMetaField();
    for (MetaModel object : assistant.getObjectSet()) {
        int colIndex = header.size() + 1;
        String[] row = new String[size];
        row[0] = object.getFullName();
        if (assistant.getTypeSelect() == PermissionAssistantRepository.TYPE_GROUPS) {
            for (Group group : assistant.getGroupSet()) {
                String permName = getPermissionName(userField, object.getName(), group.getCode());
                colIndex = writePermission(object, userField, row, colIndex, permName);
                colIndex++;
            }
        } else if (assistant.getTypeSelect() == PermissionAssistantRepository.TYPE_ROLES) {
            for (Role role : assistant.getRoleSet()) {
                String permName = getPermissionName(userField, object.getName(), role.getName());
                colIndex = writePermission(object, userField, row, colIndex, permName);
                colIndex++;
            }
        }
        csvWriter.writeNext(row);
        if (!assistant.getFieldPermission()) {
            continue;
        }
        List<MetaField> fieldList = object.getMetaFields();
        Collections.sort(fieldList, compareField());
        for (MetaField field : fieldList) {
            colIndex = header.size() + 1;
            row = new String[size];
            row[1] = field.getName();
            row[2] = getFieldTitle(field, bundle);
            if (assistant.getTypeSelect() == PermissionAssistantRepository.TYPE_GROUPS) {
                for (Group group : assistant.getGroupSet()) {
                    String permName = getPermissionName(null, object.getName(), group.getCode());
                    colIndex = writeFieldPermission(field, row, colIndex, permName);
                    colIndex++;
                }
            } else if (assistant.getTypeSelect() == PermissionAssistantRepository.TYPE_ROLES) {
                for (Role role : assistant.getRoleSet()) {
                    String permName = getPermissionName(null, object.getName(), role.getName());
                    colIndex = writeFieldPermission(field, row, colIndex, permName);
                    colIndex++;
                }
            }
            csvWriter.writeNext(row);
        }
    }
}
Also used : Role(com.axelor.auth.db.Role) Group(com.axelor.auth.db.Group) MetaModel(com.axelor.meta.db.MetaModel) MetaField(com.axelor.meta.db.MetaField)

Example 14 with MetaModel

use of com.axelor.meta.db.MetaModel in project axelor-open-suite by axelor.

the class PermissionAssistantController method fillObjects.

public void fillObjects(ActionRequest request, ActionResponse response) {
    try {
        PermissionAssistant assistant = request.getContext().asType(PermissionAssistant.class);
        MetaField metaField = assistant.getMetaField();
        if (metaField != null && (assistant.getObjectSet() == null || assistant.getObjectSet().isEmpty())) {
            List<MetaModel> models = Beans.get(MetaModelRepository.class).all().filter("self.metaFields.relationship = 'ManyToOne'" + " and self.metaFields.typeName = ?1", metaField.getTypeName()).fetch();
            Set<MetaModel> objectSet = new HashSet<>();
            objectSet.addAll(models);
            response.setValue("objectSet", objectSet);
        }
    } catch (Exception e) {
        TraceBackService.trace(response, e);
    }
}
Also used : MetaModel(com.axelor.meta.db.MetaModel) MetaModelRepository(com.axelor.meta.db.repo.MetaModelRepository) MetaField(com.axelor.meta.db.MetaField) PermissionAssistant(com.axelor.auth.db.PermissionAssistant) HashSet(java.util.HashSet)

Example 15 with MetaModel

use of com.axelor.meta.db.MetaModel in project axelor-open-suite by axelor.

the class AppServiceImpl method refreshApp.

@Override
public void refreshApp() throws IOException {
    File dataDir = Files.createTempDirectory(null).toFile();
    File imgDir = new File(dataDir, "img");
    imgDir.mkdir();
    CSVConfig csvConfig = new CSVConfig();
    csvConfig.setInputs(new ArrayList<>());
    List<MetaModel> metaModels = metaModelRepo.all().filter("self.name != 'App' and self.name like 'App%' and self.packageName =  ?1", App.class.getPackage().getName()).fetch();
    final List<String> appFieldTargetList = Stream.of(JPA.fields(App.class)).filter(p -> p.getType() == PropertyType.ONE_TO_ONE).filter(p -> p.getName().startsWith("app")).map(Property::getTarget).map(Class::getName).collect(Collectors.toList());
    log.debug("Total app models: {}", metaModels.size());
    for (MetaModel metaModel : metaModels) {
        if (!appFieldTargetList.contains(metaModel.getFullName())) {
            log.debug("Not a App class : {}", metaModel.getName());
            continue;
        }
        Class<?> klass;
        try {
            klass = Class.forName(metaModel.getFullName());
        } catch (ClassNotFoundException e) {
            continue;
        }
        Object obj = null;
        Query query = JPA.em().createQuery("SELECT id FROM " + metaModel.getName());
        try {
            obj = query.setMaxResults(1).getSingleResult();
        } catch (Exception ex) {
        }
        if (obj != null) {
            continue;
        }
        log.debug("App without app record: {}", metaModel.getName());
        String csvName = "base_" + inflector.camelize(klass.getSimpleName(), true) + ".csv";
        String pngName = inflector.dasherize(klass.getSimpleName()) + ".png";
        CSVInput input = new CSVInput();
        input.setFileName(csvName);
        input.setTypeName(App.class.getName());
        input.setCallable("com.axelor.csv.script.ImportApp:importApp");
        input.setSearch("self.code =:code");
        input.setSeparator(';');
        csvConfig.getInputs().add(input);
        CSVInput appInput = new CSVInput();
        appInput.setFileName(csvName);
        appInput.setTypeName(klass.getName());
        appInput.setSearch("self.app.code =:code");
        appInput.setSeparator(';');
        CSVBind appBind = new CSVBind();
        appBind.setColumn("code");
        appBind.setField("app");
        appBind.setSearch("self.code = :code");
        appInput.getBindings().add(appBind);
        csvConfig.getInputs().add(appInput);
        InputStream stream = klass.getResourceAsStream("/data-init/input/" + csvName);
        copyStream(stream, new File(dataDir, csvName));
        stream = klass.getResourceAsStream("/data-init/input/img/" + pngName);
        copyStream(stream, new File(imgDir, pngName));
    }
    if (!csvConfig.getInputs().isEmpty()) {
        CSVImporter importer = new CSVImporter(csvConfig, dataDir.getAbsolutePath());
        importer.run();
    }
}
Also used : App(com.axelor.apps.base.db.App) MetaModelRepository(com.axelor.meta.db.repo.MetaModelRepository) Arrays(java.util.Arrays) FileUtils(com.axelor.common.FileUtils) URL(java.net.URL) MetaScanner(com.axelor.meta.MetaScanner) Inject(com.google.inject.Inject) CSVInput(com.axelor.data.csv.CSVInput) LoggerFactory(org.slf4j.LoggerFactory) Property(com.axelor.db.mapper.Property) Scanner(java.util.Scanner) AppRepository(com.axelor.apps.base.db.repo.AppRepository) Mapper(com.axelor.db.mapper.Mapper) Transactional(com.google.inject.persist.Transactional) ArrayList(java.util.ArrayList) AxelorException(com.axelor.exception.AxelorException) App(com.axelor.apps.base.db.App) I18n(com.axelor.i18n.I18n) Inflector(com.axelor.common.Inflector) XMLImporter(com.axelor.data.xml.XMLImporter) PropertyType(com.axelor.db.mapper.PropertyType) JPA(com.axelor.db.JPA) Logger(org.slf4j.Logger) Model(com.axelor.db.Model) TraceBackRepository(com.axelor.exception.db.repo.TraceBackRepository) Files(java.nio.file.Files) Collection(java.util.Collection) CSVImporter(com.axelor.data.csv.CSVImporter) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) MetaModel(com.axelor.meta.db.MetaModel) List(java.util.List) Query(javax.persistence.Query) Stream(java.util.stream.Stream) IExceptionMessages(com.axelor.apps.base.exceptions.IExceptionMessages) CSVBind(com.axelor.data.csv.CSVBind) CSVConfig(com.axelor.data.csv.CSVConfig) AppSettings(com.axelor.app.AppSettings) ByteStreams(com.google.common.io.ByteStreams) Pattern(java.util.regex.Pattern) Importer(com.axelor.data.Importer) Singleton(com.google.inject.Singleton) InputStream(java.io.InputStream) Query(javax.persistence.Query) InputStream(java.io.InputStream) CSVInput(com.axelor.data.csv.CSVInput) CSVImporter(com.axelor.data.csv.CSVImporter) CSVConfig(com.axelor.data.csv.CSVConfig) AxelorException(com.axelor.exception.AxelorException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MetaModel(com.axelor.meta.db.MetaModel) CSVBind(com.axelor.data.csv.CSVBind) File(java.io.File) Property(com.axelor.db.mapper.Property)

Aggregations

MetaModel (com.axelor.meta.db.MetaModel)41 MetaModelRepository (com.axelor.meta.db.repo.MetaModelRepository)12 AxelorException (com.axelor.exception.AxelorException)9 MetaField (com.axelor.meta.db.MetaField)9 ArrayList (java.util.ArrayList)8 Model (com.axelor.db.Model)7 Mapper (com.axelor.db.mapper.Mapper)6 IOException (java.io.IOException)6 Transactional (com.google.inject.persist.Transactional)5 List (java.util.List)5 App (com.axelor.apps.base.db.App)4 Property (com.axelor.db.mapper.Property)4 MetaJsonModel (com.axelor.meta.db.MetaJsonModel)4 Context (com.axelor.rpc.Context)4 AuditableModel (com.axelor.auth.db.AuditableModel)3 CSVInput (com.axelor.data.csv.CSVInput)3 MetaFile (com.axelor.meta.db.MetaFile)3 ActionViewBuilder (com.axelor.meta.schema.actions.ActionView.ActionViewBuilder)3 AppFilter (com.axelor.app.internal.AppFilter)2 AdvancedExport (com.axelor.apps.base.db.AdvancedExport)2