Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

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

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:com.uber.stream.kafka.mirrormaker.common.utils.HelixUtils.java

/**
 * From IdealStates.//w ww  . java  2s  . co m
 *
 * @return InstanceToNumTopicPartitionMap
 */
public static Map<String, Set<TopicPartition>> getInstanceToTopicPartitionsMap(HelixManager helixManager,
        Map<String, KafkaBrokerTopicObserver> clusterToObserverMap) {
    Map<String, Set<TopicPartition>> instanceToNumTopicPartitionMap = new HashMap<>();
    HelixAdmin helixAdmin = helixManager.getClusterManagmentTool();
    String helixClusterName = helixManager.getClusterName();
    for (String topic : helixAdmin.getResourcesInCluster(helixClusterName)) {
        IdealState is = helixAdmin.getResourceIdealState(helixClusterName, topic);
        for (String partition : is.getPartitionSet()) {
            TopicPartition tpi;
            if (partition.startsWith("@")) {
                // topic
                if (clusterToObserverMap != null) {
                    // TODO: topic not existed
                    try {
                        int trueNumPartition = clusterToObserverMap.get(getSrcFromRoute(partition))
                                .getTopicPartitionWithRefresh(topic).getPartition();
                        tpi = new TopicPartition(topic, trueNumPartition, partition);
                    } catch (Exception e) {
                        tpi = new TopicPartition(topic, -1, partition);
                    }
                } else {
                    tpi = new TopicPartition(topic, -1, partition);
                }
            } else {
                // route
                tpi = new TopicPartition(topic, Integer.parseInt(partition));
            }
            for (String instance : is.getInstanceSet(partition)) {
                instanceToNumTopicPartitionMap.putIfAbsent(instance, new HashSet<>());
                instanceToNumTopicPartitionMap.get(instance).add(tpi);
            }
        }
    }
    return instanceToNumTopicPartitionMap;
}

From source file:com.reprezen.swagedit.core.validation.Validator.java

protected void collectDuplicates(Node parent, Map<Pair<Node, String>, Set<Node>> acc) {
    switch (parent.getNodeId()) {
    case mapping: {
        for (NodeTuple value : ((MappingNode) parent).getValue()) {
            Node keyNode = value.getKeyNode();

            if (keyNode.getNodeId() == NodeId.scalar) {
                Pair<Node, String> key = Pair.of(parent, ((ScalarNode) keyNode).getValue());
                acc.putIfAbsent(key, new HashSet<>());
                acc.get(key).add(keyNode);
            }/*from ww  w  .  j  a va 2  s.  co m*/

            collectDuplicates(value.getValueNode(), acc);
        }
    }
        break;
    case sequence: {
        for (Node value : ((SequenceNode) parent).getValue()) {
            collectDuplicates(value, acc);
        }
    }
        break;
    default:
        break;
    }
}

From source file:io.hakbot.controller.plugin.RemoteInstanceAutoConfig.java

public Map<String, RemoteInstance> createMap(Plugin.Type pluginType, String pluginId) {
    LOGGER.info("Initializing instance properties");
    final Map<String, RemoteInstance> instanceMap = new HashMap<>();
    final String type = pluginType.name().toLowerCase();
    final String[] instances = StringUtils
            .split(Config.getInstance().getProperty(type + "." + pluginId + ".instances"), ",");
    if (instances == null) {
        LOGGER.info("Instances were not specified. Unable to autoconfigure.");
        return instanceMap;
    }/*ww  w  .j ava  2 s .c  o  m*/
    for (String instanceIdentifier : instances) {
        instanceIdentifier = instanceIdentifier.trim();
        final RemoteInstance instance = generateInstance(pluginType, pluginId, instanceIdentifier);
        instanceMap.putIfAbsent(instance.getAlias(), instance);
    }
    return instanceMap;
}

From source file:com.baifendian.swordfish.common.utils.graph.Graph.java

/**
 * ?/*from   ww w  .  j  av a 2  s  . c om*/
 *
 * @param start 
 * @param end   
 * @param edge  
 * @param edges ?
 */
private synchronized void addEdge(VK start, VK end, ED edge, Map<VK, Map<VK, ED>> edges) {
    edges.putIfAbsent(start, new HashMap<>());
    Map<VK, ED> endEdges = edges.get(start);
    endEdges.put(end, edge);
}

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.InputConverterXML.java

