List of usage examples for java.util Map forEach
default void forEach(BiConsumer<? super K, ? super V> action)
From source file:femr.business.services.system.MedicationService.java
/** * {@inheritDoc}/*from ww w . j a v a 2s . c om*/ */ @Override public ServiceResponse<List<PrescriptionItem>> dispensePrescriptions( Map<Integer, Boolean> prescriptionsToDispense) { ServiceResponse<List<PrescriptionItem>> response = new ServiceResponse<>(); List<PrescriptionItem> prescriptionItems = new ArrayList<>(); DateTime dateTime = dateUtils.getCurrentDateTime(); prescriptionsToDispense.forEach((prescriptionId, isCounseled) -> { ExpressionList<PatientPrescription> prescriptionExpressionList = QueryProvider .getPatientPrescriptionQuery().where().eq("id", prescriptionId); try { IPatientPrescription prescription = patientPrescriptionRepository .findOne(prescriptionExpressionList); prescription.setDateDispensed(dateTime); prescription.setCounseled(isCounseled); prescription = patientPrescriptionRepository.update(prescription); prescriptionItems.add(itemModelMapper.createPrescriptionItem(prescription.getId(), prescription.getMedication().getName(), null, prescription.getPhysician().getFirstName(), prescription.getPhysician().getLastName(), prescription.getConceptPrescriptionAdministration(), prescription.getAmount(), prescription.getMedication(), null, prescription.isCounseled())); } catch (Exception ex) { response.addError("", ex.getMessage()); } }); response.setResponseObject(prescriptionItems); return response; }
From source file:edu.ucsd.sbrg.escher.model.EscherReaction.java
@JsonProperty("segments") public void setSegments(Map<String, Segment> segments) { this.segments = segments; if (nodes == null) { nodes = new HashSet<>(); }//from ww w . j ava 2 s . c om segments.forEach((k, v) -> { v.setId(k); nodes.add(v.getFromNodeId()); nodes.add(v.getToNodeId()); }); }
From source file:org.thingsboard.demo.loader.data.DemoData.java
public void uploadData(RestTemplate restTemplate, String baseUrl) throws Exception { plugins.forEach(plugin -> {//w ww . j a va 2s . co m try { String apiToken = plugin.getApiToken(); PluginMetaData savedPlugin = null; try { savedPlugin = restTemplate.getForObject(baseUrl + "/api/plugin/token/" + apiToken, PluginMetaData.class); } catch (HttpClientErrorException e) { if (e.getStatusCode() != HttpStatus.NOT_FOUND) { throw e; } } if (savedPlugin == null) { savedPlugin = restTemplate.postForObject(baseUrl + "/api/plugin", plugin, PluginMetaData.class); } if (savedPlugin.getState() == ComponentLifecycleState.SUSPENDED) { restTemplate.postForLocation( baseUrl + "/api/plugin/" + savedPlugin.getId().getId().toString() + "/activate", null); } } catch (Exception e) { log.error("Unable to upload plugin!"); log.error("Cause:", e); } }); rules.forEach(rule -> { try { RuleMetaData savedRule = null; TextPageData<RuleMetaData> rules; ResponseEntity<TextPageData<RuleMetaData>> entity = restTemplate.exchange( baseUrl + "/api/rule?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<RuleMetaData>>() { }, 1000, rule.getName()); rules = entity.getBody(); if (rules.getData().size() > 0) { savedRule = rules.getData().get(0); } if (savedRule == null) { savedRule = restTemplate.postForObject(baseUrl + "/api/rule", rule, RuleMetaData.class); } if (savedRule.getState() == ComponentLifecycleState.SUSPENDED) { restTemplate.postForLocation( baseUrl + "/api/rule/" + savedRule.getId().getId().toString() + "/activate", null); } } catch (Exception e) { log.error("Unable to upload rule!"); log.error("Cause:", e); } }); Map<String, CustomerId> customerIdMap = new HashMap<>(); customers.forEach(customer -> { try { Customer savedCustomer = null; TextPageData<Customer> customers; ResponseEntity<TextPageData<Customer>> entity = restTemplate.exchange( baseUrl + "/api/customers?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Customer>>() { }, 1000, customer.getTitle()); customers = entity.getBody(); if (customers.getData().size() > 0) { savedCustomer = customers.getData().get(0); } if (savedCustomer == null) { savedCustomer = restTemplate.postForObject(baseUrl + "/api/customer", customer, Customer.class); } customerIdMap.put(savedCustomer.getTitle(), savedCustomer.getId()); } catch (Exception e) { log.error("Unable to upload customer!"); log.error("Cause:", e); } }); List<Device> loadedDevices = new ArrayList<>(); Map<String, DeviceId> deviceIdMap = new HashMap<>(); devices.forEach(device -> { try { CustomerId customerId = null; String customerTitle = customerDevices.get(device.getName()); if (customerTitle != null) { customerId = customerIdMap.get(customerTitle); } Device savedDevice = null; TextPageData<Device> devices; if (customerId != null) { ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange( baseUrl + "/api/customer/{customerId}/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() { }, customerId.getId().toString(), 1000, device.getName()); devices = entity.getBody(); if (devices.getData().size() > 0) { savedDevice = devices.getData().get(0); } } if (savedDevice == null) { ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange( baseUrl + "/api/tenant/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() { }, 1000, device.getName()); devices = entity.getBody(); if (devices.getData().size() > 0) { savedDevice = devices.getData().get(0); } } if (savedDevice == null) { savedDevice = restTemplate.postForObject(baseUrl + "/api/device", device, Device.class); } if (customerId != null && savedDevice.getCustomerId().isNullUid()) { restTemplate.postForLocation(baseUrl + "/api/customer/{customerId}/device/{deviceId}", null, customerId.getId().toString(), savedDevice.getId().toString()); } String deviceName = savedDevice.getName(); DeviceId deviceId = savedDevice.getId(); deviceIdMap.put(deviceName, deviceId); loadedDevices.add(savedDevice); DeviceCredentials credentials = restTemplate.getForObject( baseUrl + "/api/device/{deviceId}/credentials", DeviceCredentials.class, deviceId.getId().toString()); loadedDevicesCredentialsMap.put(deviceId, credentials); Map<String, JsonNode> attributesMap = devicesAttributes.get(deviceName); if (attributesMap != null) { attributesMap.forEach((k, v) -> { restTemplate.postForObject(baseUrl + "/api/plugins/telemetry/{deviceId}/{attributeScope}", v, Void.class, deviceId.getId().toString(), k); }); } } catch (Exception e) { log.error("Unable to upload device!"); log.error("Cause:", e); } }); devices = loadedDevices; Map<String, Dashboard> pendingDashboards = dashboards.stream() .collect(Collectors.toMap(Dashboard::getTitle, Function.identity())); Map<String, Dashboard> savedDashboards = new HashMap<>(); while (pendingDashboards.size() != 0) { Dashboard savedDashboard = null; for (Dashboard dashboard : pendingDashboards.values()) { savedDashboard = getDashboardByName(restTemplate, baseUrl, dashboard); if (savedDashboard == null) { try { Optional<String> dashboardConfigurationBody = resolveLinks(savedDashboards, dashboard.getConfiguration()); if (dashboardConfigurationBody.isPresent()) { dashboard.setConfiguration(objectMapper.readTree(dashboardConfigurationBody.get())); JsonNode dashboardConfiguration = dashboard.getConfiguration(); JsonNode deviceAliases = dashboardConfiguration.get("deviceAliases"); deviceAliases.forEach(jsonNode -> { String aliasName = jsonNode.get("alias").asText(); DeviceId deviceId = deviceIdMap.get(aliasName); if (deviceId != null) { ((ObjectNode) jsonNode).put("deviceId", deviceId.getId().toString()); } }); savedDashboard = restTemplate.postForObject(baseUrl + "/api/dashboard", dashboard, Dashboard.class); } } catch (Exception e) { log.error("Unable to upload dashboard!"); log.error("Cause:", e); } } if (savedDashboard != null) { break; } } if (savedDashboard != null) { savedDashboards.put(savedDashboard.getTitle(), savedDashboard); pendingDashboards.remove(savedDashboard.getTitle()); } else { log.error("Unable to upload dashboards due to unresolved references!"); break; } } dashboards = new ArrayList<>(savedDashboards.values()); }
From source file:com.baidu.rigel.biplatform.tesseract.util.QueryRequestUtil.java
public static SearchIndexResultSet processGroupBy(SearchIndexResultSet dataSet, QueryRequest query, QueryContext queryContext) throws NoSuchFieldException { List<SearchIndexResultRecord> transList = null; long current = System.currentTimeMillis(); Map<String, Map<String, Set<String>>> leafValueMap = QueryRequestUtil.transQueryRequest2LeafMap(query); Map<String, String> allDimVal = collectAllMem(queryContext); LOGGER.info("cost :" + (System.currentTimeMillis() - current) + " to collect leaf map."); current = System.currentTimeMillis(); List<String> groupList = Lists.newArrayList(query.getGroupBy().getGroups()); List<QueryMeasure> queryMeasures = query.getSelect().getQueryMeasures(); // count?sum//w w w . j a v a 2 s . com queryMeasures.forEach(measure -> { if (measure.getAggregator().equals(Aggregator.COUNT)) { measure.setAggregator(Aggregator.SUM); } }); Meta meta = dataSet.getMeta(); int dimSize = query.getSelect().getQueryProperties().size(); if (dataSet != null && dataSet.size() != 0 && dataSet instanceof SearchIndexResultSet) { transList = dataSet.getDataList(); if (MapUtils.isNotEmpty(leafValueMap)) { // ??? List<SearchIndexResultRecord> copyLeafRecords = new ArrayList<SearchIndexResultRecord>(); transList.forEach(record -> { leafValueMap.forEach((prop, valueMap) -> { try { String currValue = record.getField(meta.getFieldIndex(prop)) != null ? record.getField(meta.getFieldIndex(prop)).toString() : null; Set<String> valueSet = leafValueMap.get(prop).get(currValue); if (valueSet != null) { int i = 0; for (String value : valueSet) { if (i > 0) { // ? SearchIndexResultRecord newRec = DeepcopyUtils.deepCopy(record); newRec.setField(meta.getFieldIndex(prop), value); generateGroupBy(newRec, groupList, meta); copyLeafRecords.add(newRec); } else { record.setField(meta.getFieldIndex(prop), value); generateGroupBy(record, groupList, meta); } i++; } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }); }); if (CollectionUtils.isNotEmpty(copyLeafRecords)) { // ?? transList.addAll(copyLeafRecords); } transList = AggregateCompute.aggregate(transList, dimSize, queryMeasures); } } else { return dataSet; } LOGGER.info("cost :" + (System.currentTimeMillis() - current) + " to map leaf."); current = System.currentTimeMillis(); if (CollectionUtils.isEmpty(queryMeasures)) { dataSet.setDataList(AggregateCompute.distinct(transList)); return dataSet; } if (MapUtils.isNotEmpty(allDimVal)) { // List<ResultRecord> preResultList = DeepcopyUtils.deepCopy(transList); for (String properties : allDimVal.keySet()) { LinkedList<SearchIndexResultRecord> summaryCalcList = new LinkedList<SearchIndexResultRecord>(); for (SearchIndexResultRecord record : transList) { SearchIndexResultRecord vRecord = DeepcopyUtils.deepCopy(record); vRecord.setField(meta.getFieldIndex(properties), allDimVal.get(properties)); // generateGroupBy(vRecord, groupList); vRecord.setGroupBy(allDimVal.get(properties)); summaryCalcList.add(vRecord); } transList.addAll(AggregateCompute.aggregate(summaryCalcList, dimSize, queryMeasures)); } } dataSet.setDataList(transList); LOGGER.info("cost :" + (System.currentTimeMillis() - current) + " aggregator leaf."); return dataSet; }
From source file:io.spring.initializr.actuate.info.DependencyRangesInfoContributor.java
private void contribute(Map<String, Object> details, Dependency d) { if (!ObjectUtils.isEmpty(d.getMappings())) { Map<String, VersionRange> dep = new LinkedHashMap<>(); d.getMappings().forEach((it) -> { if (it.getRange() != null && it.getVersion() != null) { dep.put(it.getVersion(), it.getRange()); }//from w w w.ja v a 2s . c o m }); if (!dep.isEmpty()) { if (d.getRange() == null) { boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null); if (!openRange) { Version higher = getHigher(dep); dep.put("managed", new VersionRange(higher)); } } Map<String, Object> depInfo = new LinkedHashMap<>(); dep.forEach((k, r) -> { depInfo.put(k, "Spring Boot " + r); }); details.put(d.getId(), depInfo); } } else if (d.getVersion() != null && d.getRange() != null) { Map<String, Object> dep = new LinkedHashMap<>(); String requirement = "Spring Boot " + d.getRange(); dep.put(d.getVersion(), requirement); details.put(d.getId(), dep); } }
From source file:org.opencb.opencga.storage.mongodb.variant.converters.DocumentToVariantAnnotationConverter.java
public Document convertToStorageType(Map<String, AdditionalAttribute> attributes) { Document document = new Document(); attributes.forEach((key, attribute) -> { document.put(key, convertToStorageType(attribute)); });// w w w . j a va 2s. c om return document; }
From source file:com.example.ekanban.service.ProductService.java
@Transactional public void sync(Boolean firstSync) { totalMonthyConsumption = 0L;/*from w w w .j a v a 2 s .c o m*/ commulativePercentage = 0.0; List<Product> products = productRepository.findAll(); Map<Long, PConsumption> consumptionMap = new HashedMap(); /*/////////Processing monthly consumption/////////*/ products.forEach(product -> { Long avgValue = consumptionRepository.findAvgConsumptionOfLastYear(product.getId()); consumptionMap.put(product.getId(), new PConsumption(product.getPrice().longValue() * avgValue)); totalMonthyConsumption += product.getPrice().longValue() * avgValue; }); //Sort on basis of consumption value descending Map<Long, PConsumption> sortedConsumptionMap = MiscUtil.sortByValueDesc(consumptionMap); //Calculate percentage contribution and commulative contribution sortedConsumptionMap.forEach((id, pConsumption) -> { double percent = (double) pConsumption.getMonthlyConsumption() / (double) totalMonthyConsumption; percent *= 100; pConsumption.setPercentage(percent); pConsumption.setCommulativePercentage(commulativePercentage + percent); commulativePercentage += percent; }); //Update product dynamically calculated values products.forEach(product -> { double cp = sortedConsumptionMap.get(product.getId()).getCommulativePercentage(); ClassType classType = cp <= 60 ? ClassType.CLASS_A : cp <= 80 ? ClassType.CLASS_B : ClassType.CLASS_C; product.setClassType(classType); ///////////////// KanbanType kanbanType = classType == ClassType.CLASS_A || classType == ClassType.CLASS_B ? KanbanType.N_BIN : KanbanType.TWO_BIN; product.setKanbanType(kanbanType); /////////////// Long maxValue = consumptionRepository.findMaxConsumptionOfLastYear(product.getId()); product.setDemand(maxValue / Constants.NO_OF_DAYS_IN_MONTH); /////////////////// long binQty = product.getDemand() > product.getMinOrderQty() ? product.getDemand() : product.getMinOrderQty(); if (product.getPacketSize().doubleValue() < 1.0) { binQty = (long) ((binQty / product.getPacketSize().doubleValue() + 1) * product.getPacketSize().doubleValue()); } else { binQty = (binQty / product.getPacketSize().longValue() + 1) * product.getPacketSize().longValue(); } product.setBinQty(binQty); int noOfBins = 2; if (classType != ClassType.CLASS_C) { int tat = product.getTimeOrdering() + product.getTimeProcurement() + product.getTimeTransporation() + product.getTimeBuffer(); noOfBins = (int) (product.getDemand() * tat / binQty + 2); } product.setNoOfBins(noOfBins); }); //Update Inventory if (firstSync) { User application = userRepository.findOne(1L); products.forEach(product -> { int noOfBins = product.getNoOfBins(); int binInStock = getNoOfBins(product.getStkOnFloor(), product.getBinQty()); Inventory inv = null; if (binInStock <= noOfBins) { //binInStock is less than NoOfBins, So add that number of bins in Stock for (int i = 0; i < binInStock; i++) { product.addInventory(new Inventory(i + 1, BinState.STORE)); } int binInOrder = getNoOfBins(product.getOrderedQty(), product.getBinQty()); if (binInStock + binInOrder <= noOfBins) { //binInStock+binInOrder is less than NoOfBins, So add binInOrder Bins in Ordered state StringBuilder builder = new StringBuilder(); for (int i = binInStock; i < binInStock + binInOrder; i++) { inv = new Inventory(i + 1, BinState.ORDERED); product.addInventory(inv); builder.append((i + 1)).append(","); } if (builder.length() >= 2) { builder.setLength(builder.length() - 1); orderRepository.save(new Order(product, builder.toString(), new Date(), application, OrderState.ORDERED.getValue())); } if (noOfBins - (binInStock + binInOrder) > 0) { //noOfBins - (binInStock + binInOrder) > 0, means this diff Bins are pending orders for (int i = binInStock + binInOrder; i < noOfBins; i++) { product.addInventory(new Inventory(i + 1, BinState.PURCHASE)); } } } else { //binInStock+binInOrder is greater than NoOfBins, So add (noOfBins - binInStock) Bins in Ordered state, and stop furhter processing StringBuilder builder = new StringBuilder(); for (int i = binInStock; i < noOfBins; i++) { product.addInventory(new Inventory(i + 1, BinState.ORDERED)); builder.append((i + 1)).append(","); } if (builder.length() >= 2) { builder.setLength(builder.length() - 1); orderRepository.save(new Order(product, builder.toString(), new Date(), application, OrderState.ORDERED.getValue())); } } } else { // //binInStock is greater than NoOfBins, So add noOfBins Bin in Stock and stop any further processing Since Stock is full for (int i = 0; i < noOfBins; i++) { product.addInventory(new Inventory(i + 1, BinState.STORE)); } } }); } else { products.forEach(product -> { int noOfInventory = product.getInventorySet().size(); //if inventory size for a product is less than no of bins, then no of bins got increased after sync. if (noOfInventory < product.getNoOfBins()) { for (int i = noOfInventory + 1; i <= product.getNoOfBins(); i++) { product.addInventory(new Inventory(i, BinState.PURCHASE)); } } }); } }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java
public DataSource getDatabase(String userName, String dbName, Map<String, String> properties) { final PGSimpleDataSource ds = new PGSimpleDataSource(); ds.setServerName("localhost"); ds.setPortNumber(port);/* w w w . java 2s . c o m*/ ds.setDatabaseName(dbName); ds.setUser(userName); properties.forEach((propertyKey, propertyValue) -> { try { ds.setProperty(propertyKey, propertyValue); } catch (SQLException e) { throw new RuntimeException(e); } }); return ds; }
From source file:org.finra.herd.dao.impl.IndexFunctionsDaoImpl.java
/** * The update index documents function will take as arguments the index name, document type, and a map of documents to update. The document map key is the * document id, and the value is the document as a JSON string. *//* w w w . j a va2s .c o m*/ @Override public final void updateIndexDocuments(String indexName, String documentType, Map<String, String> documentMap) { LOGGER.info("Updating Elasticsearch index documents, indexName={}, documentType={}.", indexName, documentType); List<String> allIndices = getAliases(indexName); allIndices.forEach((index) -> { // Prepare a bulk request builder Bulk.Builder bulkBuilder = new Bulk.Builder(); // For each document prepare an update request and add it to the bulk request builder documentMap.forEach((id, jsonString) -> { BulkableAction updateIndex = new Index.Builder(jsonString).index(index).type(documentType).id(id) .build(); bulkBuilder.addAction(updateIndex); }); // Execute the bulk update request JestResult jestResult = jestClientHelper.execute(bulkBuilder.build()); // If there are failures log them if (!jestResult.isSucceeded()) { LOGGER.error("Bulk response error = {}", jestResult.getErrorMessage()); } }); }
From source file:hydrograph.ui.graph.execution.tracking.utils.TrackingStatusUpdateUtils.java
/** * Update component status and processed record * @param executionStatus//www. j a v a 2 s . c o m * @param editor */ public void updateEditorWithCompStatus(ExecutionStatus executionStatus, ELTGraphicalEditor editor, boolean isReplay) { if (executionStatus != null) { /** * Push the tracking log in tracking console */ if (!isReplay) { pushExecutionStatusToExecutionTrackingConsole(executionStatus); ExecutionTrackingFileLogger.INSTANCE.log(executionStatus.getJobId(), executionStatus, JobManager.INSTANCE.isLocalMode()); ExecutionTrackingConsoleUtils.INSTANCE.readFile(executionStatus, null, JobManager.INSTANCE.isLocalMode()); } GraphicalViewer graphicalViewer = (GraphicalViewer) ((GraphicalEditor) editor) .getAdapter(GraphicalViewer.class); for (Iterator<EditPart> ite = graphicalViewer.getEditPartRegistry().values().iterator(); ite .hasNext();) { EditPart editPart = ite.next(); if (editPart instanceof ComponentEditPart) { Component component = ((ComponentEditPart) editPart).getCastedModel(); if (isReplay) { Map<String, String> componentNameAndLink = new HashMap(); if (Constants.SUBJOB_COMPONENT.equals(component.getComponentName())) { ViewExecutionHistoryUtility.INSTANCE.subjobParams(componentNameAndLink, component, new StringBuilder(component.getComponentId() + "."), true); componentNameAndLink.forEach((compId, compName) -> { ViewExecutionHistoryUtility.INSTANCE.addUnusedCompLabel(compId, compName); }); } } /** * Updating status and record count of subjob * component in main job. */ if (Constants.SUBJOB_COMPONENT.equals(component.getComponentName())) { if ((component.getProperties().get(Constants.TYPE).equals(Constants.INPUT) || component.getProperties().get(Constants.TYPE).equals(Constants.OPERATION))) { Map<String, SubjobDetails> componentNameAndLink = new HashMap(); StringBuilder subjobPrefix = new StringBuilder(""); populateSubjobRecordCount(componentNameAndLink, component, subjobPrefix, true); applyRecordCountOnSubjobComponent(component, componentNameAndLink, executionStatus); } updateStatusCountForSubjobComponent(executionStatus, component, isReplay); } else { updateStatusCountForComponent(executionStatus, component, isReplay); } } } } }