Search in sources :

Example 1 with ModelReader

use of org.apache.ofbiz.entity.model.ModelReader in project ofbiz-framework by apache.

the class WebToolsServices method exportEntityEoModelBundle.

public static Map<String, Object> exportEntityEoModelBundle(DispatchContext dctx, Map<String, ? extends Object> context) {
    String eomodeldFullPath = (String) context.get("eomodeldFullPath");
    String entityPackageNameOrig = (String) context.get("entityPackageName");
    String entityGroupId = (String) context.get("entityGroupId");
    String datasourceName = (String) context.get("datasourceName");
    String entityNamePrefix = (String) context.get("entityNamePrefix");
    Locale locale = (Locale) context.get("locale");
    if (datasourceName == null)
        datasourceName = "localderby";
    ModelReader reader = dctx.getDelegator().getModelReader();
    try {
        if (!eomodeldFullPath.endsWith(".eomodeld")) {
            eomodeldFullPath = eomodeldFullPath + ".eomodeld";
        }
        File outdir = new File(eomodeldFullPath);
        if (!outdir.exists()) {
            outdir.mkdir();
        }
        if (!outdir.isDirectory()) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFullPathIsNotADirectory", UtilMisc.toMap("eomodeldFullPath", eomodeldFullPath), locale));
        }
        if (!outdir.canWrite()) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFullPathIsNotWriteable", UtilMisc.toMap("eomodeldFullPath", eomodeldFullPath), locale));
        }
        Set<String> entityNames = new TreeSet<String>();
        if (UtilValidate.isNotEmpty(entityPackageNameOrig)) {
            Set<String> entityPackageNameSet = new HashSet<String>();
            entityPackageNameSet.addAll(StringUtil.split(entityPackageNameOrig, ","));
            Debug.logInfo("Exporting with entityPackageNameSet: " + entityPackageNameSet, module);
            Map<String, TreeSet<String>> entitiesByPackage = reader.getEntitiesByPackage(entityPackageNameSet, null);
            for (Map.Entry<String, TreeSet<String>> entitiesByPackageMapEntry : entitiesByPackage.entrySet()) {
                entityNames.addAll(entitiesByPackageMapEntry.getValue());
            }
        } else if (UtilValidate.isNotEmpty(entityGroupId)) {
            Debug.logInfo("Exporting entites from the Group: " + entityGroupId, module);
            entityNames.addAll(EntityGroupUtil.getEntityNamesByGroup(entityGroupId, dctx.getDelegator(), false));
        } else {
            entityNames.addAll(reader.getEntityNames());
        }
        Debug.logInfo("Exporting the following entities: " + entityNames, module);
        // remove all view-entity
        Iterator<String> filterEntityNameIter = entityNames.iterator();
        while (filterEntityNameIter.hasNext()) {
            String entityName = filterEntityNameIter.next();
            ModelEntity modelEntity = reader.getModelEntity(entityName);
            if (modelEntity instanceof ModelViewEntity) {
                filterEntityNameIter.remove();
            }
        }
        // write the index.eomodeld file
        Map<String, Object> topLevelMap = new HashMap<String, Object>();
        topLevelMap.put("EOModelVersion", "\"2.1\"");
        List<Map<String, Object>> entitiesMapList = new LinkedList<Map<String, Object>>();
        topLevelMap.put("entities", entitiesMapList);
        for (String entityName : entityNames) {
            Map<String, Object> entitiesMap = new HashMap<String, Object>();
            entitiesMapList.add(entitiesMap);
            entitiesMap.put("className", "EOGenericRecord");
            entitiesMap.put("name", entityName);
        }
        UtilPlist.writePlistFile(topLevelMap, eomodeldFullPath, "index.eomodeld", true);
        // write each <EntityName>.plist file
        for (String curEntityName : entityNames) {
            ModelEntity modelEntity = reader.getModelEntity(curEntityName);
            UtilPlist.writePlistFile(modelEntity.createEoModelMap(entityNamePrefix, datasourceName, entityNames, reader), eomodeldFullPath, curEntityName + ".plist", true);
        }
        Integer entityNamesSize = new Integer(entityNames.size());
        return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "WebtoolsEomodelExported", UtilMisc.toMap("entityNamesSize", entityNamesSize.toString(), "eomodeldFullPath", eomodeldFullPath), locale));
    } catch (UnsupportedEncodingException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelSavingFileError", UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (FileNotFoundException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFileOrDirectoryNotFound", UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelErrorGettingEntityNames", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LinkedList(java.util.LinkedList) ModelReader(org.apache.ofbiz.entity.model.ModelReader) TreeSet(java.util.TreeSet) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) HashSet(java.util.HashSet)

Example 2 with ModelReader

use of org.apache.ofbiz.entity.model.ModelReader in project ofbiz-framework by apache.

the class WebToolsServices method getEntityRefData.

/**
 * Get entity reference data. Returns the number of entities in
 * <code>numberOfEntities</code> and a List of Maps -
 * <code>packagesList</code>.
 * Each Map contains:<br>
 * <ul><li><code>packageName</code> - the entity package name</li>
 * <li><code>entitiesList</code> - a list of Maps:
 *       <ul>
 *         <li><code>entityName</code></li>
 *         <li><code>helperName</code></li>
 *         <li><code>groupName</code></li>
 *         <li><code>plainTableName</code></li>
 *         <li><code>title</code></li>
 *         <li><code>description</code></li>
 *         <!-- <li><code>location</code></li> -->
 *         <li><code>javaNameList</code> - list of Maps:
 *           <ul>
 *             <li><code>isPk</code></li>
 *             <li><code>name</code></li>
 *             <li><code>colName</code></li>
 *             <li><code>description</code></li>
 *             <li><code>type</code></li>
 *             <li><code>javaType</code></li>
 *             <li><code>sqlType</code></li>
 *           </ul>
 *         </li>
 *         <li><code>relationsList</code> - list of Maps:
 *           <ul>
 *             <li><code>title</code></li>
 *             <!-- <li><code>description</code></li> -->
 *             <li><code>relEntity</code></li>
 *             <li><code>fkName</code></li>
 *             <li><code>type</code></li>
 *             <li><code>length</code></li>
 *             <li><code>keysList</code> - list of Maps:
 *               <ul>
 *                 <li><code>row</code></li>
 *                 <li><code>fieldName</code></li>
 *                 <li><code>relFieldName</code></li>
 *               </ul>
 *             </li>
 *           </ul>
 *         </li>
 *         <li><code>indexList</code> - list of Maps:
 *           <ul>
 *             <li><code>name</code></li>
 *             <!-- <li><code>description</code></li> -->
 *             <li><code>fieldNameList</code> - list of Strings</li>
 *           </ul>
 *         </li>
 *       </ul>
 *       </li></ul>
 */
public static Map<String, Object> getEntityRefData(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Map<String, Object> resultMap = ServiceUtil.returnSuccess();
    ModelReader reader = delegator.getModelReader();
    Map<String, TreeSet<String>> entitiesByPackage = new HashMap<String, TreeSet<String>>();
    Set<String> packageNames = new TreeSet<String>();
    Set<String> tableNames = new TreeSet<String>();
    // put the entityNames TreeSets in a HashMap by packageName
    try {
        Collection<String> ec = reader.getEntityNames();
        resultMap.put("numberOfEntities", ec.size());
        for (String eName : ec) {
            ModelEntity ent = reader.getModelEntity(eName);
            // make sure the table name is in the list of all table names, if not null
            if (UtilValidate.isNotEmpty(ent.getPlainTableName())) {
                tableNames.add(ent.getPlainTableName());
            }
            TreeSet<String> entities = entitiesByPackage.get(ent.getPackageName());
            if (entities == null) {
                entities = new TreeSet<String>();
                entitiesByPackage.put(ent.getPackageName(), entities);
                packageNames.add(ent.getPackageName());
            }
            entities.add(eName);
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale) + e.getMessage());
    }
    String search = (String) context.get("search");
    List<Map<String, Object>> packagesList = new LinkedList<Map<String, Object>>();
    try {
        for (String pName : packageNames) {
            Map<String, Object> packageMap = new HashMap<String, Object>();
            TreeSet<String> entities = entitiesByPackage.get(pName);
            List<Map<String, Object>> entitiesList = new LinkedList<Map<String, Object>>();
            for (String entityName : entities) {
                Map<String, Object> entityMap = new HashMap<String, Object>();
                String helperName = delegator.getEntityHelperName(entityName);
                String groupName = delegator.getEntityGroupName(entityName);
                if (search == null || entityName.toLowerCase().indexOf(search.toLowerCase()) != -1) {
                    ModelEntity entity = reader.getModelEntity(entityName);
                    ResourceBundle bundle = null;
                    if (UtilValidate.isNotEmpty(entity.getDefaultResourceName())) {
                        try {
                            bundle = UtilResourceBundle.getBundle(entity.getDefaultResourceName(), locale, loader);
                        } catch (Exception exception) {
                            Debug.logInfo(exception.getMessage(), module);
                        }
                    }
                    String entityDescription = null;
                    if (bundle != null) {
                        try {
                            entityDescription = bundle.getString("EntityDescription." + entity.getEntityName());
                        } catch (Exception exception) {
                        }
                    }
                    if (UtilValidate.isEmpty(entityDescription)) {
                        entityDescription = entity.getDescription();
                    }
                    // fields list
                    List<Map<String, Object>> javaNameList = new LinkedList<Map<String, Object>>();
                    for (Iterator<ModelField> f = entity.getFieldsIterator(); f.hasNext(); ) {
                        Map<String, Object> javaNameMap = new HashMap<String, Object>();
                        ModelField field = f.next();
                        ModelFieldType type = delegator.getEntityFieldType(entity, field.getType());
                        javaNameMap.put("isPk", field.getIsPk());
                        javaNameMap.put("name", field.getName());
                        javaNameMap.put("colName", field.getColName());
                        String fieldDescription = null;
                        if (bundle != null) {
                            try {
                                fieldDescription = bundle.getString("FieldDescription." + entity.getEntityName() + "." + field.getName());
                            } catch (Exception exception) {
                            }
                        }
                        if (UtilValidate.isEmpty(fieldDescription)) {
                            fieldDescription = field.getDescription();
                        }
                        if (UtilValidate.isEmpty(fieldDescription) && bundle != null) {
                            try {
                                fieldDescription = bundle.getString("FieldDescription." + field.getName());
                            } catch (Exception exception) {
                            }
                        }
                        if (UtilValidate.isEmpty(fieldDescription)) {
                            fieldDescription = ModelUtil.javaNameToDbName(field.getName()).toLowerCase();
                            fieldDescription = ModelUtil.upperFirstChar(fieldDescription.replace('_', ' '));
                        }
                        javaNameMap.put("description", fieldDescription);
                        javaNameMap.put("type", (field.getType()) != null ? field.getType() : null);
                        javaNameMap.put("javaType", (field.getType() != null && type != null) ? type.getJavaType() : "Undefined");
                        javaNameMap.put("sqlType", (type != null && type.getSqlType() != null) ? type.getSqlType() : "Undefined");
                        javaNameMap.put("encrypted", field.getEncryptMethod().isEncrypted());
                        javaNameMap.put("encryptMethod", field.getEncryptMethod());
                        javaNameList.add(javaNameMap);
                    }
                    // relations list
                    List<Map<String, Object>> relationsList = new LinkedList<Map<String, Object>>();
                    for (int r = 0; r < entity.getRelationsSize(); r++) {
                        Map<String, Object> relationMap = new HashMap<String, Object>();
                        ModelRelation relation = entity.getRelation(r);
                        List<Map<String, Object>> keysList = new LinkedList<Map<String, Object>>();
                        int row = 1;
                        for (ModelKeyMap keyMap : relation.getKeyMaps()) {
                            Map<String, Object> keysMap = new HashMap<String, Object>();
                            String fieldName = null;
                            String relFieldName = null;
                            if (keyMap.getFieldName().equals(keyMap.getRelFieldName())) {
                                fieldName = keyMap.getFieldName();
                                relFieldName = "aa";
                            } else {
                                fieldName = keyMap.getFieldName();
                                relFieldName = keyMap.getRelFieldName();
                            }
                            keysMap.put("row", row++);
                            keysMap.put("fieldName", fieldName);
                            keysMap.put("relFieldName", relFieldName);
                            keysList.add(keysMap);
                        }
                        relationMap.put("title", relation.getTitle());
                        relationMap.put("description", relation.getDescription());
                        relationMap.put("relEntity", relation.getRelEntityName());
                        relationMap.put("fkName", relation.getFkName());
                        relationMap.put("type", relation.getType());
                        relationMap.put("length", relation.getType().length());
                        relationMap.put("keysList", keysList);
                        relationsList.add(relationMap);
                    }
                    // index list
                    List<Map<String, Object>> indexList = new LinkedList<Map<String, Object>>();
                    for (int r = 0; r < entity.getIndexesSize(); r++) {
                        List<String> fieldNameList = new LinkedList<String>();
                        ModelIndex index = entity.getIndex(r);
                        for (Iterator<ModelIndex.Field> fieldIterator = index.getFields().iterator(); fieldIterator.hasNext(); ) {
                            fieldNameList.add(fieldIterator.next().getFieldName());
                        }
                        Map<String, Object> indexMap = new HashMap<String, Object>();
                        indexMap.put("name", index.getName());
                        indexMap.put("description", index.getDescription());
                        indexMap.put("fieldNameList", fieldNameList);
                        indexList.add(indexMap);
                    }
                    entityMap.put("entityName", entityName);
                    entityMap.put("helperName", helperName);
                    entityMap.put("groupName", groupName);
                    entityMap.put("plainTableName", entity.getPlainTableName());
                    entityMap.put("title", entity.getTitle());
                    entityMap.put("description", entityDescription);
                    String entityLocation = entity.getLocation();
                    entityLocation = entityLocation.replaceFirst(System.getProperty("ofbiz.home") + "/", "");
                    entityMap.put("location", entityLocation);
                    entityMap.put("javaNameList", javaNameList);
                    entityMap.put("relationsList", relationsList);
                    entityMap.put("indexList", indexList);
                    entitiesList.add(entityMap);
                }
            }
            packageMap.put("packageName", pName);
            packageMap.put("entitiesList", entitiesList);
            packagesList.add(packageMap);
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale) + e.getMessage());
    }
    resultMap.put("packagesList", packagesList);
    return resultMap;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) ModelRelation(org.apache.ofbiz.entity.model.ModelRelation) ModelField(org.apache.ofbiz.entity.model.ModelField) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ModelField(org.apache.ofbiz.entity.model.ModelField) TreeSet(java.util.TreeSet) ModelIndex(org.apache.ofbiz.entity.model.ModelIndex) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) ResourceBundle(java.util.ResourceBundle) UtilResourceBundle(org.apache.ofbiz.base.util.UtilProperties.UtilResourceBundle) Map(java.util.Map) HashMap(java.util.HashMap) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Example 3 with ModelReader