/**
 * Creates a map from a string representation: "KEY1=VALUE1,KEY2=VALUE2"
 *
 * @param setting/*from   ww w .  ja va 2  s .c  om*/
 * @return
 */
private Map<String, String> createMapFromSetting(String setting) {
    Map<String, String> map = new HashMap<>();

    if (!StringUtils.isEmpty(setting)) {
        String[] entries = setting.split(","); // will contain KEY=VALUE entires
        for (String entry : entries) {
            String[] keyValue = entry.split("="); // split the KEY=VALUE string
            if (keyValue.length != 2) {
                logger.warn("Invalid setting: {} entry: {} - KEY=VALUE format was expected", setting, entry);
            } else {
                String key = keyValue[0];
                String value = keyValue[1];

                if (map.putIfAbsent(key, value) != null) {
                    logger.warn("Invalid setting: {} entry: {} - key: {} was already provided before", setting,
                            entry, key);
                }
            }
        }
    }
    return map;
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/book", method = RequestMethod.GET)
public String showPaymentPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        //paypal related parameters
        @RequestParam(value = "paymentId", required = false) String paypalPaymentId,
        @RequestParam(value = "PayerID", required = false) String paypalPayerID,
        @RequestParam(value = "paypal-success", required = false) Boolean isPaypalSuccess,
        @RequestParam(value = "paypal-error", required = false) Boolean isPaypalError,
        @RequestParam(value = "fullName", required = false) String fullName,
        @RequestParam(value = "firstName", required = false) String firstName,
        @RequestParam(value = "lastName", required = false) String lastName,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "billingAddress", required = false) String billingAddress,
        @RequestParam(value = "hmac", required = false) String hmac,
        @RequestParam(value = "postponeAssignment", required = false) Boolean postponeAssignment, Model model,
        Locale locale) {//from   ww  w. j  a  va2 s . c  o  m

    return eventRepository.findOptionalByShortName(eventName)
            .map(event -> ticketReservationManager.findById(reservationId).map(reservation -> {

                if (reservation.getStatus() != TicketReservationStatus.PENDING) {
                    return redirectReservation(Optional.of(reservation), eventName, reservationId);
                }

                List<Ticket> ticketsInReservation = ticketReservationManager
                        .findTicketsInReservation(reservationId);
                if (Boolean.TRUE.equals(isPaypalSuccess) && paypalPayerID != null && paypalPaymentId != null) {
                    model.addAttribute("paypalPaymentId", paypalPaymentId)
                            .addAttribute("paypalPayerID", paypalPayerID)
                            .addAttribute("paypalCheckoutConfirmation", true).addAttribute("fullName", fullName)
                            .addAttribute("firstName", firstName).addAttribute("lastName", lastName)
                            .addAttribute("email", email).addAttribute("billingAddress", billingAddress)
                            .addAttribute("hmac", hmac)
                            .addAttribute("postponeAssignment", Boolean.TRUE.equals(postponeAssignment))
                            .addAttribute("showPostpone", Boolean.TRUE.equals(postponeAssignment));
                } else {
                    model.addAttribute("paypalCheckoutConfirmation", false)
                            .addAttribute("postponeAssignment", false)
                            .addAttribute("showPostpone", ticketsInReservation.size() > 1);
                }

                try {
                    model.addAttribute("delayForOfflinePayment", Math.max(1, TicketReservationManager
                            .getOfflinePaymentWaitingPeriod(event, configurationManager)));
                } catch (TicketReservationManager.OfflinePaymentException e) {
                    if (event.getAllowedPaymentProxies().contains(PaymentProxy.OFFLINE)) {
                        log.error("Already started event {} has been found with OFFLINE payment enabled",
                                event.getDisplayName(), e);
                    }
                    model.addAttribute("delayForOfflinePayment", 0);
                }

                OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId,
                        event, locale);
                List<PaymentProxy> activePaymentMethods = paymentManager
                        .getPaymentMethods(event.getOrganizationId()).stream()
                        .filter(p -> TicketReservationManager.isValidPaymentMethod(p, event,
                                configurationManager))
                        .map(PaymentManager.PaymentMethod::getPaymentProxy).collect(toList());

                if (orderSummary.getFree() || activePaymentMethods.stream()
                        .anyMatch(p -> p == PaymentProxy.OFFLINE || p == PaymentProxy.ON_SITE)) {
                    boolean captchaForOfflinePaymentEnabled = configurationManager
                            .isRecaptchaForOfflinePaymentEnabled(event);
                    model.addAttribute("captchaRequestedForOffline", captchaForOfflinePaymentEnabled)
                            .addAttribute("recaptchaApiKey",
                                    configurationManager.getStringConfigValue(
                                            Configuration.getSystemConfiguration(RECAPTCHA_API_KEY), null))
                            .addAttribute("captchaRequestedFreeOfCharge",
                                    orderSummary.getFree() && captchaForOfflinePaymentEnabled);
                }

                boolean invoiceAllowed = configurationManager.hasAllConfigurationsForInvoice(event)
                        || vatChecker.isVatCheckingEnabledFor(event.getOrganizationId());
                PaymentForm paymentForm = PaymentForm.fromExistingReservation(reservation);
                model.addAttribute("multiplePaymentMethods", activePaymentMethods.size() > 1)
                        .addAttribute("orderSummary", orderSummary).addAttribute("reservationId", reservationId)
                        .addAttribute("reservation", reservation)
                        .addAttribute("pageTitle", "reservation-page.header.title").addAttribute("event", event)
                        .addAttribute("activePaymentMethods", activePaymentMethods)
                        .addAttribute("expressCheckoutEnabled", isExpressCheckoutEnabled(event, orderSummary))
                        .addAttribute("useFirstAndLastName", event.mustUseFirstAndLastName())
                        .addAttribute("countries", TicketHelper.getLocalizedCountries(locale))
                        .addAttribute("euCountries",
                                TicketHelper.getLocalizedEUCountries(locale,
                                        configurationManager.getRequiredValue(
                                                getSystemConfiguration(ConfigurationKeys.EU_COUNTRIES_LIST))))
                        .addAttribute("euVatCheckingEnabled",
                                vatChecker.isVatCheckingEnabledFor(event.getOrganizationId()))
                        .addAttribute("invoiceIsAllowed", invoiceAllowed)
                        .addAttribute("vatNrIsLinked",
                                orderSummary.isVatExempt() || paymentForm.getHasVatCountryCode())
                        .addAttribute("billingAddressLabel", invoiceAllowed ? "reservation-page.billing-address"
                                : "reservation-page.receipt-address");

                boolean includeStripe = !orderSummary.getFree()
                        && activePaymentMethods.contains(PaymentProxy.STRIPE);
                model.addAttribute("includeStripe", includeStripe);
                if (includeStripe) {
                    model.addAttribute("stripe_p_key", paymentManager.getStripePublicKey(event));
                }
                Map<String, Object> modelMap = model.asMap();
                modelMap.putIfAbsent("paymentForm", paymentForm);
                modelMap.putIfAbsent("hasErrors", false);

                boolean hasPaidSupplement = ticketReservationManager.hasPaidSupplements(reservationId);
                model.addAttribute("ticketsByCategory", ticketsInReservation.stream()
                        .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream().map((e) -> {
                            TicketCategory category = eventManager.getTicketCategoryById(e.getKey(),
                                    event.getId());
                            List<TicketDecorator> decorators = TicketDecorator
                                    .decorate(e.getValue(),
                                            !hasPaidSupplement && configurationManager.getBooleanConfigValue(
                                                    Configuration.from(event.getOrganizationId(), event.getId(),
                                                            category.getId(), ALLOW_FREE_TICKETS_CANCELLATION),
                                                    false),
                                            eventManager.checkTicketCancellationPrerequisites(),
                                            ticket -> ticketHelper.findTicketFieldConfigurationAndValue(
                                                    event.getId(), ticket, locale),
                                            true, (t) -> "tickets['" + t.getUuid() + "'].");
                            return Pair.of(category, decorators);
                        }).collect(toList()));
                return "/event/reservation-page";
            }).orElseGet(() -> redirectReservation(Optional.empty(), eventName, reservationId)))
            .orElse("redirect:/");
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.CommonSF424BaseGenerator.java

