Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:org.eclipse.xtext.validation.impl.AssignmentQuantityAllocator.java

@Override
public IQuantities getAssignmentQuantities(EObject obj, ISyntaxConstraint rule,
        List<IConcreteSyntaxDiagnostic> acceptor) {
    Multimap<EStructuralFeature, ISyntaxConstraint> assignments = HashMultimap.create();
    collectAssignments(rule, obj, rule, assignments, acceptor);
    //      Map<EStructuralFeature, Integer> quantities = Maps.newHashMap();
    Quantities quants = createQuantities(obj);
    for (EStructuralFeature f : obj.eClass().getEAllStructuralFeatures()) {
        int quantity = getFeatureQuantity(obj, f);
        if (quantity > 0 && !assignments.containsKey(f))
            acceptor.add(diagnosticProvider.createAssignmentMissingDiagnostic(rule, obj, f,
                    Collections.<ISyntaxConstraint>emptySet()));
        else/* w ww.j a v  a  2  s .c o  m*/
            quants.setFeatureQuantity(f, quantity);
    }
    Multimap<EStructuralFeature, ISyntaxConstraint> multipleAssignments = HashMultimap.create();
    Multimap<EStructuralFeature, ISyntaxConstraint> allowTransients = HashMultimap.create();
    for (Map.Entry<EStructuralFeature, Integer> f : quants.getFeatureQuantities().entrySet()) {
        Collection<ISyntaxConstraint> ass = assignments.get(f.getKey());
        if (ass.isEmpty())
            continue;
        boolean allowTransient = f.getKey() instanceof EAttribute && !f.getKey().isMany() && f.getValue() == 0
                && allowTransient(obj, f.getKey(), ass);
        boolean multiNeeded = ass.size() > 1 && f.getValue() != 0;
        if (allowTransient)
            allowTransients.putAll(f.getKey(), ass);
        if (multiNeeded)
            multipleAssignments.putAll(f.getKey(), ass);
        if (!allowTransient && !multiNeeded)
            for (ISyntaxConstraint a : ass)
                quants.setAssignmentQuantity(a, f.getValue());
    }
    if (multipleAssignments.isEmpty() && allowTransients.isEmpty())
        return quants;
    for (Map.Entry<EStructuralFeature, Collection<ISyntaxConstraint>> e : allowTransients.asMap().entrySet()) {
        int min = 0;
        for (ISyntaxConstraint x : e.getValue())
            min += intervalProvider.getMin(quants, x, Sets.<ISyntaxConstraint>newHashSet());
        int val = min > 0 ? 1 : 0;
        quants.setFeatureQuantity(e.getKey(), val);
        if (e.getValue().size() == 1)
            quants.setAssignmentQuantity(e.getValue().iterator().next(), val);
    }
    //      System.out.println("AllowTransientsQuantities: " + quants.toString());
    if (multipleAssignments.isEmpty())
        return quants;
    return null;
    // TODO: implement an algorithm to handle multipleAssignments. For details, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=310454 
}

From source file:org.eclipse.xtext.xtext.XtextValidator.java

public void createMessageForNameClashes(Multimap<String, ENamedElement> nameToElement) {
    for (Entry<String, Collection<ENamedElement>> entry : nameToElement.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            if (!Iterables.isEmpty(Iterables.filter(entry.getValue(), EStructuralFeature.class))
                    && !Iterables.isEmpty(Iterables.filter(entry.getValue(), EClassifier.class))) {
                String constantName = entry.getKey();
                String message = "Name clash in generated code: '" + constantName + "'.";
                for (ENamedElement element : entry.getValue()) {
                    String myMessage = message;
                    if (element.getName().indexOf('_') >= 0) {
                        myMessage = myMessage + " Try to avoid underscores in names to prevent conflicts.";
                    }/*w  w  w.ja v  a2s  . c  o  m*/
                    createMessageForSource(myMessage, null, Diagnostic.ERROR, element, getMessageAcceptor());
                }
            }
        }
    }
}

From source file:com.microsoft.thrifty.gen.ThriftyCodeGenerator.java

