List of usage examples for java.math BigDecimal negate
public BigDecimal negate()
From source file:org.gnucash.android.ui.transaction.TransactionFormFragment.java
/** * Parse an input string into a {@link BigDecimal} * This method expects the amount including the decimal part * @param amountString String with amount information * @return BigDecimal with the amount parsed from <code>amountString</code> *//* ww w. j av a2 s. c o m*/ public BigDecimal parseInputToDecimal(String amountString) { String clean = stripCurrencyFormatting(amountString); //all amounts are input to 2 decimal places, so after removing decimal separator, divide by 100 BigDecimal amount = new BigDecimal(clean).setScale(2, RoundingMode.HALF_EVEN).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN); if (mTransactionTypeButton.isChecked() && amount.doubleValue() > 0) amount = amount.negate(); return amount; }
From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java
/** * This function should only be called when it should update the payment amounts *//*from w w w.j av a2s . c om*/ public static void restorePaidAmounts(FIN_PaymentScheduleDetail paymentScheduleDetail) { BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount(); BigDecimal psdAmount = paymentScheduleDetail.getAmount(); BigDecimal amount = psdAmount.add(psdWriteoffAmount); BusinessPartner businessPartner = paymentScheduleDetail.getPaymentDetails().getFinPayment() .getBusinessPartner(); if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) { FIN_AddPayment.updatePaymentScheduleAmounts(paymentScheduleDetail.getPaymentDetails(), paymentScheduleDetail.getInvoicePaymentSchedule(), psdAmount.negate(), psdWriteoffAmount.negate()); // BP SO_CreditUsed businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule().getInvoice().getBusinessPartner(); if (paymentScheduleDetail.getPaymentDetails().getFinPayment().isReceipt()) { increaseCustomerCredit(businessPartner, amount); } else { decreaseCustomerCredit(businessPartner, amount); } } if (paymentScheduleDetail.getOrderPaymentSchedule() != null) { FIN_AddPayment.updatePaymentScheduleAmounts(paymentScheduleDetail.getPaymentDetails(), paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(), psdWriteoffAmount.negate()); } // when generating credit for a BP SO_CreditUsed is also updated if (paymentScheduleDetail.getInvoicePaymentSchedule() == null && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail.getPaymentDetails().getGLItem() == null && !paymentScheduleDetail.getPaymentDetails().isRefund()) { // BP SO_CreditUsed if (paymentScheduleDetail.getPaymentDetails().getFinPayment().isReceipt()) { increaseCustomerCredit(businessPartner, amount); } else { decreaseCustomerCredit(businessPartner, amount); } } paymentScheduleDetail.setInvoicePaid(false); OBDal.getInstance().save(paymentScheduleDetail); }
From source file:org.openvpms.hl7.impl.TestPharmacyService.java
/** * Dispenses an order.//from w w w . ja v a2 s . c o m * * @param order the order */ private void dispense(RDE_O11 order) { Connection connection = null; try { connection = sendContext.newClient(outboundHost, outboundPort, false); RXO rxo = order.getORDER().getORDER_DETAIL().getRXO(); BigDecimal quantity = new BigDecimal(rxo.getRequestedDispenseAmount().getValue()); if (quantity.compareTo(BigDecimal.ONE) != 0 && dispenses != 1) { BigDecimal[] decimals = quantity.divideAndRemainder(BigDecimal.valueOf(dispenses)); for (int i = 0; i < dispenses; ++i) { BigDecimal qty = (i == 0) ? decimals[0].add(decimals[1]) : decimals[0]; RDS_O13 dispense = createRDS(order, qty); send(dispense, connection); } } else { RDS_O13 dispense = createRDS(order, quantity); send(dispense, connection); } if (returnAfterDispense) { quantity = quantity.negate(); RDS_O13 dispense = createRDS(order, quantity); send(dispense, connection); } } catch (Throwable exception) { exception.printStackTrace(); } finally { if (connection != null) { connection.close(); } } }
From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java
protected List<Document> checkAccounts(final Parameter _parameter, final File _file, final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse) throws IOException, EFapsException { final List<Document> ret = new ArrayList<>(); final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8")); final List<String[]> entries = reader.readAll(); reader.close();// ww w. ja va 2s . c o m entries.remove(0); int i = 1; final Map<String, Document> map = new HashMap<>(); for (final String[] row : entries) { i++; final String docNumber = row[0]; final String ruc = row[1]; final String dateStr = row[2]; final String accountStr = row[5]; final String accountDesc = row[4]; final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN); formater.setParseBigDecimal(true); final String amountMEStr = row[6]; final String amountMNStr = row[7]; final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim()); final InstanceQuery query = queryBldr.getQuery(); query.executeWithoutAccessCheck(); if (query.next()) { ImportDetails.LOG.info("Found account: '{}' ", accountStr); final String[] docSplit = docNumber.split("-"); if (docSplit.length != 2 && _docMap != null) { ImportDetails.LOG.warn( "Document '{}' - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber, i); } else { try { final Formatter criteria = new Formatter(); String name = docNumber; if (_docMap != null) { final String serialNo = docSplit[0]; final String docNo = docSplit[1]; final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", "")); final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", "")); criteria.format("%03d-%06d", serial, no); name = criteria.toString(); } Document doc; if (map.containsKey(name)) { doc = map.get(name); } else { if (_docMap != null && _docMap.containsKey(name)) { doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc); } else { doc = new Document(name, null, ruc, dateStr, accountDesc); } } BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr); BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr); if (_inverse) { amountME = amountME.negate(); amountMN = amountMN.negate(); } if (amountMN.compareTo(BigDecimal.ZERO) >= 0) { doc.addAmountMECredit(amountME); doc.addAmountMNCredit(amountMN); } else { doc.addAmountMEDebit(amountME); doc.addAmountMNDebit(amountMN); } final Map<String, Account> accounts = doc.getAccounts(); Account acc; if (accounts.containsKey(accountStr)) { acc = accounts.get(accountStr); } else { acc = new Account(accountStr, accountDesc); accounts.put(accountStr, acc); } acc.addAmountME(amountME); acc.addAmountMN(amountMN); acc.setInstance(query.getCurrentValue()); map.put(name, doc); criteria.close(); } catch (final NumberFormatException e) { ImportDetails.LOG.error("wrong format for document '{}'", docNumber); } catch (final ParseException e) { ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr); } } } else { ImportDetails.LOG.error("Not found account: {}", accountStr); } } final Instance periodInst = getPeriodInstance(); for (final Document doc : map.values()) { final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit() : BigDecimal.ZERO; final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit() : BigDecimal.ZERO; final BigDecimal amountMN = amountCreditMN.add(amountDebitMN); final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit() : BigDecimal.ZERO; final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit() : BigDecimal.ZERO; final BigDecimal amountME = amountCreditME.add(amountDebitME); if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) { ImportDetails.LOG.info( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)", doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN); } else { ImportDetails.LOG.error( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'", doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN, amountMN); } final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance); insert.add(CIAccounting.TransactionOpeningBalance.Date, _date); final StringBuilder descBldr = new StringBuilder() .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento") .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ") .append(doc.getDate()).append(" - ").append(doc.getDesc()); insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString()); insert.add(CIAccounting.TransactionOpeningBalance.Status, Status.find(CIAccounting.TransactionStatus.Open)); insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst); insert.executeWithoutAccessCheck(); if (_docMap != null) { final Instance instance = insert.getInstance(); new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance()); } final Map<String, Account> accounts = doc.getAccounts(); final Instance basCur = Currency.getBaseCurrency(); for (final Account acc : accounts.values()) { final Insert insertpos = new Insert( acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit : CIAccounting.TransactionPositionDebit); insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) { Insert insertpos = null; Account acc = null; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT); acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT); acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) { Insert insertpos = null; final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT); ; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } } return ret; }
From source file:org.totschnig.myexpenses.activity.AccountEdit.java
/** * validates currency (must be code from ISO 4217) and opening balance * (a valid float according to the format from the locale) * @return true upon success, false if validation fails *//*w w w . ja va 2 s . co m*/ protected void saveState() { BigDecimal openingBalance = validateAmountInput(true); if (openingBalance == null) return; String label; String currency = ((CurrencyEnum) mCurrencySpinner.getSelectedItem()).name(); try { mAccount.setCurrency(currency); } catch (IllegalArgumentException e) { Toast.makeText(this, currency + " not supported by your OS. Please select a different currency.", Toast.LENGTH_LONG).show(); return; } label = mLabelText.getText().toString(); if (label.equals("")) { mLabelText.setError(getString(R.string.no_title_given)); return; } mAccount.label = label; mAccount.description = mDescriptionText.getText().toString(); if (mType == EXPENSE) { openingBalance = openingBalance.negate(); } mAccount.openingBalance.setAmountMajor(openingBalance); mAccount.type = (AccountType) mAccountTypeSpinner.getSelectedItem(); //EditActivity.saveState calls DbWriteFragment super.saveState(); }
From source file:nl.strohalm.cyclos.services.elements.MemberImportServiceImpl.java
private void importMember(final MemberImport memberImport, final MemberGroupAccountSettings accountSettings, final int lineNumber, final Map<String, CustomField> customFieldMap, final Map<String, MemberRecordType> recordTypeMap, final Map<MemberRecordType, Map<String, CustomField>> recordTypeFieldsMap, final LocalSettings localSettings, final AccessSettings accessSettings, final List<String> headers, final List<String> values, final Set<String> importedUsernames) { final Map<MemberRecordType, ImportedMemberRecord> records = new HashMap<MemberRecordType, ImportedMemberRecord>(); final Map<String, String> customFieldValues = new HashMap<String, String>(); final Map<MemberRecordType, Map<String, String>> recordFieldValues = new HashMap<MemberRecordType, Map<String, String>>(); // Insert the member ImportedMember member = new ImportedMember(); member.setSalt(hashHandler.newSalt()); member.setLineNumber(lineNumber);//from ww w . ja va2s .co m member.setImport(memberImport); member.setStatus(ImportedMember.Status.SUCCESS); member = importedMemberDao.insert(member); final Calendar today = DateHelper.truncate(Calendar.getInstance()); try { member.setCustomValues(new ArrayList<MemberCustomFieldValue>()); final CalendarConverter dateConverter = localSettings.getRawDateConverter(); // Process each field. Field names are lowercased to ignore case for (int i = 0; i < headers.size() && i < values.size(); i++) { final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase(); final String value = StringUtils.trimToNull(values.get(i)); if ("name".equals(field)) { member.setName(value); } else if ("username".equals(field)) { member.setUsername(value); } else if ("password".equals(field)) { member.setPassword(hashHandler.hash(member.getSalt(), value)); } else if ("email".equals(field)) { member.setEmail(value); } else if ("creationdate".equals(field)) { try { final Calendar creationDate = dateConverter.valueOf(value); if (creationDate != null) { if (creationDate.after(today) || creationDate.get(Calendar.YEAR) < 1950) { throw new Exception(); } member.setCreationDate(creationDate); } } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREATION_DATE); member.setErrorArgument1(value); break; } } else if ("balance".equals(field)) { try { member.setInitialBalance(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_BALANCE); member.setErrorArgument1(value); break; } } else if ("creditlimit".equals(field)) { try { BigDecimal limit = localSettings.getNumberConverter().valueOf(value); // Ensure the limit is positive if (limit != null) { limit = limit.abs(); } member.setCreditLimit(limit); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if ("uppercreditlimit".equals(field)) { try { member.setUpperCreditLimit(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_UPPER_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if (customFieldMap.containsKey(field)) { // Create a custom field value CustomField customField = customFieldMap.get(field); final MemberCustomFieldValue fieldValue = new MemberCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); member.getCustomValues().add(fieldValue); customFieldValues.put(field, value); } else if (field.contains(".")) { // A record type value final String[] parts = field.split("\\."); // Find the record type final String recordTypeName = parts[0]; final MemberRecordType recordType = recordTypeMap.get(recordTypeName); if (recordType == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE); member.setErrorArgument1(recordTypeName); break; } // Find the custom field final String recordTypeField = parts[1]; final Map<String, CustomField> fieldsMap = recordTypeFieldsMap.get(recordType); final CustomField customField = fieldsMap.get(recordTypeField); if (customField == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE_FIELD); member.setErrorArgument1(recordTypeName); member.setErrorArgument2(recordTypeField); break; } // Find the imported member record ImportedMemberRecord record = records.get(recordType); if (record == null) { // None yet - create a new one record = new ImportedMemberRecord(); record.setMember(member); record.setType(recordType); record = importedMemberRecordDao.insert(record); record.setCustomValues(new ArrayList<ImportedMemberRecordCustomFieldValue>()); records.put(recordType, record); } // Set the custom field final ImportedMemberRecordCustomFieldValue fieldValue = new ImportedMemberRecordCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); record.getCustomValues().add(fieldValue); // Store the field value in a map Map<String, String> fieldValues = recordFieldValues.get(recordType); if (fieldValues == null) { fieldValues = new HashMap<String, String>(); recordFieldValues.put(recordType, fieldValues); } fieldValues.put(recordTypeField, value); } else { throw new UnknownColumnException(field); } } // When there was an error, stop processing if (member.getStatus() != ImportedMember.Status.SUCCESS) { return; } // Validate some data if (member.getName() == null) { // Name is always required member.setStatus(ImportedMember.Status.MISSING_NAME); return; } final String username = member.getUsername(); if (accessSettings.getUsernameGeneration() == UsernameGeneration.NONE && username == null) { // Username is required when it's not generated member.setStatus(ImportedMember.Status.MISSING_USERNAME); return; } // Validate the username if (username != null) { // Check the username format ValidationError error = new RegexValidation(accessSettings.getUsernameRegex()).validate(null, null, username); if (error == null) { // Check the username length error = new LengthValidation(accessSettings.getUsernameLength()).validate(null, null, username); } if (error != null) { member.setStatus(ImportedMember.Status.INVALID_USERNAME); member.setErrorArgument1(username); return; } // Check if username is duplicated in this import if (!importedUsernames.add(username)) { member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } // Check if username is already used by another member in cyclos try { elementService.loadUser(username); // If an user could be loaded, it means that the username is already in use member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } catch (final EntityNotFoundException e) { // Ok - not used yet } } if (member.getEmail() == null && localSettings.isEmailRequired()) { // Mail is required member.setStatus(ImportedMember.Status.MISSING_EMAIL); return; } if (EmailValidation.instance().validate(null, null, member.getEmail()) != null) { // Mail format is invalid member.setStatus(ImportedMember.Status.INVALID_EMAIL); member.setErrorArgument1(member.getEmail()); return; } if (memberImport.getAccountType() == null) { // Nothing related to accounts will be imported member.setInitialBalance(null); member.setCreditLimit(null); member.setUpperCreditLimit(null); } else { if (member.getCreditLimit() == null) { // Get the default group credit limit member.setCreditLimit(accountSettings.getDefaultCreditLimit()); } if (member.getUpperCreditLimit() == null) { // Get the default group upper credit limit member.setUpperCreditLimit(accountSettings.getDefaultUpperCreditLimit()); } final BigDecimal balance = member.getInitialBalance(); if (balance != null) { double balanceValue = balance.doubleValue(); if (balanceValue > 0 && memberImport.getInitialCreditTransferType() == null) { // There was an initial credit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } else if (balanceValue < 0 && memberImport.getInitialDebitTransferType() == null) { // There was an initial debit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } final BigDecimal creditLimit = member.getCreditLimit(); if (creditLimit != null && balanceValue < 0 && balance.compareTo(creditLimit.negate()) < 0) { // When the initial balance is negative, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_LOWER_THAN_CREDIT_LIMIT); return; } final BigDecimal upperCreditLimit = member.getUpperCreditLimit(); if (upperCreditLimit != null && balanceValue > 0 && balance.compareTo(upperCreditLimit) > 0) { // When the initial balance is positive, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_UPPER_THAN_CREDIT_LIMIT); return; } } } // Save the custom field values try { memberCustomFieldService.saveValues(member); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); final String displayName = vex.getDisplayNameByProperty().get(fieldName); member.setErrorArgument1(StringUtils.isEmpty(displayName) ? fieldName : displayName); final String fieldValue = StringUtils .trimToNull(customFieldValues.get(fieldName.toLowerCase())); if (CollectionUtils.isNotEmpty(errorsByProperty.get(fieldName))) { ValidationError ve = errorsByProperty.get(fieldName).iterator().next(); if (ve instanceof UniqueError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_UNIQUE); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof RequiredError) { member.setStatus(ImportedMember.Status.MISSING_CUSTOM_FIELD); } else if (ve instanceof MaxLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MAX_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof MinLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MIN_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } } if (StringUtils.isEmpty(member.getErrorArgument2()) && fieldValue != null) { member.setErrorArgument2(fieldValue); } } } return; } // Save each record field values for (final ImportedMemberRecord record : records.values()) { final MemberRecordType recordType = record.getType(); final Map<String, String> fieldValues = recordFieldValues.get(recordType); // Check if the record is not empty boolean empty = true; for (final String value : fieldValues.values()) { if (StringUtils.isNotEmpty(value)) { empty = false; break; } } if (empty) { // There are no fields for this record: remove the record itself importedMemberRecordDao.delete(record.getId()); continue; } try { memberRecordCustomFieldService.saveValues(record); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_RECORD_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); member.setErrorArgument1(recordType.getName() + "." + fieldName); final String fieldValue = StringUtils.trimToNull(fieldValues.get(fieldName)); if (fieldValue == null) { // When validation failed and the field is null, it's actually missing member.setStatus(ImportedMember.Status.MISSING_RECORD_FIELD); } else { member.setErrorArgument2(fieldValue); } } } return; } } } catch (final UnknownColumnException e) { throw e; } catch (final Exception e) { member.setStatus(ImportedMember.Status.UNKNOWN_ERROR); member.setErrorArgument1(e.toString()); } finally { importedMemberDao.update(member); } }
From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java
private BigDecimal calculateVolumeCharge(final MemberAccount account, final AccountFee volumeFee, final Period period, final BigDecimal additionalReserved, final boolean currentPeriod) { Calendar fromDate = period.getBegin(); // Get the account status right after the last charged period AccountStatus status = accountService.getStatus(account, fromDate); // When there is some additional amount to consider as reserved, add it to the status status.setReservedAmount(status.getReservedAmount().add(additionalReserved)); // Calculate the total days. We want the entire charged period. For example: if the fee was enabled in the middle of a month, it would be the // entire month. Likewise, if no end limit was given, the current period will be used (ie, and the last day in the current month) TimePeriod recurrence = volumeFee.getRecurrence(); Period totalPeriod = recurrence.currentPeriod(period.getBegin()); int totalDays = totalPeriod.getDays() + 1; // Calculate each difference, with the corresponding reserved amount Calendar lastDay = fromDate;//from w ww .j a va 2 s . com Calendar lastChargedDay = fromDate; BigDecimal result = BigDecimal.ZERO; IteratorList<AccountDailyDifference> diffs = accountDao.iterateDailyDifferences(account, period); if (LOG.isDebugEnabled()) { LOG.debug("********************************"); LOG.debug(FormatObject.formatObject(period.getBegin()) + "\t" + status.getBalance() + "\t" + status.getAvailableBalance()); } try { if (diffs.hasNext()) { // There are differences - the lastChargedAvailable balance will be obtained within the loop for (AccountDailyDifference diff : diffs) { Calendar day = diff.getDay(); int days = DateHelper.daysBetween(lastDay, day); // Get the available balance at that day BigDecimal available = status.getAvailableBalanceWithoutCreditLimit(); if (volumeFee.getChargeMode().isNegative()) { // If the charge is over negative amounts, consider the negated amount available = available.negate(); } // Take the free base into account if (volumeFee.getFreeBase() != null) { available = available.subtract(volumeFee.getFreeBase()); } // If the available balance was significant, calculate the charge if (available.compareTo(BigDecimal.ZERO) > 0) { BigDecimal volume = new BigDecimal(available.doubleValue() * days / totalDays); if (LOG.isDebugEnabled()) { LOG.debug(FormatObject.formatObject(day) + "\t" + diff.getBalance() + "\t" + status.getAvailableBalanceWithoutCreditLimit().add(diff.getBalance()) + "\t" + days + "\t" + totalDays + "\t" + volume); } BigDecimal toCharge = volume.multiply(volumeFee.getAmount()) .divide(BigDecimalHelper.ONE_HUNDRED); // status.setReservedAmount(status.getReservedAmount().add(toCharge)); result = result.add(toCharge); lastChargedDay = day; } lastDay = day; status.setBalance(status.getBalance().add(diff.getBalance())); status.setReservedAmount(status.getReservedAmount().add(diff.getReserved())); } } } finally { DataIteratorHelper.close(diffs); } Calendar toDate = period.getEnd(); boolean lastPaymentInPeriodEnd = !toDate.before(lastChargedDay); LocalSettings settings = settingsService.getLocalSettings(); // Only if the last payment was not today we have to take into account the results so far if (DateHelper.daysBetween(lastChargedDay, Calendar.getInstance()) != 0) { BigDecimal resultSoFar = settings.round(result); status.setReservedAmount(status.getReservedAmount().add(resultSoFar)); } // Calculate the avaliable balance after the last diff, which will remain the same until the period end BigDecimal finalAvailableBalance = status.getAvailableBalanceWithoutCreditLimit(); if (volumeFee.getChargeMode().isNegative()) { finalAvailableBalance = finalAvailableBalance.negate(); } if (volumeFee.getFreeBase() != null) { finalAvailableBalance = finalAvailableBalance.subtract(volumeFee.getFreeBase()); } // Consider the last time slice, between the last diff and the period end, if any if (lastPaymentInPeriodEnd && finalAvailableBalance.compareTo(BigDecimal.ZERO) > 0) { int days = DateHelper.daysBetween(lastChargedDay, toDate) + (currentPeriod ? 0 : 1); // Here, the lastChargedAvailableBalance is already subtracted from the free base (if any) BigDecimal volume = new BigDecimal(finalAvailableBalance.doubleValue() * days / totalDays); BigDecimal toCharge = volume.multiply(volumeFee.getAmount()).divide(BigDecimalHelper.ONE_HUNDRED); result = result.add(toCharge); if (LOG.isDebugEnabled()) { status.setReservedAmount(settings.round(status.getReservedAmount().add(toCharge))); LOG.debug(FormatObject.formatObject(lastChargedDay) + "\t0\t" + status.getAvailableBalanceWithoutCreditLimit() + "\t" + days + "\t" + totalDays + "\t" + volume); } } return settings.round(result); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The cube root.// w w w . j a v a 2s . co m * * @param x The argument. * @return The cubic root of the BigDecimal rounded to the precision implied by x. * The sign of the result is the sign of the argument. */ static public BigDecimal cbrt(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return root(3, x.negate()).negate(); } else { return root(3, x); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic tangent.//from w w w.j a v a 2 s. c o m * * @param x The argument. * @return The tanh(x) = sinh(x)/cosh(x). */ static public BigDecimal tanh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return tanh(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) . */ BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2))); /* The error in tanh x is err(x)/cosh^2(x). */ double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0); MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps)); return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic cosine.//from w w w . j ava 2s . c o m * * @param x The argument. * @return The cosh(x) = (exp(x)+exp(-x))/2 . */ static public BigDecimal cosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { if (x.doubleValue() > 1.5) { /* cosh^2(x) = 1+ sinh^2(x). */ return hypot(1, sinh(x)); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* 2i factorial */ BigInteger ifac = BigInteger.ONE; /* The absolute error in the result is the error in x^2/2 which is x times the error in x. */ double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); /* The error in the result is set by the error in x^2/2 itself, xUlpDbl. * We need at most k terms to push x^(2k)/(2k)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; /* The individual terms are all smaller than 1, so an estimate of 1.0 for * the absolute value will give a safe relative error estimate for the indivdual terms */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i-1 or 2*i overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); ifac = ifac.multiply(new BigInteger("" + (2 * i))); xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is governed by the error in x itself. */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } }