Search in sources :

Example 21 with ModelEntity

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

the class EntitySyncContext method assembleValuesToCreate.

public ArrayList<GenericValue> assembleValuesToCreate() throws SyncDataErrorException {
    // first grab all values inserted in the date range, then get the updates (leaving out all values inserted in the data range)
    // make it an ArrayList to easily merge in sorted lists
    ArrayList<GenericValue> valuesToCreate = new ArrayList<GenericValue>();
    if (this.nextCreateTxTime != null && (this.nextCreateTxTime.equals(currentRunEndTime) || this.nextCreateTxTime.after(currentRunEndTime))) {
        // this means that for all entities in this pack we found on the last pass that there would be nothing for this one, so just return nothing...
        return valuesToCreate;
    }
    // Debug.logInfo("Getting values to create; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
    int entitiesSkippedForKnownNext = 0;
    // iterate through entities, get all records with tx stamp in the current time range, put all in a single list
    for (ModelEntity modelEntity : entityModelToUseList) {
        int insertBefore = 0;
        // first test to see if we know that there are no records for this entity in this time period...
        Timestamp knownNextCreateTime = this.nextEntityCreateTxTime.get(modelEntity.getEntityName());
        if (knownNextCreateTime != null && (knownNextCreateTime.equals(currentRunEndTime) || knownNextCreateTime.after(currentRunEndTime))) {
            // Debug.logInfo("In assembleValuesToCreate found knownNextCreateTime [" + knownNextCreateTime + "] after currentRunEndTime [" + currentRunEndTime + "], so skipping time per period for entity [" + modelEntity.getEntityName() + "]", module);
            entitiesSkippedForKnownNext++;
            continue;
        }
        boolean beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin(7200);
        } catch (GenericTransactionException e) {
            throw new SyncDataErrorException("Unable to begin JTA transaction", e);
        }
        try {
            EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
            EntityQuery eq = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findValCondition).orderBy(ModelEntity.CREATE_STAMP_TX_FIELD, ModelEntity.CREATE_STAMP_FIELD);
            long valuesPerEntity = 0;
            try (EntityListIterator eli = eq.queryIterator()) {
                // get the values created within the current time range
                GenericValue nextValue = null;
                while ((nextValue = eli.next()) != null) {
                    // find first value in valuesToCreate list, starting with the current insertBefore value, that has a CREATE_STAMP_TX_FIELD after the nextValue.CREATE_STAMP_TX_FIELD, then do the same with CREATE_STAMP_FIELD
                    while (insertBefore < valuesToCreate.size() && valuesToCreate.get(insertBefore).getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD).before(nextValue.getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD))) {
                        insertBefore++;
                    }
                    while (insertBefore < valuesToCreate.size() && valuesToCreate.get(insertBefore).getTimestamp(ModelEntity.CREATE_STAMP_FIELD).before(nextValue.getTimestamp(ModelEntity.CREATE_STAMP_FIELD))) {
                        insertBefore++;
                    }
                    valuesToCreate.add(insertBefore, nextValue);
                    valuesPerEntity++;
                }
            } catch (GenericEntityException e) {
                try {
                    TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleValuesToCreate", e);
                } catch (GenericTransactionException e2) {
                    Debug.logWarning(e2, "Unable to call rollback()", module);
                }
                throw new SyncDataErrorException("Error getting values to create from the datasource", e);
            }
            // if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
            if (valuesPerEntity == 0) {
                Timestamp startCheckStamp = new Timestamp(System.currentTimeMillis() - syncEndBufferMillis);
                EntityCondition findNextCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime));
                eq = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findNextCondition).orderBy(ModelEntity.CREATE_STAMP_TX_FIELD);
                GenericValue firstVal = null;
                try (EntityListIterator eliNext = eq.queryIterator()) {
                    // get the first element and it's tx time value...
                    firstVal = eliNext.next();
                } catch (GenericEntityException e) {
                    try {
                        TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleValuesToCreate", e);
                    } catch (GenericTransactionException e2) {
                        Debug.logWarning(e2, "Unable to call rollback()", module);
                    }
                    throw new SyncDataErrorException("Error getting values to create from the datasource", e);
                }
                Timestamp nextTxTime;
                if (firstVal != null) {
                    nextTxTime = firstVal.getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD);
                } else {
                    // no results? well, then it's safe to say that up to the pre-querytime (minus the buffer, as usual) we are okay
                    nextTxTime = startCheckStamp;
                }
                if (this.nextCreateTxTime == null || nextTxTime.before(this.nextCreateTxTime)) {
                    this.nextCreateTxTime = nextTxTime;
                    Debug.logInfo("EntitySync: Set nextCreateTxTime to [" + nextTxTime + "]", module);
                }
                Timestamp curEntityNextTxTime = this.nextEntityCreateTxTime.get(modelEntity.getEntityName());
                if (curEntityNextTxTime == null || nextTxTime.before(curEntityNextTxTime)) {
                    this.nextEntityCreateTxTime.put(modelEntity.getEntityName(), nextTxTime);
                    Debug.logInfo("EntitySync: Set nextEntityCreateTxTime to [" + nextTxTime + "] for the entity [" + modelEntity.getEntityName() + "]", module);
                }
            }
        } catch (Throwable t) {
            try {
                TransactionUtil.rollback(beganTransaction, "Throwable error in assembleValuesToCreate", t);
            } catch (GenericTransactionException e2) {
                Debug.logWarning(e2, "Unable to call rollback()", module);
            }
            throw new SyncDataErrorException("Caught runtime error while getting values to create", t);
        }
        try {
            TransactionUtil.commit(beganTransaction);
        } catch (GenericTransactionException e) {
            throw new SyncDataErrorException("Commit transaction failed", e);
        }
    }
    if (entitiesSkippedForKnownNext > 0) {
        if (Debug.infoOn())
            Debug.logInfo("In assembleValuesToCreate skipped [" + entitiesSkippedForKnownNext + "/" + entityModelToUseList + "] entities for the time period ending at [" + currentRunEndTime + "] because of next known create times", module);
    }
    // TEST SECTION: leave false for normal use
    boolean logValues = false;
    if (logValues && valuesToCreate.size() > 0) {
        StringBuilder toCreateInfo = new StringBuilder();
        for (GenericValue valueToCreate : valuesToCreate) {
            toCreateInfo.append("\n-->[");
            toCreateInfo.append(valueToCreate.get(ModelEntity.CREATE_STAMP_TX_FIELD));
            toCreateInfo.append(":");
            toCreateInfo.append(valueToCreate.get(ModelEntity.CREATE_STAMP_FIELD));
            toCreateInfo.append("] ");
            toCreateInfo.append(valueToCreate.getPrimaryKey());
        }
        Debug.logInfo(toCreateInfo.toString(), module);
    }
    // this calculation is false, so it needs to be nullified
    if (valuesToCreate.size() > 0) {
        this.nextCreateTxTime = null;
    }
    return valuesToCreate;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ArrayList(java.util.ArrayList) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 22 with ModelEntity

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

