use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class ModelFormField method getEntry.
public String getEntry(Map<String, ? extends Object> context, String defaultValue) {
Boolean isError = (Boolean) context.get("isError");
Boolean useRequestParameters = (Boolean) context.get("useRequestParameters");
Locale locale = (Locale) context.get("locale");
if (locale == null) {
locale = Locale.getDefault();
}
TimeZone timeZone = (TimeZone) context.get("timeZone");
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
UtilCodec.SimpleEncoder simpleEncoder = (UtilCodec.SimpleEncoder) context.get("simpleEncoder");
String returnValue;
// if isError is TRUE and useRequestParameters is not FALSE (ie is null or TRUE) then parameters will be used
if ((Boolean.TRUE.equals(isError) && !Boolean.FALSE.equals(useRequestParameters)) || (Boolean.TRUE.equals(useRequestParameters))) {
Map<String, Object> parameters = UtilGenerics.checkMap(context.get("parameters"), String.class, Object.class);
String parameterName = this.getParameterName(context);
if (parameters != null && parameters.get(parameterName) != null) {
Object parameterValue = parameters.get(parameterName);
if (parameterValue instanceof String) {
returnValue = (String) parameterValue;
} else {
// we might want to do something else here in the future, but for now this is probably best
Debug.logWarning("Found a non-String parameter value for field [" + this.getModelForm().getName() + "." + this.getFieldName() + "]", module);
returnValue = defaultValue;
}
} else {
returnValue = defaultValue;
}
} else {
Map<String, ? extends Object> dataMap = this.getMap(context);
boolean dataMapIsContext = false;
if (dataMap == null) {
dataMap = context;
dataMapIsContext = true;
}
Object retVal = null;
if (UtilValidate.isNotEmpty(this.entryAcsr)) {
if (dataMap instanceof GenericEntity) {
GenericEntity genEnt = (GenericEntity) dataMap;
if (genEnt.getModelEntity().isField(this.entryAcsr.getOriginalName())) {
retVal = genEnt.get(this.entryAcsr.getOriginalName(), locale);
} else {
// TODO: this may never come up, but if necessary use the FlexibleStringExander to eval the name first: String evaled = this.entryAcsr
}
} else {
retVal = this.entryAcsr.get(dataMap, locale);
}
} else {
// if no entry name was specified, use the field's name
if (dataMap.containsKey(this.name)) {
retVal = dataMap.get(this.name);
}
}
// this is a special case to fill in fields during a create by default from parameters passed in
if (dataMapIsContext && retVal == null && !Boolean.FALSE.equals(useRequestParameters)) {
Map<String, ? extends Object> parameters = UtilGenerics.checkMap(context.get("parameters"));
if (parameters != null) {
if (UtilValidate.isNotEmpty(this.entryAcsr)) {
retVal = this.entryAcsr.get(parameters);
} else {
retVal = parameters.get(this.name);
}
}
}
if (retVal != null) {
// format string based on the user's locale and time zone
if (retVal instanceof Double || retVal instanceof Float || retVal instanceof BigDecimal) {
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumFractionDigits(10);
return nf.format(retVal);
} else if (retVal instanceof java.sql.Date) {
DateFormat df = UtilDateTime.toDateFormat(UtilDateTime.getDateFormat(), timeZone, null);
return df.format((java.util.Date) retVal);
} else if (retVal instanceof java.sql.Time) {
DateFormat df = UtilDateTime.toTimeFormat(UtilDateTime.getTimeFormat(), timeZone, null);
return df.format((java.util.Date) retVal);
} else if (retVal instanceof java.sql.Timestamp) {
DateFormat df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, null);
return df.format((java.util.Date) retVal);
} else if (retVal instanceof java.util.Date) {
DateFormat df = UtilDateTime.toDateTimeFormat("EEE MMM dd hh:mm:ss z yyyy", timeZone, null);
return df.format((java.util.Date) retVal);
} else if (retVal instanceof Collection) {
Collection<Object> col = UtilGenerics.checkCollection(retVal);
Iterator<Object> iter = col.iterator();
List<Object> newCol = new ArrayList<>(col.size());
while (iter.hasNext()) {
Object item = iter.next();
if (item == null) {
continue;
}
if (simpleEncoder != null) {
newCol.add(simpleEncoder.encode(item.toString()));
} else {
newCol.add(item.toString());
}
}
return newCol.toString();
} else {
returnValue = retVal.toString();
}
} else {
returnValue = defaultValue;
}
}
if (this.getEncodeOutput() && returnValue != null) {
if (simpleEncoder != null) {
returnValue = simpleEncoder.encode(returnValue);
}
}
if (returnValue != null) {
returnValue = returnValue.trim();
}
return returnValue;
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class EntitySyncServices method pullAndReportEntitySyncData.
/**
* Pull and Report Entity Sync Data - Called Remotely to Push Results from last pull, the Pull next set of results.
*@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> pullAndReportEntitySyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
EntitySyncContext esc = null;
Locale locale = (Locale) context.get("locale");
try {
esc = new EntitySyncContext(dctx, context);
Debug.logInfo("Doing pullAndReportEntitySyncData for entitySyncId=" + esc.entitySyncId + ", currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
if ("Y".equals(esc.entitySync.get("forPushOnly"))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotDoEntitySyncPush", locale));
}
// Part 1: if any results are passed, store the results for the given startDate, update EntitySync, etc
// restore info from last pull, or if no results start new run
esc.runPullStartOrRestoreSavedResults();
// increment starting time to run until now
while (esc.hasMoreTimeToSync()) {
// make sure the following message is commented out before commit:
// Debug.logInfo("(loop)Doing pullAndReportEntitySyncData split, currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
esc.totalSplits++;
// tx times are indexed
// keep track of how long these sync runs take and store that info on the history table
// saves info about removed, all entities that don't have no-auto-stamp set, this will be done in the GenericDAO like the stamp sets
// Part 2: get the next set of data for the given entitySyncId
// Part 2a: return it back for storage but leave the EntitySyncHistory without results, and don't update the EntitySync last time
// ===== INSERTS =====
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
// ===== UPDATES =====
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
// ===== DELETES =====
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
esc.setTotalRowCounts(valuesToCreate, valuesToStore, keysToRemove);
if (Debug.infoOn())
Debug.logInfo("Service pullAndReportEntitySyncData returning - [" + valuesToCreate.size() + "] to create; [" + valuesToStore.size() + "] to store; [" + keysToRemove.size() + "] to remove; [" + esc.totalRowsPerSplit + "] total rows per split.", module);
if (esc.totalRowsPerSplit > 0) {
// stop if we found some data, otherwise look and try again
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("startDate", esc.startDate);
result.put("valuesToCreate", valuesToCreate);
result.put("valuesToStore", valuesToStore);
result.put("keysToRemove", keysToRemove);
return result;
} else {
// save the progress to EntitySync and EntitySyncHistory, and move on...
esc.saveResultsReportedFromDataStore();
esc.advanceRunTimes();
}
}
// if no more results from database to return, save final settings
if (!esc.hasMoreTimeToSync()) {
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 runEntitySync.
/**
* Run an Entity Sync (checks to see if other already running, etc)
*@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> runEntitySync(DispatchContext dctx, Map<String, ? extends Object> context) {
Locale locale = (Locale) context.get("locale");
EntitySyncContext esc = null;
try {
esc = new EntitySyncContext(dctx, context);
if ("Y".equals(esc.entitySync.get("forPullOnly"))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotDoEntitySyncPush", locale));
}
esc.runPushStartRunning();
// 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()) {
// this will result in lots of log messages, so leaving commented out unless needed/wanted later
// Debug.logInfo("Doing runEntitySync split, currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
esc.totalSplits++;
// tx times are indexed
// keep track of how long these sync runs take and store that info on the history table
// saves info about removed, all entities that don't have no-auto-stamp set, this will be done in the GenericDAO like the stamp sets
// ===== INSERTS =====
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
// ===== UPDATES =====
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
// ===== DELETES =====
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
esc.runPushSendData(valuesToCreate, valuesToStore, keysToRemove);
esc.saveResultsReportedFromDataStore();
esc.advanceRunTimes();
}
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 loadOfflineSyncData.
public static Map<String, Object> loadOfflineSyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String fileName = (String) context.get("xmlFileName");
Locale locale = (Locale) context.get("locale");
URL xmlFile = UtilURL.fromResource(fileName);
if (xmlFile != null) {
Document xmlSyncDoc = null;
try {
xmlSyncDoc = UtilXml.readXmlDocument(xmlFile, false);
} catch (SAXException e) {
Debug.logError(e, module);
} catch (ParserConfigurationException e) {
Debug.logError(e, module);
} catch (IOException e) {
Debug.logError(e, module);
}
if (xmlSyncDoc == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtEntitySyncXMLDocumentIsNotValid", UtilMisc.toMap("fileName", fileName), locale));
}
List<? extends Element> syncElements = UtilXml.childElementList(xmlSyncDoc.getDocumentElement());
if (syncElements != null) {
for (Element entitySync : syncElements) {
String entitySyncId = entitySync.getAttribute("entitySyncId");
String startTime = entitySync.getAttribute("lastSuccessfulSynchTime");
String createString = UtilXml.childElementValue(entitySync, "values-to-create");
String storeString = UtilXml.childElementValue(entitySync, "values-to-store");
String removeString = UtilXml.childElementValue(entitySync, "keys-to-remove");
// de-serialize the value lists
try {
List<GenericValue> valuesToCreate = checkList(XmlSerializer.deserialize(createString, delegator), GenericValue.class);
List<GenericValue> valuesToStore = checkList(XmlSerializer.deserialize(storeString, delegator), GenericValue.class);
List<GenericEntity> keysToRemove = checkList(XmlSerializer.deserialize(removeString, delegator), GenericEntity.class);
Map<String, Object> storeContext = UtilMisc.toMap("entitySyncId", entitySyncId, "valuesToCreate", valuesToCreate, "valuesToStore", valuesToStore, "keysToRemove", keysToRemove, "userLogin", userLogin);
// store the value(s)
Map<String, Object> storeResult = dispatcher.runSync("storeEntitySyncData", storeContext);
if (ServiceUtil.isError(storeResult)) {
throw new Exception(ServiceUtil.getErrorMessage(storeResult));
}
// TODO create a response document to send back to the initial sync machine
} catch (GenericServiceException gse) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", gse.getMessage()), locale));
} catch (Exception e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", e.getMessage()), locale));
}
}
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtOfflineXMLFileNotFound", UtilMisc.toMap("fileName", fileName), locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.GenericEntity in project ofbiz-framework by apache.
the class EntitySyncContext method assembleKeysToRemove.
public LinkedList<GenericEntity> assembleKeysToRemove() throws SyncDataErrorException {
// get all removed items from the given time range, add to list for those
LinkedList<GenericEntity> keysToRemove = new LinkedList<GenericEntity>();
if (this.nextRemoveTxTime != null && (this.nextRemoveTxTime.equals(currentRunEndTime) || this.nextRemoveTxTime.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 keysToRemove;
}
// Debug.logInfo("Getting keys to remove; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin(7200);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Unable to begin JTA transaction", e);
}
try {
// 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
EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
EntityListIterator removeEli = EntityQuery.use(delegator).from("EntitySyncRemove").where(findValCondition).orderBy(ModelEntity.STAMP_TX_FIELD, ModelEntity.STAMP_FIELD).queryIterator();
GenericValue entitySyncRemove = null;
while ((entitySyncRemove = removeEli.next()) != null) {
// pull the PK from the EntitySyncRemove in the primaryKeyRemoved field, de-XML-serialize it
String primaryKeyRemoved = entitySyncRemove.getString("primaryKeyRemoved");
GenericEntity pkToRemove = null;
try {
pkToRemove = (GenericEntity) XmlSerializer.deserialize(primaryKeyRemoved, delegator);
} catch (IOException e) {
String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
Debug.logError(e, errorMsg, module);
throw new SyncDataErrorException(errorMsg, e);
} catch (SAXException e) {
String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
Debug.logError(e, errorMsg, module);
throw new SyncDataErrorException(errorMsg, e);
} catch (ParserConfigurationException e) {
String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
Debug.logError(e, errorMsg, module);
throw new SyncDataErrorException(errorMsg, e);
} catch (SerializeException e) {
String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
Debug.logError(e, errorMsg, module);
throw new SyncDataErrorException(errorMsg, e);
}
// set the stamp fields for future reference
pkToRemove.set(ModelEntity.STAMP_TX_FIELD, entitySyncRemove.get(ModelEntity.STAMP_TX_FIELD));
pkToRemove.set(ModelEntity.STAMP_FIELD, entitySyncRemove.get(ModelEntity.STAMP_FIELD));
pkToRemove.set(ModelEntity.CREATE_STAMP_TX_FIELD, entitySyncRemove.get(ModelEntity.CREATE_STAMP_TX_FIELD));
pkToRemove.set(ModelEntity.CREATE_STAMP_FIELD, entitySyncRemove.get(ModelEntity.CREATE_STAMP_FIELD));
if (this.entityNameToUseSet.contains(pkToRemove.getEntityName())) {
keysToRemove.add(pkToRemove);
}
}
removeEli.close();
// if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
if (keysToRemove.size() == 0) {
EntityCondition findNextCondition = EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime);
EntityListIterator eliNext = EntityQuery.use(delegator).from("EntitySyncRemove").where(findNextCondition).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
// get the first element and it's tx time value...
GenericValue firstVal = eliNext.next();
eliNext.close();
if (firstVal != null) {
Timestamp nextTxTime = firstVal.getTimestamp(ModelEntity.STAMP_TX_FIELD);
if (this.nextRemoveTxTime == null || nextTxTime.before(this.nextRemoveTxTime)) {
this.nextRemoveTxTime = nextTxTime;
}
}
}
} catch (GenericEntityException e) {
try {
TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleKeysToRemove", e);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Error getting keys to remove from the datasource", e);
} catch (Throwable t) {
try {
TransactionUtil.rollback(beganTransaction, "General error in assembleKeysToRemove", t);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Caught runtime error while getting keys to remove", t);
}
try {
TransactionUtil.commit(beganTransaction);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Commit transaction failed", e);
}
// TEST SECTION: leave false for normal use
boolean logValues = false;
if (logValues && keysToRemove.size() > 0) {
StringBuilder toRemoveInfo = new StringBuilder();
for (GenericEntity keyToRemove : keysToRemove) {
toRemoveInfo.append("\n-->[");
toRemoveInfo.append(keyToRemove.get(ModelEntity.STAMP_TX_FIELD));
toRemoveInfo.append(":");
toRemoveInfo.append(keyToRemove.get(ModelEntity.STAMP_FIELD));
toRemoveInfo.append("] ");
toRemoveInfo.append(keyToRemove);
}
Debug.logInfo(toRemoveInfo.toString(), module);
}
// this calculation is false, so it needs to be nullified
if (keysToRemove.size() > 0) {
this.nextRemoveTxTime = null;
}
return keysToRemove;
}
Aggregations