Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

In this page you can find the example usage for java.util Map forEach.

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:org.onosproject.bmv2.demo.app.wcmp.WcmpFabricApp.java

@Override
public List<FlowRule> generateLeafRules(DeviceId deviceId, Host srcHost, Collection<Host> dstHosts,
        Collection<DeviceId> availableSpines, Topology topo) throws FlowRuleGeneratorException {

    Set<PortNumber> hostPortNumbers = Sets.newHashSet();
    Set<PortNumber> fabricPortNumbers = Sets.newHashSet();
    deviceService.getPorts(deviceId)/*from   w w w  .ja  v a2  s  . c  o  m*/
            .forEach(p -> (isFabricPort(p, topo) ? fabricPortNumbers : hostPortNumbers).add(p.number()));

    if (hostPortNumbers.size() != 1 || fabricPortNumbers.size() == 0) {
        log.error("Leaf switch has invalid port configuration: hostPorts={}, fabricPorts={}",
                hostPortNumbers.size(), fabricPortNumbers.size());
        throw new FlowRuleGeneratorException();
    }
    PortNumber hostPort = hostPortNumbers.iterator().next();

    TopologyGraph graph = topologyService.getGraph(topo);
    // Map key: spine device id, value: leaf switch ports which connect to spine in the key.
    Map<DeviceId, Set<PortNumber>> spineToPortsMap = Maps.newHashMap();
    graph.getEdgesFrom(new DefaultTopologyVertex(deviceId)).forEach(edge -> {
        spineToPortsMap.putIfAbsent(edge.dst().deviceId(), Sets.newHashSet());
        spineToPortsMap.get(edge.dst().deviceId()).add(edge.link().src().port());
    });

    double baseWeight = 1d / spineToPortsMap.size();

    int numSinglePorts = (int) spineToPortsMap.values().stream().filter(s -> s.size() == 1).count();
    int numMultiPorts = spineToPortsMap.size() - numSinglePorts;

    // Reduce weight portion assigned to multi-ports to mitigate flow assignment imbalance (measured empirically).
    double multiPortBaseWeight = baseWeight * MULTI_PORT_WEIGHT_COEFFICIENT;
    double excess = (baseWeight - multiPortBaseWeight) * numMultiPorts;
    double singlePortBaseWeight = baseWeight + (excess / numSinglePorts);

    Map<PortNumber, Double> weighedPortNumbers = Maps.newHashMap();
    spineToPortsMap.forEach((did, portSet) -> {
        double base = (portSet.size() == 1) ? singlePortBaseWeight : multiPortBaseWeight;
        double weight = base / portSet.size();
        portSet.forEach(portNumber -> weighedPortNumbers.put(portNumber, weight));
    });

    List<FlowRule> rules = Lists.newArrayList();

    Pair<ExtensionTreatment, List<FlowRule>> result = provisionWcmpTreatment(deviceId, weighedPortNumbers);
    ExtensionTreatment wcmpTreatment = result.getLeft();
    rules.addAll(result.getRight());

    // From src host to dst hosts, WCMP to all fabric ports.
    for (Host dstHost : dstHosts) {
        FlowRule rule = flowRuleBuilder(deviceId, TABLE0)
                .withSelector(DefaultTrafficSelector.builder().matchInPort(hostPort)
                        .matchEthType(IPV4.ethType().toShort()).matchEthSrc(srcHost.mac())
                        .matchEthDst(dstHost.mac()).build())
                .withTreatment(DefaultTrafficTreatment.builder().extension(wcmpTreatment, deviceId).build())
                .build();
        rules.add(rule);
    }

    // From fabric ports to src host.
    for (PortNumber port : fabricPortNumbers) {
        FlowRule rule = flowRuleBuilder(deviceId, TABLE0)
                .withSelector(DefaultTrafficSelector.builder().matchInPort(port)
                        .matchEthType(IPV4.ethType().toShort()).matchEthDst(srcHost.mac()).build())
                .withTreatment(DefaultTrafficTreatment.builder().setOutput(hostPort).build()).build();
        rules.add(rule);
    }

    return rules;
}

From source file:femr.business.services.system.MedicationService.java

/**
 * {@inheritDoc}//from   w  ww  .  jav  a2 s  . c  o m
 */
