Example usage for java.util.stream Collectors toMap

List of usage examples for java.util.stream Collectors toMap

Introduction

In this page you can find the example usage for java.util.stream Collectors toMap.

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:com.ericsson.deviceaccess.tutorial.rest.GenericDeviceServlet.java

private String getAllDevices() {
    try {//from   www. jav a 2 s . c  o m
        Map<String, GenericDevice> devices = context.getServiceReferences(GenericDevice.class, null).stream()
                .map(ref -> context.getService(ref))
                .collect(Collectors.toMap(dev -> dev.getId(), Function.identity()));
        return SerializationUtil.execute(Format.JSON,
                mapper -> mapper.writerWithView(View.ID.Ignore.class).writeValueAsString(devices));
    } catch (InvalidSyntaxException | SerializationException e) {
        logger.error(e);
    }
    return "{}";
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Service.java

default String getResourceYaml(AccountDeploymentDetails<KubernetesAccount> details,
        GenerateService.ResolvedConfiguration resolvedConfiguration) {
    ServiceSettings settings = resolvedConfiguration.getServiceSettings(getService());
    SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings();
    String namespace = getNamespace(settings);

    List<ConfigSource> configSources = stageConfig(details, resolvedConfiguration);

    List<SidecarConfig> sidecarConfigs = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getSidecars().getOrDefault(getService().getServiceName(), new ArrayList<>());

    List<String> initContainers = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getInitContainers().getOrDefault(getService().getServiceName(), new ArrayList<>()).stream()
            .map(o -> {//from   w ww .j  av a  2 s  .co  m
                try {
                    return getObjectMapper().writeValueAsString(o);
                } catch (JsonProcessingException e) {
                    throw new HalException(Problem.Severity.FATAL,
                            "Invalid init container format: " + e.getMessage(), e);
                }
            }).collect(Collectors.toList());

    if (initContainers.isEmpty()) {
        initContainers = null;
    }

    List<String> hostAliases = details.getDeploymentConfiguration().getDeploymentEnvironment().getHostAliases()
            .getOrDefault(getService().getServiceName(), new ArrayList<>()).stream().map(o -> {
                try {
                    return getObjectMapper().writeValueAsString(o);
                } catch (JsonProcessingException e) {
                    throw new HalException(Problem.Severity.FATAL,
                            "Invalid host alias format: " + e.getMessage(), e);
                }
            }).collect(Collectors.toList());

    if (hostAliases.isEmpty()) {
        hostAliases = null;
    }

    configSources.addAll(sidecarConfigs
            .stream().filter(c -> StringUtils.isNotEmpty(c.getMountPath())).map(c -> new ConfigSource()
                    .setMountPath(c.getMountPath()).setId(c.getName()).setType(ConfigSource.Type.emptyDir))
            .collect(Collectors.toList()));

    Map<String, String> env = configSources.stream().map(ConfigSource::getEnv).map(Map::entrySet)
            .flatMap(Collection::stream).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

    List<String> volumes = configSources.stream()
            .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream()
            .map(this::getVolumeYaml).collect(Collectors.toList());

    volumes.addAll(settings.getKubernetes().getVolumes().stream()
            .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream()
            .map(this::getVolumeYaml).collect(Collectors.toList()));

    volumes.addAll(
            sidecarConfigs.stream().map(SidecarConfig::getConfigMapVolumeMounts).flatMap(Collection::stream)
                    .map(c -> new ConfigSource().setMountPath(c.getMountPath()).setId(c.getConfigMapName())
                            .setType(ConfigSource.Type.configMap))
                    .map(this::getVolumeYaml).collect(Collectors.toList()));

    env.putAll(settings.getEnv());

    Integer targetSize = settings.getTargetSize();
    CustomSizing customSizing = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getCustomSizing();
    if (customSizing != null) {
        Map componentSizing = customSizing.getOrDefault(getService().getServiceName(), new HashMap());
        targetSize = (Integer) componentSizing.getOrDefault("replicas", targetSize);
    }

    String primaryContainer = buildContainer(getService().getCanonicalName(), details, settings, configSources,
            env);
    List<String> sidecarContainers = getSidecars(runtimeSettings).stream().map(SidecarService::getService)
            .map(s -> buildContainer(s.getCanonicalName(), details, runtimeSettings.getServiceSettings(s),
                    configSources, env))
            .collect(Collectors.toList());

    sidecarContainers
            .addAll(sidecarConfigs.stream().map(this::buildCustomSidecar).collect(Collectors.toList()));

    List<String> containers = new ArrayList<>();
    containers.add(primaryContainer);
    containers.addAll(sidecarContainers);

    TemplatedResource podSpec = new JinjaJarResource("/kubernetes/manifests/podSpec.yml")
            .addBinding("containers", containers).addBinding("initContainers", initContainers)
            .addBinding("hostAliases", hostAliases)
            .addBinding("imagePullSecrets", settings.getKubernetes().getImagePullSecrets())
            .addBinding("serviceAccountName", settings.getKubernetes().getServiceAccountName())
            .addBinding("terminationGracePeriodSeconds", terminationGracePeriodSeconds())
            .addBinding("volumes", volumes);

    String version = makeValidLabel(details.getDeploymentConfiguration().getVersion());
    if (version.isEmpty()) {
        version = "unknown";
    }

    return new JinjaJarResource("/kubernetes/manifests/deployment.yml")
            .addBinding("name", getService().getCanonicalName()).addBinding("namespace", namespace)
            .addBinding("replicas", targetSize).addBinding("version", version)
            .addBinding("podAnnotations", settings.getKubernetes().getPodAnnotations())
            .addBinding("podSpec", podSpec.toString()).toString();
}

From source file:com.serphacker.serposcope.scraper.google.scraper.GoogleScraper.java

protected String extractLink(Element element) {
    if (element == null) {
        return null;
    }//w  ww  .  j  a va2  s.  c om

    String attr = element.attr("href");
    if (attr == null) {
        return null;
    }

    if ((attr.startsWith("http://www.google") || attr.startsWith("https://www.google"))) {
        if (attr.contains("/aclk?")) {
            return null;
        }
    }

    if (attr.startsWith("http://") || attr.startsWith("https://")) {
        return attr;
    }

    if (attr.startsWith("/url?")) {
        try {
            List<NameValuePair> parse = URLEncodedUtils.parse(attr.substring(5), Charset.forName("utf-8"));
            Map<String, String> map = parse.stream()
                    .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
            return map.get("q");
        } catch (Exception ex) {
            return null;
        }
    }

    return null;
}

From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java

private void contributeMutations(Builder mutation, Class<?> record, GraphQLObjectType type,
        List<PropertyDescriptor> fields, PhantasmProcessor processor) {
    Map<String, GraphQLType> types = fields.stream()
            .collect(Collectors.toMap(field -> field.getName(), field -> type(field, processor)));
    contributeCreate(mutation, record, type, fields, types, processor);
    contributeUpdate(mutation, record, type, fields, types, processor);
    contributeDelete(mutation, record, type, fields, types);
}

From source file:com.hurence.logisland.processor.datastore.EnrichRecords.java

/**
 * process events//from w w  w .jav a2  s . c o m
 *
 * @param context
 * @param records
 * @return
 */
@Override
public Collection<Record> process(final ProcessContext context, final Collection<Record> records) {

    List<Record> outputRecords = new ArrayList<>();
    List<Triple<Record, String, IncludeFields>> recordsToEnrich = new ArrayList<>();

    if (records.size() != 0) {
        String excludesFieldName = context.getPropertyValue(EXCLUDES_FIELD).asString();

        // Excludes :
        String[] excludesArray = null;
        if ((excludesFieldName != null) && (!excludesFieldName.isEmpty())) {
            excludesArray = excludesFieldName.split("\\s*,\\s*");
        }

        //List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>();
        MultiGetQueryRecordBuilder mgqrBuilder = new MultiGetQueryRecordBuilder();

        mgqrBuilder.excludeFields(excludesArray);

        List<MultiGetResponseRecord> multiGetResponseRecords = null;
        // HashSet<String> ids = new HashSet<>(); // Use a Set to avoid duplicates

        for (Record record : records) {

            String recordKeyName = null;
            String indexName = null;
            String typeName = FieldDictionary.RECORD_TYPE;
            String includesFieldName = null;

            try {
                recordKeyName = context.getPropertyValue(RECORD_KEY_FIELD).evaluate(record).asString();
                indexName = context.getPropertyValue(COLLECTION_NAME).evaluate(record).asString();
                if (context.getPropertyValue(TYPE_NAME).isSet())
                    typeName = context.getPropertyValue(TYPE_NAME).evaluate(record).asString();
                includesFieldName = context.getPropertyValue(INCLUDES_FIELD).evaluate(record).asString();
            } catch (Throwable t) {
                record.setStringField(FieldDictionary.RECORD_ERRORS,
                        "Failure in executing EL. Error: " + t.getMessage());
                getLogger().error("Cannot interpret EL : " + record, t);
            }

            if (recordKeyName != null) {
                try {
                    String key = record.getField(recordKeyName).asString();
                    // Includes :
                    String[] includesArray = null;
                    if ((includesFieldName != null) && (!includesFieldName.isEmpty())) {
                        includesArray = includesFieldName.split("\\s*,\\s*");
                    }
                    IncludeFields includeFields = new IncludeFields(includesArray);
                    mgqrBuilder.add(indexName, typeName, includeFields.getAttrsToIncludeArray(), key);

                    recordsToEnrich.add(
                            new ImmutableTriple(record, asUniqueKey(indexName, typeName, key), includeFields));
                } catch (Throwable t) {
                    record.setStringField(FieldDictionary.RECORD_ERRORS, "Can not request datastore with "
                            + indexName + " " + typeName + " " + recordKeyName);
                    outputRecords.add(record);
                }
            } else {
                //record.setStringField(FieldDictionary.RECORD_ERRORS, "Interpreted EL returned null for recordKeyName");
                outputRecords.add(record);
                //logger.error("Interpreted EL returned null for recordKeyName");
            }
        }

        try {
            List<MultiGetQueryRecord> mgqrs = mgqrBuilder.build();

            multiGetResponseRecords = datastoreClientService.multiGet(mgqrs);
        } catch (InvalidMultiGetQueryRecordException e) {
            getLogger().error("error while multiger", e);
        }

        if (multiGetResponseRecords == null || multiGetResponseRecords.isEmpty()) {
            return records;
        }

        // Transform the returned documents from ES in a Map
        Map<String, MultiGetResponseRecord> responses = multiGetResponseRecords.stream()
                .collect(Collectors.toMap(EnrichRecords::asUniqueKey, Function.identity()));

        recordsToEnrich.forEach(recordToEnrich -> {

            Triple<Record, String, IncludeFields> triple = recordToEnrich;
            Record outputRecord = triple.getLeft();

            // TODO: should probably store the resulting recordKeyName during previous invocation above
            String key = triple.getMiddle();
            IncludeFields includeFields = triple.getRight();

            MultiGetResponseRecord responseRecord = responses.get(key);
            if ((responseRecord != null) && (responseRecord.getRetrievedFields() != null)) {
                // Retrieve the fields from responseRecord that matches the ones in the recordToEnrich.
                responseRecord.getRetrievedFields().forEach((k, v) -> {
                    String fieldName = k.toString();
                    if (includeFields.includes(fieldName)) {
                        // Now check if there is an attribute mapping rule to apply
                        if (includeFields.hasMappingFor(fieldName)) {
                            String mappedAttributeName = includeFields.getAttributeToMap(fieldName);
                            // Replace the attribute name
                            outputRecord.setStringField(mappedAttributeName, v.toString());
                        } else {
                            outputRecord.setStringField(fieldName, v.toString());
                        }
                    }
                });
            }
            outputRecords.add(outputRecord);

        });
    }
    return outputRecords;
}

From source file:com.netflix.spinnaker.igor.jenkins.service.JenkinsService.java

@Override
@SuppressWarnings("unchecked")
public Map<String, Object> getBuildProperties(String job, int buildNumber, String fileName) {
    if (StringUtils.isEmpty(fileName)) {
        return new HashMap<>();
    }//  w  w  w . j  av a2 s .c  o  m
    Map<String, Object> map = new HashMap<>();
    try {
        String path = getArtifactPathFromBuild(job, buildNumber, fileName);
        try (InputStream propertyStream = this.getPropertyFile(job, buildNumber, path).getBody().in()) {
            if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) {
                Yaml yml = new Yaml(new SafeConstructor());
                map = (Map<String, Object>) yml.load(propertyStream);
            } else if (fileName.endsWith(".json")) {
                map = objectMapper.readValue(propertyStream, new TypeReference<Map<String, Object>>() {
                });
            } else {
                Properties properties = new Properties();
                properties.load(propertyStream);
                map = properties.entrySet().stream()
                        .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue));
            }
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        log.error("Unable to get igorProperties '{}'", kv("job", job), e);
    }
    return map;
}

