Search in sources :

Example 31 with MetaModel

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

the class DataBackupCreateService method create.

/* Generate csv Files for each individual MetaModel and single config file */
public DataBackup create(DataBackup dataBackup) throws IOException {
    File tempDir = Files.createTempDirectory(null).toFile();
    String tempDirectoryPath = tempDir.getAbsolutePath();
    int fetchLimit = dataBackup.getFetchLimit();
    int errorsCount = 0;
    fileNameList = new ArrayList<>();
    List<MetaModel> metaModelList = getMetaModels();
    LinkedList<CSVInput> simpleCsvs = new LinkedList<>();
    LinkedList<CSVInput> refernceCsvs = new LinkedList<>();
    LinkedList<CSVInput> notNullReferenceCsvs = new LinkedList<>();
    Map<String, List<String>> subClassesMap = getSubClassesMap();
    if (dataBackup.getCheckAllErrorFirst()) {
        dataBackup.setFetchLimit(1);
        errorsCount = checkErrors(dataBackup, metaModelList, tempDirectoryPath, subClassesMap);
        dataBackup.setFetchLimit(fetchLimit);
        fileNameList.clear();
    }
    if (errorsCount == 0) {
        for (MetaModel metaModel : metaModelList) {
            try {
                List<String> subClasses = subClassesMap.get(metaModel.getFullName());
                long totalRecord = getMetaModelDataCount(metaModel, subClasses);
                if (totalRecord > 0) {
                    LOG.debug("Exporting Model : " + metaModel.getFullName());
                    notNullReferenceFlag = false;
                    referenceFlag = false;
                    CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(tempDirectoryPath, metaModel.getName() + ".csv")), SEPARATOR, QUOTE_CHAR);
                    CSVInput csvInput = writeCSVData(metaModel, csvWriter, dataBackup, totalRecord, subClasses, tempDirectoryPath);
                    csvWriter.close();
                    if (notNullReferenceFlag) {
                        notNullReferenceCsvs.add(csvInput);
                    } else if (referenceFlag) {
                        refernceCsvs.add(csvInput);
                        CSVInput temcsv = new CSVInput();
                        temcsv.setFileName(csvInput.getFileName());
                        temcsv.setTypeName(csvInput.getTypeName());
                        if (dataBackup.getIsRelativeDate()) {
                            temcsv.setBindings(new ArrayList<>());
                            getCsvInputForDateorDateTime(metaModel, temcsv);
                        }
                        if (AutoImportModelMap.containsKey(csvInput.getTypeName())) {
                            temcsv.setSearch(AutoImportModelMap.get(csvInput.getTypeName()).toString());
                        }
                        if (Class.forName(metaModel.getFullName()).getSuperclass() == App.class) {
                            temcsv.setSearch("self.code = :code");
                        }
                        if (!AutoImportModelMap.containsKey(csvInput.getTypeName()) && !((Class.forName(metaModel.getFullName()).getSuperclass()).equals(App.class))) {
                            temcsv.setSearch("self.importId = :importId");
                        }
                        simpleCsvs.add(temcsv);
                    } else {
                        simpleCsvs.add(csvInput);
                    }
                    fileNameList.add(metaModel.getName() + ".csv");
                }
            } catch (ClassNotFoundException | IOException e) {
                TraceBackService.trace(e, DataBackupService.class.getName());
            } catch (Exception e) {
                JPA.em().getTransaction().rollback();
                if (!dataBackup.getCheckAllErrorFirst()) {
                    sb.append("\nError occured while processing model : " + metaModel.getFullName() + "\n");
                    sb.append(e.getMessage() + "\n");
                }
                JPA.em().getTransaction().begin();
                dataBackup = Beans.get(DataBackupRepository.class).find(dataBackup.getId());
                errorsCount++;
            }
        }
        CSVConfig csvConfig = new CSVConfig();
        csvConfig.setInputs(simpleCsvs);
        csvConfig.getInputs().addAll(notNullReferenceCsvs);
        csvConfig.getInputs().addAll(refernceCsvs);
        csvConfig.getInputs().addAll(notNullReferenceCsvs);
        generateConfig(tempDirectoryPath, csvConfig);
        fileNameList.add(DataBackupServiceImpl.CONFIG_FILE_NAME);
    }
    try {
        if (!Strings.isNullOrEmpty(sb.toString())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmSS");
            String logFileName = "DataBackupLog_" + LocalDateTime.now().format(formatter) + ".log";
            File file = new File(tempDir.getAbsolutePath(), logFileName);
            PrintWriter pw = new PrintWriter(file);
            pw.write(sb.toString());
            pw.close();
            if (file != null) {
                dataBackup.setLogMetaFile(metaFiles.upload(file));
            }
        }
        if (errorsCount == 0) {
            File zippedFile = generateZIP(tempDirectoryPath, fileNameList);
            dataBackup.setBackupMetaFile(metaFiles.upload(zippedFile));
        } else {
            dataBackup.setStatusSelect(DataBackupRepository.DATA_BACKUP_STATUS_ERROR);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return dataBackup;
}
Also used : App(com.axelor.apps.base.db.App) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) CSVInput(com.axelor.data.csv.CSVInput) CSVWriter(com.opencsv.CSVWriter) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) PrintWriter(java.io.PrintWriter) IOException(java.io.IOException) LinkedList(java.util.LinkedList) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) IOException(java.io.IOException) CSVConfig(com.axelor.data.csv.CSVConfig) MetaModel(com.axelor.meta.db.MetaModel) DataBackupRepository(com.axelor.apps.base.db.repo.DataBackupRepository) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 32 with MetaModel

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