@Override
public ServiceResponse<List<PrescriptionItem>> replacePrescriptions(Map<Integer, Integer> prescriptionPairs) {

    ServiceResponse<List<PrescriptionItem>> response = new ServiceResponse<>();
    List<PrescriptionItem> prescriptionItems = new ArrayList<>();
    List<IPatientPrescriptionReplacement> patientPrescriptionReplacements = new ArrayList<>();

    //get the reason for replacing
    ExpressionList<PatientPrescriptionReplacementReason> replacementReasonExpressionList = QueryProvider
            .getPatientPrescriptionReasonQuery().where().eq("name", "pharmacist replacement");
    IPatientPrescriptionReplacementReason patientPrescriptionReplacementReason = patientPrescriptionReplacementReasonRepository
            .findOne(replacementReasonExpressionList);

    //iterate over each prescription and its replacement
    prescriptionPairs.forEach((newId, oldId) -> {

        ExpressionList<PatientPrescription> newPrescriptionExpressionList = QueryProvider
                .getPatientPrescriptionQuery().where().eq("id", newId);

        ExpressionList<PatientPrescription> replacedPrescriptionExpressionList = QueryProvider
                .getPatientPrescriptionQuery().where().eq("id", oldId);

        try {
            IPatientPrescription newPrescription = patientPrescriptionRepository
                    .findOne(newPrescriptionExpressionList);
            IPatientPrescription replacedPrescription = patientPrescriptionRepository
                    .findOne(replacedPrescriptionExpressionList);

            if (newPrescription == null) {

                response.addError("not found", "new prescription with id: " + newId + " not found.");
            } else if (replacedPrescription == null) {

                response.addError("not found", "old prescription with id: " + oldId + " not found.");
            } else {
                patientPrescriptionReplacements
                        .add(dataModelMapper.createPatientPrescriptionReplacement(replacedPrescription.getId(),
                                newPrescription.getId(), patientPrescriptionReplacementReason.getId()));

            }

        } catch (Exception ex) {

            response.addError("", ex.getMessage());
        }
    });

    try {

        List<? extends IPatientPrescriptionReplacement> replacements = patientPrescriptionReplacementRepository
                .createAll(patientPrescriptionReplacements);
        for (IPatientPrescriptionReplacement prescriptionReplacement : replacements) {

            prescriptionItems.add(itemModelMapper.createPrescriptionItem(
                    prescriptionReplacement.getReplacementPrescription().getId(),
                    prescriptionReplacement.getReplacementPrescription().getMedication().getName(), null,
                    prescriptionReplacement.getReplacementPrescription().getPhysician().getFirstName(),
                    prescriptionReplacement.getReplacementPrescription().getPhysician().getLastName(),
                    prescriptionReplacement.getReplacementPrescription().getConceptPrescriptionAdministration(),
                    prescriptionReplacement.getReplacementPrescription().getAmount(),
                    prescriptionReplacement.getReplacementPrescription().getMedication(), null,
                    prescriptionReplacement.getReplacementPrescription().isCounseled()));
        }
    } catch (Exception ex) {

        response.addError("", ex.getMessage());
    }

    response.setResponseObject(prescriptionItems);

    return response;
}

From source file:com.idrene.emefana.repositories.RepositoriesTest.java

public void saveServicesTest() {
    offeringTypeRepository.deleteAll();//from   w ww  .  ja  v a 2  s  . c o  m
    Map<String, Set<ProviderType>> servicesMap = new HashMap<>();

    List<String> typesRandom = Arrays.asList("precede", "deliver", "rampant", "lewd", "lunch", "great",
            "contain", "offer", "screw", "handsomely", "snobbish", "flashy", "pencil", "man", "squeal", "shelf",
            "wound", "moon", "optimal", "carry");

    int randomsize = typesRandom.size();
    typesRandom.forEach(service -> servicesMap.put(service, new HashSet<>()));

    List<ProviderType> pTypes = providerTypeRepository.findAll();
    pTypes.forEach(type -> {
        int randomApp = 1 + (int) (Math.random() * 10);
        while (randomApp > 0) {
            int randomCatNumber = (int) (Math.random() * randomsize);
            String serv = typesRandom.get(randomCatNumber);
            servicesMap.get(serv).add(type);
            randomApp--;
        }
    });

    servicesMap.forEach((key, value) -> offeringTypeRepository.save(new ServiceOffering(key, value)));
    List<ServiceOffering> offerings = offeringTypeRepository.findAll();
    assertNotNull(offerings);
    assertTrue(randomsize == offerings.size());
}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.cnw.CNWConverter.java

