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.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java

private Map<String, TopicVO> getTopicMetadata(BlockingChannel channel, String... topics) {
    final TopicMetadataRequest request = new TopicMetadataRequest((short) 0, 0, clientId(),
            Arrays.asList(topics));

    LOG.debug("Sending topic metadata request: {}", request);

    channel.send(request);//from w  w w. java  2 s .  c  o  m
    final kafka.api.TopicMetadataResponse underlyingResponse = kafka.api.TopicMetadataResponse
            .readFrom(channel.receive().buffer());

    LOG.debug("Received topic metadata response: {}", underlyingResponse);

    TopicMetadataResponse response = new TopicMetadataResponse(underlyingResponse);
    return response.topicsMetadata().stream().filter(tmd -> tmd.errorCode() == ErrorMapping.NoError())
            .map(this::processTopicMetadata).collect(Collectors.toMap(TopicVO::getName, t -> t));
}

From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java

/**
 * Generate a new stream cut./*from   w ww .  j a v  a2  s  .  com*/
 *
 * @param scope      scope.
 * @param stream     stream name.
 * @param contextOpt optional context
 * @return streamCut.
 */
public CompletableFuture<StreamCutRecord> generateStreamCut(final String scope, final String stream,
        final OperationContext contextOpt) {
    final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream)
            : contextOpt;

    final long generationTime = System.currentTimeMillis();
    return streamMetadataStore.getActiveSegments(scope, stream, context, executor)
            .thenCompose(activeSegments -> Futures.allOfWithResults(activeSegments.stream().parallel().collect(
                    Collectors.toMap(Segment::getNumber, x -> getSegmentOffset(scope, stream, x.getNumber())))))
            .thenApply(map -> new StreamCutRecord(generationTime, Long.MIN_VALUE, ImmutableMap.copyOf(map)));
}

From source file:delfos.rs.trustbased.WeightedGraph.java

protected final Map<Node, Integer> makeIndex(List<Node> nodes) {
    return IntStream.range(0, nodes.size()).boxed()
            .collect(Collectors.toMap(indexNode -> nodes.get(indexNode), indexNode -> indexNode));
}

From source file:energy.usef.dso.service.business.DsoPlanboardBusinessService.java

/**
 * Creates flex offers map required to place flex orders.
 *
 * @return Map: Congestion point entity address -> Map: PTU Date -> Flex Offer list
 *///from  w w  w .j  av  a  2s. c o  m
public Map<String, Map<LocalDate, List<PlanboardMessage>>> findOrderableFlexOffers() {
    List<PlanboardMessage> flexOffers = planboardMessageRepository.findOrderableFlexOffers();

    Map<String, List<PlanboardMessage>> flexOffersPerConnectionGroup = flexOffers.stream()
            .filter(this::validateOffer)
            .collect(Collectors.groupingBy(pm -> pm.getConnectionGroup().getUsefIdentifier()));

    return flexOffersPerConnectionGroup.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> entry.getValue().stream().collect(Collectors.groupingBy(PlanboardMessage::getPeriod))));
}

From source file:org.codelibs.fess.es.config.exentity.DataConfig.java

private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName,
        final String scheme) {
    AuthScheme authScheme = null;//from w  w  w  . ja va  2  s . co  m
    if (Constants.BASIC.equals(scheme)) {
        authScheme = new BasicScheme();
    } else if (Constants.DIGEST.equals(scheme)) {
        authScheme = new DigestScheme();
    } else if (Constants.NTLM.equals(scheme)) {
        final Properties props = new Properties();
        paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> {
            props.setProperty(e.getKey(), e.getValue());
        });
        authScheme = new NTLMScheme(new JcifsEngine(props));
    } else if (Constants.FORM.equals(scheme)) {
        final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + ".";
        final Map<String, String> parameterMap = paramMap.entrySet().stream()
                .filter(e -> e.getKey().startsWith(prefix))
                .collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), e -> e.getValue()));
        authScheme = new FormScheme(parameterMap);
    }
    return authScheme;
}

From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java