the class EntitySyncContext method getCurrentRunStartTime.

protected static Timestamp getCurrentRunStartTime(Timestamp lastSuccessfulSynchTime, List<ModelEntity> entityModelToUseList, Delegator delegator) throws GenericEntityException {
    // if currentRunStartTime is null, what to do? I guess iterate through all entities and find earliest tx stamp
    if (lastSuccessfulSynchTime == null) {
        Timestamp currentRunStartTime = null;
        for (ModelEntity modelEntity : entityModelToUseList) {
            // fields to select will be PK and the STAMP_TX_FIELD, slimmed down so we don't get a ton of data back
            Set<String> fieldsToSelect = UtilMisc.toSet(modelEntity.getPkFieldNames());
            // find all instances of this entity with the STAMP_TX_FIELD != null, sort ascending to get lowest/oldest value first, then grab first and consider as candidate currentRunStartTime
            fieldsToSelect.add(ModelEntity.STAMP_TX_FIELD);
            EntityListIterator eli = EntityQuery.use(delegator).select(fieldsToSelect).from(modelEntity.getEntityName()).where(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null)).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
            GenericValue nextValue = eli.next();
            eli.close();
            if (nextValue != null) {
                Timestamp candidateTime = nextValue.getTimestamp(ModelEntity.STAMP_TX_FIELD);
                if (currentRunStartTime == null || candidateTime.before(currentRunStartTime)) {
                    currentRunStartTime = candidateTime;
                }
            }
        }
        if (Debug.infoOn())
            Debug.logInfo("No currentRunStartTime was stored on the EntitySync record, so searched for the earliest value and got: " + currentRunStartTime, module);
        return currentRunStartTime;
    } else {
        return lastSuccessfulSynchTime;
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) Timestamp(java.sql.Timestamp)

Example 23 with ModelEntity

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

