use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class FinAccountPaymentServices method finAccountWithdraw.
// base account transaction services
public static Map<String, Object> finAccountWithdraw(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
String productStoreId = (String) context.get("productStoreId");
String finAccountId = (String) context.get("finAccountId");
String orderItemSeqId = (String) context.get("orderItemSeqId");
String reasonEnumId = (String) context.get("reasonEnumId");
String orderId = (String) context.get("orderId");
Boolean requireBalance = (Boolean) context.get("requireBalance");
BigDecimal amount = (BigDecimal) context.get("amount");
if (requireBalance == null) {
requireBalance = Boolean.TRUE;
}
final String WITHDRAWAL = "WITHDRAWAL";
String partyId = (String) context.get("partyId");
if (UtilValidate.isEmpty(partyId)) {
partyId = "_NA_";
}
String currencyUom = (String) context.get("currency");
if (UtilValidate.isEmpty(currencyUom)) {
currencyUom = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
// validate the amount
if (amount.compareTo(BigDecimal.ZERO) < 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountMustBePositive", locale));
}
GenericValue finAccount;
try {
finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// verify we have a financial account
if (finAccount == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", ""), locale));
}
// make sure the fin account itself has not expired
if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale));
}
// check the actual balance (excluding authorized amounts) and create the
// transaction if it is sufficient
BigDecimal previousBalance = finAccount.getBigDecimal("actualBalance");
if (previousBalance == null) {
previousBalance = FinAccountHelper.ZERO;
}
BigDecimal balance;
String refNum;
Boolean procResult;
if (requireBalance && previousBalance.compareTo(amount) < 0) {
procResult = Boolean.FALSE;
balance = previousBalance;
refNum = "N/A";
} else {
try {
refNum = FinAccountPaymentServices.createFinAcctPaymentTransaction(delegator, dispatcher, userLogin, amount, productStoreId, partyId, orderId, orderItemSeqId, currencyUom, WITHDRAWAL, finAccountId, reasonEnumId);
finAccount.refresh();
balance = finAccount.getBigDecimal("actualBalance");
procResult = Boolean.TRUE;
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// make sure balance is not null
if (balance == null) {
balance = FinAccountHelper.ZERO;
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("previousBalance", previousBalance);
result.put("balance", balance);
result.put("amount", amount);
result.put("processResult", procResult);
result.put("referenceNum", refNum);
return result;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class FinAccountPaymentServices method createFinAcctPaymentTransaction.
private static String createFinAcctPaymentTransaction(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, BigDecimal amount, String productStoreId, String partyId, String orderId, String orderItemSeqId, String currencyUom, String txType, String finAccountId, String reasonEnumId) throws GeneralException {
final String coParty = ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
final String paymentMethodType = "FIN_ACCOUNT";
if (UtilValidate.isEmpty(partyId)) {
partyId = "_NA_";
}
String paymentType;
String partyIdFrom;
String partyIdTo;
BigDecimal paymentAmount;
// determine the payment type and which direction the parties should go
if ("DEPOSIT".equals(txType)) {
paymentType = "RECEIPT";
partyIdFrom = partyId;
partyIdTo = coParty;
paymentAmount = amount;
} else if ("WITHDRAWAL".equals(txType)) {
paymentType = "DISBURSEMENT";
partyIdFrom = coParty;
partyIdTo = partyId;
paymentAmount = amount;
} else if ("ADJUSTMENT".equals(txType)) {
if (amount.compareTo(BigDecimal.ZERO) < 0) {
paymentType = "DISBURSEMENT";
partyIdFrom = coParty;
partyIdTo = partyId;
// must be positive
paymentAmount = amount.negate();
} else {
paymentType = "RECEIPT";
partyIdFrom = partyId;
partyIdTo = coParty;
paymentAmount = amount;
}
} else {
throw new GeneralException("Unable to create financial account transaction!");
}
// payment amount should always be positive; adjustments may
// create the payment for the transaction
Map<String, Object> paymentCtx = UtilMisc.<String, Object>toMap("paymentTypeId", paymentType);
paymentCtx.put("paymentMethodTypeId", paymentMethodType);
paymentCtx.put("partyIdTo", partyIdTo);
paymentCtx.put("partyIdFrom", partyIdFrom);
paymentCtx.put("statusId", "PMNT_RECEIVED");
paymentCtx.put("currencyUomId", currencyUom);
paymentCtx.put("amount", paymentAmount);
paymentCtx.put("userLogin", userLogin);
paymentCtx.put("paymentRefNum", Long.toString(UtilDateTime.nowTimestamp().getTime()));
String paymentId;
Map<String, Object> payResult;
try {
payResult = dispatcher.runSync("createPayment", paymentCtx);
if (ServiceUtil.isError(payResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(payResult));
}
} catch (GenericServiceException e) {
throw new GeneralException(e);
}
if (payResult == null) {
throw new GeneralException("Unknow error in creating financial account transaction!");
}
if (ServiceUtil.isError(payResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(payResult));
}
paymentId = (String) payResult.get("paymentId");
// create the initial transaction
Map<String, Object> transCtx = UtilMisc.<String, Object>toMap("finAccountTransTypeId", txType);
transCtx.put("finAccountId", finAccountId);
transCtx.put("partyId", partyId);
transCtx.put("orderId", orderId);
transCtx.put("orderItemSeqId", orderItemSeqId);
transCtx.put("reasonEnumId", reasonEnumId);
transCtx.put("amount", amount);
transCtx.put("userLogin", userLogin);
transCtx.put("paymentId", paymentId);
Map<String, Object> transResult;
try {
transResult = dispatcher.runSync("createFinAccountTrans", transCtx);
if (ServiceUtil.isError(transResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(transResult));
}
} catch (GenericServiceException e) {
throw new GeneralException(e);
}
if (transResult == null) {
throw new GeneralException("Unknown error in creating financial account transaction!");
}
if (ServiceUtil.isError(transResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(transResult));
}
return (String) transResult.get("finAccountTransId");
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class BlogRssServices method generateEntryList.
public static List<SyndEntry> generateEntryList(LocalDispatcher dispatcher, Delegator delegator, String contentId, String entryLink, Locale locale, GenericValue userLogin) {
List<SyndEntry> entries = new LinkedList<SyndEntry>();
List<GenericValue> contentRecs = null;
try {
contentRecs = EntityQuery.use(delegator).from("ContentAssocViewTo").where("contentIdStart", contentId, "caContentAssocTypeId", "PUBLISH_LINK", "statusId", "CTNT_PUBLISHED").orderBy("-caFromDate").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (contentRecs != null) {
for (GenericValue v : contentRecs) {
String sub = null;
try {
Map<String, Object> dummy = new HashMap<String, Object>();
sub = ContentWorker.renderSubContentAsText(dispatcher, v.getString("contentId"), mapKey, dummy, locale, mimeTypeId, true);
} catch (GeneralException e) {
Debug.logError(e, module);
} catch (IOException e) {
Debug.logError(e, module);
}
if (sub != null) {
String thisLink = entryLink + "?articleContentId=" + v.getString("contentId") + "&blogContentId=" + contentId;
SyndContent desc = new SyndContentImpl();
desc.setType("text/plain");
desc.setValue(sub);
SyndEntry entry = new SyndEntryImpl();
entry.setTitle(v.getString("contentName"));
entry.setPublishedDate(v.getTimestamp("createdDate"));
entry.setDescription(desc);
entry.setLink(thisLink);
entry.setAuthor((v.getString("createdByUserLogin")));
entries.add(entry);
}
}
}
return entries;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class JNDITransactionFactory method getTransactionManager.
public TransactionManager getTransactionManager() {
if (transactionManager == null) {
synchronized (JNDITransactionFactory.class) {
// try again inside the synch just in case someone when through while we were waiting
if (transactionManager == null) {
try {
String jndiName = EntityConfig.getInstance().getTransactionFactory().getTransactionManagerJndi().getJndiName();
String jndiServerName = EntityConfig.getInstance().getTransactionFactory().getTransactionManagerJndi().getJndiServerName();
if (UtilValidate.isNotEmpty(jndiName)) {
try {
InitialContext ic = JNDIContextFactory.getInitialContext(jndiServerName);
if (ic != null) {
transactionManager = (TransactionManager) ic.lookup(jndiName);
}
} catch (NamingException ne) {
Debug.logWarning(ne, "NamingException while finding TransactionManager named " + jndiName + " in JNDI.", module);
transactionManager = null;
}
if (transactionManager == null) {
Debug.logWarning("Failed to find TransactionManager named " + jndiName + " in JNDI.", module);
}
}
} catch (GeneralException e) {
Debug.logError(e, module);
transactionManager = null;
}
}
}
}
return transactionManager;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ListFinder method runFind.
@Override
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
String entityName = this.entityNameExdr.expandString(context);
String useCacheStr = this.useCacheStrExdr.expandString(context);
String filterByDateStr = this.filterByDateStrExdr.expandString(context);
String distinctStr = this.distinctStrExdr.expandString(context);
String delegatorName = this.delegatorNameExdr.expandString(context);
ModelEntity modelEntity = delegator.getModelEntity(entityName);
String resultSetTypeString = this.resultSetTypeExdr.expandString(context);
if (modelEntity == null) {
throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "].");
}
boolean useCache = "true".equals(useCacheStr);
boolean filterByDate = "true".equals(filterByDateStr);
boolean distinct = "true".equals(distinctStr);
int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
if ("forward".equals(resultSetTypeString)) {
resultSetType = ResultSet.TYPE_FORWARD_ONLY;
}
if (UtilValidate.isNotEmpty(delegatorName)) {
delegator = DelegatorFactory.getDelegator(delegatorName);
}
EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
EntityCondition havingEntityCondition = getHavingEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
if (useCache) {
// if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
if (outputHandler instanceof UseIterator) {
Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", module);
outputHandler = new GetAll();
}
if (distinct) {
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true.");
}
if (havingEntityCondition != null) {
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list).");
}
}
// get the list of fieldsToSelect from selectFieldExpanderList
Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
// if fieldsToSelect != null and useCacheBool is true, throw an error
if (fieldsToSelect != null && useCache) {
throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when use-cache is set to true");
}
// get the list of orderByFields from orderByExpanderList
List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
try {
// if filterByDate, do a date filter on the results based on the now-timestamp
if (filterByDate && !useCache) {
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
if (whereEntityCondition != null) {
whereEntityCondition = EntityCondition.makeCondition(UtilMisc.toList(whereEntityCondition, filterByDateCondition));
} else {
whereEntityCondition = filterByDateCondition;
}
}
if (useCache) {
List<GenericValue> results = delegator.findList(entityName, whereEntityCondition, fieldsToSelect, orderByFields, null, true);
if (filterByDate) {
results = EntityUtil.filterByDate(results);
}
this.outputHandler.handleOutput(results, context, listAcsr);
} else {
boolean useTransaction = true;
if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
Exception newE = new Exception("Stack Trace");
Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
useTransaction = false;
}
EntityFindOptions options = new EntityFindOptions();
options.setDistinct(distinct);
options.setResultSetType(resultSetType);
if (outputHandler instanceof LimitRange) {
LimitRange limitRange = (LimitRange) outputHandler;
int start = limitRange.getStart(context);
int size = limitRange.getSize(context);
options.setMaxRows(start + size);
} else if (outputHandler instanceof LimitView) {
LimitView limitView = (LimitView) outputHandler;
int index = limitView.getIndex(context);
int size = limitView.getSize(context);
options.setMaxRows(size * (index + 1));
}
boolean beganTransaction = false;
try {
if (useTransaction) {
beganTransaction = TransactionUtil.begin();
}
EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options);
this.outputHandler.handleOutput(eli, context, listAcsr);
// NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see EntityAnd.getChildren() in ModelTree.java)
} catch (GenericEntityException e) {
String errMsg = "Failure in by " + label + " find operation, rolling back transaction";
Debug.logError(e, errMsg, module);
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, errMsg, e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
// after rolling back, rethrow the exception
throw e;
} finally {
// only commit the transaction if we started one... this will throw an exception if it fails
TransactionUtil.commit(beganTransaction);
}
}
} catch (GenericEntityException e) {
String errMsg = "Error doing find by " + label + ": " + e.toString();
Debug.logError(e, module);
throw new GeneralException(errMsg, e);
}
}
Aggregations