private TopicVO processTopicMetadata(TopicMetadata tmd) {
    TopicVO topic = new TopicVO(tmd.topic());

    topic.setConfig(Optional/*from w w w  . j  ava  2 s  .co  m*/
            .ofNullable(topicConfigPathCache.getCurrentData(ZkUtils.TopicConfigPath() + "/" + topic.getName()))
            .map(this::readTopicConfig).orElse(Collections.emptyMap()));

    topic.setPartitions(tmd.partitionsMetadata().stream().map((pmd) -> parsePartitionMetadata(tmd.topic(), pmd))
            .collect(Collectors.toMap(TopicPartitionVO::getId, p -> p)));
    return topic;
}

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

@RequestMapping("/events/{eventName}/export.csv")
public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request,
        HttpServletResponse response, Principal principal) throws IOException {
    List<String> fields = Arrays
            .asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
    Event event = loadEvent(eventName, principal);
    Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream()
            .collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
    ZoneId eventZoneId = event.getZoneId();

    Predicate<String> contains = FIXED_FIELDS::contains;

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

    try (ServletOutputStream out = response.getOutputStream();
            CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {

        for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
            out.write(marker);/* w  ww. j ava2 s .com*/
        }

        writer.writeNext(fields.stream().map(f -> {
            if (f.startsWith(CUSTOM_FIELDS_PREFIX)) {
                return f.substring(CUSTOM_FIELDS_PREFIX.length());
            }
            return f;
        }).toArray(String[]::new));

        eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> {
            List<String> line = new ArrayList<>();
            if (fields.contains("ID")) {
                line.add(t.getUuid());
            }
            if (fields.contains("Creation")) {
                line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
            }
            if (fields.contains("Category")) {
                line.add(categoriesMap.get(t.getCategoryId()).getName());
            }
            if (fields.contains("Event")) {
                line.add(eventName);
            }
            if (fields.contains("Status")) {
                line.add(t.getStatus().toString());
            }
            if (fields.contains("OriginalPrice")) {
                line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
            }
            if (fields.contains("PaidPrice")) {
                line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
            }
            if (fields.contains("Discount")) {
                line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
            }
            if (fields.contains("VAT")) {
                line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
            }
            if (fields.contains("ReservationID")) {
                line.add(t.getTicketsReservationId());
            }
            if (fields.contains("Full Name")) {
                line.add(t.getFullName());
            }
            if (fields.contains("First Name")) {
                line.add(t.getFirstName());
            }
            if (fields.contains("Last Name")) {
                line.add(t.getLastName());
            }
            if (fields.contains("E-Mail")) {
                line.add(t.getEmail());
            }
            if (fields.contains("Locked")) {
                line.add(String.valueOf(t.getLockedAssignment()));
            }
            if (fields.contains("Language")) {
                line.add(String.valueOf(t.getUserLanguage()));
            }
            if (fields.contains("Confirmation")) {
                line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId)
                        .toString());
            }
            if (fields.contains("Billing Address")) {
                line.add(t.getTicketReservation().getBillingAddress());
            }

            //obviously not optimized
            Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId());

            fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX))
                    .forEachOrdered(field -> {
                        String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length());
                        line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", ""));
                    });

            return line.toArray(new String[line.size()]);
        }).forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}

From source file:com.intellij.lang.jsgraphql.endpoint.ide.annotator.JSGraphQLEndpointErrorAnnotator.java