use of org.apache.ofbiz.entity.model.ModelReader in project ofbiz-framework by apache.

the class WebToolsServices method entityExportAll.

public static Map<String, Object> entityExportAll(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    // mandatory
    String outpath = (String) context.get("outpath");
    Timestamp fromDate = (Timestamp) context.get("fromDate");
    Integer txTimeout = (Integer) context.get("txTimeout");
    if (txTimeout == null) {
        txTimeout = Integer.valueOf(7200);
    }
    List<String> results = new LinkedList<String>();
    if (UtilValidate.isNotEmpty(outpath)) {
        File outdir = new File(outpath);
        if (!outdir.exists()) {
            outdir.mkdir();
        }
        if (outdir.isDirectory() && outdir.canWrite()) {
            Set<String> passedEntityNames;
            try {
                ModelReader reader = delegator.getModelReader();
                Collection<String> ec = reader.getEntityNames();
                passedEntityNames = new TreeSet<String>(ec);
            } catch (Exception exc) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale));
            }
            int fileNumber = 1;
            for (String curEntityName : passedEntityNames) {
                long numberWritten = 0;
                ModelEntity me = delegator.getModelEntity(curEntityName);
                if (me instanceof ModelViewEntity) {
                    results.add("[" + fileNumber + "] [vvv] " + curEntityName + " skipping view entity");
                    continue;
                }
                List<EntityCondition> conds = new LinkedList<EntityCondition>();
                if (UtilValidate.isNotEmpty(fromDate)) {
                    conds.add(EntityCondition.makeCondition("createdStamp", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
                }
                EntityQuery eq = EntityQuery.use(delegator).from(curEntityName).where(conds).orderBy(me.getPkFieldNames());
                try {
                    boolean beganTx = TransactionUtil.begin();
                    // Don't bother writing the file if there's nothing to put into it
                    try (EntityListIterator values = eq.queryIterator()) {
                        GenericValue value = values.next();
                        if (value != null) {
                            try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outdir, curEntityName + ".xml")), "UTF-8")))) {
                                writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                                writer.println("<entity-engine-xml>");
                                do {
                                    value.writeXmlText(writer, "");
                                    numberWritten++;
                                    if (numberWritten % 500 == 0) {
                                        TransactionUtil.commit(beganTx);
                                        beganTx = TransactionUtil.begin();
                                    }
                                } while ((value = values.next()) != null);
                                writer.println("</entity-engine-xml>");
                            } catch (UnsupportedEncodingException | FileNotFoundException e) {
                                results.add("[" + fileNumber + "] [xxx] Error when writing " + curEntityName + ": " + e);
                            }
                            results.add("[" + fileNumber + "] [" + numberWritten + "] " + curEntityName + " wrote " + numberWritten + " records");
                        } else {
                            results.add("[" + fileNumber + "] [---] " + curEntityName + " has no records, not writing file");
                        }
                        TransactionUtil.commit(beganTx);
                    } catch (GenericEntityException entityEx) {
                        results.add("[" + fileNumber + "] [xxx] Error when writing " + curEntityName + ": " + entityEx);
                        continue;
                    }
                    fileNumber++;
                } catch (GenericTransactionException e) {
                    Debug.logError(e, module);
                    results.add(e.getLocalizedMessage());
                }
            }
        } else {
            results.add("Path not found or no write access.");
        }
    } else {
        results.add("No path specified, doing nothing.");
    }
    // send the notification
    Map<String, Object> resp = UtilMisc.<String, Object>toMap("results", results);
    return resp;
}
Also used : Locale(java.util.Locale) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) FileNotFoundException(java.io.FileNotFoundException) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) BufferedWriter(java.io.BufferedWriter) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) PrintWriter(java.io.PrintWriter) GenericValue(org.apache.ofbiz.entity.GenericValue) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FileOutputStream(java.io.FileOutputStream) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) OutputStreamWriter(java.io.OutputStreamWriter) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) File(java.io.File)