public ImmutableList<JavaFile> generateTypes() {
    ImmutableList.Builder<JavaFile> generatedTypes = ImmutableList.builder();

    for (EnumType type : schema.enums()) {
        TypeSpec spec = buildEnum(type);
        JavaFile file = assembleJavaFile(type, spec);
        if (file != null) {
            generatedTypes.add(file);/*w w w.ja  v  a2  s. c  o  m*/
        }
    }

    for (StructType type : schema.structs()) {
        TypeSpec spec = buildStruct(type);
        JavaFile file = assembleJavaFile(type, spec);
        if (file != null) {
            generatedTypes.add(file);
        }
    }

    for (StructType type : schema.exceptions()) {
        TypeSpec spec = buildStruct(type);
        JavaFile file = assembleJavaFile(type, spec);
        if (file != null) {
            generatedTypes.add(file);
        }
    }

    for (StructType type : schema.unions()) {
        TypeSpec spec = buildStruct(type);
        JavaFile file = assembleJavaFile(type, spec);
        if (file != null) {
            generatedTypes.add(file);
        }
    }

    Multimap<String, Constant> constantsByPackage = HashMultimap.create();
    for (Constant constant : schema.constants()) {
        constantsByPackage.put(constant.getNamespaceFor(NamespaceScope.JAVA), constant);
    }

    for (Map.Entry<String, Collection<Constant>> entry : constantsByPackage.asMap().entrySet()) {
        String packageName = entry.getKey();
        Collection<Constant> values = entry.getValue();
        TypeSpec spec = buildConst(values);
        JavaFile file = assembleJavaFile(packageName, spec);
        if (file != null) {
            generatedTypes.add(file);
        }
    }

    for (ServiceType type : schema.services()) {
        TypeSpec spec = serviceBuilder.buildServiceInterface(type);
        JavaFile file = assembleJavaFile(type, spec);
        if (file == null) {
            continue;
        }

        generatedTypes.add(file);

        spec = serviceBuilder.buildService(type, spec);
        file = assembleJavaFile(type, spec);
        if (file != null) {
            generatedTypes.add(file);
        }
    }

    return generatedTypes.build();
}

From source file:eu.itesla_project.cases.EntsoeCaseRepository.java

@Override
public Set<DateTime> dataAvailable(CaseType type, Set<Country> countries, Interval interval) {
    Set<UcteGeographicalCode> geographicalCodes = new HashSet<>();
    if (countries == null) {
        geographicalCodes.add(UcteGeographicalCode.UX);
    } else {/*from   w  ww  . j a  v  a  2  s.  c o m*/
        for (Country country : countries) {
            geographicalCodes.addAll(forCountryHacked(country));
        }
    }
    Multimap<DateTime, UcteGeographicalCode> dates = HashMultimap.create();
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                browse(typeDir, path -> {
                    UcteFileName ucteFileName = UcteFileName.parse(path.getFileName().toString());
                    UcteGeographicalCode geographicalCode = ucteFileName.getGeographicalCode();
                    if (geographicalCode != null
                            && !config.getForbiddenFormatsByGeographicalCode().get(geographicalCode)
                                    .contains(format.getImporter().getFormat())
                            && interval.contains(ucteFileName.getDate())) {
                        dates.put(ucteFileName.getDate(), geographicalCode);
                    }
                });
            }
        }
    }
    return dates.asMap().entrySet().stream()
            .filter(e -> new HashSet<>(e.getValue()).containsAll(geographicalCodes)).map(Map.Entry::getKey)
            .collect(Collectors.toCollection(TreeSet::new));
}

From source file:br.com.bluesoft.pronto.controller.TicketController.java