private void convertPersons(Map<String, Map<String, String>> listMaps) throws Exception {
    Progress progress = new Progress();
    PrintWriter out = createPrintWriter(CNWPerson.class);
    //    Set<RelationDTO> knownRelations = Sets.newHashSet();
    Map<String, String> shortDescriptionMap = Maps.newHashMap();
    try {//from w  w w.  j ava2s. c  o  m
        Collection<File> files = FileUtils.listFiles(inputDir, TEI_EXTENSIONS, false);
        for (File file : Sets.newTreeSet(files)) {
            progress.step();
            String fileName = file.getName();
            log(".. %s%n", fileName);
            String xml = Files.readTextFromFile(file);
            //      LOG.info("xml={}", xml);
            String pid = "cnw:pers:" + fileName.replace(".xml", "");
            PersonContext personContext = new PersonContext(pid);
            Visitor visitor = new PersonVisitor(personContext, listMaps);
            Document.createFromXml(xml).accept(visitor);
            CNWPerson person = personContext.person;
            koppelnaam2pid.put(person.getKoppelnaam(), person.getId());
            jsonConverter.appendTo(out, person);
            shortDescriptionMap.put(person.getKoppelnaam(), person.getShortDescription());
        }
        out.close();

        File personDescription = new File("import/CNW/person-short_description.csv");
        FileUtils.write(personDescription, "koppelnaam;korte_omschrijving\n", false);
        shortDescriptionMap.forEach((koppelnaam, description) -> {
            CharSequence data = StringEscapeUtils.escapeCsv(koppelnaam) + ";"
                    + StringEscapeUtils.escapeCsv(description) + "\n";
            try {
                FileUtils.write(personDescription, data, true);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });

    } finally {
        out.close();
        progress.done();
    }
}

From source file:org.springframework.integration.support.json.EmbeddedJsonHeadersMessageMapper.java

@Nullable
private Message<?> decodeNativeFormat(byte[] bytes, @Nullable Map<String, Object> headersToAdd)
        throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    if (buffer.remaining() > 4) {
        int headersLen = buffer.getInt();
        if (headersLen >= 0 && headersLen < buffer.remaining() - 4) {
            buffer.position(headersLen + 4);
            int payloadLen = buffer.getInt();
            if (payloadLen != buffer.remaining()) {
                return null;
            } else {
                buffer.position(4);/* w  ww .j av a 2 s .c  o  m*/
                @SuppressWarnings("unchecked")
                Map<String, Object> headers = this.objectMapper.readValue(bytes, buffer.position(), headersLen,
                        HashMap.class);

                buffer.position(buffer.position() + headersLen);
                buffer.getInt();
                Object payload;
                byte[] payloadBytes = new byte[payloadLen];
                buffer.get(payloadBytes);
                payload = payloadBytes;

                if (headersToAdd != null) {
                    headersToAdd.forEach(headers::putIfAbsent);
                }

                return new GenericMessage<>(payload, new MutableMessageHeaders(headers));
            }
        }
    }
    return null;
}

From source file:io.swagger.v3.parser.converter.SwaggerConverter.java

private List<io.swagger.v3.oas.models.security.SecurityRequirement> convertSecurityRequirementsMap(
        List<Map<String, List<String>>> security) {
    List<io.swagger.v3.oas.models.security.SecurityRequirement> securityRequirements = new ArrayList<>();

    //        for (SecurityRequirement requirement : security) {
    //            io.swagger.v3.oas.models.security.SecurityRequirement securityRequirement = new io.swagger.v3.oas.models.security.SecurityRequirement();
    ////from w w w  . jav  a  2  s.c  om
    //            requirement.getRequirements().forEach((k,v) -> securityRequirement.addList(k, v));
    //
    //            securityRequirements.add(securityRequirement);
    //        }

    for (Map<String, List<String>> map : security) {
        io.swagger.v3.oas.models.security.SecurityRequirement securityRequirement = new io.swagger.v3.oas.models.security.SecurityRequirement();

        map.forEach((k, v) -> securityRequirement.addList(k, v));

        securityRequirements.add(securityRequirement);
    }

    return securityRequirements;
}

