Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

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

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:alfio.controller.api.admin.EventApiController.java

@RequestMapping("/events/{eventName}/sponsor-scan/export.csv")
public void downloadSponsorScanExport(@PathVariable("eventName") String eventName, HttpServletResponse response,
        Principal principal) throws IOException {
    Event event = loadEvent(eventName, principal);
    List<TicketFieldConfiguration> fields = ticketFieldRepository.findAdditionalFieldsForEvent(event.getId());

    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-sponsor-scan.csv");

    try (ServletOutputStream out = response.getOutputStream();
            CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
        for (int marker : BOM_MARKERS) {
            out.write(marker);// w w w.  ja va 2 s .c  o m
        }

        List<String> header = new ArrayList<>();
        header.add("Username");
        header.add("Timestamp");
        header.add("Full name");
        header.add("Email");
        header.addAll(fields.stream().map(TicketFieldConfiguration::getName).collect(toList()));
        writer.writeNext(header.toArray(new String[header.size()]));
        userManager.findAllEnabledUsers(principal.getName()).stream()
                .map(u -> Pair.of(u, userManager.getUserRole(u))).filter(p -> p.getRight() == Role.SPONSOR)
                .flatMap(p -> sponsorScanRepository
                        .loadSponsorData(
                                event.getId(), p.getKey().getId(), SponsorScanRepository.DEFAULT_TIMESTAMP)
                        .stream()
                        .map(v -> Pair.of(v,
                                ticketFieldRepository.findAllValuesForTicketId(v.getTicket().getId()))))
                .map(p -> {
                    DetailedScanData data = p.getLeft();
                    Map<String, String> descriptions = p.getRight();
                    return Pair.of(data, fields.stream().map(x -> descriptions.getOrDefault(x.getName(), ""))
                            .collect(toList()));
                }).map(p -> {
                    List<String> line = new ArrayList<>();
                    Ticket ticket = p.getLeft().getTicket();
                    SponsorScan sponsorScan = p.getLeft().getSponsorScan();
                    line.add(userManager.findUser(sponsorScan.getUserId()).getUsername());
                    line.add(sponsorScan.getTimestamp().toString());
                    line.add(ticket.getFullName());
                    line.add(ticket.getEmail());
                    line.addAll(p.getRight());
                    return line.toArray(new String[line.size()]);
                }).forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

@SuppressWarnings("unchecked")
private List<Argument> getArgumentsFromDoStep(Map<String, Serializable> preStepData) {
    return (List<Argument>) preStepData.getOrDefault(DO_EXTERNAL_KEY, preStepData.get(DO_KEY));
}

From source file:com.ggvaidya.scinames.summary.HigherStabilityView.java

private void generateHigherTaxonomyList(String higherTaxonomyColName) {
    Project project = projectView.getProject();
    DatasetColumn GENUS = DatasetColumn.fakeColumnFor("genus");
    DatasetColumn column;/* w w  w  .j a va2  s  . c  o  m*/

    if (higherTaxonomyColName.equals(""))
        column = GENUS;
    else if (datasetColumns.contains(DatasetColumn.of(higherTaxonomyColName))) {
        column = DatasetColumn.of(higherTaxonomyColName);
    } else {
        // Don't actually change until we have a valid column name.
        return;
    }

    // Group names by dataset column.
    Table<String, Dataset, Set<Name>> namesByDataset = HashBasedTable.create();

    for (String dsName : datasetNamesInOrder) {
        Dataset ds = datasetNames.get(dsName);

        if (column == GENUS) {
            Map<String, List<Name>> rowsByGenus = ds.getNamesInAllRows().stream()
                    .collect(Collectors.groupingBy(n -> n.getGenus()));

            for (String genus : rowsByGenus.keySet()) {
                namesByDataset.put(genus, ds, new HashSet<>(rowsByGenus.get(genus)));
            }
        } else {
            Map<DatasetRow, Set<Name>> namesByRow = ds.getNamesByRow();

            for (DatasetRow row : namesByRow.keySet()) {
                String colValue = row.get(column);
                if (colValue == null)
                    colValue = "(null)";

                if (!namesByDataset.contains(colValue, ds))
                    namesByDataset.put(colValue, ds, new HashSet<>());

                namesByDataset.get(colValue, ds).addAll(namesByRow.getOrDefault(row, new HashSet<>()));
            }
        }
    }

    // LOGGER.info("namesByDataset = " + namesByDataset);

    // By this point, namesByDataset should be ready to go.
    // So let's fill out precalc.
    precalc.clear();

    for (String rowName : namesByDataset.rowKeySet()) {
        precalc.put(rowName, "HigherTaxon", rowName);

        Set<Name> prevNames = new HashSet<>();

        for (String dsName : datasetNamesInOrder) {
            Dataset ds = datasetNames.get(dsName);
            Set<Name> names = namesByDataset.get(rowName, ds);

            // Missing?! Oh noes.
            if (names == null)
                names = new HashSet<>();

            // For now, let's just note down how many names we have.
            precalc.put(rowName, dsName + "_with_synonymy", calculateDifferenceWithSynonymy(prevNames, names));
            precalc.put(rowName, dsName + "_without_synonymy",
                    calculateDifferenceWithoutSynonymy(prevNames, names));

            // Set up prevNames for next time 'round
            prevNames = names;
        }
    }

    // LOGGER.info("precalc = " + precalc);

    // Tell everybody what we did.
    higherTaxaList.clear();
    higherTaxaList.addAll(namesByDataset.rowKeySet());
    LOGGER.info("higherTaxaList = " + higherTaxaList);

    controller.getTableView().refresh();
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ClusterProvider.java

private Set<KubernetesV2Cluster> translateClustersWithRelationships(Collection<CacheData> clusterData) {
    // TODO(lwander) possible optimization: store lb relationships in cluster object to cut down on number of loads here.
    List<CacheData> serverGroupData = kindMap.translateSpinnakerKind(SERVER_GROUPS).stream()
            .map(kind -> cacheUtils.loadRelationshipsFromCache(clusterData, kind.toString()))
            .flatMap(Collection::stream).collect(Collectors.toList());

    List<CacheData> loadBalancerData = kindMap.translateSpinnakerKind(LOAD_BALANCERS).stream()
            .map(kind -> cacheUtils.loadRelationshipsFromCache(serverGroupData, kind.toString()))
            .flatMap(Collection::stream).collect(Collectors.toList());

    List<CacheData> instanceData = kindMap.translateSpinnakerKind(INSTANCES).stream()
            .map(kind -> cacheUtils.loadRelationshipsFromCache(serverGroupData, kind.toString()))
            .flatMap(Collection::stream).collect(Collectors.toList());

    Map<String, List<CacheData>> clusterToServerGroups = new HashMap<>();
    for (CacheData serverGroupDatum : serverGroupData) {
        Collection<String> clusterKeys = serverGroupDatum.getRelationships().get(CLUSTERS.toString());
        if (clusterKeys == null || clusterKeys.size() != 1) {
            log.warn("Malformed cache, server group stored without cluster");
            continue;
        }// w  w  w .  j  av a  2  s  . c om

        String clusterKey = clusterKeys.iterator().next();
        List<CacheData> storedData = clusterToServerGroups.getOrDefault(clusterKey, new ArrayList<>());
        storedData.add(serverGroupDatum);
        clusterToServerGroups.put(clusterKey, storedData);
    }

    Map<String, List<CacheData>> serverGroupToLoadBalancers = cacheUtils.mapByRelationship(loadBalancerData,
            SERVER_GROUPS);
    Map<String, List<CacheData>> serverGroupToInstances = cacheUtils.mapByRelationship(instanceData,
            SERVER_GROUPS);
    Map<String, List<CacheData>> loadBalancerToServerGroups = cacheUtils.mapByRelationship(serverGroupData,
            LOAD_BALANCERS);

    Set<KubernetesV2Cluster> result = new HashSet<>();
    for (CacheData clusterDatum : clusterData) {
        List<CacheData> clusterServerGroups = clusterToServerGroups.getOrDefault(clusterDatum.getId(),
                new ArrayList<>());
        List<CacheData> clusterLoadBalancers = clusterServerGroups.stream().map(CacheData::getId)
                .map(id -> serverGroupToLoadBalancers.getOrDefault(id, new ArrayList<>()))
                .flatMap(Collection::stream).collect(Collectors.toList());

        result.add(translateCluster(clusterDatum, clusterServerGroups, clusterLoadBalancers,
                serverGroupToInstances, loadBalancerToServerGroups, serverGroupToLoadBalancers));
    }

    return result.stream().filter(Objects::nonNull).collect(Collectors.toSet());
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.KubernetesV2ClouddriverProfileFactory.java

private void processKubernetesAccount(KubernetesAccount account) {
    if (account.usesServiceAccount()) {
        return;/*  w  ww  . ja  v a2s . co m*/
    }

    String kubeconfigFile = account.getKubeconfigFile();
    String context = account.getContext();
    FileInputStream is = null;
    try {
        is = new FileInputStream(kubeconfigFile);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(
                "No kubeconfig file '" + kubeconfigFile + "' found, but validation passed: " + e.getMessage(),
                e);
    }

    Object obj = yamlParser.load(is);
    Map<String, Object> parsedKubeconfig = objectMapper.convertValue(obj,
            new TypeReference<Map<String, Object>>() {
            });

    if (StringUtils.isEmpty(context)) {
        context = (String) parsedKubeconfig.get("current-context");
    }

    if (StringUtils.isEmpty(context)) {
        throw new HalException(Problem.Severity.FATAL, "No context specified in kubernetes account "
                + account.getName() + " and no 'current-context' in " + kubeconfigFile);
    }

    final String finalContext = context;

    String user = (String) ((List<Map<String, Object>>) parsedKubeconfig.getOrDefault("contexts",
            new ArrayList<>())).stream().filter(c -> c.getOrDefault("name", "").equals(finalContext))
                    .findFirst()
                    .map(m -> ((Map<String, Object>) m.getOrDefault("context", new HashMap<>())).get("user"))
                    .orElse("");

    if (StringUtils.isEmpty(user)) {
        return;
    }

    Map<String, Object> userProperties = (Map<String, Object>) ((List<Map<String, Object>>) parsedKubeconfig
            .getOrDefault("users", new ArrayList<>())).stream()
                    .filter(c -> c.getOrDefault("name", "").equals(user)).findFirst().map(u -> u.get("user"))
                    .orElse(null);

    if (userProperties == null) {
        throw new HalException(Problem.Severity.FATAL,
                "No user named '" + user + "' exists in your kubeconfig file.");
    }

    Map<String, Object> authProvider = (Map<String, Object>) userProperties.get("auth-provider");

    if (authProvider == null || !authProvider.getOrDefault("name", "").equals("gcp")) {
        return;
    }

    Map<String, String> authProviderConfig = (Map<String, String>) authProvider.get("config");

    if (authProviderConfig == null) {
        return;
    }

    authProviderConfig.put("cmd-path", "gcloud");

    try {
        yamlParser.dump(parsedKubeconfig, new FileWriter(kubeconfigFile));
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL,
                "Unable to write the kubeconfig file to the staging area. This may be a user permissions issue.");
    }
}

From source file:com.github.camellabs.iot.cloudlet.geofencing.service.DefaultRouteService.java

private List<List<String>> exportRoutes(String client) {
    List<Route> routes = routes(client);
    List<String> routesIds = routes.parallelStream().map(Route::getId).collect(toList());
    Query commentsQuery = new Query().addCriteria(where("routeId").in(routesIds));
    List<RouteComment> routeComments = mongoTemplate.find(commentsQuery, RouteComment.class, "RouteComment");
    Map<String, List<String>> commentsForRoute = newHashMap();
    for (RouteComment comment : routeComments) {
        String routeId = comment.getRouteId();
        if (!commentsForRoute.containsKey(routeId)) {
            commentsForRoute.put(routeId, newLinkedList());
        }// www  .  j a v  a2s. co  m
        commentsForRoute.get(routeId).add(comment.getCreated().toString());
        commentsForRoute.get(routeId).add(comment.getText());
    }
    return routes.parallelStream()
            .map(route -> ImmutableList.<String>builder().add(route.getCreated().toString())
                    .addAll(commentsForRoute.getOrDefault(route.getId(), emptyList())).build())
            .collect(toList());
}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

@SuppressWarnings("unchecked")
private Map<String, Object> getRawDataFromDoStep(Map<String, Object> stepRawData) {
    try {//from w  ww .jav  a  2s . c  o m
        return (Map<String, Object>) stepRawData.getOrDefault(DO_EXTERNAL_KEY, stepRawData.get(DO_KEY));
    } catch (ClassCastException ex) {
        return Collections.emptyMap();
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ClusterProvider.java

private KubernetesV2Cluster translateCluster(CacheData clusterDatum, List<CacheData> serverGroupData,
        List<CacheData> loadBalancerData, Map<String, List<CacheData>> instanceDataByServerGroup,
        Map<String, List<CacheData>> serverGroupDataByLoadBalancer,
        Map<String, List<CacheData>> loadBalancerDataByServerGroup) {
    if (clusterDatum == null) {
        return null;
    }/*  w ww .j ava 2  s . co  m*/

    List<KubernetesV2ServerGroup> serverGroups = serverGroupData.stream()
            .map(cd -> cacheUtils.<KubernetesV2ServerGroup>resourceModelFromCacheData(
                    KubernetesV2ServerGroupCacheData.builder().serverGroupData(cd)
                            .instanceData(instanceDataByServerGroup.getOrDefault(cd.getId(), new ArrayList<>()))
                            .loadBalancerData(
                                    loadBalancerDataByServerGroup.getOrDefault(cd.getId(), new ArrayList<>()))
                            .build()))
            .filter(Objects::nonNull).collect(Collectors.toList());

    List<KubernetesV2LoadBalancer> loadBalancers = loadBalancerData.stream()
            .map(cd -> KubernetesV2LoadBalancer.fromCacheData(cd,
                    serverGroupDataByLoadBalancer.getOrDefault(cd.getId(), new ArrayList<>()),
                    instanceDataByServerGroup))
            .filter(Objects::nonNull).collect(Collectors.toList());

    return new KubernetesV2Cluster(clusterDatum.getId(), serverGroups, loadBalancers);
}

From source file:org.onosproject.ecord.co.BigSwitchDeviceProvider.java

private boolean postNetworkConfig(String subject, ObjectNode cfg) {
    // TODO Slice out REST Client code as library?
    Client client = ClientBuilder.newClient();

    client.property(ClientProperties.FOLLOW_REDIRECTS, true);

    // Trying to do JSON processing using Jackson triggered OSGi nightmare
    //client.register(JacksonFeature.class);

    final Map<String, String> env = System.getenv();
    // TODO Where should we get the user/password from?
    String user = env.getOrDefault("ONOS_WEB_USER", "onos");
    String pass = env.getOrDefault("ONOS_WEB_PASS", "rocks");
    HttpAuthenticationFeature auth = HttpAuthenticationFeature.basic(user, pass);
    client.register(auth);//from w ww  .j  ava 2 s.c  o  m

    // TODO configurable base path
    WebTarget target = client.target("http://" + metroIp + ":8181/onos/v1/").path("network/configuration/")
            .path(subject);

    Response response = target.request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(cfg.toString(), MediaType.APPLICATION_JSON));

    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        log.error("POST failed {}\n{}", response, cfg.toString());
        return false;
    }
    return true;
}

From source file:io.stallion.dataAccess.LocalMemoryStash.java

@Override
public FilterChain<T> filterByKey(String keyName, Object value) {
    onPreRead();/*from  w w w  .j av a  2  s  .  c  o  m*/
    Map<Object, Set<T>> keyValMap = this.keyNameToKeyToValue.getOrDefault(keyName, null);
    if (keyValMap == null) {
        throw new ConfigException("The key " + keyName + " is not a valid key for the bucket " + getBucket()
                + ". You must either override getKeyFields() in your controller, or pass in the key during the constructore");
    }
    Set<T> vals = keyValMap.getOrDefault(value, null);
    // If no values with this key, return an empty filter chain
    if (vals == null) {
        Log.finer("No items found for key field {0} key value {1}", keyName, value);
        return new FilterChain<>(getBucket(), this);
    }

    FilterChain chain = filterChain(new ArrayList<T>(vals)).filter(keyName, value);
    return chain;
}