From source file:com.spankingrpgs.scarletmoon.characters.CrimsonGameCharacter.java

/**
 * Initializes a character with the specified system name, and a host of reasonable defaults.
 * <p>/*from  w  w  w.  j ava2  s .com*/
 * @param name  The system name for the character
 */
public CrimsonGameCharacter(String name) {
    super(name, Arrays.stream(Gender.values()).collect(Collectors.toMap(Function.identity(), ignored -> name)),
            name, name, Gender.UNKNOWN, Arrays.asList(CombatRange.ARMSLENGTH, CombatRange.GRAPPLE),
            Arrays.stream(PrimaryStatisticName.values())
                    .collect(CollectionUtils.toLinkedHashMap(Enum::name, ignored -> 2)),
            Arrays.stream(SecondaryStatisticName.values()).map(Enum::name).collect(Collectors.toList()),
            new LinkedHashMap<>(),
            Arrays.stream(CrimsonGlowEquipSlotNames.values())
                    .collect(CollectionUtils.toLinkedHashMap(Enum::name, slot -> new EquipSlot(slot.name()))),
            new LinkedHashMap<>(), SpankingRole.SWITCH);
}

From source file:nu.yona.server.goals.service.ActivityCategoryService.java

private void deleteRemovedActivityCategories(Set<ActivityCategory> activityCategoriesInRepository,
        Set<ActivityCategoryDto> activityCategoryDtos) {
    Map<UUID, ActivityCategoryDto> activityCategoryDtosMap = activityCategoryDtos.stream()
            .collect(Collectors.toMap(ActivityCategoryDto::getId, ac -> ac));

    activityCategoriesInRepository.stream().filter(ac -> !activityCategoryDtosMap.containsKey(ac.getId()))
            .forEach(this::deleteActivityCategory);
}