the class AccessTemplateServiceImpl method updateNoMenuObjects.

private void updateNoMenuObjects() {
    List<MetaModel> metaModels = metaModelRepo.all().filter("self.fullName not in ?1", objMenu.keySet()).fetch();
    Iterator<MetaModel> modelIter = metaModels.iterator();
    String appMenu = objMenu.get(App.class.getName());
    while (modelIter.hasNext()) {
        MetaModel model = modelIter.next();
        try {
            Class klass = Class.forName(model.getFullName());
            if (App.class.isAssignableFrom(klass)) {
                objMenu.put(model.getFullName(), appMenu);
                modelIter.remove();
            } else if (addObject(model)) {
                modelIter.remove();
            } else {
                objMenu.put(model.getFullName(), appMenu);
            }
        } catch (ClassNotFoundException e) {
            continue;
        }
    }
}
Also used : App(com.axelor.apps.base.db.App) MetaModel(com.axelor.meta.db.MetaModel)

Example 33 with MetaModel

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

the class DataBackupServiceImpl method updateImportId.

@Transactional
public void updateImportId() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyHHmm");
    String filterStr = "self.packageName NOT LIKE '%meta%' AND self.packageName !='com.axelor.studio.db' AND self.name!='DataBackup' AND self.tableName IS NOT NULL";
    List<MetaModel> metaModelList = metaModelRepo.all().filter(filterStr).fetch();
    metaModelList.add(metaModelRepo.findByName(MetaFile.class.getSimpleName()));
    metaModelList.add(metaModelRepo.findByName(MetaJsonField.class.getSimpleName()));
    for (MetaModel metaModel : metaModelList) {
        try {
            Class.forName(metaModel.getFullName());
            String currentDateTimeStr = "'" + LocalDateTime.now().format(formatter) + "'";
            String query = "Update " + metaModel.getName() + " self SET self.importId = CONCAT(CAST(self.id as text)," + currentDateTimeStr + ") WHERE self.importId=null";
            JPA.execute(query);
        } catch (ClassNotFoundException e) {
            TraceBackService.trace(e);
        }
    }
}
Also used : MetaModel(com.axelor.meta.db.MetaModel) DateTimeFormatter(java.time.format.DateTimeFormatter) Transactional(com.google.inject.persist.Transactional)

Example 34 with MetaModel

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

the class PrintTemplateLineServiceImpl method checkExpression.

