List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.egov.stms.transactions.service.SewerageConnectionSmsAndEmailService.java
/** * @param SewerageAppliationDetails/*ww w .ja va 2 s . c o m*/ * @param type * @return Sum Of Sewerage Application charges including only the difference with first application */ public BigDecimal sumOfChangeClosetSewerageApplnCharges( final SewerageApplicationDetails sewerageApplicationDetails) { BigDecimal totalAmt = BigDecimal.ZERO; BigDecimal oldDonationCharge = BigDecimal.ZERO; BigDecimal oldSewerageTax = BigDecimal.ZERO; BigDecimal currentDonationCharge = BigDecimal.ZERO; BigDecimal currentSewerageTax = BigDecimal.ZERO; BigDecimal currentEstimationCharges = BigDecimal.ZERO; BigDecimal totalDonationCharge = BigDecimal.ZERO; BigDecimal totalSewerageTax = BigDecimal.ZERO; if (sewerageApplicationDetails.getCurrentDemand() != null) { SewerageApplicationDetails oldApplicationDtl = sewerageApplicationDetailsService .findByConnection_ShscNumberAndIsActive( sewerageApplicationDetails.getConnection().getShscNumber()); if (oldApplicationDtl != null) { for (final SewerageConnectionFee oldSewerageConnectionFee : oldApplicationDtl.getConnectionFees()) { if (oldSewerageConnectionFee.getFeesDetail().getCode().equalsIgnoreCase(FEES_SEWERAGETAX_CODE)) oldSewerageTax = oldSewerageTax .add(BigDecimal.valueOf(oldSewerageConnectionFee.getAmount())); if (oldSewerageConnectionFee.getFeesDetail().getCode() .equalsIgnoreCase(FEES_DONATIONCHARGE_CODE)) oldDonationCharge = oldDonationCharge .add(BigDecimal.valueOf(oldSewerageConnectionFee.getAmount())); } } for (final SewerageConnectionFee scf : sewerageApplicationDetails.getConnectionFees()) { if (scf.getFeesDetail().getCode().equalsIgnoreCase(FEES_SEWERAGETAX_CODE)) currentSewerageTax = currentSewerageTax.add(BigDecimal.valueOf(scf.getAmount())); if (scf.getFeesDetail().getCode().equalsIgnoreCase(FEES_DONATIONCHARGE_CODE)) currentDonationCharge = currentDonationCharge.add(BigDecimal.valueOf(scf.getAmount())); if (scf.getFeesDetail().getCode().equalsIgnoreCase(FEES_ESTIMATIONCHARGES_CODE)) currentEstimationCharges = BigDecimal.valueOf(scf.getAmount()); } if (currentDonationCharge.compareTo(oldDonationCharge) > 0) { totalDonationCharge = currentDonationCharge.subtract(oldDonationCharge); } if (currentSewerageTax.compareTo(oldSewerageTax) > 0) { totalSewerageTax = currentSewerageTax.subtract(oldSewerageTax); } totalAmt = totalSewerageTax.add(totalDonationCharge).add(currentEstimationCharges); } return totalAmt; }
From source file:logic.EntityCar.java
public EntityCar(List<BaseParam> bpList, Set<String> staticUids, String radCore, String radColor, Car car, String markTitle, String modelTitle, String carTitle, BigDecimal carPrice, IdealEntity ie, BigDecimal moneyFound, AStrategy1 a1, AStrategy2 a2, BStrategy1 b1, BStrategy2 b2, ToxicParamType paramTox1, ToxicParamType paramTox2, ToxicValueType valueTox1, ToxicValueType valueTox2, ResourceProfitability resPropf, ResourceStaticType resStatType, Perception percType) { this.car = car; this.markTitle = markTitle; this.modelTitle = modelTitle; this.carTitle = carTitle; this.basePrice = carPrice; if (moneyFound == null) { this.moneyFound = BigDecimal.valueOf(0); } else {// w w w .jav a 2 s . c om this.moneyFound = moneyFound; } this.moneyFound = moneyFound.subtract(basePrice); fullPrice = basePrice; this.ie = ie; this.a1 = a1; this.a2 = a2; this.b1 = b1; this.b2 = b2; this.radCore = radCore; this.radColor = radColor; /*suplog+=" pt1="+paramTox1+"; "; suplog+=" pv1="+valueTox1+"; "; suplog+=" pt2="+paramTox2+"; "; suplog+=" pv2="+valueTox2+"; ";*/ /*if (paramTox1 != null && !ToxicParamType.NOSTRATEGY.equals(paramTox1)) { //this.minParamToxic1 = BigDecimal.valueOf(getMinToxParam(paramTox1)); } else { this.minParamToxic1 = null; }*/ //this.minParamToxic2=BigDecimal.valueOf(getMinToxParam(paramTox2)); //this.minValueToxic1 = BigDecimal.valueOf(getMinToxVal(ToxicValueType.CLEAR)); /*if (valueTox1 != null && !ToxicValueType.NOSTRATEGY.equals(valueTox1)) { //this.minValueToxic1 = BigDecimal.valueOf(getMinToxVal(valueTox1)); } else { this.minValueToxic1 = null; }*/ //this.minValueToxic2=BigDecimal.valueOf(getMinToxVal(valueTox2)); if (paramTox1 != null && !ToxicParamType.NOSTRATEGY.equals(paramTox1)) { this.minParamToxic1 = BigDecimal.valueOf(getMinToxParam(paramTox1)); } else { this.minParamToxic1 = null; } if (valueTox1 != null && !ToxicValueType.NOSTRATEGY.equals(valueTox1)) { this.minValueToxic1 = BigDecimal.valueOf(getMinToxVal(valueTox1)); } else { this.minValueToxic1 = null; } if (paramTox2 != null && !ToxicParamType.NOSTRATEGY.equals(paramTox2)) { this.minParamToxic2 = BigDecimal.valueOf(getMinToxParam(paramTox2)); } else { this.minParamToxic2 = null; } if (valueTox2 != null && !ToxicValueType.NOSTRATEGY.equals(valueTox2)) { this.minValueToxic2 = BigDecimal.valueOf(getMinToxVal(valueTox2)); } else { this.minValueToxic2 = null; } this.percType = percType; this.allParams = bpList; this.staticUids = staticUids; this.resPropf = resPropf; this.resStatType = resStatType; }
From source file:org.egov.egf.commons.EgovCommon.java
/** * This method will return the amount that are available to make further payments. * * @param VoucherDate/*from w ww . j a v a 2s . com*/ * @param bankaccountId * @return * @throws ValidationException */ @SuppressWarnings("unchecked") public BigDecimal getBankBalanceAvailableforPayment(final Date VoucherDate, final Integer bankaccountId) throws ValidationException { // return getAccountBalance(VoucherDate, bankId,null,null); BigDecimal TotalbankBalance = BigDecimal.ZERO; BigDecimal bankBalanceasofBankBookReport = BigDecimal.ZERO; BigDecimal amountApprovedForPayment = BigDecimal.ZERO; bankBalanceasofBankBookReport = getAccountBalance(VoucherDate, bankaccountId.longValue(), null, null, null); if (LOGGER.isDebugEnabled()) LOGGER.debug("Bank balance as per Bank book:" + bankBalanceasofBankBookReport); amountApprovedForPayment = getAmountApprovedForPaymentAndVoucherNotCreated(VoucherDate, bankaccountId); LOGGER.debug("Amount that are approved but voucher creation in progress:" + amountApprovedForPayment); TotalbankBalance = bankBalanceasofBankBookReport.subtract(amountApprovedForPayment); if (LOGGER.isDebugEnabled()) LOGGER.debug("Total amount available for payment :" + TotalbankBalance); return TotalbankBalance; }
From source file:org.egov.ptis.actions.reports.DefaultersReportAction.java
/** * @param propertyViewList// w w w . ja va2 s.c om * @return List of Defaulters */ private List<DefaultersInfo> prepareOutput(final List<PropertyMaterlizeView> propertyViewList) { List<DefaultersInfo> defaultersList = new ArrayList<DefaultersInfo>(); DefaultersInfo defaultersInfo = null; BigDecimal totalDue = BigDecimal.ZERO; BigDecimal currPenalty = BigDecimal.ZERO; BigDecimal currPenaltyColl = BigDecimal.ZERO; int count = 0; Installment curInstallment = propertyTaxCommonUtils.getCurrentInstallment(); for (final PropertyMaterlizeView propView : propertyViewList) { defaultersInfo = new DefaultersInfo(); totalDue = BigDecimal.ZERO; currPenalty = BigDecimal.ZERO; currPenaltyColl = BigDecimal.ZERO; count++; defaultersInfo.setSlNo(count); defaultersInfo.setAssessmentNo(propView.getPropertyId()); defaultersInfo.setOwnerName( propView.getOwnerName().contains(",") ? propView.getOwnerName().replace(",", " & ") : propView.getOwnerName()); defaultersInfo.setWardName(propView.getWard().getName()); defaultersInfo.setHouseNo(propView.getHouseNo()); defaultersInfo.setLocality((propView.getLocality()) != null ? propView.getLocality().getName() : "NA"); defaultersInfo.setMobileNumber( (StringUtils.isNotBlank(propView.getMobileNumber()) ? propView.getMobileNumber() : "NA")); defaultersInfo.setArrearsDue(propView.getAggrArrDmd().subtract(propView.getAggrArrColl())); defaultersInfo.setCurrentDue( (propView.getAggrCurrFirstHalfDmd().add(propView.getAggrCurrSecondHalfDmd())).subtract( (propView.getAggrCurrFirstHalfColl().add(propView.getAggrCurrSecondHalfColl())))); defaultersInfo.setAggrArrearPenalyDue( (propView.getAggrArrearPenaly() != null ? propView.getAggrArrearPenaly() : ZERO).subtract( propView.getAggrArrearPenalyColl() != null ? propView.getAggrArrearPenalyColl() : ZERO)); currPenalty = (propView.getAggrCurrFirstHalfPenaly() != null ? propView.getAggrCurrFirstHalfPenaly() : ZERO).add( propView.getAggrCurrSecondHalfPenaly() != null ? propView.getAggrCurrSecondHalfPenaly() : ZERO); currPenaltyColl = (propView.getAggrCurrFirstHalfPenalyColl() != null ? propView.getAggrCurrFirstHalfPenalyColl() : ZERO).add( propView.getAggrCurrSecondHalfPenalyColl() != null ? propView.getAggrCurrSecondHalfPenalyColl() : ZERO); defaultersInfo.setAggrCurrPenalyDue(currPenalty.subtract(currPenaltyColl)); totalDue = defaultersInfo.getArrearsDue().add(defaultersInfo.getCurrentDue()) .add(defaultersInfo.getAggrArrearPenalyDue()).add(defaultersInfo.getAggrCurrPenalyDue()); defaultersInfo.setTotalDue(totalDue); if (propView.getInstDmdColl().size() != 0 && !propView.getInstDmdColl().isEmpty()) { defaultersInfo.setArrearsFrmInstallment( propView.getInstDmdColl().iterator().next().getInstallment().getDescription()); final Iterator itr = propView.getInstDmdColl().iterator(); InstDmdCollMaterializeView idc = new InstDmdCollMaterializeView(); InstDmdCollMaterializeView lastElement = new InstDmdCollMaterializeView(); while (itr.hasNext()) { idc = (InstDmdCollMaterializeView) itr.next(); if (!idc.getInstallment().equals(curInstallment)) lastElement = idc; } if (lastElement != null && lastElement.getInstallment() != null) defaultersInfo.setArrearsToInstallment(lastElement.getInstallment().getDescription()); } defaultersList.add(defaultersInfo); } return defaultersList; }
From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java
private void setDemandAmountsForTableData(String name, CollTableData collIndData, BigDecimal totalAssessments, BigDecimal currentYearTotalDemand, int noOfMonths, Map<String, BigDecimal> totalDemandMap) { BigDecimal variance;/* w w w . j av a2 s . c om*/ // Proportional Demand = (totalDemand/12)*noOfmonths BigDecimal cytdDmd = (currentYearTotalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)) .multiply(BigDecimal.valueOf(noOfMonths)); collIndData.setCytdDmd(cytdDmd); if (cytdDmd != BigDecimal.valueOf(0)) { BigDecimal balance = cytdDmd.subtract(collIndData.getCytdColl()); BigDecimal performance = (collIndData.getCytdColl().multiply(PropertyTaxConstants.BIGDECIMAL_100)) .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP); collIndData.setPerformance(performance); collIndData.setCytdBalDmd(balance); } collIndData.setTotalDmd(totalDemandMap.get(name) == null ? BigDecimal.ZERO : totalDemandMap.get(name)); collIndData.setDayTargetDemand(collIndData.getTotalDmd().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : collIndData.getTotalDmd().divide(new BigDecimal("365"), 0, BigDecimal.ROUND_HALF_UP)); collIndData.setTotalAssessments(totalAssessments); // variance = ((currentYearCollection - lastYearCollection)*100)/lastYearCollection if (collIndData.getLytdColl().compareTo(BigDecimal.ZERO) == 0) variance = PropertyTaxConstants.BIGDECIMAL_100; else variance = ((collIndData.getCytdColl().subtract(collIndData.getLytdColl())) .multiply(PropertyTaxConstants.BIGDECIMAL_100)).divide(collIndData.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP); collIndData.setLyVar(variance); }
From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java
private String computeDiffBetweenCumulativeAndInstallment(DateTime dateOfCashFlow, BigDecimal cashflow, LoanScheduleDto loanScheduleDto) { BigDecimal totalInstallmentForMonth = cumulativeTotalForMonth(dateOfCashFlow, loanScheduleDto); return String.valueOf(cashflow.subtract(totalInstallmentForMonth) .setScale(AccountingRules.getDigitsAfterDecimal(), RoundingMode.HALF_UP)); }
From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java
protected void internalMpsLevelTransfer(int mpsSrcId, int mpsDstId) { generatedMPSLines = new ArrayList<MpsLine>(); Mps mpsSrc = mpsService.load(mpsSrcId); Mps mpsDst = mpsService.load(mpsDstId); PlanningRange planningRange = calculateMPSPlanningRange(mpsDst); clearMPS(mpsDst);/*from w w w . java2s .com*/ List<MpsLine> lines = ormTemplate .findByCriteria(OrmTemplate.createCriteria(MpsLine.class).add(Restrictions.eq("Mps", mpsSrc)) .add(Restrictions.or(Restrictions.gt("PlannedQty", BigDecimal.ZERO), Restrictions.gt("AdjustmentQty", BigDecimal.ZERO))) .addOrder(Order.asc("BucketOffset"))); BucketRange bucketRange = null; int mpsDstSequence = 1; boolean firstLine = true; long numberOfDays = 1; int currentBucketOffset = 1; for (MpsLine mpsLine : lines) { //? ? ? ? if- if (firstLine || currentBucketOffset != mpsLine.getBucketOffset()) { bucketRange = MfUtils.determineBucketRange(mpsSrc.getPlanningLevel().getId(), mpsLine.getBucketOffset()); //NumberOfDays = EndDay - StartDay + 1 numberOfDays = DateTimeUtils.getDaysBetween(bucketRange.getBucketStart(), bucketRange.getBucketEnd()) + 1; currentBucketOffset = mpsLine.getBucketOffset(); firstLine = false; } BigDecimal remainingQty = mpsLine.getPlannedQty().add(mpsLine.getAdjustmentQty()); // if PlanStartDay <= EndDay and PlanEndDay >= StartDay then // , ? ? ? int c1 = planningRange.startPlanningDate.compareTo(bucketRange.getBucketEnd()); int c2 = planningRange.endPlanningDate.compareTo(bucketRange.getBucketStart()); if (c1 <= 0 && c2 >= 0) { long remainingNumberOfDays = numberOfDays; //PlanStartDay > StartDay if (planningRange.startPlanningDate.compareTo(bucketRange.getBucketStart()) > 0) remainingNumberOfDays = numberOfDays - DateTimeUtils .getDaysBetween(planningRange.startPlanningDate, bucketRange.getBucketStart()); BigDecimal srcQty = MathUtils.divide(remainingQty, new BigDecimal(remainingNumberOfDays), Constants.QUANTITY_ROUND_CONTEXT); Date countDay = bucketRange.getBucketStart(); //while CountDay <= EndDay while (MathUtils.compareToZero(remainingQty) > 0 && countDay.compareTo(bucketRange.getBucketEnd()) <= 0) { //if CountDay >= PlanStartDay and CountDay <= PlanEndDay then if (countDay.compareTo(planningRange.startPlanningDate) >= 0 && countDay.compareTo(planningRange.endPlanningDate) <= 0) { RollUpMPSResult rollUpMPSResult = rollUpMPS(mpsDst, mpsLine, srcQty, countDay, mpsDstSequence); mpsDstSequence = rollUpMPSResult.mpsSequence; // ? remainingNumberOfDays -= 1; remainingQty = remainingQty.subtract(rollUpMPSResult.quan); if (remainingNumberOfDays > 0) srcQty = MathUtils.divide(remainingQty, new BigDecimal(remainingNumberOfDays), Constants.QUANTITY_ROUND_CONTEXT); } countDay = DateTimeUtils.incDay(countDay, 1); } } } persistGeneratedMPSLines(); }
From source file:loci.formats.in.MetamorphReader.java
@Override protected void initFile(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) { LOGGER.info("Initializing " + id); // find an associated STK file String stkFile = id.substring(0, id.lastIndexOf(".")); if (stkFile.indexOf(File.separatorChar) != -1) { stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1); }//from ww w. jav a 2 s . c om Location parent = new Location(id).getAbsoluteFile().getParentFile(); LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath()); String[] dirList = parent.list(true); Arrays.sort(dirList); for (String f : dirList) { int underscore = f.indexOf('_'); if (underscore < 0) underscore = f.indexOf('.'); if (underscore < 0) underscore = f.length(); String prefix = f.substring(0, underscore); if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) { stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath(); break; } } if (!checkSuffix(stkFile, STK_SUFFIX)) { throw new FormatException("STK file not found in " + parent.getAbsolutePath() + "."); } super.initFile(stkFile); } else super.initFile(id); Location ndfile = null; if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id); else if (canLookForND && isGroupFiles()) { // an STK file was passed to initFile // let's check the parent directory for an .nd file Location stk = new Location(id).getAbsoluteFile(); String stkName = stk.getName(); String stkPrefix = stkName; if (stkPrefix.indexOf('_') >= 0) { stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1); } Location parent = stk.getParentFile(); String[] list = parent.list(true); int matchingChars = 0; for (String f : list) { if (checkSuffix(f, ND_SUFFIX)) { String prefix = f.substring(0, f.lastIndexOf(".")); if (prefix.indexOf('_') >= 0) { prefix = prefix.substring(0, prefix.indexOf('_') + 1); } if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) { int charCount = 0; for (int i = 0; i < f.length(); i++) { if (i >= stkName.length()) { break; } if (f.charAt(i) == stkName.charAt(i)) { charCount++; } else { break; } } if (charCount > matchingChars || (charCount == matchingChars && f.charAt(charCount) == '.')) { ndfile = new Location(parent, f).getAbsoluteFile(); matchingChars = charCount; } } } } } String creationTime = null; if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) { // parse key/value pairs from .nd file int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT(); int nstages = 0; String z = null, c = null, t = null; final List<Boolean> hasZ = new ArrayList<Boolean>(); waveNames = new ArrayList<String>(); stageNames = new ArrayList<String>(); boolean useWaveNames = true; ndFilename = ndfile.getAbsolutePath(); String[] lines = DataTools.readFile(ndFilename).split("\n"); boolean globalDoZ = true; boolean doTimelapse = false; StringBuilder currentValue = new StringBuilder(); String key = ""; for (String line : lines) { int comma = line.indexOf(','); if (comma <= 0) { currentValue.append("\n"); currentValue.append(line); continue; } String value = currentValue.toString(); addGlobalMeta(key, value); if (key.equals("NZSteps")) z = value; else if (key.equals("DoTimelapse")) { doTimelapse = Boolean.parseBoolean(value); } else if (key.equals("NWavelengths")) c = value; else if (key.equals("NTimePoints")) t = value; else if (key.startsWith("WaveDoZ")) { hasZ.add(Boolean.parseBoolean(value)); } else if (key.startsWith("WaveName")) { String waveName = value.substring(1, value.length() - 1); if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) { bizarreMultichannelAcquisition = true; } waveNames.add(waveName); } else if (key.startsWith("Stage")) { stageNames.add(value); } else if (key.startsWith("StartTime")) { creationTime = value; } else if (key.equals("ZStepSize")) { value = value.replace(',', '.'); stepSize = Double.parseDouble(value); } else if (key.equals("NStagePositions")) { nstages = Integer.parseInt(value); } else if (key.equals("WaveInFileName")) { useWaveNames = Boolean.parseBoolean(value); } else if (key.equals("DoZSeries")) { globalDoZ = Boolean.parseBoolean(value); } key = line.substring(1, comma - 1).trim(); currentValue.delete(0, currentValue.length()); currentValue.append(line.substring(comma + 1).trim()); } if (!globalDoZ) { for (int i = 0; i < hasZ.size(); i++) { hasZ.set(i, false); } } // figure out how many files we need if (z != null) zc = Integer.parseInt(z); if (c != null) cc = Integer.parseInt(c); if (t != null) tc = Integer.parseInt(t); else if (!doTimelapse) { tc = 1; } if (cc == 0) cc = 1; if (cc == 1 && bizarreMultichannelAcquisition) { cc = 2; } if (tc == 0) { tc = 1; } int numFiles = cc * tc; if (nstages > 0) numFiles *= nstages; // determine series count int stagesCount = nstages == 0 ? 1 : nstages; int seriesCount = stagesCount; firstSeriesChannels = new boolean[cc]; Arrays.fill(firstSeriesChannels, true); boolean differentZs = false; for (int i = 0; i < cc; i++) { boolean hasZ1 = i < hasZ.size() && hasZ.get(i); boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1); if (i > 0 && hasZ1 != hasZ2 && globalDoZ) { if (!differentZs) seriesCount *= 2; differentZs = true; } } int channelsInFirstSeries = cc; if (differentZs) { channelsInFirstSeries = 0; for (int i = 0; i < cc; i++) { if ((!hasZ.get(0) && i == 0) || (hasZ.get(0) && hasZ.get(i))) { channelsInFirstSeries++; } else firstSeriesChannels[i] = false; } } stks = new String[seriesCount][]; if (seriesCount == 1) stks[0] = new String[numFiles]; else if (differentZs) { for (int i = 0; i < stagesCount; i++) { stks[i * 2] = new String[channelsInFirstSeries * tc]; stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc]; } } else { for (int i = 0; i < stks.length; i++) { stks[i] = new String[numFiles / stks.length]; } } String prefix = ndfile.getPath(); prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf(".")); // build list of STK files boolean anyZ = hasZ.contains(Boolean.TRUE); int[] pt = new int[seriesCount]; for (int i = 0; i < tc; i++) { for (int s = 0; s < stagesCount; s++) { for (int j = 0; j < cc; j++) { boolean validZ = j >= hasZ.size() || hasZ.get(j); int seriesNdx = s * (seriesCount / stagesCount); if ((seriesCount != 1 && (!validZ || (hasZ.size() > 0 && !hasZ.get(0)))) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) { if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) { seriesNdx++; } } if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) { continue; } stks[seriesNdx][pt[seriesNdx]] = prefix; if (j < waveNames.size() && waveNames.get(j) != null) { stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1); if (useWaveNames) { String waveName = waveNames.get(j); // If there are underscores in the wavelength name, translate // them to hyphens. (See #558) waveName = waveName.replace('_', '-'); // If there are slashes (forward or backward) in the wavelength // name, translate them to hyphens. (See #5922) waveName = waveName.replace('/', '-'); waveName = waveName.replace('\\', '-'); waveName = waveName.replace('(', '-'); waveName = waveName.replace(')', '-'); stks[seriesNdx][pt[seriesNdx]] += waveName; } } if (nstages > 0) { stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1); } if (tc > 1 || doTimelapse) { stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK"; } else stks[seriesNdx][pt[seriesNdx]] += ".STK"; pt[seriesNdx]++; } } } ndfile = ndfile.getAbsoluteFile(); // check that each STK file exists for (int s = 0; s < stks.length; s++) { for (int f = 0; f < stks[s].length; f++) { Location l = new Location(ndfile.getParent(), stks[s][f]); stks[s][f] = getRealSTKFile(l); } } String file = locateFirstValidFile(); if (file == null) { throw new FormatException("Unable to locate at least one valid STK file!"); } RandomAccessInputStream s = new RandomAccessInputStream(file, 16); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); CoreMetadata ms0 = core.get(0); s.close(); ms0.sizeX = (int) ifd.getImageWidth(); ms0.sizeY = (int) ifd.getImageLength(); if (bizarreMultichannelAcquisition) { ms0.sizeX /= 2; } ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc; ms0.sizeC = cc; ms0.sizeT = tc; ms0.imageCount = getSizeZ() * getSizeC() * getSizeT(); if (isRGB()) { ms0.sizeC *= 3; } ms0.dimensionOrder = "XYZCT"; if (stks != null && stks.length > 1) { // Note that core can't be replaced with newCore until the end of this block. ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>(); for (int i = 0; i < stks.length; i++) { CoreMetadata ms = new CoreMetadata(); newCore.add(ms); ms.sizeX = getSizeX(); ms.sizeY = getSizeY(); ms.sizeZ = getSizeZ(); ms.sizeC = getSizeC(); ms.sizeT = getSizeT(); ms.pixelType = getPixelType(); ms.imageCount = getImageCount(); ms.dimensionOrder = getDimensionOrder(); ms.rgb = isRGB(); ms.littleEndian = isLittleEndian(); ms.interleaved = isInterleaved(); ms.orderCertain = true; } if (stks.length > nstages) { for (int j = 0; j < stagesCount; j++) { int idx = j * 2 + 1; CoreMetadata midx = newCore.get(idx); CoreMetadata pmidx = newCore.get(j * 2); pmidx.sizeC = stks[j * 2].length / getSizeT(); midx.sizeC = stks[idx].length / midx.sizeT; midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1; pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ; midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ; } } core = newCore; } } if (stks == null) { stkReaders = new MetamorphReader[1][1]; stkReaders[0][0] = new MetamorphReader(); stkReaders[0][0].setCanLookForND(false); } else { stkReaders = new MetamorphReader[stks.length][]; for (int i = 0; i < stks.length; i++) { stkReaders[i] = new MetamorphReader[stks[i].length]; for (int j = 0; j < stkReaders[i].length; j++) { stkReaders[i][j] = new MetamorphReader(); stkReaders[i][j].setCanLookForND(false); if (j > 0) { stkReaders[i][j].setMetadataOptions(new DynamicMetadataOptions(MetadataLevel.MINIMUM)); } } } } // check stage labels for plate data int rows = 0; int cols = 0; Map<String, Integer> rowMap = null; Map<String, Integer> colMap = null; isHCS = true; if (null == stageLabels) { isHCS = false; } else { Set<Map.Entry<Integer, Integer>> uniqueWells = new HashSet<Map.Entry<Integer, Integer>>(); rowMap = new HashMap<String, Integer>(); colMap = new HashMap<String, Integer>(); for (String label : stageLabels) { if (null == label) { isHCS = false; break; } Map.Entry<Integer, Integer> wellCoords = getWellCoords(label); if (null == wellCoords) { isHCS = false; break; } uniqueWells.add(wellCoords); rowMap.put(label, wellCoords.getKey()); colMap.put(label, wellCoords.getValue()); } if (uniqueWells.size() != stageLabels.length) { isHCS = false; } else { rows = Collections.max(rowMap.values()); cols = Collections.max(colMap.values()); CoreMetadata c = core.get(0); core.clear(); c.sizeZ = 1; c.sizeT = 1; c.imageCount = 1; for (int s = 0; s < uniqueWells.size(); s++) { CoreMetadata toAdd = new CoreMetadata(c); if (s > 0) { toAdd.seriesMetadata.clear(); } core.add(toAdd); } seriesToIFD = true; } } List<String> timestamps = null; MetamorphHandler handler = null; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); if (isHCS) { store.setPlateID(MetadataTools.createLSID("Plate", 0), 0); store.setPlateRows(new PositiveInteger(rows), 0); store.setPlateColumns(new PositiveInteger(cols), 0); store.setPlateRowNamingConvention(NamingConvention.LETTER, 0); store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0); } int nextObjective = 0; String instrumentID = MetadataTools.createLSID("Instrument", 0); String detectorID = MetadataTools.createLSID("Detector", 0, 0); store.setInstrumentID(instrumentID, 0); store.setDetectorID(detectorID, 0, 0); store.setDetectorType(getDetectorType("Other"), 0, 0); for (int i = 0; i < getSeriesCount(); i++) { setSeries(i); // do not reparse the same XML for every well if (i == 0 || !isHCS) { handler = new MetamorphHandler(getSeriesMetadata()); } if (isHCS) { String label = stageLabels[i]; String wellID = MetadataTools.createLSID("Well", 0, i); store.setWellID(wellID, 0, i); store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i); store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i); store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0); store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0); store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0); } store.setImageInstrumentRef(instrumentID, i); String comment = getFirstComment(i); if (i == 0 || !isHCS) { if (comment != null && comment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler); } catch (IOException e) { } } } if (creationTime != null) { String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, "."); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } } store.setImageName(makeImageName(i).trim(), i); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { continue; } store.setImageDescription("", i); store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), i); if (sizeX == null) sizeX = handler.getPixelSizeX(); if (sizeY == null) sizeY = handler.getPixelSizeY(); Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX); Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY); if (physicalSizeX != null) { store.setPixelsPhysicalSizeX(physicalSizeX, i); } if (physicalSizeY != null) { store.setPixelsPhysicalSizeY(physicalSizeY, i); } if (zDistances != null) { stepSize = zDistances[0]; } else { List<Double> zPositions = new ArrayList<Double>(); final List<Double> uniqueZ = new ArrayList<Double>(); for (IFD ifd : ifds) { MetamorphHandler zPlaneHandler = new MetamorphHandler(); String zComment = ifd.getComment(); if (zComment != null && zComment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(zComment), zPlaneHandler); } catch (IOException e) { } } zPositions = zPlaneHandler.getZPositions(); for (Double z : zPositions) { if (!uniqueZ.contains(z)) uniqueZ.add(z); } } if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) { BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1)); BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0)); BigDecimal zRange = (lastZ.subtract(firstZ)).abs(); BigDecimal zSize = BigDecimal.valueOf((double) (getSizeZ() - 1)); MathContext mc = new MathContext(10, RoundingMode.HALF_UP); stepSize = zRange.divide(zSize, mc).doubleValue(); } } Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize); if (physicalSizeZ != null) { store.setPixelsPhysicalSizeZ(physicalSizeZ, i); } if (handler.getLensNA() != 0 || handler.getLensRI() != 0) { String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective); store.setObjectiveID(objectiveID, 0, nextObjective); if (handler.getLensNA() != 0) { store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective); } store.setObjectiveSettingsID(objectiveID, i); if (handler.getLensRI() != 0) { store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i); } nextObjective++; } int waveIndex = 0; for (int c = 0; c < getEffectiveSizeC(); c++) { if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) { waveIndex = c; } else if (firstSeriesChannels != null) { int s = i % 2; while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) { waveIndex++; } } if (waveNames != null && waveIndex < waveNames.size()) { store.setChannelName(waveNames.get(waveIndex).trim(), i, c); } if (handler.getBinning() != null) binning = handler.getBinning(); if (binning != null) { store.setDetectorSettingsBinning(getBinning(binning), i, c); } if (handler.getReadOutRate() != 0) { store.setDetectorSettingsReadOutRate(new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i, c); } if (gain == null) { gain = handler.getGain(); } if (gain != null) { store.setDetectorSettingsGain(gain, i, c); } store.setDetectorSettingsID(detectorID, i, c); if (wave != null && waveIndex < wave.length) { Length wavelength = FormatTools.getWavelength(wave[waveIndex]); if ((int) wave[waveIndex] >= 1) { // link LightSource to Image int laserIndex = i * getEffectiveSizeC() + c; String lightSourceID = MetadataTools.createLSID("LightSource", 0, laserIndex); store.setLaserID(lightSourceID, 0, laserIndex); store.setChannelLightSourceSettingsID(lightSourceID, i, c); store.setLaserType(getLaserType("Other"), 0, laserIndex); store.setLaserLaserMedium(getLaserMedium("Other"), 0, laserIndex); if (wavelength != null) { store.setChannelLightSourceSettingsWavelength(wavelength, i, c); } } } waveIndex++; } timestamps = handler.getTimestamps(); for (int t = 0; t < timestamps.size(); t++) { String date = DateTools.convertDate(DateTools.getTime(timestamps.get(t), SHORT_DATE_FORMAT, "."), DateTools.UNIX, SHORT_DATE_FORMAT + ".SSS"); addSeriesMetaList("timestamp", date); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, "."); } final Length positionX = handler.getStagePositionX(); final Length positionY = handler.getStagePositionY(); final List<Double> exposureTimes = handler.getExposures(); if (exposureTimes.size() == 0) { for (int p = 0; p < getImageCount(); p++) { exposureTimes.add(exposureTime); } } else if (exposureTimes.size() == 1 && exposureTimes.size() < getEffectiveSizeC()) { for (int c = 1; c < getEffectiveSizeC(); c++) { MetamorphHandler channelHandler = new MetamorphHandler(); String channelComment = getComment(i, c); if (channelComment != null && channelComment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler); } catch (IOException e) { } } final List<Double> channelExpTime = channelHandler.getExposures(); exposureTimes.add(channelExpTime.get(0)); } } int lastFile = -1; IFDList lastIFDs = null; IFD lastIFD = null; double distance = zStart; TiffParser tp = null; RandomAccessInputStream stream = null; for (int p = 0; p < getImageCount(); p++) { int[] coords = getZCTCoords(p); Double deltaT = 0d; Double expTime = exposureTime; Double xmlZPosition = null; int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ(); if (fileIndex >= 0) { String file = stks == null ? currentId : stks[i][fileIndex]; if (file != null) { if (fileIndex != lastFile) { if (stream != null) { stream.close(); } stream = new RandomAccessInputStream(file, 16); tp = new TiffParser(stream); tp.checkHeader(); IFDList f = tp.getMainIFDs(); if (f.size() > 0) { lastFile = fileIndex; lastIFDs = f; } else { file = null; stks[i][fileIndex] = null; } } } if (file != null) { lastIFD = lastIFDs.get(p % lastIFDs.size()); Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION); if (commentEntry != null) { if (commentEntry instanceof String) { comment = (String) commentEntry; } else if (commentEntry instanceof TiffIFDEntry) { comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString(); } } if (comment != null) comment = comment.trim(); if (comment != null && comment.startsWith("<MetaData>")) { String[] lines = comment.split("\n"); timestamps = new ArrayList<String>(); for (String line : lines) { line = line.trim(); if (line.startsWith("<prop")) { int firstQuote = line.indexOf("\"") + 1; int lastQuote = line.lastIndexOf("\""); String key = line.substring(firstQuote, line.indexOf("\"", firstQuote)); String value = line.substring(line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote); if (key.equals("z-position")) { xmlZPosition = new Double(value); } else if (key.equals("acquisition-time-local")) { timestamps.add(value); } } } } } } int index = 0; if (timestamps.size() > 0) { if (coords[2] < timestamps.size()) index = coords[2]; String stamp = timestamps.get(index); long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, "."); deltaT = (ms - startDate) / 1000.0; } else if (internalStamps != null && p < internalStamps.length) { long delta = internalStamps[p] - internalStamps[0]; deltaT = delta / 1000.0; if (coords[2] < exposureTimes.size()) index = coords[2]; } if (index == 0 && p > 0 && exposureTimes.size() > 0) { index = coords[1] % exposureTimes.size(); } if (index < exposureTimes.size()) { expTime = exposureTimes.get(index); } if (deltaT != null) { store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p); } if (expTime != null) { store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p); } if (stageX != null && p < stageX.length) { store.setPlanePositionX(stageX[p], i, p); } else if (positionX != null) { store.setPlanePositionX(positionX, i, p); } if (stageY != null && p < stageY.length) { store.setPlanePositionY(stageY[p], i, p); } else if (positionY != null) { store.setPlanePositionY(positionY, i, p); } if (zDistances != null && p < zDistances.length) { if (p > 0) { if (zDistances[p] != 0d) distance += zDistances[p]; else distance += zDistances[0]; } final Length zPos = new Length(distance, UNITS.REFERENCEFRAME); store.setPlanePositionZ(zPos, i, p); } else if (xmlZPosition != null) { final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME); store.setPlanePositionZ(zPos, i, p); } } if (stream != null) { stream.close(); } } setSeries(0); }
From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java
@Deprecated private BigDecimal getDetails(final Long financialyearid, final Integer moduleid, final String referencenumber, final Integer departmentid, final Long functionid, final Integer functionaryid, final Integer schemeid, final Integer subschemeid, final Integer boundaryid, final List<Long> budgetheadid, final Integer fundid, final double amount, final boolean consumeOrRelease, final String appropriationnumber) { try {/* w ww .ja va 2s.co m*/ if (LOGGER.isDebugEnabled()) LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber==" + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid==" + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid + ",amount==" + amount); validateMandatoryParameters(moduleid, referencenumber); BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid, functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid); if (consumeOrRelease) amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount)); else amtavailable = amtavailable.add(BigDecimal.valueOf(amount)); if (LOGGER.isDebugEnabled()) LOGGER.debug("budget available after consuming/releasing=" + amtavailable); if (amtavailable != null && amtavailable.compareTo(BigDecimal.ZERO) >= 0) { // need to update budget details final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid, boundaryid, fundid); final Query q = persistenceService.getSession().createQuery( " from BudgetDetail bd where bd.budget.financialYear.id=:finYearId and bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)" + query); if (budgetService.hasApprovedReForYear(financialyearid)) q.setParameter("type", "RE"); else q.setParameter("type", "BE"); q.setParameter("finYearId", financialyearid); q.setParameterList("bgId", budgetheadid); final List<BudgetDetail> bdList = q.list(); if (bdList == null || bdList.size() == 0) { if (LOGGER.isDebugEnabled()) LOGGER.debug( "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!"); if (LOGGER.isDebugEnabled()) LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group - " + budgetheadid.toString() + " Query - " + query); throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed"); } final BudgetDetail bd = bdList.get(0); bd.setBudgetAvailable(amtavailable); update(bd); final BudgetUsage budgetUsage = new BudgetUsage(); budgetUsage.setFinancialYearId(financialyearid.intValue()); budgetUsage.setModuleId(moduleid); budgetUsage.setReferenceNumber(referencenumber); budgetUsage.setBudgetDetail(bd); budgetUsage.setAppropriationnumber(appropriationnumber); if (consumeOrRelease) { budgetUsage.setConsumedAmount(amount); budgetUsage.setReleasedAmount(0.0); } else { budgetUsage.setConsumedAmount(0.0); budgetUsage.setReleasedAmount(amount); } budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue()); budgetUsageService.create(budgetUsage); return BigDecimal.ONE; } else return BigDecimal.ZERO; } catch (final ValidationException v) { throw v; } catch (final Exception e) { throw new ValidationException(EMPTY_STRING, e.getMessage()); } }
From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java
BigDecimal interestDueForNextInstallment(BigDecimal totalRepaymentAmount, BigDecimal waivedAmount, LoanBO loan, boolean waiveInterest) { BigDecimal result = BigDecimal.ZERO; if (!waiveInterest) { if (loan.isDecliningBalanceInterestRecalculation()) { result = totalRepaymentAmount.subtract(waivedAmount); } else {/* ww w . ja va2s .co m*/ AccountActionDateEntity nextInstallment = loan.getDetailsOfNextInstallment(); if (nextInstallment != null) { LoanScheduleEntity loanScheduleEntity = (LoanScheduleEntity) nextInstallment; result = loanScheduleEntity.getInterestDue().getAmount(); } } } return result; }