From source file:io.druid.query.lookup.LookupReferencesManager.java

/**
 * Returns a list of lookups from the coordinator if the coordinator is available. If it's not available, returns null.
 *
 * @param tier lookup tier name/* w  w  w .  j  a  v a2 s .  c o  m*/
 *
 * @return list of LookupBean objects, or null
 */
@Nullable
private List<LookupBean> getLookupListFromCoordinator(String tier) {
    try {
        MutableBoolean firstAttempt = new MutableBoolean(true);
        Map<String, LookupExtractorFactoryContainer> lookupMap = RetryUtils.retry(() -> {
            if (firstAttempt.isTrue()) {
                firstAttempt.setValue(false);
            } else {
                // Adding an extra minute in addition to the retry wait. In RetryUtils, retry wait starts from a few
                // seconds, that is likely not enough to coordinator to be back to healthy state, e. g. if it experiences
                // 30-second GC pause.
                Thread.sleep(60_000);
            }
            return tryGetLookupListFromCoordinator(tier);
        }, e -> true, lookupConfig.getCoordinatorFetchRetries());
        if (lookupMap != null) {
            List<LookupBean> lookupBeanList = new ArrayList<>();
            lookupMap.forEach((k, v) -> lookupBeanList.add(new LookupBean(k, null, v)));
            return lookupBeanList;
        } else {
            return null;
        }
    } catch (Exception e) {
        LOG.error(e, "Error while trying to get lookup list from coordinator for tier[%s]", tier);
        return null;
    }
}

From source file:com.melusyn.sendgrid.SendGridMod.java

public void sendEmailV2(Message<JsonObject> message) {
    SendGridRequestV2 request;/*  ww w.  ja  v  a 2s. c o m*/
    try {
        request = jsonMapper.readValue(message.body().encode(), SendGridRequestV2.class);
    } catch (IOException e) {
        logger.error(e);
        message.fail(400, e.getMessage());
        return;
    }

    if (request.getRecipients() == null || request.getRecipients().isEmpty()) {
        String errorMessage = "Your request has no recipient. It must at least have one recipient";
        logger.error(errorMessage);
        message.fail(400, errorMessage);
        return;
    }

    Email email = new Email();

    if (request.getTemplateId() != null) {
        email.addFilter("templates", "template_id", request.getTemplateId());
    }

    email.setFrom(request.getFrom());
    email.setFromName(request.getFromName());
    email.setSubject(request.getSubject());

    if (request.getCcs() != null) {
        request.getCcs().forEach(recipient -> email.addCc(recipient.getEmail()));
    }

    if (request.getBccs() != null) {
        request.getBccs().forEach(recipient -> email.addBcc(recipient.getEmail()));
    }

    if (request.getReplyTo() != null) {
        email.setReplyTo(request.getReplyTo());
    }

    if (request.getSections() != null) {
        request.getSections().forEach(email::addSection);
    }

    if (request.getBodyAsHtml()) {
        email.setHtml(request.getBody());
    }
    email.setText(request.getBody());

    Map<String, List<String>> substitutions = new HashMap<>();
    request.getRecipients().forEach(recipient -> {
        email.addTo(recipient.getEmail(), recipient.getFullName());

        if (recipient.getSubstitutions() != null) {
            recipient.getSubstitutions().forEach((name, value) -> {
                List<String> substitution = substitutions.get(name);
                if (substitution == null) {
                    substitution = new ArrayList<>();
                    substitutions.put(name, substitution);
                }
                substitution.add(value);
            });
        }
    });

    if (request.getAttachments() != null) {
        request.getAttachments().forEach((name, attachment) -> {
            try {
                email.addAttachment(name, new ByteArrayInputStream(attachment));
            } catch (IOException ignored) {
                logger.error("Michel owes a beer to Hugo.", ignored);
            }
        });
    }

    substitutions.forEach((key, list) -> email.addSubstitution(key, list.toArray(new String[list.size()])));

    int suppressionGroupId = templateSuppressionGroup.getOrDefault(request.getTemplateId(), 0);
    if (suppressionGroupId != 0) {
        email.setASMGroupId(suppressionGroupId);
    }

    request.getContext().forEach(email::addUniqueArg);

    String uuid = UUID.randomUUID().toString();
    email.addUniqueArg(MELUSYN_MAIL_ID, uuid);
    email.addUniqueArg("HOSTNAME", hostname);

    try {
        Response response = sendgrid.send(email);
        if (response.getCode() != 200) {
            JsonObject emailJson = new JsonObject(jsonMapper.writeValueAsString(request));
            logger.error("SendGrid failed and responded with : " + response.getCode() + " - "
                    + response.getMessage() + " with email:" + emailJson.encodePrettily());
            message.fail(500, response.getMessage());
            logger.warn(message.body().encodePrettily());
            return;
        }

        JsonObject jResponse = SendGridResponse.instance().code(response.getCode())
                .message(response.getMessage()).status(response.getStatus()).toJson();

        logger.debug("SendGrid successfully responded with : " + jResponse.encode());
        message.reply(jResponse);

    } catch (Exception e) {
        logger.error(e, e);
        message.fail(500, e.getMessage());
    }
}

