List of usage examples for java.util Map.Entry get
V get(Object key);
From source file:com.wanikani.wklib.Connection.java
protected void measureHeaders(Meter meter, URLConnection conn, boolean clen) { Map<String, List<String>> hdrs; hdrs = conn.getHeaderFields();/* www . ja v a 2 s. c om*/ if (hdrs == null) return; for (Map.Entry<String, List<String>> e : hdrs.entrySet()) { if (e.getKey() != null) meter.count(e.getKey().length() + 1); for (String s : e.getValue()) meter.count(s.length() + 3); if (clen && e.getKey() != null && e.getKey().equals("Content-Length") && !e.getValue().isEmpty()) { try { meter.count(Integer.parseInt(e.getValue().get(0))); } catch (NumberFormatException x) { /* empty */ } } } meter.sync(); }
From source file:org.geppetto.simulation.manager.ExperimentRunThread.java
/** * @param experiment/* w ww. ja v a 2s .c o m*/ * @throws GeppettoInitializationException */ private void init(IExperiment experiment) throws GeppettoInitializationException { try { GeppettoModelAccess modelAccess = new GeppettoModelAccess(runtimeProject.getGeppettoModel()); List<? extends IAspectConfiguration> aspectConfigs = experiment.getAspectConfigurations(); for (IAspectConfiguration aspectConfig : aspectConfigs) { ISimulatorConfiguration simConfig = aspectConfig.getSimulatorConfiguration(); String simulatorId = simConfig.getSimulatorId(); String instancePath = aspectConfig.getInstance(); Pointer pointer = PointerUtility.getPointer(runtimeProject.getGeppettoModel(), instancePath); // We are taking the domain model for the last element of the pointer DomainModel model = PointerUtility.getType(pointer).getDomainModel(); if (simConfig.getConversionServiceId() != null && !simConfig.getConversionServiceId().isEmpty()) { AConversion conversionService = (AConversion) ServiceCreator .getNewServiceInstance(simConfig.getConversionServiceId()); conversionService.setScope(Scope.RUN); conversionService.setProjectId(experiment.getParentProject().getId()); conversionServices.put(instancePath, conversionService); } ASimulator simulator = (ASimulator) ServiceCreator.getNewServiceInstance(simulatorId); simulator.setProjectId(experiment.getParentProject().getId()); simulatorServices.put(instancePath, simulator); simulatorRuntimes.put(instancePath, new SimulatorRuntime()); // get conversion service IConversion conversionService = null; if (simConfig.getConversionServiceId() != null && !simConfig.getConversionServiceId().isEmpty()) { conversionService = this.conversionServices.get(simConfig.getConversionServiceId()); } IModelInterpreter modelService = runtimeProject.getModelInterpreter(pointer); // TODO: Extract formats from model interpreters from within here somehow List<ModelFormat> inputFormats = ServicesRegistry.getModelInterpreterServiceFormats(modelService); List<ModelFormat> outputFormats = ServicesRegistry.getSimulatorServiceFormats(simulator); if (inputFormats == null || inputFormats.isEmpty()) { throw new GeppettoInitializationException( "No supported formats for the model interpreter " + modelService.getName()); } if (outputFormats == null || outputFormats.isEmpty()) { throw new GeppettoInitializationException( "No supported formats for the simulator " + simulator.getName()); } DomainModel iConvertedModel = null; if (conversionService != null) { // Read conversion supported model formats List<ModelFormat> supportedInputFormats = conversionService.getSupportedInputs(); // FIXME: We can pass the model and the input format so it brings back a filtered list of outputs format List<ModelFormat> supportedOutputFormats = conversionService.getSupportedOutputs(); // Check if real model formats and conversion supported model formats match supportedInputFormats.retainAll(inputFormats); supportedOutputFormats.retainAll(outputFormats); // Try to convert until a input-output format combination works for (ModelFormat inputFormat : supportedInputFormats) { if (iConvertedModel == null) { for (ModelFormat outputFormat : supportedOutputFormats) { try { iConvertedModel = conversionService.convert(model, outputFormat, aspectConfig, modelAccess); break; } catch (ConversionException e) { throw new GeppettoInitializationException(e); } } } } } else { // Check format returned by the model interpreter matches with the one accepted by the simulator if (Collections.disjoint(inputFormats, outputFormats) && inputFormats != null && outputFormats != null) { Map<ConversionServiceKey, List<IConversion>> conversionServices = ServicesRegistry .getConversionService(inputFormats, outputFormats); for (Map.Entry<ConversionServiceKey, List<IConversion>> entry : conversionServices .entrySet()) { if (iConvertedModel == null) { // FIXME: Assuming we will only have one conversion service ConversionServiceKey conversionServiceKey = entry.getKey(); for (ModelFormat supportedModelFormat : entry.getValue().get(0) .getSupportedOutputs(model)) { // Verify supported outputs for this model if (supportedModelFormat.equals(conversionServiceKey.getOutputModelFormat())) { ((AConversion) entry.getValue().get(0)).setScope(Scope.RUN); ((AConversion) entry.getValue().get(0)) .setProjectId(experiment.getParentProject().getId()); iConvertedModel = entry.getValue().get(0).convert(model, conversionServiceKey.getOutputModelFormat(), aspectConfig, modelAccess); break; } } } } } } // code to initialize simulator if (simulator != null) { long start = System.currentTimeMillis(); ExperimentState experimentState = runtimeProject.getRuntimeExperiment(experiment) .getExperimentState(); if (iConvertedModel == null) { simulator.initialize(model, aspectConfig, experimentState, this, modelAccess); } else { simulator.initialize(iConvertedModel, aspectConfig, experimentState, this, modelAccess); } long end = System.currentTimeMillis(); logger.info("Finished initializing simulator, took " + (end - start) + " ms "); } else { throw new GeppettoInitializationException( "A simulator for " + instancePath + " already exists, something did not get cleared"); } } } catch (Exception e) { throw new GeppettoInitializationException(e); } }
From source file:org.apache.hadoop.ipc.DecayRpcScheduler.java
/** * Decay the stored counts for each user and clean as necessary. * This method should be called periodically in order to keep * counts current./*www . j a v a 2s . c o m*/ */ private void decayCurrentCounts() { try { long totalDecayedCount = 0; long totalRawCount = 0; Iterator<Map.Entry<Object, List<AtomicLong>>> it = callCounts.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Object, List<AtomicLong>> entry = it.next(); AtomicLong decayedCount = entry.getValue().get(0); AtomicLong rawCount = entry.getValue().get(1); // Compute the next value by reducing it by the decayFactor totalRawCount += rawCount.get(); long currentValue = decayedCount.get(); long nextValue = (long) (currentValue * decayFactor); totalDecayedCount += nextValue; decayedCount.set(nextValue); if (nextValue == 0) { // We will clean up unused keys here. An interesting optimization // might be to have an upper bound on keyspace in callCounts and only // clean once we pass it. it.remove(); } } // Update the total so that we remain in sync totalDecayedCallCount.set(totalDecayedCount); totalRawCallCount.set(totalRawCount); // Now refresh the cache of scheduling decisions recomputeScheduleCache(); // Update average response time with decay updateAverageResponseTime(true); } catch (Exception ex) { LOG.error("decayCurrentCounts exception: " + ExceptionUtils.getFullStackTrace(ex)); throw ex; } }
From source file:org.apache.hadoop.hbase.client.transactional.TransactionalAggregationClient.java
/** * This is the client side interface/handler for calling the median method for a * given cf-cq combination. This method collects the necessary parameters * to compute the median and returns the median. * @param table//from ww w . j a v a2 s.c o m * @param ci * @param scan * @return R the median * @throws Throwable */ public <R, S, P extends Message, Q extends Message, T extends Message> R median(final long transactionId, final TransactionalTable table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { Pair<NavigableMap<byte[], List<S>>, List<S>> p = getMedianArgs(transactionId, table, ci, scan); byte[] startRow = null; byte[] colFamily = scan.getFamilies()[0]; NavigableSet<byte[]> quals = scan.getFamilyMap().get(colFamily); NavigableMap<byte[], List<S>> map = p.getFirst(); S sumVal = p.getSecond().get(0); S sumWeights = p.getSecond().get(1); double halfSumVal = ci.divideForAvg(sumVal, 2L); double movingSumVal = 0; boolean weighted = false; if (quals.size() > 1) { weighted = true; halfSumVal = ci.divideForAvg(sumWeights, 2L); } for (Map.Entry<byte[], List<S>> entry : map.entrySet()) { S s = weighted ? entry.getValue().get(1) : entry.getValue().get(0); double newSumVal = movingSumVal + ci.divideForAvg(s, 1L); if (newSumVal > halfSumVal) break; // we found the region with the median movingSumVal = newSumVal; startRow = entry.getKey(); } // scan the region with median and find it Scan scan2 = new Scan(scan); // inherit stop row from method parameter if (startRow != null) scan2.setStartRow(startRow); ResultScanner scanner = null; try { int cacheSize = scan2.getCaching(); if (!scan2.getCacheBlocks() || scan2.getCaching() < 2) { scan2.setCacheBlocks(true); cacheSize = 5; scan2.setCaching(cacheSize); } scanner = table.getScanner(scan2); Result[] results = null; byte[] qualifier = quals.pollFirst(); // qualifier for the weight column byte[] weightQualifier = weighted ? quals.pollLast() : qualifier; R value = null; do { results = scanner.next(cacheSize); if (results != null && results.length > 0) { for (int i = 0; i < results.length; i++) { Result r = results[i]; // retrieve weight Cell kv = r.getColumnLatest(colFamily, weightQualifier); R newValue = ci.getValue(colFamily, weightQualifier, kv); S s = ci.castToReturnType(newValue); double newSumVal = movingSumVal + ci.divideForAvg(s, 1L); // see if we have moved past the median if (newSumVal > halfSumVal) { return value; } movingSumVal = newSumVal; kv = r.getColumnLatest(colFamily, qualifier); value = ci.getValue(colFamily, qualifier, kv); } } } while (results != null && results.length > 0); } finally { if (scanner != null) { scanner.close(); } } return null; }
From source file:com.redhat.lightblue.metadata.rdbms.converter.Translator.java
protected void recursiveTranslateNaryLogicalExpression(TranslationContext translationContext, NaryLogicalExpression naryLogicalExpression) { String ops = NARY_TO_SQL.get(naryLogicalExpression.getOp()); boolean noStatement = translationContext.logicalStmt.size() == 0; translationContext.logicalStmt/*from ww w. ja v a 2 s .c o m*/ .add(new AbstractMap.SimpleEntry<String, List<String>>(ops, new ArrayList<String>())); for (QueryExpression queryExpression : naryLogicalExpression.getQueries()) { recursiveTranslateQuery(translationContext, queryExpression); } Map.Entry<String, List<String>> remove = translationContext.logicalStmt .remove(translationContext.logicalStmt.size() - 1); String op = remove.getKey() + " "; StringBuilder conditionalStringBuilder = new StringBuilder(); if (!noStatement || !translationContext.baseStmt.getWhereConditionals().isEmpty()) { conditionalStringBuilder.append("("); } for (int i = 0; i < remove.getValue().size(); i++) { String value = remove.getValue().get(i); if (i == (remove.getValue().size() - 1)) { conditionalStringBuilder.append(value); if (!noStatement || !translationContext.baseStmt.getWhereConditionals().isEmpty()) { conditionalStringBuilder.append(") "); } } else { conditionalStringBuilder.append(value).append(" ").append(op); } } if (noStatement) { translationContext.baseStmt.getWhereConditionals().add(conditionalStringBuilder.toString()); } else { translationContext.logicalStmt.get(translationContext.logicalStmt.size() - 1).getValue() .add(conditionalStringBuilder.toString()); } }
From source file:org.apache.hadoop.ipc.DecayRpcScheduler.java
/** * Update the scheduleCache to match current conditions in callCounts. *///from www.j a va2 s . c o m private void recomputeScheduleCache() { Map<Object, Integer> nextCache = new HashMap<Object, Integer>(); for (Map.Entry<Object, List<AtomicLong>> entry : callCounts.entrySet()) { Object id = entry.getKey(); AtomicLong value = entry.getValue().get(0); long snapshot = value.get(); int computedLevel = computePriorityLevel(snapshot); nextCache.put(id, computedLevel); } // Swap in to activate scheduleCacheRef.set(Collections.unmodifiableMap(nextCache)); }
From source file:com.streamsets.pipeline.stage.origin.http.HttpClientSource.java
/** * Adds the HTTP response headers to the record header. * @param header an SDC record header to populate *//*from w w w .j a va 2 s. c o m*/ private void addResponseHeaders(Record.Header header) { final MultivaluedMap<String, String> headers = getResponse().getStringHeaders(); if (headers == null) { return; } for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (!entry.getValue().isEmpty()) { String firstValue = entry.getValue().get(0); header.setAttribute(entry.getKey(), firstValue); } } }
From source file:org.apache.cxf.jaxrs.swagger.DefaultSwagger2Serializers.java
@Override public void writeTo(final Swagger data, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream out) throws IOException { if (dynamicBasePath) { MessageContext ctx = JAXRSUtils.createContextValue(JAXRSUtils.getCurrentMessage(), null, MessageContext.class); String currentBasePath = StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/"); if (!currentBasePath.equals(beanConfig.getBasePath())) { data.setBasePath(currentBasePath); data.setHost(beanConfig.getHost()); data.setInfo(beanConfig.getInfo()); }//from www .j a v a2 s. c om if (beanConfig.getSwagger() != null && beanConfig.getSwagger().getSecurityDefinitions() != null && data.getSecurityDefinitions() == null) { data.setSecurityDefinitions(beanConfig.getSwagger().getSecurityDefinitions()); } } if (replaceTags || javadocProvider != null) { Map<String, ClassResourceInfo> operations = new HashMap<>(); Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>(); for (ClassResourceInfo cri : cris) { for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) { String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue()); operations.put(normalizedPath, cri); methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori); } } if (replaceTags && data.getTags() != null) { data.getTags().clear(); } for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) { Tag tag = null; if (replaceTags && operations.containsKey(entry.getKey())) { ClassResourceInfo cri = operations.get(entry.getKey()); tag = new Tag(); tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_")); if (javadocProvider != null) { tag.setDescription(javadocProvider.getClassDoc(cri)); } data.addTag(tag); } for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) { if (replaceTags && tag != null) { subentry.getValue().setTags(Collections.singletonList(tag.getName())); } Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey()); if (methods.containsKey(key) && javadocProvider != null) { OperationResourceInfo ori = methods.get(key); subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori)); for (int i = 0; i < subentry.getValue().getParameters().size(); i++) { subentry.getValue().getParameters().get(i) .setDescription(javadocProvider.getMethodParameterDoc(ori, i)); } addParameters(subentry.getValue().getParameters()); if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) { subentry.getValue().getResponses().entrySet().iterator().next().getValue() .setDescription(javadocProvider.getMethodResponseDoc(ori)); } } } } } if (replaceTags && data.getTags() != null) { Collections.sort(data.getTags(), new Comparator<Tag>() { @Override public int compare(final Tag tag1, final Tag tag2) { return tag1.getName().compareTo(tag2.getName()); } }); } super.writeTo(data, type, genericType, annotations, mediaType, headers, out); }
From source file:org.apache.cxf.jaxrs.swagger.Swagger2Customizer.java
public Swagger customize(Swagger data) { if (dynamicBasePath) { MessageContext ctx = createMessageContext(); String currentBasePath = StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/"); if (!currentBasePath.equals(beanConfig.getBasePath())) { data.setBasePath(currentBasePath); data.setHost(beanConfig.getHost()); data.setInfo(beanConfig.getInfo()); }/*w ww. j a va 2s .co m*/ if (beanConfig.getSwagger() != null && beanConfig.getSwagger().getSecurityDefinitions() != null && data.getSecurityDefinitions() == null) { data.setSecurityDefinitions(beanConfig.getSwagger().getSecurityDefinitions()); } } if (replaceTags || javadocProvider != null) { Map<String, ClassResourceInfo> operations = new HashMap<>(); Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>(); for (ClassResourceInfo cri : cris) { for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) { String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue()); operations.put(normalizedPath, cri); methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori); } } if (replaceTags && data.getTags() != null) { data.getTags().clear(); } for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) { Tag tag = null; if (replaceTags && operations.containsKey(entry.getKey())) { ClassResourceInfo cri = operations.get(entry.getKey()); tag = new Tag(); tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_")); if (javadocProvider != null) { tag.setDescription(javadocProvider.getClassDoc(cri)); } data.addTag(tag); } for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) { if (replaceTags && tag != null) { subentry.getValue().setTags(Collections.singletonList(tag.getName())); } Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey()); if (methods.containsKey(key) && javadocProvider != null) { OperationResourceInfo ori = methods.get(key); subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori)); for (int i = 0; i < subentry.getValue().getParameters().size(); i++) { subentry.getValue().getParameters().get(i) .setDescription(javadocProvider.getMethodParameterDoc(ori, i)); } addParameters(subentry.getValue().getParameters()); if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) { subentry.getValue().getResponses().entrySet().iterator().next().getValue() .setDescription(javadocProvider.getMethodResponseDoc(ori)); } } } } } if (replaceTags && data.getTags() != null) { Collections.sort(data.getTags(), new Comparator<Tag>() { @Override public int compare(final Tag tag1, final Tag tag2) { return tag1.getName().compareTo(tag2.getName()); } }); } applyDefaultVersion(data); return data; }
From source file:org.egov.ptis.actions.edit.AddDemandAction.java
@SuppressWarnings("unchecked") @ValidationErrorPage(value = RESULT_NEW) @Action(value = "/addDemand-update") public String update() { if (LOGGER.isDebugEnabled()) LOGGER.info("Entered into update, basicProperty=" + basicProperty); final Query qry = entityManager.createNamedQuery("QUERY_DEMAND_DET_NON_ZERODEMAND"); qry.setParameter(BASIC_PROPERTY, basicProperty); final List<EgDemandDetails> demandDetailsFromDB = qry.getResultList(); final Installment currentInstallment = propertyTaxCommonUtils.getCurrentInstallment(); final Map<Installment, List<EgDemandDetails>> demandDetails = new TreeMap<>(); final Query qry1 = entityManager.createNamedQuery("QUERY_DEMAND_DET_WITH_ZERODEMAND"); qry1.setParameter(BASIC_PROPERTY, basicProperty); final List<EgDemandDetails> dmdDtlsWithZeroAmt = qry1.getResultList(); final Set<Installment> zeroInstallments = new TreeSet<>(); BigDecimal totalDmd = BigDecimal.ZERO; EgDemandDetails egDemandDtls = null; demandAudit.setBasicproperty(basicProperty.getUpicNo()); demandAudit.setTransaction(ADD_DEMAND); demandAudit.setRemarks(remarks);/*from w w w . java 2 s .c o m*/ demandAudit.setLastModifiedDate(new Date()); for (final DemandDetail dmdDetail : demandDetailBeanList) if (dmdDetail.getIsNew() != null && dmdDetail.getIsNew() && dmdDetail.getActualAmount() != null) { final EgDemandReason egDmdRsn = propertyTaxUtil.getDemandReasonByCodeAndInstallment( demandReasonMap.get(dmdDetail.getReasonMaster()), dmdDetail.getInstallment()); /** * Checking whether already EgDemandDetails exists for this, if yes updating the same. this may be when taxes * updated to 0 and then later adding the installment taxes. */ for (final EgDemandDetails details : dmdDtlsWithZeroAmt) if (details.getEgDemandReason().equals(egDmdRsn)) { zeroInstallments.add(details.getEgDemandReason().getEgInstallmentMaster()); details.setAmount(dmdDetail.getActualAmount()); details.setAmtCollected(dmdDetail.getActualCollection() == null ? BigDecimal.ZERO : dmdDetail.getActualCollection()); egDemandDtls = details; } else if (dmdDetail.getActualAmount().compareTo(BigDecimal.ZERO) != 0 && dmdDetail.getIsNew()) { egDemandDtls = propService.createDemandDetails(dmdDetail.getActualAmount(), dmdDetail.getActualCollection(), egDmdRsn, dmdDetail.getInstallment()); totalDmd = totalDmd.add(egDemandDtls.getAmount()); } if (dmdDtlsWithZeroAmt.isEmpty() && dmdDetail.getActualAmount().compareTo(BigDecimal.ZERO) != 0 && dmdDetail.getIsNew()) { egDemandDtls = propService.createDemandDetails(dmdDetail.getActualAmount(), dmdDetail.getActualCollection(), egDmdRsn, dmdDetail.getInstallment()); totalDmd = totalDmd.add(egDemandDtls.getAmount()); } logAudit(dmdDetail); final List<EgDemandDetails> dmdDtl = new ArrayList<>(); if (demandDetails.get(dmdDetail.getInstallment()) == null) { dmdDtl.add(egDemandDtls); demandDetails.put(dmdDetail.getInstallment(), dmdDtl); } else demandDetails.get(dmdDetail.getInstallment()).add(egDemandDtls); } for (final EgDemandDetails ddFromDB : demandDetailsFromDB) for (final DemandDetail dmdDetail : demandDetailBeanList) if (dmdDetail.getIsNew() != null && !dmdDetail.getIsNew()) { Boolean isUpdateAmount = false; Boolean isUpdateCollection = false; if (dmdDetail.getRevisedAmount() != null && dmdDetail.getInstallment() .equals(ddFromDB.getEgDemandReason().getEgInstallmentMaster()) && ddFromDB.getEgDemandReason().getEgDemandReasonMaster().getCode() .equalsIgnoreCase(demandReasonMap.get(dmdDetail.getReasonMaster()))) isUpdateAmount = true; if (dmdDetail.getRevisedCollection() != null && ddFromDB.getEgDemand().getEgInstallmentMaster().equals(currentInstallment) && ddFromDB.getEgDemandReason().getEgDemandReasonMaster().getCode() .equalsIgnoreCase(demandReasonMap.get(dmdDetail.getReasonMaster()))) { final Installment inst = installmentDAO.findById(dmdDetail.getInstallment().getId(), false); if (ddFromDB.getEgDemandReason().getEgInstallmentMaster().equals(inst)) isUpdateCollection = true; } if (isUpdateAmount) ddFromDB.setAmount(dmdDetail.getRevisedAmount() != null ? dmdDetail.getRevisedAmount() : BigDecimal.ZERO); if (isUpdateCollection) ddFromDB.setAmtCollected( dmdDetail.getRevisedCollection() != null ? dmdDetail.getRevisedCollection() : BigDecimal.ZERO); if (isUpdateAmount || isUpdateCollection) { ddFromDB.setModifiedDate(new Date()); logAudit(dmdDetail); demandDetailsDao.update(ddFromDB); break; } } if (!demandAudit.getDemandAuditDetails().isEmpty()) demandAuditService.saveDetails(demandAudit); final Query query = entityManager.createNamedQuery("QUERY_DEMAND_DETAILS_FOR_CURRINST"); query.setParameter(BASIC_PROPERTY, basicProperty); query.setParameter(INSTALLMENT2, propertyTaxCommonUtils.getCurrentInstallment()); final List<EgDemandDetails> currentInstdemandDetailsFromDB = query.getResultList(); final Map<Installment, Set<EgDemandDetails>> demandDetailsSetByInstallment = getEgDemandDetailsSetByInstallment( currentInstdemandDetailsFromDB); final List<Installment> installments = new ArrayList<>(demandDetailsSetByInstallment.keySet()); Collections.sort(installments); for (final Installment inst : installments) { final Map<String, BigDecimal> dmdRsnAmt = new LinkedHashMap<>(); for (final String rsn : DEMAND_RSNS_LIST) { final EgDemandDetails newDmndDtls = propService .getEgDemandDetailsForReason(demandDetailsSetByInstallment.get(inst), rsn); if (newDmndDtls != null && newDmndDtls.getAmtCollected() != null) { final BigDecimal extraCollAmt = newDmndDtls.getAmtCollected().subtract(newDmndDtls.getAmount()); // If there is extraColl then add to map if (extraCollAmt.compareTo(BigDecimal.ZERO) > 0) { dmdRsnAmt.put(newDmndDtls.getEgDemandReason().getEgDemandReasonMaster().getCode(), extraCollAmt); newDmndDtls.setAmtCollected(newDmndDtls.getAmtCollected().subtract(extraCollAmt)); newDmndDtls.setModifiedDate(new Date()); demandDetailsDao.update(newDmndDtls); } } } propService.getExcessCollAmtMap().put(inst, dmdRsnAmt); } LOGGER.info("Excess Collection - " + propService.getExcessCollAmtMap()); final Set<EgDemandDetails> demandDetailsToBeSaved = new HashSet<>(); for (final Map.Entry<Installment, List<EgDemandDetails>> entry : demandDetails.entrySet()) if (!entry.getValue().get(0).getEgDemandReason().getEgDemandReasonMaster().getReasonMaster() .equalsIgnoreCase(DEMANDRSN_STR_CHQ_BOUNCE_PENALTY)) demandDetailsToBeSaved.addAll(new HashSet<EgDemandDetails>(entry.getValue())); final Query query1 = entityManager.createNamedQuery("QUERY_CURRENT_PTDEMAND"); query1.setParameter(BASIC_PROPERTY, basicProperty); query1.setParameter(INSTALLMENT2, propertyTaxCommonUtils.getCurrentInstallment()); final List<Ptdemand> currPtdemand = query1.getResultList(); if (currPtdemand.isEmpty()) { final Ptdemand ptDemand = new Ptdemand(); final PTDemandCalculations ptDmdCalc = new PTDemandCalculations(); ptDemand.setEgInstallmentMaster(propertyTaxCommonUtils.getCurrentInstallment()); ptDemand.setEgDemandDetails(demandDetailsToBeSaved); ptDemand.setBaseDemand(totalDmd); ptDemand.setCreateDate(new Date()); ptDemand.setModifiedDate(new Date()); ptDemand.setIsHistory("N"); ptDemand.setEgptProperty((PropertyImpl) basicProperty.getProperty()); ptDmdCalc.setPtDemand(ptDemand); ptDemand.setDmdCalculations(ptDmdCalc); getPersistenceService().applyAuditing(ptDmdCalc); basicProperty.getProperty().getPtDemandSet().add(ptDemand); } else { final Ptdemand ptdemand = currPtdemand.get(0); ptdemand.setBaseDemand( ptdemand.getBaseDemand() != null ? ptdemand.getBaseDemand().add(totalDmd) : totalDmd); ptdemand.getEgDemandDetails().addAll(demandDetailsToBeSaved); getPersistenceService().applyAuditing(ptdemand.getDmdCalculations()); basicProperty.getProperty().getPtDemandSet().add(ptdemand); } propertyImplService.update(basicProperty.getProperty()); LOGGER.info("Exiting from update"); return RESULT_ACK; }