@SuppressWarnings("unchecked")
@Transactional
@Override
public void checkExpression(Long objectId, MetaModel metaModel, PrintTemplateLine printTemplateLine) throws ClassNotFoundException, AxelorException {
    if (metaModel == null) {
        return;
    }
    String model = metaModel.getFullName();
    String simpleModel = metaModel.getName();
    PrintTemplateLineTest test = printTemplateLine.getPrintTemplateLineTest();
    Context scriptContext = null;
    if (StringUtils.notEmpty(model)) {
        Class<? extends Model> modelClass = (Class<? extends Model>) Class.forName(model);
        Model modelObject = JPA.find(modelClass, objectId);
        if (ObjectUtils.notEmpty(modelObject)) {
            scriptContext = new Context(Mapper.toMap(modelObject), modelClass);
        }
    }
    String resultOfTitle = null;
    String resultOfContent = null;
    Locale locale = Optional.ofNullable(printTemplateLine.getPrintTemplate().getLanguage()).map(Language::getCode).map(Locale::new).orElseGet(AppFilter::getLocale);
    TemplateMaker maker = initMaker(objectId, model, simpleModel, locale);
    try {
        if (StringUtils.notEmpty(printTemplateLine.getTitle())) {
            maker.setTemplate(printTemplateLine.getTitle());
            resultOfTitle = maker.make();
        }
    } catch (Exception e) {
        resultOfTitle = "Error in title";
    }
    try {
        if (StringUtils.notEmpty(printTemplateLine.getContent())) {
            maker.setTemplate(printTemplateLine.getContent());
            resultOfContent = maker.make();
        }
    } catch (Exception e) {
        resultOfContent = "Error in content";
    }
    test.setContentResult(resultOfTitle + "<br>" + resultOfContent);
    Boolean present = Boolean.TRUE;
    if (StringUtils.notEmpty(printTemplateLine.getConditions())) {
        Object evaluation = null;
        try {
            evaluation = templateContextService.computeTemplateContext(printTemplateLine.getConditions(), scriptContext);
        } catch (Exception e) {
            throw new AxelorException(TraceBackRepository.CATEGORY_INCONSISTENCY, I18n.get(IExceptionMessage.PRINT_TEMPLATE_CONDITION_MUST_BE_BOOLEAN));
        }
        if (evaluation instanceof Boolean) {
            present = (Boolean) evaluation;
        }
    }
    test.setConditionsResult(present);
    printTemplateLineRepo.save(printTemplateLine);
}
Also used : Context(com.axelor.rpc.Context) Locale(java.util.Locale) AxelorException(com.axelor.exception.AxelorException) PrintTemplateLineTest(com.axelor.apps.base.db.PrintTemplateLineTest) AxelorException(com.axelor.exception.AxelorException) AppFilter(com.axelor.app.internal.AppFilter) Language(com.axelor.apps.base.db.Language) TemplateMaker(com.axelor.tool.template.TemplateMaker) Model(com.axelor.db.Model) MetaModel(com.axelor.meta.db.MetaModel) Transactional(com.google.inject.persist.Transactional)

Example 35 with MetaModel

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

the class WkfModelController method openRecordView.

@SuppressWarnings("unchecked")
private void openRecordView(ActionRequest request, ActionResponse response, String statusKey, String modelKey, String recordkey) {
    LinkedHashMap<String, Object> _map = (LinkedHashMap<String, Object>) request.getData().get("context");
    String status = "";
    if (statusKey != null) {
        status = _map.get("title").toString();
    }
    String modelName = _map.get(modelKey).toString();
    boolean isMetaModel = (boolean) _map.get("isMetaModel");
    List<Long> recordIds = (List<Long>) _map.get(recordkey);
    ActionViewBuilder actionViewBuilder = null;
    if (isMetaModel) {
        MetaModel metaModel = Beans.get(MetaModelRepository.class).findByName(modelName);
        actionViewBuilder = this.createActionBuilder(status, metaModel);
    } else {
        MetaJsonModel metaJsonModel = Beans.get(MetaJsonModelRepository.class).findByName(modelName);
        actionViewBuilder = this.createActionBuilder(status, metaJsonModel);
    }
    response.setView(actionViewBuilder.context("ids", !recordIds.isEmpty() ? recordIds : 0).map());
}
Also used : MetaJsonModel(com.axelor.meta.db.MetaJsonModel) MetaModelRepository(com.axelor.meta.db.repo.MetaModelRepository) MetaJsonModelRepository(com.axelor.meta.db.repo.MetaJsonModelRepository) ActionViewBuilder(com.axelor.meta.schema.actions.ActionView.ActionViewBuilder) LinkedHashMap(java.util.LinkedHashMap) MetaModel(com.axelor.meta.db.MetaModel) ArrayList(java.util.ArrayList) List(java.util.List)

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