From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java

protected void buildDiscriminationMap(Swagger swagger) {
    swagger.getDefinitions().forEach((name, model) -> {
        ObjectNode discriminatorMapExtention = (ObjectNode) model.getVendorExtensions()
                .get("x-openapi-v3-discriminator");
        if (discriminatorMapExtention != null) {

            String propertyName = discriminatorMapExtention.get("propertyName").asText();
            ObjectNode mapping = (ObjectNode) discriminatorMapExtention.get("mapping");

            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> result = mapper.convertValue(mapping, Map.class);
            result = result.entrySet().stream().collect(Collectors
                    .toMap(e -> e.getValue().substring(e.getValue().lastIndexOf('/') + 1), e -> e.getKey()));
            result.forEach((key, value) -> {
                reverseDiscriminatorMap.put(key, name);
            });//from   ww w  .  j  a va 2 s.co  m
            discriminatorMap.put(name, new Discriminator(name, propertyName, result));
        }
    });
}

From source file:com.epam.ta.reportportal.ws.controller.impl.ProjectControllerTest.java

@Test
public void getUsersFilterByEmailTest() throws Exception {
    MvcResult mvcResult = mvcMock/* w  w w .  j a v a  2s. c o m*/
            .perform(get("/project/project1/users?filter.cnt.email=user").principal(authentication()))
            .andExpect(status().is(200)).andReturn();
    Page<UserResource> userResources = new Gson().fromJson(mvcResult.getResponse().getContentAsString(),
            new TypeToken<Page<UserResource>>() {
            }.getType());
    Map<String, UserResource> userResourceMap = userResources.getContent().stream()
            .collect(Collectors.toMap(UserResource::getUserId, it -> it));
    Assert.assertEquals(3, userResourceMap.size());
    Assert.assertTrue(userResourceMap.containsKey("user1"));
    Assert.assertTrue(userResourceMap.containsKey("user2"));
    Assert.assertTrue(userResourceMap.containsKey("user4"));
}