Example 4 with ModelReader

use of org.apache.ofbiz.entity.model.ModelReader in project ofbiz-framework by apache.

the class DataResourceWorker method renderDataResourceAsText.

public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
    if (delegator == null) {
        delegator = dispatcher.getDelegator();
    }
    if (dataResourceId == null) {
        throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
    }
    if (templateContext == null) {
        templateContext = new HashMap<>();
    }
    if (UtilValidate.isEmpty(targetMimeTypeId)) {
        targetMimeTypeId = "text/html";
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    // FIXME correctly propagate the theme, then fixes also the related FIXME below
    VisualTheme visualTheme = ThemeFactory.getVisualThemeFromId("COMMON");
    ModelTheme modelTheme = visualTheme.getModelTheme();
    // if the target mimeTypeId is not a text type, throw an exception
    if (!targetMimeTypeId.startsWith("text/")) {
        throw new GeneralException("The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId);
    }
    // get the data resource object
    GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
    if (dataResource == null) {
        throw new GeneralException("No data resource object found for dataResourceId: [" + dataResourceId + "]");
    }
    // a data template attached to the data resource
    String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");
    // no template; or template is NONE; render the data
    if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
        DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, out, cache);
    } else {
        // a template is defined; render the template first
        templateContext.put("mimeTypeId", targetMimeTypeId);
        // FTL template
        if ("FTL".equals(dataTemplateTypeId)) {
            try {
                // get the template data for rendering
                String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
                // if use web analytics.
                if (UtilValidate.isNotEmpty(webAnalytics)) {
                    StringBuffer newTemplateText = new StringBuffer(templateText);
                    String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">";
                    for (GenericValue webAnalytic : webAnalytics) {
                        StringWrapper wrapString = StringUtil.wrapString((String) webAnalytic.get("webAnalyticsCode"));
                        webAnalyticsCode += wrapString.toString();
                    }
                    webAnalyticsCode += "</script>";
                    newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode);
                    templateText = newTemplateText.toString();
                }
                // render the FTL template
                boolean useTemplateCache = cache && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
                // Do not use dataResource.lastUpdatedStamp for dataResource template caching as it may use ftl file or electronicText
                // If dataResource using ftl file use nowTimestamp to avoid freemarker caching
                Timestamp lastUpdatedStamp = UtilDateTime.nowTimestamp();
                // If dataResource is type of ELECTRONIC_TEXT then only use the lastUpdatedStamp of electronicText entity for freemarker caching
                if ("ELECTRONIC_TEXT".equals(dataResource.getString("dataResourceTypeId"))) {
                    GenericValue electronicText = dataResource.getRelatedOne("ElectronicText", true);
                    if (electronicText != null) {
                        lastUpdatedStamp = electronicText.getTimestamp("lastUpdatedStamp");
                    }
                }
                FreeMarkerWorker.renderTemplateFromString("delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId, templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
            } catch (TemplateException e) {
                throw new GeneralException("Error rendering FTL template", e);
            }
        } else if ("XSLT".equals(dataTemplateTypeId)) {
            File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
            // This is related with the other FIXME above: we need to correctly propagate the theme.
            String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
            visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
            modelTheme = visualTheme.getModelTheme();
            String docbookStylesheet = modelTheme.getProperty("VT_DOCBOOKSTYLESHEET").toString();
            File sourceFileLocation = new File(System.getProperty("ofbiz.home") + "/themes" + docbookStylesheet.substring(1, docbookStylesheet.length() - 1));
            UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
            // get the template data for rendering
            String templateLocation = DataResourceWorker.getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")).toString();
            // render the XSLT template and file
            String outDoc = null;
            try {
                outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile"));
            } catch (TransformerException c) {
                Debug.logError("XSL TransformerException: " + c.getMessage(), module);
            }
            out.append(outDoc);
        // Screen Widget template
        } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
            try {
                MapStack<String> context = MapStack.create(templateContext);
                context.put("locale", locale);
                // prepare the map for preRenderedContent
                String textData = (String) context.get("textData");
                if (UtilValidate.isNotEmpty(textData)) {
                    Map<String, Object> prc = new HashMap<>();
                    String mapKey = (String) context.get("mapKey");
                    if (mapKey != null) {
                        prc.put(mapKey, mapKey);
                    }
                    // used for default screen defs
                    prc.put("body", textData);
                    context.put("preRenderedContent", prc);
                }
                // get the screen renderer; or create a new one
                ScreenRenderer screens = (ScreenRenderer) context.get("screens");
                if (screens == null) {
                    // TODO: replace "screen" to support dynamic rendering of different output
                    ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
                    screens = new ScreenRenderer(out, context, screenStringRenderer);
                    screens.getContext().put("screens", screens);
                }
                // render the screen
                ModelScreen modelScreen = null;
                ScreenStringRenderer renderer = screens.getScreenStringRenderer();
                String combinedName = dataResource.getString("objectInfo");
                if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId")) && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) {
                    modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
                } else {
                    // stored in  a single file, long or short text
                    Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache), true, true);
                    Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml, "DataResourceId: " + dataResource.getString("dataResourceId"));
                    if (UtilValidate.isNotEmpty(modelScreenMap)) {
                        // get first entry, only one screen allowed per file
                        Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next();
                        modelScreen = entry.getValue();
                    }
                }
                if (UtilValidate.isNotEmpty(modelScreen)) {
                    modelScreen.renderScreenString(out, context, renderer);
                } else {
                    throw new GeneralException("The dataResource file [" + dataResourceId + "] could not be found");
                }
            } catch (SAXException | ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            }
        } else if ("FORM_COMBINED".equals(dataTemplateTypeId)) {
            try {
                Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("globalContext"));
                context.put("locale", locale);
                context.put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder("screen")));
                HttpServletRequest request = (HttpServletRequest) context.get("request");
                HttpServletResponse response = (HttpServletResponse) context.get("response");
                ModelForm modelForm = null;
                ModelReader entityModelReader = delegator.getModelReader();
                String formText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
                Document formXml = UtilXml.readXmlDocument(formText, true, true);
                Map<String, ModelForm> modelFormMap = FormFactory.readFormDocument(formXml, entityModelReader, dispatcher.getDispatchContext(), null);
                if (UtilValidate.isNotEmpty(modelFormMap)) {
                    // get first entry, only one form allowed per file
                    Map.Entry<String, ModelForm> entry = modelFormMap.entrySet().iterator().next();
                    modelForm = entry.getValue();
                }
                String formrenderer = modelTheme.getFormRendererLocation("screen");
                MacroFormRenderer renderer = new MacroFormRenderer(formrenderer, request, response);
                FormRenderer formRenderer = new FormRenderer(modelForm, renderer);
                formRenderer.render(out, context);
            } catch (SAXException | ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            } catch (Exception e) {
                throw new GeneralException("Error rendering Screen template", e);
            }
        } else {
            throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
        }
    }
}
Also used : HashMap(java.util.HashMap) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) ModelScreen(org.apache.ofbiz.widget.model.ModelScreen) Document(org.w3c.dom.Document) Timestamp(java.sql.Timestamp) SAXException(org.xml.sax.SAXException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) GenericValue(org.apache.ofbiz.entity.GenericValue) StringWrapper(org.apache.ofbiz.base.util.StringUtil.StringWrapper) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TransformerException(javax.xml.transform.TransformerException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) FileUploadException(org.apache.commons.fileupload.FileUploadException) FormRenderer(org.apache.ofbiz.widget.renderer.FormRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) ModelForm(org.apache.ofbiz.widget.model.ModelForm)

