Search in sources :

Example 11 with Model

use of com.axelor.db.Model 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 12 with Model

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

the class DataBackupCreateService method getMetaModelData.

/* Get Data For csv File */
protected String getMetaModelData(String metaModelName, Mapper metaModelMapper, Property property, Object dataObject, String dirPath, boolean isRelativeDate, boolean updateImportId) {
    String id = metaModelMapper.get(dataObject, "id").toString();
    Object value = metaModelMapper.get(dataObject, property.getName());
    if (value == null) {
        return "";
    }
    String propertyTypeStr = property.getType().toString();
    switch(propertyTypeStr) {
        case "LONG":
            if (updateImportId) {
                return ((Model) dataObject).getImportId();
            }
            return value.toString();
        case "DATE":
            if (isRelativeDate) {
                return createRelativeDate((LocalDate) value);
            }
            return value.toString();
        case "DATETIME":
            if (isRelativeDate) {
                if (property.getJavaType() == ZonedDateTime.class) {
                    return createRelativeDateTime(((ZonedDateTime) value).toLocalDateTime());
                }
                return createRelativeDateTime((LocalDateTime) value);
            }
            return property.getJavaType() == ZonedDateTime.class ? ((ZonedDateTime) value).toLocalDateTime().toString() : value.toString();
        case "BINARY":
            String fileName = metaModelName + "_" + property.getName() + "_" + id + ".png";
            try {
                org.apache.commons.io.FileUtils.writeByteArrayToFile(new File(dirPath, fileName), (byte[]) value);
                fileNameList.add(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return fileName;
        case "ONE_TO_ONE":
        case "MANY_TO_ONE":
            return getRelationalFieldValue(property, value, updateImportId);
        case "ONE_TO_MANY":
        case "MANY_TO_MANY":
            return getRelationalFieldData(property, value, updateImportId);
        default:
            return value.toString();
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) MetaModel(com.axelor.meta.db.MetaModel) AuditableModel(com.axelor.auth.db.AuditableModel) Model(com.axelor.db.Model) IOException(java.io.IOException) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile)

Example 13 with Model

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

the class DataBackupRestoreService method restore.

/* Restore the Data using provided zip File and prepare Log File and Return it*/
public File restore(MetaFile zipedBackupFile) {
    Logger LOG = LoggerFactory.getLogger(getClass());
    File tempDir = Files.createTempDir();
    String dirPath = tempDir.getAbsolutePath();
    StringBuilder sb = new StringBuilder();
    try {
        unZip(zipedBackupFile, dirPath);
        String configFName = tempDir.getAbsolutePath() + File.separator + DataBackupServiceImpl.CONFIG_FILE_NAME;
        CSVImporter csvImporter = new CSVImporter(configFName, tempDir.getAbsolutePath());
        csvImporter.addListener(new Listener() {

            String modelName;

            StringBuilder sb1 = new StringBuilder();

            @Override
            public void handle(Model bean, Exception e) {
                if (e.getMessage() != null && !e.getMessage().equals("null")) {
                    if (bean != null) {
                        sb1.append(bean.getClass().getSimpleName() + " : \n" + e.getMessage() + "\n\n");
                    } else {
                        sb1.append(e.getMessage() + "\n\n");
                    }
                }
            }

            @Override
            public void imported(Model model) {
                modelName = model.getClass().getSimpleName();
            }

            @Override
            public void imported(Integer total, Integer count) {
                String str = "", strError = "";
                if (!StringUtils.isBlank(sb1)) {
                    strError = "Errors : \n" + sb1.toString();
                }
                str = "Total Records :  {" + total + "} - Success Records :  {" + count + "}  \n";
                if (total != 0 && count != 0) {
                    sb.append(modelName + " : \n");
                }
                sb.append(strError).append(str + "-----------------------------------------\n");
                sb1.setLength(0);
            }
        });
        csvImporter.run();
        LOG.info("Data Restore Completed");
        FileUtils.cleanDirectory(new File(tempDir.getAbsolutePath()));
        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();
        return file;
    } catch (IOException e) {
        TraceBackService.trace(e);
        return null;
    }
}
Also used : Listener(com.axelor.data.Listener) IOException(java.io.IOException) Logger(org.slf4j.Logger) CSVImporter(com.axelor.data.csv.CSVImporter) IOException(java.io.IOException) Model(com.axelor.db.Model) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile) DateTimeFormatter(java.time.format.DateTimeFormatter) PrintWriter(java.io.PrintWriter)

Example 14 with Model

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

the class AppController method configure.

public void configure(ActionRequest request, ActionResponse response) {
    Context context = request.getContext();
    MetaView formView = null;
    String code = (String) context.get("code");
    String appName = Inflector.getInstance().camelize(code);
    Model config = (Model) context.get("app" + appName);
    String model = "com.axelor.apps.base.db.App" + appName;
    if (config != null) {
        formView = Beans.get(MetaViewRepository.class).all().filter("self.type = 'form' AND self.model = ? AND self.name like '%-config-form'", model).fetchOne();
    }
    if (formView == null) {
        response.setFlash(I18n.get(IExceptionMessages.NO_CONFIG_REQUIRED));
    } else {
        response.setView(ActionView.define(I18n.get("Configure") + ": " + context.get("name")).add("form", formView.getName()).model(model).context("_showRecord", config.getId()).param("forceEdit", "true").map());
    }
}
Also used : Context(com.axelor.rpc.Context) Model(com.axelor.db.Model) MetaView(com.axelor.meta.db.MetaView)

Example 15 with Model

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

the class WkfModelServiceImpl method getMetaModelRecordFilter.

@SuppressWarnings("unchecked")
private Object[] getMetaModelRecordFilter(WkfTaskConfig config, String modelName, User user) {
    MetaModel metaModel = metaModelRepo.findByName(modelName);
    String model = metaModel.getFullName();
    String filter = "self.processInstanceId IN (:processInstanceIds)";
    Class<Model> klass = null;
    try {
        klass = (Class<Model>) Class.forName(model);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    if (user != null) {
        String path = config.getUserPath();
        Property property = Mapper.of(klass).getProperty(path.split("\\.")[0]);
        if (property == null) {
            filter += " AND self.attrs." + path + ".id = '" + user.getId() + "'";
        } else {
            filter += " AND self." + path + ".id = " + user.getId();
        }
    }
    return new Object[] { klass, filter };
}
Also used : MetaModel(com.axelor.meta.db.MetaModel) WkfModel(com.axelor.apps.bpm.db.WkfModel) MetaModel(com.axelor.meta.db.MetaModel) Model(com.axelor.db.Model) Property(com.axelor.db.mapper.Property)

Aggregations

Model (com.axelor.db.Model)77 MetaModel (com.axelor.meta.db.MetaModel)22 AxelorException (com.axelor.exception.AxelorException)19 ArrayList (java.util.ArrayList)18 HashMap (java.util.HashMap)16 Context (com.axelor.rpc.Context)15 Transactional (com.google.inject.persist.Transactional)15 List (java.util.List)14 Mapper (com.axelor.db.mapper.Mapper)13 IOException (java.io.IOException)13 File (java.io.File)12 Map (java.util.Map)12 Property (com.axelor.db.mapper.Property)11 MetaJsonRecord (com.axelor.meta.db.MetaJsonRecord)9 JsonContext (com.axelor.rpc.JsonContext)8 MetaModelRepository (com.axelor.meta.db.repo.MetaModelRepository)7 Strings (com.google.common.base.Strings)7 HashSet (java.util.HashSet)7 FullContext (com.axelor.apps.tool.context.FullContext)6 Beans (com.axelor.inject.Beans)6