use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class ContentManagementWorker method setCurrentEntityMap.
public static void setCurrentEntityMap(HttpServletRequest request, String entityName, GenericEntity ent) {
HttpSession session = request.getSession();
Map<String, GenericEntity> currentEntityMap = UtilGenerics.checkMap(session.getAttribute("currentEntityMap"));
if (currentEntityMap == null) {
currentEntityMap = new HashMap<String, GenericEntity>();
session.setAttribute("currentEntityMap", currentEntityMap);
}
currentEntityMap.put(entityName, ent);
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class EntityCacheServices method clearCacheLine.
/**
* Clear Cache Line Service: one of the following context parameters is required: value, dummyPK or primaryKey
* @param dctx The DispatchContext that this service is operating in
* @param context Map containing the input parameters
* @return Map with the result of the service, the output parameters
*/
public static Map<String, Object> clearCacheLine(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
Boolean distributeBool = (Boolean) context.get("distribute");
boolean distribute = false;
if (distributeBool != null)
distribute = distributeBool.booleanValue();
if (context.containsKey("value")) {
GenericValue value = (GenericValue) context.get("value");
if (Debug.infoOn())
Debug.logInfo("Got a clear cache line by value service call; entityName: " + value.getEntityName(), module);
if (Debug.verboseOn())
Debug.logVerbose("Got a clear cache line by value service call; value: " + value, module);
delegator.clearCacheLine(value, distribute);
} else if (context.containsKey("dummyPK")) {
GenericEntity dummyPK = (GenericEntity) context.get("dummyPK");
if (Debug.infoOn())
Debug.logInfo("Got a clear cache line by dummyPK service call; entityName: " + dummyPK.getEntityName(), module);
if (Debug.verboseOn())
Debug.logVerbose("Got a clear cache line by dummyPK service call; dummyPK: " + dummyPK, module);
delegator.clearCacheLineFlexible(dummyPK, distribute);
} else if (context.containsKey("primaryKey")) {
GenericPK primaryKey = (GenericPK) context.get("primaryKey");
if (Debug.infoOn())
Debug.logInfo("Got a clear cache line by primaryKey service call; entityName: " + primaryKey.getEntityName(), module);
if (Debug.verboseOn())
Debug.logVerbose("Got a clear cache line by primaryKey service call; primaryKey: " + primaryKey, module);
delegator.clearCacheLine(primaryKey, distribute);
} else if (context.containsKey("condition")) {
String entityName = (String) context.get("entityName");
EntityCondition condition = (EntityCondition) context.get("condition");
if (Debug.infoOn())
Debug.logInfo("Got a clear cache line by condition service call; entityName: " + entityName, module);
if (Debug.verboseOn())
Debug.logVerbose("Got a clear cache line by condition service call; condition: " + condition, module);
delegator.clearCacheLineByCondition(entityName, condition, distribute);
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class FormRenderer method renderItemRows.
private void renderItemRows(Appendable writer, Map<String, Object> context, FormStringRenderer formStringRenderer, boolean formPerItem, int numOfColumns) throws IOException {
String lookupName = modelForm.getListName();
if (UtilValidate.isEmpty(lookupName)) {
Debug.logError("No value for list or iterator name found.", module);
return;
}
Object obj = context.get(lookupName);
if (obj == null) {
if (Debug.verboseOn()) {
Debug.logVerbose("No object for list or iterator name [" + lookupName + "] found, so not rendering rows.", module);
}
return;
}
// if list is empty, do not render rows
Iterator<?> iter = null;
if (obj instanceof Iterator<?>) {
iter = (Iterator<?>) obj;
} else if (obj instanceof List<?>) {
iter = ((List<?>) obj).listIterator();
}
// set low and high index
Paginator.getListLimits(modelForm, context, obj);
int listSize = ((Integer) context.get("listSize")).intValue();
int lowIndex = ((Integer) context.get("lowIndex")).intValue();
int highIndex = ((Integer) context.get("highIndex")).intValue();
// we're passed a subset of the list, so use (0, viewSize) range
if (modelForm.isOverridenListSize()) {
lowIndex = 0;
highIndex = ((Integer) context.get("viewSize")).intValue();
}
if (iter != null) {
// render item rows
if (UtilValidate.isNotEmpty(context.get("itemIndex"))) {
if (UtilValidate.isNotEmpty(context.get("parentItemIndex"))) {
context.put("parentItemIndex", context.get("parentItemIndex") + modelForm.getItemIndexSeparator() + context.get("itemIndex"));
} else {
context.put("parentItemIndex", modelForm.getItemIndexSeparator() + context.get("itemIndex"));
}
}
int itemIndex = -1;
Object item = null;
context.put("wholeFormContext", context);
Map<String, Object> previousItem = new HashMap<>();
while ((item = safeNext(iter)) != null) {
itemIndex++;
if (itemIndex >= highIndex) {
break;
}
// TODO: this is a bad design, for EntityListIterators we should skip to the lowIndex and go from there, MUCH more efficient...
if (itemIndex < lowIndex) {
continue;
}
Map<String, Object> itemMap = UtilGenerics.checkMap(item);
MapStack<String> localContext = MapStack.create(context);
if (UtilValidate.isNotEmpty(modelForm.getListEntryName())) {
localContext.put(modelForm.getListEntryName(), item);
} else {
if (itemMap instanceof GenericEntity) {
// Rendering code might try to modify the GenericEntity instance,
// so we make a copy of it.
Map<String, Object> genericEntityClone = UtilGenerics.cast(((GenericEntity) itemMap).clone());
localContext.push(genericEntityClone);
} else {
localContext.push(itemMap);
}
}
localContext.push();
localContext.put("previousItem", previousItem);
previousItem = new HashMap<>();
previousItem.putAll(itemMap);
AbstractModelAction.runSubActions(modelForm.getRowActions(), localContext);
localContext.put("itemIndex", Integer.valueOf(itemIndex - lowIndex));
if (UtilValidate.isNotEmpty(context.get("renderFormSeqNumber"))) {
localContext.put("formUniqueId", "_" + context.get("renderFormSeqNumber"));
}
if (Debug.verboseOn()) {
Debug.logVerbose("In form got another row, context is: " + localContext, module);
}
// Check to see if there is a field, same name and same use-when (could come from extended form)
List<ModelFormField> tempFieldList = new LinkedList<>();
tempFieldList.addAll(modelForm.getFieldList());
for (int j = 0; j < tempFieldList.size(); j++) {
ModelFormField modelFormField = tempFieldList.get(j);
if (!modelFormField.isUseWhenEmpty()) {
boolean shouldUse1 = modelFormField.shouldUse(localContext);
for (int i = j + 1; i < tempFieldList.size(); i++) {
ModelFormField curField = tempFieldList.get(i);
if (curField.getName() != null && curField.getName().equals(modelFormField.getName())) {
boolean shouldUse2 = curField.shouldUse(localContext);
if (shouldUse1 == shouldUse2) {
tempFieldList.remove(i--);
}
} else {
continue;
}
}
}
}
// Each single item is rendered in one or more rows if its fields have
// different "position" attributes. All the fields with the same position
// are rendered in the same row.
// The default position is 1, and represents the main row:
// it contains the fields that are in the list header (columns).
// The positions lower than 1 are rendered in rows before the main one;
// positions higher than 1 are rendered after the main one.
// We get a sorted (by position, ascending) set of lists;
// each list contains all the fields with that position.
Collection<List<ModelFormField>> fieldListsByPosition = this.getFieldListsByPosition(tempFieldList);
// List hiddenIgnoredFieldList = getHiddenIgnoredFields(localContext, null, tempFieldList);
for (List<ModelFormField> fieldListByPosition : fieldListsByPosition) {
// For each position (the subset of fields with the same position attribute)
// we have two phases: preprocessing and rendering
List<ModelFormField> innerDisplayHyperlinkFieldsBegin = new LinkedList<>();
List<ModelFormField> innerFormFields = new LinkedList<>();
List<ModelFormField> innerDisplayHyperlinkFieldsEnd = new LinkedList<>();
// Preprocessing:
// all the form fields are evaluated and the ones that will
// appear in the form are put into three separate lists:
// - hyperlink fields that will appear at the beginning of the row
// - fields of other types
// - hyperlink fields that will appear at the end of the row
Iterator<ModelFormField> innerDisplayHyperlinkFieldIter = fieldListByPosition.iterator();
int currentPosition = 1;
while (innerDisplayHyperlinkFieldIter.hasNext()) {
ModelFormField modelFormField = innerDisplayHyperlinkFieldIter.next();
FieldInfo fieldInfo = modelFormField.getFieldInfo();
// don't do any header for hidden or ignored fields
if (fieldInfo.getFieldType() == FieldInfo.HIDDEN || fieldInfo.getFieldType() == FieldInfo.IGNORED) {
continue;
}
if (FieldInfo.isInputFieldType(fieldInfo.getFieldType())) {
// okay, now do the form cell
break;
}
// if this is a list or multi form don't skip here because we don't want to skip the table cell, will skip the actual field later
if (!"list".equals(modelForm.getType()) && !"multi".equals(modelForm.getType()) && !modelFormField.shouldUse(localContext)) {
continue;
}
innerDisplayHyperlinkFieldsBegin.add(modelFormField);
currentPosition = modelFormField.getPosition();
}
Iterator<ModelFormField> innerFormFieldIter = fieldListByPosition.iterator();
while (innerFormFieldIter.hasNext()) {
ModelFormField modelFormField = innerFormFieldIter.next();
FieldInfo fieldInfo = modelFormField.getFieldInfo();
// don't do any header for hidden or ignored fields
if (fieldInfo.getFieldType() == FieldInfo.HIDDEN || fieldInfo.getFieldType() == FieldInfo.IGNORED) {
continue;
}
// skip all of the display/hyperlink fields
if (!FieldInfo.isInputFieldType(fieldInfo.getFieldType())) {
continue;
}
// if this is a list or multi form don't skip here because we don't want to skip the table cell, will skip the actual field later
if (!"list".equals(modelForm.getType()) && !"multi".equals(modelForm.getType()) && !modelFormField.shouldUse(localContext)) {
continue;
}
innerFormFields.add(modelFormField);
currentPosition = modelFormField.getPosition();
}
while (innerDisplayHyperlinkFieldIter.hasNext()) {
ModelFormField modelFormField = innerDisplayHyperlinkFieldIter.next();
FieldInfo fieldInfo = modelFormField.getFieldInfo();
// don't do any header for hidden or ignored fields
if (fieldInfo.getFieldType() == FieldInfo.HIDDEN || fieldInfo.getFieldType() == FieldInfo.IGNORED) {
continue;
}
// skip all non-display and non-hyperlink fields
if (FieldInfo.isInputFieldType(fieldInfo.getFieldType())) {
continue;
}
// if this is a list or multi form don't skip here because we don't want to skip the table cell, will skip the actual field later
if (!"list".equals(modelForm.getType()) && !"multi".equals(modelForm.getType()) && !modelFormField.shouldUse(localContext)) {
continue;
}
innerDisplayHyperlinkFieldsEnd.add(modelFormField);
currentPosition = modelFormField.getPosition();
}
List<ModelFormField> hiddenIgnoredFieldList = getHiddenIgnoredFields(localContext, null, tempFieldList, currentPosition);
// of one row (for the current position).
if (innerDisplayHyperlinkFieldsBegin.size() > 0 || innerFormFields.size() > 0 || innerDisplayHyperlinkFieldsEnd.size() > 0) {
this.renderItemRow(writer, localContext, formStringRenderer, formPerItem, hiddenIgnoredFieldList, innerDisplayHyperlinkFieldsBegin, innerFormFields, innerDisplayHyperlinkFieldsEnd, fieldListByPosition, currentPosition, numOfColumns);
}
}
// iteration on positions
}
// reduce the highIndex if number of items falls short
if ((itemIndex + 1) < highIndex) {
highIndex = itemIndex + 1;
// if list size is overridden, use full listSize
context.put("highIndex", Integer.valueOf(modelForm.isOverridenListSize() ? listSize : highIndex));
}
context.put("actualPageSize", Integer.valueOf(highIndex - lowIndex));
if (iter instanceof EntityListIterator) {
try {
((EntityListIterator) iter).close();
} catch (GenericEntityException e) {
Debug.logError(e, "Error closing list form render EntityListIterator: " + e.toString(), module);
}
}
}
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class EntitySyncServices method runOfflineEntitySync.
public static Map<String, Object> runOfflineEntitySync(DispatchContext dctx, Map<String, ? extends Object> context) {
String fileName = (String) context.get("fileName");
EntitySyncContext esc = null;
long totalRowsExported = 0;
try {
esc = new EntitySyncContext(dctx, context);
Debug.logInfo("Doing runManualEntitySync for entitySyncId=" + esc.entitySyncId + ", currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
Document mainDoc = UtilXml.makeEmptyXmlDocument("xml-entity-synchronization");
Element docElement = mainDoc.getDocumentElement();
docElement.setAttribute("xml:lang", "en-US");
esc.runOfflineStartRunning();
// increment starting time to run until now
// just run this the first time, will be updated between each loop automatically
esc.setSplitStartTime();
while (esc.hasMoreTimeToSync()) {
esc.totalSplits++;
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
long currentRows = esc.setTotalRowCounts(valuesToCreate, valuesToStore, keysToRemove);
totalRowsExported += currentRows;
if (currentRows > 0) {
// create the XML document
Element syncElement = UtilXml.addChildElement(docElement, "entity-sync", mainDoc);
syncElement.setAttribute("entitySyncId", esc.entitySyncId);
syncElement.setAttribute("lastSuccessfulSynchTime", esc.currentRunEndTime.toString());
// serialize the list data for XML storage
try {
UtilXml.addChildElementValue(syncElement, "values-to-create", XmlSerializer.serialize(valuesToCreate), mainDoc);
UtilXml.addChildElementValue(syncElement, "values-to-store", XmlSerializer.serialize(valuesToStore), mainDoc);
UtilXml.addChildElementValue(syncElement, "keys-to-remove", XmlSerializer.serialize(keysToRemove), mainDoc);
} catch (SerializeException e) {
throw new EntitySyncContext.SyncOtherErrorException("List serialization problem", e);
} catch (IOException e) {
throw new EntitySyncContext.SyncOtherErrorException("XML writing problem", e);
}
}
// update the result info
esc.runSaveOfflineSyncInfo(currentRows);
esc.advanceRunTimes();
}
if (totalRowsExported > 0) {
// check the file name; use a default if none is passed in
if (UtilValidate.isEmpty(fileName)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
fileName = "offline_entitySync-" + esc.entitySyncId + "-" + sdf.format(new Date()) + ".xml";
}
// write the XML file
try {
UtilXml.writeXmlDocument(fileName, mainDoc);
} catch (java.io.FileNotFoundException e) {
throw new EntitySyncContext.SyncOtherErrorException(e);
} catch (java.io.IOException e) {
throw new EntitySyncContext.SyncOtherErrorException(e);
}
} else {
Debug.logInfo("No rows to write; no data exported.", module);
}
// save the final results
esc.saveFinalSyncResults();
} catch (SyncAbortException e) {
return e.returnError(module);
} catch (SyncErrorException e) {
e.saveSyncErrorInfo(esc);
return e.returnError(module);
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class EntitySyncServices method storeEntitySyncData.
/**
* Store Entity Sync Data
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> storeEntitySyncData(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
String overrideDelegatorName = (String) context.get("delegatorName");
Locale locale = (Locale) context.get("locale");
if (UtilValidate.isNotEmpty(overrideDelegatorName)) {
delegator = DelegatorFactory.getDelegator(overrideDelegatorName);
if (delegator == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotFindDelegator", UtilMisc.toMap("overrideDelegatorName", overrideDelegatorName), locale));
}
}
// LocalDispatcher dispatcher = dctx.getDispatcher();
String entitySyncId = (String) context.get("entitySyncId");
// incoming lists will already be sorted by lastUpdatedStamp (or lastCreatedStamp)
List<GenericValue> valuesToCreate = UtilGenerics.cast(context.get("valuesToCreate"));
List<GenericValue> valuesToStore = UtilGenerics.cast(context.get("valuesToStore"));
List<GenericEntity> keysToRemove = UtilGenerics.cast(context.get("keysToRemove"));
if (Debug.infoOn())
Debug.logInfo("Running storeEntitySyncData (" + entitySyncId + ") - [" + valuesToCreate.size() + "] to create; [" + valuesToStore.size() + "] to store; [" + keysToRemove.size() + "] to remove.", module);
try {
long toCreateInserted = 0;
long toCreateUpdated = 0;
long toCreateNotUpdated = 0;
long toStoreInserted = 0;
long toStoreUpdated = 0;
long toStoreNotUpdated = 0;
long toRemoveDeleted = 0;
long toRemoveAlreadyDeleted = 0;
// create all values in the valuesToCreate List; if the value already exists update it, or if exists and was updated more recently than this one dont update it
for (GenericValue valueToCreate : valuesToCreate) {
// to Create check if exists (find by pk), if not insert; if exists check lastUpdatedStamp: if null or before the candidate value insert, otherwise don't insert
// NOTE: use the delegator from this DispatchContext rather than the one named in the GenericValue
// maintain the original timestamps when doing storage of synced data, by default with will update the timestamps to now
valueToCreate.setIsFromEntitySync(true);
// check to make sure all foreign keys are created; if not create dummy values as place holders
valueToCreate.checkFks(true);
GenericValue existingValue = EntityQuery.use(delegator).from(valueToCreate.getEntityName()).where(valueToCreate.getPrimaryKey()).queryOne();
if (existingValue == null) {
delegator.create(valueToCreate);
toCreateInserted++;
} else {
// if the existing value has a stamp field that is AFTER the stamp on the valueToCreate, don't update it
if (existingValue.get(ModelEntity.STAMP_FIELD) != null && existingValue.getTimestamp(ModelEntity.STAMP_FIELD).after(valueToCreate.getTimestamp(ModelEntity.STAMP_FIELD))) {
toCreateNotUpdated++;
} else {
delegator.store(valueToCreate);
toCreateUpdated++;
}
}
}
// iterate through to store list and store each
for (GenericValue valueToStore : valuesToStore) {
// to store check if exists (find by pk), if not insert; if exists check lastUpdatedStamp: if null or before the candidate value insert, otherwise don't insert
// maintain the original timestamps when doing storage of synced data, by default with will update the timestamps to now
valueToStore.setIsFromEntitySync(true);
// check to make sure all foreign keys are created; if not create dummy values as place holders
valueToStore.checkFks(true);
GenericValue existingValue = EntityQuery.use(delegator).from(valueToStore.getEntityName()).where(valueToStore.getPrimaryKey()).queryOne();
if (existingValue == null) {
delegator.create(valueToStore);
toStoreInserted++;
} else {
// if the existing value has a stamp field that is AFTER the stamp on the valueToStore, don't update it
if (existingValue.get(ModelEntity.STAMP_FIELD) != null && existingValue.getTimestamp(ModelEntity.STAMP_FIELD).after(valueToStore.getTimestamp(ModelEntity.STAMP_FIELD))) {
toStoreNotUpdated++;
} else {
delegator.store(valueToStore);
toStoreUpdated++;
}
}
}
// iterate through to remove list and remove each
for (GenericEntity pkToRemove : keysToRemove) {
// check to see if it exists, if so remove and count, if not just count already removed
// always do a removeByAnd, if it was a removeByAnd great, if it was a removeByPrimaryKey, this will also work and save us a query
pkToRemove.setIsFromEntitySync(true);
// remove the stamp fields inserted by EntitySyncContext.java at or near line 646
pkToRemove.remove(ModelEntity.STAMP_TX_FIELD);
pkToRemove.remove(ModelEntity.STAMP_FIELD);
pkToRemove.remove(ModelEntity.CREATE_STAMP_TX_FIELD);
pkToRemove.remove(ModelEntity.CREATE_STAMP_FIELD);
int numRemByAnd = delegator.removeByAnd(pkToRemove.getEntityName(), pkToRemove);
if (numRemByAnd == 0) {
toRemoveAlreadyDeleted++;
} else {
toRemoveDeleted++;
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("toCreateInserted", Long.valueOf(toCreateInserted));
result.put("toCreateUpdated", Long.valueOf(toCreateUpdated));
result.put("toCreateNotUpdated", Long.valueOf(toCreateNotUpdated));
result.put("toStoreInserted", Long.valueOf(toStoreInserted));
result.put("toStoreUpdated", Long.valueOf(toStoreUpdated));
result.put("toStoreNotUpdated", Long.valueOf(toStoreNotUpdated));
result.put("toRemoveDeleted", Long.valueOf(toRemoveDeleted));
result.put("toRemoveAlreadyDeleted", Long.valueOf(toRemoveAlreadyDeleted));
if (Debug.infoOn())
Debug.logInfo("Finisching storeEntitySyncData (" + entitySyncId + ") - [" + keysToRemove.size() + "] to remove. Actually removed: " + toRemoveDeleted + " already removed: " + toRemoveAlreadyDeleted, module);
return result;
} catch (GenericEntityException e) {
Debug.logError(e, "Exception saving Entity Sync Data for entitySyncId [" + entitySyncId + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtExceptionSavingEntitySyncData", UtilMisc.toMap("entitySyncId", entitySyncId, "errorString", e.toString()), locale));
} catch (Throwable t) {
Debug.logError(t, "Error saving Entity Sync Data for entitySyncId [" + entitySyncId + "]: " + t.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorSavingEntitySyncData", UtilMisc.toMap("entitySyncId", entitySyncId, "errorString", t.toString()), locale));
}
}
Aggregations