/**
  * This method returns a map containing the answers related to EOState REview for a given proposal
  *//w  ww  .  ja  va  2s  .  co m
  * @param pdDoc Proposal Development Document.
  * @return Map&lt;String, String&gt; map containing the answers related to EOState Review for a given proposal.
  */
public Map<String, String> getEOStateReview(ProposalDevelopmentDocumentContract pdDoc) {
    Map<String, String> stateReview = new HashMap<>();
    List<? extends AnswerHeaderContract> answerHeaders = propDevQuestionAnswerService
            .getQuestionnaireAnswerHeaders(pdDoc.getDevelopmentProposal().getProposalNumber());
    if (!answerHeaders.isEmpty()) {
        for (AnswerContract answers : answerHeaders.get(0).getAnswers()) {
            Integer questionSeqId = getQuestionAnswerService().findQuestionById(answers.getQuestionId())
                    .getQuestionSeqId();
            if (questionSeqId != null && questionSeqId.equals(PROPOSAL_YNQ_QUESTION_129)) {
                stateReview.putIfAbsent(YNQ_ANSWER, answers.getAnswer());
            }
            if (questionSeqId != null && questionSeqId.equals(PROPOSAL_YNQ_QUESTION_130)) {
                stateReview.putIfAbsent(YNQ_REVIEW_DATE, answers.getAnswer());
            }
            if (questionSeqId != null && questionSeqId.equals(PROPOSAL_YNQ_QUESTION_131)) {
                stateReview.putIfAbsent(YNQ_STATE_REVIEW_DATA, answers.getAnswer());
            }
        }
    }
    // If question is not answered or question is inactive
    if (stateReview.size() == 0) {
        stateReview.put(YNQ_ANSWER, YNQ_NOT_REVIEWED);
        stateReview.put(YNQ_REVIEW_DATE, null);
    }
    return stateReview;
}