@RequestMapping("/ticket/listarPendentesPorCliente.action")
public String listarTicketsPendentesPorCliente(final Model model, final Integer kanbanStatusKey,
        final Integer clienteKey, final String ordem, final String classificacao) throws SegurancaException {

    Seguranca.validarPermissao(Papel.PRODUCT_OWNER, Papel.EQUIPE, Papel.SCRUM_MASTER);

    TicketOrdem ticketOrdem = TicketOrdem.TITULO;

    if (ordem != null && ordem.length() > 0) {
        ticketOrdem = TicketOrdem.valueOf(ordem);
    }//from   w w w .j a  v a2s .  com

    Classificacao ticketClassificacao = Classificacao.ASCENDENTE;
    if (classificacao != null && classificacao.length() > 0) {
        ticketClassificacao = Classificacao.valueOf(classificacao);
    }

    List<Ticket> tickets = null;
    tickets = ticketDao.buscar(null, kanbanStatusKey, clienteKey, ticketOrdem, ticketClassificacao);

    final Multimap<String, Ticket> ticketsAgrupados = ArrayListMultimap.create();
    for (final Ticket ticket : tickets) {
        // No exibe nem as tarefas nem os itens na lixeira
        if (ticket.getPai() == null && ticket.getBacklog().getBacklogKey() != Backlog.LIXEIRA) {
            ticketsAgrupados.put(ticket.getCliente() != null ? ticket.getCliente().getNome() : "Indefinido",
                    ticket);
        }
    }

    model.addAttribute("ticketsAgrupados", ticketsAgrupados.asMap());

    final ArrayList<String> grupo = new ArrayList<String>(ticketsAgrupados.keySet());
    Collections.sort(grupo);

    model.addAttribute("grupos", grupo);
    model.addAttribute("clienteKey", clienteKey);
    model.addAttribute("kanbanStatusKey", kanbanStatusKey);
    model.addAttribute("kanbanStatus", kanbanStatusDao.listar());
    model.addAttribute("clientes", clienteDao.listar());
    model.addAttribute("ordens", TicketOrdem.values());
    model.addAttribute("ordem", ticketOrdem);
    model.addAttribute("classificacoes", Classificacao.values());
    model.addAttribute("classificacao", ticketClassificacao);

    return VIEW_LISTAR_AGRUPADO;
}

From source file:com.sam.moca.servlet.support.SupportZip.java

/**
 * @param writer/*from  w ww.ja  v a  2 s. c  o  m*/
 * @throws IOException
 * 
 */
private void generateClusterRolesEntry(ZipOutputStream zip, CsvWriter csvWriter, BufferedWriter writer)
        throws IOException {
    ClusterRoleManager manager = (ClusterRoleManager) _system.getAttribute(ClusterRoleManager.class.getName());

    if (manager != null) {
        zip.putNextEntry(new ZipEntry("cluster-roles.csv"));
        Multimap<Node, RoleDefinition> multiMap = manager.getClusterRoles();
        MocaClusterAdministration clusterAdmin = (MocaClusterAdministration) _system
                .getAttribute(MocaClusterAdministration.class.getName());
        Map<Node, InstanceUrl> urls = clusterAdmin.getKnownNodes();

        Multimap<InstanceUrl, RoleDefinition> urlRoleMap = HashMultimap.create();

        for (Entry<Node, Collection<RoleDefinition>> entry : multiMap.asMap().entrySet()) {
            urlRoleMap.putAll(urls.get(entry.getKey()), entry.getValue());
        }

        Map<InstanceUrl, List<RoleDefinition>> copy = new HashMap<InstanceUrl, List<RoleDefinition>>();
        for (Entry<InstanceUrl, Collection<RoleDefinition>> entry : urlRoleMap.asMap().entrySet()) {
            copy.put(entry.getKey(), new ArrayList<RoleDefinition>(entry.getValue()));
        }

        csvWriter.writeValue("url");
        csvWriter.writeValue("roles");
        csvWriter.writeEndLine();

        for (Entry<InstanceUrl, List<RoleDefinition>> entry : copy.entrySet()) {
            csvWriter.writeValue(entry.getKey());
            csvWriter.writeValue(entry.getValue());
            csvWriter.writeEndLine();
        }

        // Have to flush before closing the entry
        writer.flush();
        zip.closeEntry();
    }
}

From source file:org.janusgraph.diskstorage.es.ElasticSearchIndex.java