Example 5 with ModelReader

use of org.apache.ofbiz.entity.model.ModelReader in project ofbiz-framework by apache.

the class EntityDataLoader method generateData.

public static int generateData(Delegator delegator, List<Object> errorMessages) throws GenericEntityException {
    int rowsChanged = 0;
    ModelReader reader = delegator.getModelReader();
    for (String entityName : reader.getEntityNames()) {
        ModelEntity entity = reader.getModelEntity(entityName);
        String baseName = entity.getPlainTableName();
        if (entity instanceof ModelViewEntity) {
            baseName = ModelUtil.javaNameToDbName(entity.getEntityName());
        }
        if (baseName != null) {
            try {
                List<GenericValue> toBeStored = new LinkedList<GenericValue>();
                toBeStored.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_ADMIN", "description", "Permission to Administer a " + entity.getEntityName() + " entity."));
                toBeStored.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FULLADMIN", "permissionId", baseName + "_ADMIN", "fromDate", UtilDateTime.nowTimestamp()));
                rowsChanged += delegator.storeAll(toBeStored);
            } catch (GenericEntityException e) {
                errorMessages.add("[generateData] ERROR: Failed Security Generation for entity \"" + baseName + "\"");
            }
        /*
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_VIEW", "description", "Permission to View a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_CREATE", "description", "Permission to Create a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_UPDATE", "description", "Permission to Update a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_DELETE", "description", "Permission to Delete a " + entity.getEntityName() + " entity."));

                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_VIEW"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_CREATE"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_UPDATE"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_DELETE"));
                */
        }
    }
    return rowsChanged;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ModelReader(org.apache.ofbiz.entity.model.ModelReader) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) LinkedList(java.util.LinkedList)

Aggregations

GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)7 ModelReader (org.apache.ofbiz.entity.model.ModelReader)7 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)6 FileNotFoundException (java.io.FileNotFoundException)4 LinkedList (java.util.LinkedList)4 Locale (java.util.Locale)4 Map (java.util.Map)4 GenericValue (org.apache.ofbiz.entity.GenericValue)4 File (java.io.File)3 IOException (java.io.IOException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 HashMap (java.util.HashMap)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)3 Delegator (org.apache.ofbiz.entity.Delegator)3 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)3 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)3 SAXException (org.xml.sax.SAXException)3 MalformedURLException (java.net.MalformedURLException)2 Timestamp (java.sql.Timestamp)2