From source file:org.onosproject.drivers.odtn.InfineraOpenConfigDeviceDiscovery.java

/**
 * Converts Component subtree to PortDescription.
 *
 * @param component subtree to parse/*  w  w w.j a  v a  2 s.c  om*/
 * @return PortDescription or null if component is not an ONOS Port
 */
private PortDescription toPortDescriptionInternal(HierarchicalConfiguration component) {

    // to access other part of <data> tree:
    //log.warn("parent data Node: {}",
    //       ((SubnodeConfiguration) component).getParent().getRootNode().getName());

    String name = component.getString("name");
    checkNotNull(name);
    if (!name.contains("GIGECLIENTCTP")) {
        return null;
    }

    Builder builder = DefaultPortDescription.builder();

    Map<String, String> props = new HashMap<>();
    props.put(OdtnDeviceDescriptionDiscovery.OC_NAME, name);
    props.put(OdtnDeviceDescriptionDiscovery.OC_TYPE, name);

    Pattern clientPattern = Pattern.compile("GIGECLIENTCTP.1-A-2-T(\\d+)");
    Pattern linePattern = Pattern.compile("GIGECLIENTCTP.1-L(\\d+)-1-1");
    Matcher clientMatch = clientPattern.matcher(name);
    Matcher lineMatch = linePattern.matcher(name);

    if (clientMatch.find()) {
        String num = clientMatch.group(1);
        Integer connection = (Integer.parseInt(num) + 1) / 2;
        props.putIfAbsent(PORT_TYPE, OdtnPortType.CLIENT.value());
        props.putIfAbsent(CONNECTION_ID, "connection:" + connection.toString());
        builder.withPortNumber(PortNumber.portNumber(Long.parseLong(num), name));
        builder.type(Type.PACKET);
    } else if (lineMatch.find()) {
        String num = lineMatch.group(1);
        props.putIfAbsent(PORT_TYPE, OdtnPortType.LINE.value());
        props.putIfAbsent(CONNECTION_ID, "connection:" + num);
        builder.withPortNumber(PortNumber.portNumber(100 + Long.parseLong(num), name));
        builder.type(Type.OCH);
    } else {
        return null;
    }

    builder.annotations(DefaultAnnotations.builder().putAll(props).build());
    return builder.build();

}

From source file:org.springframework.boot.actuate.endpoint.annotation.AnnotationEndpointDiscoverer.java

private void addEndpoint(Map<Class<?>, DiscoveredEndpoint> endpoints,
        Map<String, DiscoveredEndpoint> endpointsById, String beanName) {
    Class<?> endpointType = this.applicationContext.getType(beanName);
    Object target = this.applicationContext.getBean(beanName);
    DiscoveredEndpoint endpoint = createEndpoint(target, endpointType);
    String id = endpoint.getInfo().getId();
    DiscoveredEndpoint previous = endpointsById.putIfAbsent(id, endpoint);
    Assert.state(previous == null,/*  w  w  w .  j  a  v  a  2  s.c o  m*/
            () -> "Found two endpoints with the id '" + id + "': " + endpoint + " and " + previous);
    endpoints.put(endpointType, endpoint);
}