public XContentBuilder getNewDocument(final List<IndexEntry> additions,
        KeyInformation.StoreRetriever informations, int ttl) throws BackendException {
    Preconditions.checkArgument(ttl >= 0);
    try {/*from www .  ja  va2 s.  c  o  m*/
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject();

        // JSON writes duplicate fields one after another, which forces us
        // at this stage to make de-duplication on the IndexEntry list. We don't want to pay the
        // price map storage on the Mutation level because non of other backends need that.

        Multimap<String, IndexEntry> uniq = LinkedListMultimap.create();
        for (IndexEntry e : additions) {
            uniq.put(e.field, e);
        }

        for (Map.Entry<String, Collection<IndexEntry>> add : uniq.asMap().entrySet()) {
            KeyInformation keyInformation = informations.get(add.getKey());
            Object value = null;
            switch (keyInformation.getCardinality()) {
            case SINGLE:
                value = convertToEsType(Iterators.getLast(add.getValue().iterator()).value);
                break;
            case SET:
            case LIST:
                value = add.getValue().stream().map(v -> convertToEsType(v.value)).collect(Collectors.toList())
                        .toArray();
                break;
            }

            builder.field(add.getKey(), value);
            if (hasDualStringMapping(informations.get(add.getKey()))
                    && keyInformation.getDataType() == String.class) {
                builder.field(getDualMappingName(add.getKey()), value);
            }

        }
        if (ttl > 0)
            builder.field(TTL_FIELD, TimeUnit.MILLISECONDS.convert(ttl, TimeUnit.SECONDS));

        builder.endObject();

        return builder;
    } catch (IOException e) {
        throw new PermanentBackendException("Could not write json");
    }
}

From source file:gobblin.config.client.ConfigClient.java

/**
 * batch process for {@link #getConfig(URI)} method
 * @param configKeyUris/* w  ww.  jav  a 2 s. c  o  m*/
 * @return
 * @throws ConfigStoreFactoryDoesNotExistsException
 * @throws ConfigStoreCreationException
 * @throws VersionDoesNotExistException
 */
public Map<URI, Config> getConfigs(Collection<URI> configKeyUris)
        throws ConfigStoreFactoryDoesNotExistsException, ConfigStoreCreationException,
        VersionDoesNotExistException {
    if (configKeyUris == null || configKeyUris.size() == 0)
        return Collections.emptyMap();

    Map<URI, Config> result = new HashMap<>();
    Multimap<ConfigStoreAccessor, ConfigKeyPath> partitionedAccessor = ArrayListMultimap.create();

    // map contains the mapping between ConfigKeyPath back to original URI , partitioned by ConfigStoreAccessor
    Map<ConfigStoreAccessor, Map<ConfigKeyPath, URI>> reverseMap = new HashMap<>();

    // partitioned the ConfigKeyPaths which belongs to the same store to one accessor
    for (URI u : configKeyUris) {
        ConfigStoreAccessor accessor = this.getConfigStoreAccessor(u);
        ConfigKeyPath configKeypath = ConfigClientUtils.buildConfigKeyPath(u, accessor.configStore);
        partitionedAccessor.put(accessor, configKeypath);

        if (!reverseMap.containsKey(accessor)) {
            reverseMap.put(accessor, new HashMap<ConfigKeyPath, URI>());
        }
        reverseMap.get(accessor).put(configKeypath, u);
    }

    for (Map.Entry<ConfigStoreAccessor, Collection<ConfigKeyPath>> entry : partitionedAccessor.asMap()
            .entrySet()) {
        Map<ConfigKeyPath, Config> batchResult = entry.getKey().valueInspector
                .getResolvedConfigs(entry.getValue());

        for (Map.Entry<ConfigKeyPath, Config> resultEntry : batchResult.entrySet()) {
            // get the original URI from reverseMap
            URI orgURI = reverseMap.get(entry.getKey()).get(resultEntry.getKey());
            result.put(orgURI, resultEntry.getValue());
        }
    }

    return result;
}

From source file:eu.itesla_project.entsoe.cases.EntsoeCaseRepository.java

@Override
public Set<DateTime> dataAvailable(CaseType type, Set<Country> countries, Interval interval) {
    Set<EntsoeGeographicalCode> geographicalCodes = new HashSet<>();
    if (countries == null) {
        geographicalCodes.add(EntsoeGeographicalCode.UX);
    } else {//from   w ww  . ja va  2 s  .  c  o m
        for (Country country : countries) {
            geographicalCodes.addAll(forCountryHacked(country));
        }
    }
    Multimap<DateTime, EntsoeGeographicalCode> dates = HashMultimap.create();
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                browse(typeDir, path -> {
                    EntsoeFileName entsoeFileName = EntsoeFileName.parse(path.getFileName().toString());
                    EntsoeGeographicalCode geographicalCode = entsoeFileName.getGeographicalCode();
                    if (geographicalCode != null
                            && !config.getForbiddenFormatsByGeographicalCode().get(geographicalCode)
                                    .contains(format.getImporter().getFormat())
                            && interval.contains(entsoeFileName.getDate())) {
                        dates.put(entsoeFileName.getDate(), geographicalCode);
                    }
                });
            }
        }
    }
    return dates.asMap().entrySet().stream()
            .filter(e -> new HashSet<>(e.getValue()).containsAll(geographicalCodes)).map(Map.Entry::getKey)
            .collect(Collectors.toCollection(TreeSet::new));
}