@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {

    // references, e.g. to unknown types
    if (element instanceof JSGraphQLEndpointNamedTypePsiElement) {
        final PsiReference reference = element.getReference();
        if (reference != null) {
            final PsiElement resolved = reference.resolve();
            if (resolved == null) {
                holder.createErrorAnnotation(element,
                        "Unknown type '" + element.getText() + "'. Are you missing an import?")
                        .setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES);
            } else {

                // types referenced after implements must be interfaces
                if (PsiTreeUtil.getParentOfType(element, JSGraphQLEndpointImplementsInterfaces.class) != null) {
                    if (PsiTreeUtil.getParentOfType(resolved,
                            JSGraphQLEndpointInterfaceTypeDefinition.class) == null) {
                        holder.createErrorAnnotation(element,
                                "'" + element.getText() + "' must be an interface to be used here");
                    }/*w  w w .  j a v  a 2  s  . c om*/
                }

                // input types must be declared before their use (imports are considered as declared before)
                final JSGraphQLEndpointInputObjectTypeDefinition resolvedInputDef = PsiTreeUtil
                        .getParentOfType(resolved, JSGraphQLEndpointInputObjectTypeDefinition.class);
                if (resolvedInputDef != null) {
                    if (resolvedInputDef.getTextOffset() > element.getTextOffset()
                            && resolvedInputDef.getContainingFile() == element.getContainingFile()) {
                        // non-imported input types must be declare earlier in the buffer than the usage
                        holder.createErrorAnnotation(element, "Input type must be declared before use");
                    }
                }

            }
        }

        return;
    }

    // imports
    if (element instanceof JSGraphQLEndpointImportFileReference) {
        final PsiReference reference = element.getReference();
        if (reference == null || reference.resolve() == null) {
            // file not found
            holder.createErrorAnnotation(element, "Cannot resolve file " + element.getText());
        }

        final JSGraphQLEndpointImportDeclaration[] importDeclarations = PsiTreeUtil
                .getChildrenOfType(element.getContainingFile(), JSGraphQLEndpointImportDeclaration.class);
        if (importDeclarations != null) {
            final String importName = element.getText();
            for (JSGraphQLEndpointImportDeclaration anImport : importDeclarations) {
                final JSGraphQLEndpointImportFileReference fileReference = anImport.getImportFileReference();
                if (fileReference != null && fileReference != element) {
                    if (Objects.equals(fileReference.getText(), importName)) {
                        holder.createErrorAnnotation(element,
                                element.getText() + " is imported more than once");
                    }
                }
            }
        }

        return;
    }

    // fields
    if (element instanceof JSGraphQLEndpointFieldDefinition) {
        final JSGraphQLEndpointFieldDefinition fieldDefinition = (JSGraphQLEndpointFieldDefinition) element;
        final PsiElement identifier = fieldDefinition.getProperty().getIdentifier();
        final String fieldName = identifier.getText();
        // duplicate fields
        final JSGraphQLEndpointFieldDefinitionSet fieldDefinitionSet = PsiTreeUtil.getParentOfType(element,
                JSGraphQLEndpointFieldDefinitionSet.class);
        if (fieldDefinitionSet != null) {
            final JSGraphQLEndpointFieldDefinition[] allFields = PsiTreeUtil
                    .getChildrenOfType(fieldDefinitionSet, JSGraphQLEndpointFieldDefinition.class);
            if (allFields != null) {
                for (JSGraphQLEndpointFieldDefinition otherField : allFields) {
                    if (otherField == fieldDefinition) {
                        continue;
                    }
                    if (Objects.equals(otherField.getProperty().getIdentifier().getText(), fieldName)) {
                        holder.createErrorAnnotation(identifier,
                                "Field '" + identifier.getText() + "' is declared more than once");
                    }
                }
            }
        }
        // field return type must not be input inside non-input types
        if (fieldDefinition.getCompositeType() != null) {
            final JSGraphQLEndpointNamedTypePsiElement fieldReturnType = PsiTreeUtil.findChildOfType(
                    fieldDefinition.getCompositeType(), JSGraphQLEndpointNamedTypePsiElement.class);
            if (fieldReturnType != null && PsiTreeUtil.getParentOfType(fieldDefinition,
                    JSGraphQLEndpointInputObjectTypeDefinition.class) == null) {
                final PsiReference reference = fieldReturnType.getReference();
                if (reference != null) {
                    final PsiElement resolved = reference.resolve();
                    if (resolved != null && PsiTreeUtil.getParentOfType(resolved,
                            JSGraphQLEndpointInputObjectTypeDefinition.class) != null) {
                        holder.createErrorAnnotation(fieldReturnType, "Field return type '"
                                + fieldReturnType.getText() + "' cannot be an input type");
                    }
                }
            }
        }

        final JSGraphQLEndpointFieldDefinition overridenField = getOverriddenField(fieldDefinition);
        if (overridenField != null) {
            if (!hasSameSignature(fieldDefinition, overridenField)) {
                final JSGraphQLEndpointInterfaceTypeDefinition overridenInterface = PsiTreeUtil
                        .getParentOfType(overridenField, JSGraphQLEndpointInterfaceTypeDefinition.class);
                if (overridenInterface != null && overridenInterface.getNamedTypeDef() != null) {
                    int endOffset = fieldDefinition.getProperty().getTextRange().getEndOffset();
                    if (fieldDefinition.getCompositeType() != null) {
                        endOffset = fieldDefinition.getCompositeType().getTextRange().getEndOffset();
                    }
                    holder.createErrorAnnotation(
                            TextRange.create(fieldDefinition.getProperty().getTextOffset(), endOffset),
                            "Field signature doesn't match the field it overrides in interface '"
                                    + overridenInterface.getNamedTypeDef().getText() + "'");
                }
            }
        }

        return;
    }

    // argument types must be input, scalar, enum
    if (element instanceof JSGraphQLEndpointArgumentsDefinition) {
        final Collection<JSGraphQLEndpointNamedTypePsiElement> argumentTypes = PsiTreeUtil
                .findChildrenOfType(element, JSGraphQLEndpointNamedTypePsiElement.class);
        for (JSGraphQLEndpointNamedTypePsiElement argumentType : argumentTypes) {
            final PsiReference reference = argumentType.getReference();
            if (reference != null) {
                final PsiElement resolved = reference.resolve();
                if (resolved != null) {
                    boolean valid = true;
                    boolean builtInScalar = JSGraphQLScalars.SCALAR_TYPES.contains(resolved.getText());
                    if (!builtInScalar) {
                        if (PsiTreeUtil.getParentOfType(resolved,
                                JSGraphQLEndpointObjectTypeDefinition.class) != null) {
                            valid = false;
                        } else if (PsiTreeUtil.getParentOfType(resolved,
                                JSGraphQLEndpointInterfaceTypeDefinition.class) != null) {
                            valid = false;
                        } else if (PsiTreeUtil.getParentOfType(resolved,
                                JSGraphQLEndpointUnionTypeDefinition.class) != null) {
                            valid = false;
                        }
                        if (!valid) {
                            holder.createErrorAnnotation(argumentType,
                                    "Argument type '" + argumentType.getText()
                                            + "' must be one of the following: 'input', 'enum', 'scalar'");
                        }
                    }
                }
            }
        }

        return;
    }

    // annotations
    if (element instanceof JSGraphQLEndpointAnnotation) {
        final JSGraphQLEndpointAnnotation annotation = (JSGraphQLEndpointAnnotation) element;
        final PsiElement atAnnotation = annotation.getAtAnnotation();
        List<JSGraphQLSchemaEndpointAnnotation> annotations = holder.getCurrentAnnotationSession()
                .getUserData(ANNOTATIONS);
        if (annotations == null) {
            final JSGraphQLConfigurationProvider configurationProvider = JSGraphQLConfigurationProvider
                    .getService(element.getProject());
            annotations = configurationProvider.getEndpointAnnotations();
            holder.getCurrentAnnotationSession().putUserData(ANNOTATIONS, annotations);
        }
        boolean knownAnnotation = false;
        for (JSGraphQLSchemaEndpointAnnotation endpointAnnotation : annotations) {
            if (Objects.equals("@" + endpointAnnotation.name, atAnnotation.getText())) {
                knownAnnotation = true;
                // check argument names and types
                if (endpointAnnotation.arguments != null) {
                    final Map<String, String> argumentNameToType = endpointAnnotation.arguments.stream()
                            .collect(
                                    Collectors.toMap(a -> a.name, a -> Optional.ofNullable(a.type).orElse("")));
                    if (annotation.getAnnotationArguments() != null
                            && annotation.getAnnotationArguments().getNamedAnnotationArguments() != null) {
                        for (JSGraphQLEndpointNamedAnnotationArgument namedArgument : annotation
                                .getAnnotationArguments().getNamedAnnotationArguments()
                                .getNamedAnnotationArgumentList()) {
                            final String type = argumentNameToType.get(namedArgument.getIdentifier().getText());
                            if (type == null) {
                                holder.createErrorAnnotation(namedArgument.getIdentifier(),
                                        "Unknown argument '" + namedArgument.getIdentifier().getText() + "'");
                            } else {
                                if (namedArgument.getAnnotationArgumentValue() != null) {
                                    switch (type) {
                                    case "String":
                                        if (namedArgument.getAnnotationArgumentValue()
                                                .getQuotedString() == null) {
                                            holder.createErrorAnnotation(
                                                    namedArgument.getAnnotationArgumentValue(),
                                                    "String value expected");
                                        }
                                        break;
                                    case "Boolean": {
                                        final PsiElement firstChild = namedArgument.getAnnotationArgumentValue()
                                                .getFirstChild();
                                        if (firstChild != null) {
                                            if (!TokenSet
                                                    .create(JSGraphQLEndpointTokenTypes.TRUE,
                                                            JSGraphQLEndpointTokenTypes.FALSE)
                                                    .contains(firstChild.getNode().getElementType())) {
                                                holder.createErrorAnnotation(
                                                        namedArgument.getAnnotationArgumentValue(),
                                                        "true or false expected");
                                            }
                                        }
                                        break;
                                    }
                                    case "Number": {
                                        final PsiElement firstChild = namedArgument.getAnnotationArgumentValue()
                                                .getFirstChild();
                                        if (firstChild != null) {
                                            if (!JSGraphQLEndpointTokenTypes.NUMBER
                                                    .equals(firstChild.getNode().getElementType())) {
                                                holder.createErrorAnnotation(
                                                        namedArgument.getAnnotationArgumentValue(),
                                                        "Number expected");
                                            }
                                        }
                                        break;
                                    }
                                    }
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
        if (!knownAnnotation) {
            holder.createErrorAnnotation(atAnnotation, "Unknown annotation '" + atAnnotation.getText()
                    + "'. Annotations are specified in the 'schema.endpoint.annotations' array in graphql.config.json.");
        }
        return;

    }

    // duplicate types with same name
    if (element instanceof JSGraphQLEndpointNamedTypeDef) {
        final JSGraphQLEndpointNamedTypeDef namedTypeDef = (JSGraphQLEndpointNamedTypeDef) element;

        // current file
        annotateRedeclarations(namedTypeDef, element.getContainingFile(), KNOWN_DEFINITIONS, holder);

    }

}

From source file:com.github.helenusdriver.driver.impl.RootClassInfoImpl.java

/**
 * Instantiates a new <code>RootClassInfoImpl</code> object.
 *
 * @author paouelle/*ww  w . j a  v a  2 s  .c  om*/
 *
 * @param  mgr the non-<code>null</code> statement manager
 * @param  clazz the root class of POJO for which to get a class info object for
 * @param  types the non-<code>null</code> map of all type class infos
 * @throws NullPointerException if <code>clazz</code> is <code>null</code>
 * @throws IllegalArgumentException if <code>clazz</code> or any of its type
 *         classes don't represent valid POJO classes
 */
private RootClassInfoImpl(StatementManagerImpl mgr, Class<T> clazz,
        Map<Class<? extends T>, TypeClassInfoImpl<? extends T>> types) {
    super(mgr, clazz, RootEntity.class);
    // first make sure the class is abstract
    org.apache.commons.lang3.Validate.isTrue(Modifier.isAbstract(clazz.getModifiers()),
            "root entity class '%s', must be abstract", clazz.getSimpleName());
    this.ctypes = types;
    this.ntypes = types.values().stream()
            .collect(Collectors.toMap(tcinfo -> tcinfo.getType(), tcinfo -> tcinfo));
    validateAndComplementSchema();
}