use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class SurveyWrapper method getNumberResult.
private double[] getNumberResult(GenericValue question, int type) throws SurveyWrapperException {
double[] result = { 0, 0, 0 };
// index 0 = total responses
// index 1 = tally
// index 2 = average
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
} catch (GenericTransactionException gte) {
Debug.logError(gte, "Unable to begin transaction", module);
}
try (EntityListIterator eli = this.getEli(question, -1)) {
if (eli != null) {
GenericValue value;
while (((value = eli.next()) != null)) {
switch(type) {
case 1:
Long n = value.getLong("numericResponse");
if (UtilValidate.isNotEmpty(n)) {
result[1] += n.longValue();
}
break;
case 2:
Double c = value.getDouble("currencyResponse");
if (UtilValidate.isNotEmpty(c)) {
result[1] += (((double) Math.round((c.doubleValue() - c.doubleValue()) * 100)) / 100);
}
break;
case 3:
Double f = value.getDouble("floatResponse");
if (UtilValidate.isNotEmpty(f)) {
result[1] += f.doubleValue();
}
break;
}
// increment the count
result[0]++;
}
}
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Number result", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
}
}
// average
switch(type) {
case 1:
if (result[0] > 0) {
result[2] = result[1] / ((long) result[0]);
}
break;
case 2:
if (result[0] > 0) {
result[2] = (((double) Math.round((result[1] / result[0]) * 100)) / 100);
}
break;
case 3:
if (result[0] > 0) {
result[2] = result[1] / (long) result[0];
}
break;
}
return result;
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class SurveyWrapper method getBooleanResult.
private long[] getBooleanResult(GenericValue question) throws SurveyWrapperException {
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
long[] result = { 0, 0, 0 };
try (EntityListIterator eli = this.getEli(question, -1)) {
if (eli != null) {
GenericValue value;
while (((value = eli.next()) != null)) {
if ("Y".equalsIgnoreCase(value.getString("booleanResponse"))) {
result[1]++;
} else {
result[2]++;
}
// increment the count
result[0]++;
}
}
}
return result;
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Boolean result", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
}
}
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class ContentEvents method updateAllContentKeywords.
/**
* Updates/adds keywords for all contents
*
* @param request HTTPRequest object for the current request
* @param response HTTPResponse object for the current request
* @return String specifying the exit status of this event
*/
public static String updateAllContentKeywords(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Security security = (Security) request.getAttribute("security");
String updateMode = "CREATE";
String errMsg = null;
String doAll = request.getParameter("doAll");
// check permissions before moving on...
if (!security.hasEntityPermission("CONTENTMGR", "_" + updateMode, request.getSession())) {
Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
errMsg = UtilProperties.getMessage(resource, "contentevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
int numConts = 0;
int errConts = 0;
boolean beganTx = false;
EntityQuery contentQuery = EntityQuery.use(delegator).from("Content");
try {
// begin the transaction
beganTx = TransactionUtil.begin(7200);
if (Debug.infoOn()) {
long count = contentQuery.queryCount();
Debug.logInfo("========== Found " + count + " contents to index ==========", module);
}
GenericValue content;
try (EntityListIterator entityListIterator = contentQuery.queryIterator()) {
while ((content = entityListIterator.next()) != null) {
ContentKeywordIndex.indexKeywords(content, "Y".equals(doAll));
numConts++;
if (numConts % 500 == 0) {
Debug.logInfo("Keywords indexed for " + numConts + " so far", module);
}
}
} catch (GenericEntityException e) {
errMsg = "[ContentEvents.updateAllContentKeywords] Could not create content-keyword (write error); message: " + e.getMessage();
Debug.logWarning(errMsg, module);
errConts++;
request.setAttribute("_ERROR_MESSAGE_", errMsg);
}
} catch (GenericEntityException gee) {
Debug.logWarning(gee, gee.getMessage(), module);
Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
errMsg = UtilProperties.getMessage(resource, "contentevents.error_getting_content_list", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
try {
TransactionUtil.rollback(beganTx, gee.getMessage(), gee);
} catch (GenericTransactionException e1) {
Debug.logError(e1, module);
}
return "error";
}
// commit the transaction
try {
TransactionUtil.commit(beganTx);
} catch (GenericTransactionException e) {
Debug.logError(e, module);
}
if (errConts == 0) {
Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_EVENT_MESSAGE_", errMsg);
return "success";
} else {
Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
messageMap.put("errConts", Integer.toString(errConts));
errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents_with_errors", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class FindServices method performFindList.
/**
* same as performFind but now returning a list instead of an iterator
* Extra parameters viewIndex: startPage of the partial list (0 = first page)
* viewSize: the length of the page (number of records)
* Extra output parameter: listSize: size of the totallist
* list : the list itself.
*
* @param dctx
* @param context
* @return Map
*/
public static Map<String, Object> performFindList(DispatchContext dctx, Map<String, Object> context) {
Integer viewSize = (Integer) context.get("viewSize");
if (viewSize == null) {
// default
viewSize = Integer.valueOf(20);
}
context.put("viewSize", viewSize);
Integer viewIndex = (Integer) context.get("viewIndex");
if (viewIndex == null) {
// default
viewIndex = Integer.valueOf(0);
}
context.put("viewIndex", viewIndex);
Map<String, Object> result = performFind(dctx, context);
int start = viewIndex.intValue() * viewSize.intValue();
List<GenericValue> list = null;
Integer listSize = 0;
try (EntityListIterator it = (EntityListIterator) result.get("listIt")) {
// list starts at '1'
list = it.getPartialList(start + 1, viewSize);
listSize = it.getResultsSizeAfterPartialList();
} catch (ClassCastException | NullPointerException | GenericEntityException e) {
Debug.logInfo("Problem getting partial list" + e, module);
}
result.put("listSize", listSize);
result.put("list", list);
result.remove("listIt");
return result;
}
use of org.apache.ofbiz.entity.util.EntityListIterator 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);
}
}
}
}
Aggregations