From source file:eu.itesla_project.online.tools.RunSecurityRulesOnStateTool.java

@Override
public void run(CommandLine line) throws Exception {
    String workflowId = line.getOptionValue("workflow");
    Integer stateId = Integer.valueOf(line.getOptionValue("state"));
    System.out.println("loading state " + stateId + " of workflow " + workflowId + " from the online db ...");
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    // load the network
    Network network = onlinedb.getState(workflowId, stateId);
    if (network != null) {
        OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId);
        String offlineWorkflowId = parameters.getOfflineWorkflowId();
        if (line.hasOption("offline-workflow"))
            offlineWorkflowId = line.getOptionValue("offline-workflow");
        System.out.println("checking state " + stateId + " of workflow " + workflowId
                + " against rules of offline workflow " + offlineWorkflowId + " ...");
        RulesDbClient rulesDb = config.getRulesDbClientFactoryClass().newInstance().create("rulesdb");
        RuleAttributeSet attributeSet = RuleAttributeSet.MONTE_CARLO;
        if (line.hasOption("wca"))
            attributeSet = RuleAttributeSet.WORST_CASE;
        double purityThreshold = parameters.getRulesPurityThreshold();
        // get rules from db
        Collection<RuleId> ruleIds = rulesDb.listRules(offlineWorkflowId, attributeSet);
        // TODO filter rules that does not apply to the network
        // .../*  w  w w . ja va2 s .c om*/
        // sort rules per contingency
        Multimap<String, RuleId> ruleIdsPerContingency = Multimaps.index(ruleIds,
                new Function<RuleId, String>() {
                    @Override
                    public String apply(RuleId ruleId) {
                        return ruleId.getSecurityIndexId().getContingencyId();
                    }
                });
        Map<HistoDbAttributeId, Object> values = IIDM2DB
                .extractCimValues(network, new IIDM2DB.Config(null, false)).getSingleValueMap();
        SecurityIndexType[] securityIndexTypes = parameters.getSecurityIndexes() == null
                ? SecurityIndexType.values()
                : parameters.getSecurityIndexes()
                        .toArray(new SecurityIndexType[parameters.getSecurityIndexes().size()]);
        Table table = new Table(1 + securityIndexTypes.length, BorderStyle.CLASSIC_WIDE);
        table.addCell("Contingency");
        for (SecurityIndexType securityIndexType : securityIndexTypes) {
            table.addCell(securityIndexType.toString());
        }
        // check rules
        for (Map.Entry<String, Collection<RuleId>> entry : ruleIdsPerContingency.asMap().entrySet()) {
            String contingencyId = entry.getKey();
            table.addCell(contingencyId);
            Map<SecurityIndexType, CheckStatus> checkStatus = new EnumMap<>(SecurityIndexType.class);
            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                checkStatus.put(securityIndexType, CheckStatus.NA);
            }
            for (RuleId ruleId : entry.getValue()) {
                List<SecurityRule> rules = rulesDb.getRules(offlineWorkflowId, attributeSet, contingencyId,
                        ruleId.getSecurityIndexId().getSecurityIndexType());
                if (rules.size() > 0) {
                    SecurityRule rule = rules.get(0);
                    SecurityRuleExpression securityRuleExpression = rule.toExpression(purityThreshold);
                    boolean ok = securityRuleExpression.check(values).isSafe();
                    checkStatus.put(rule.getId().getSecurityIndexId().getSecurityIndexType(),
                            ok ? CheckStatus.OK : CheckStatus.NOK);
                }
            }
            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                table.addCell(checkStatus.get(securityIndexType).name());
            }
        }
        System.out.println(table.render());
    } else {
        System.out.println("no state " + stateId + " of workflow " + workflowId + " stored in the online db");
    }
    onlinedb.close();
}