From source file:org.corpus_tools.graphannis.SaltExport.java

private static void recreateText(final String name, List<SNode> rootNodes, final SDocumentGraph g) {
    final StringBuilder text = new StringBuilder();
    final STextualDS ds = g.createTextualDS("");

    ds.setName(name);//from   w  w  w .  ja v  a2s  . c om

    Map<SToken, Range<Integer>> token2Range = new HashMap<>();

    // traverse the token chain using the order relations
    g.traverse(rootNodes, SGraph.GRAPH_TRAVERSE_TYPE.TOP_DOWN_DEPTH_FIRST, "ORDERING_" + name,
            new GraphTraverseHandler() {
                @Override
                public void nodeReached(SGraph.GRAPH_TRAVERSE_TYPE traversalType, String traversalId,
                        SNode currNode, SRelation<SNode, SNode> relation, SNode fromNode, long order) {
                    if (fromNode != null) {
                        text.append(" ");
                    }

                    SFeature featTok = currNode.getFeature("annis::tok");
                    if (featTok != null && currNode instanceof SToken) {
                        int idxStart = text.length();
                        text.append(featTok.getValue_STEXT());
                        token2Range.put((SToken) currNode, Range.closed(idxStart, text.length()));
                    }
                }

                @Override
                public void nodeLeft(SGraph.GRAPH_TRAVERSE_TYPE traversalType, String traversalId,
                        SNode currNode, SRelation<SNode, SNode> relation, SNode fromNode, long order) {
                }

                @Override
                public boolean checkConstraint(SGraph.GRAPH_TRAVERSE_TYPE traversalType, String traversalId,
                        SRelation relation, SNode currNode, long order) {
                    if (relation == null) {
                        // TODO: check if this is ever true
                        return true;
                    } else if (relation instanceof SOrderRelation && Objects.equal(name, relation.getType())) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });

    // update the actual text
    ds.setText(text.toString());

    // add all relations

    token2Range.forEach((t, r) -> {
        STextualRelation rel = SaltFactory.createSTextualRelation();
        rel.setSource(t);
        rel.setTarget(ds);
        rel.setStart(r.lowerEndpoint());
        rel.setEnd(r.upperEndpoint());
        g.addRelation(rel);
    });
}

From source file:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.java

/**
 * Look for handler methods in a handler.
 * @param handler the bean name of a handler or a handler instance
 *///  www  .j a va2  s  .com
protected void detectHandlerMethods(final Object handler) {
    Class<?> handlerType = (handler instanceof String ? obtainApplicationContext().getType((String) handler)
            : handler.getClass());

    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> {
                    try {
                        return getMappingForMethod(method, userType);
                    } catch (Throwable ex) {
                        throw new IllegalStateException(
                                "Invalid mapping on handler class [" + userType.getName() + "]: " + method, ex);
                    }
                });
        if (logger.isTraceEnabled()) {
            logger.trace("Mapped " + methods.size() + " handler method(s) for " + userType + ": " + methods);
        }
        methods.forEach((method, mapping) -> {
            Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
            registerHandlerMethod(handler, invocableMethod, mapping);
        });
    }
}