the class ModelServiceReader method createAutoAttrDef.

private void createAutoAttrDef(Element autoElement, ModelService service) {
    // get the entity name; first from the auto-attributes then from the service def
    String entityName = UtilXml.checkEmpty(autoElement.getAttribute("entity-name"));
    if (UtilValidate.isEmpty(entityName)) {
        entityName = service.defaultEntityName;
        if (UtilValidate.isEmpty(entityName)) {
            Debug.logWarning("Auto-Attribute does not specify an entity-name; not default-entity on service definition", module);
        }
    }
    // get the include type 'pk|nonpk|all'
    String includeType = UtilXml.checkEmpty(autoElement.getAttribute("include"));
    boolean includePk = "pk".equals(includeType) || "all".equals(includeType);
    boolean includeNonPk = "nonpk".equals(includeType) || "all".equals(includeType);
    if (delegator == null) {
        Debug.logWarning("Cannot use auto-attribute fields with a null delegator", module);
    }
    if (delegator != null && entityName != null) {
        Map<String, ModelParam> modelParamMap = new LinkedHashMap<>();
        try {
            ModelEntity entity = delegator.getModelEntity(entityName);
            if (entity == null) {
                throw new GeneralException("Could not find entity with name [" + entityName + "]");
            }
            Iterator<ModelField> fieldsIter = entity.getFieldsIterator();
            while (fieldsIter.hasNext()) {
                ModelField field = fieldsIter.next();
                if ((!field.getIsAutoCreatedInternal()) && ((field.getIsPk() && includePk) || (!field.getIsPk() && includeNonPk))) {
                    ModelFieldType fieldType = delegator.getEntityFieldType(entity, field.getType());
                    if (fieldType == null) {
                        throw new GeneralException("Null field type from delegator for entity [" + entityName + "]");
                    }
                    ModelParam param = new ModelParam();
                    param.entityName = entityName;
                    param.fieldName = field.getName();
                    param.name = field.getName();
                    param.type = fieldType.getJavaType();
                    // this is a special case where we use something different in the service layer than we do in the entity/data layer
                    if ("java.sql.Blob".equals(param.type)) {
                        param.type = "java.nio.ByteBuffer";
                    }
                    param.mode = UtilXml.checkEmpty(autoElement.getAttribute("mode")).intern();
                    // default to true
                    param.optional = "true".equalsIgnoreCase(autoElement.getAttribute("optional"));
                    // default to false
                    param.formDisplay = !"false".equalsIgnoreCase(autoElement.getAttribute("form-display"));
                    // default to none
                    param.allowHtml = UtilXml.checkEmpty(autoElement.getAttribute("allow-html"), "none").intern();
                    modelParamMap.put(field.getName(), param);
                }
            }
            // get the excludes list; and remove those from the map
            List<? extends Element> excludes = UtilXml.childElementList(autoElement, "exclude");
            if (excludes != null) {
                for (Element exclude : excludes) {
                    modelParamMap.remove(UtilXml.checkEmpty(exclude.getAttribute("field-name")));
                }
            }
            // now add in all the remaining params
            for (ModelParam thisParam : modelParamMap.values()) {
                service.addParam(thisParam);
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Problem loading auto-attributes [" + entityName + "] for " + service.name, module);
        } catch (GeneralException e) {
            Debug.logError(e, "Cannot load auto-attributes : " + e.getMessage() + " for " + service.name, module);
        }
    }
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) Element(org.w3c.dom.Element) LinkedHashMap(java.util.LinkedHashMap) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 24 with ModelEntity

use of org.apache.ofbiz.entity.model.ModelEntity 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 25 with ModelEntity

use of org.apache.ofbiz.entity.model.ModelEntity 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)

Aggregations

ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)102 GenericValue (org.apache.ofbiz.entity.GenericValue)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)29 ModelField (org.apache.ofbiz.entity.model.ModelField)28 HashMap (java.util.HashMap)22 Delegator (org.apache.ofbiz.entity.Delegator)17 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)16 LinkedList (java.util.LinkedList)14 Locale (java.util.Locale)12 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)11 ArrayList (java.util.ArrayList)10 ModelRelation (org.apache.ofbiz.entity.model.ModelRelation)10 IOException (java.io.IOException)8 TreeSet (java.util.TreeSet)8 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)8 Map (java.util.Map)7 GeneralRuntimeException (org.apache.ofbiz.base.util.GeneralRuntimeException)7 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)7 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)7 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)7