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.immutables.value.processor.OkJsons.java

public Iterable<OkTypeAdapterTypes> typeAdapters() {
    Multimap<AbstractDeclaring, ValueType> byDeclaring = HashMultimap.create();
    for (ValueType value : values().values()) {
        Protoclass protoclass = value.constitution.protoclass();
        if (protoclass.kind().isValue()) {
            Optional<AbstractDeclaring> typeAdaptersProvider = protoclass.okTypeAdaptersProvider();
            if (typeAdaptersProvider.isPresent()) {
                byDeclaring.put(typeAdaptersProvider.get(), value);
            } else if (protoclass.okJsonTypeAdapters().isPresent() && protoclass.declaringType().isPresent()) {
                DeclaringType topLevel = protoclass.declaringType().get().associatedTopLevel();
                byDeclaring.put(topLevel, value);
            }/*www.  j  a  v a2  s.  c o  m*/
        }
    }

    ImmutableList.Builder<OkTypeAdapterTypes> builder = ImmutableList.builder();
    for (Entry<AbstractDeclaring, Collection<ValueType>> entry : byDeclaring.asMap().entrySet()) {
        builder.add(ImmutableOkTypeAdapterTypes.builder().definedBy(entry.getKey())
                .addAllTypes(entry.getValue()).build());
    }

    return builder.build();
}

From source file:org.sonar.ide.eclipse.internal.ui.views.MeasuresView.java

@Override
protected void doSetInput(Object input) {
    final ISonarResource element = (ISonarResource) input;
    Job job = new AbstractRemoteSonarJob("Loading measures") {
        @Override/*from   w  w w .ja va 2s.c o m*/
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Loading measures for " + element.getKey(), IProgressMonitor.UNKNOWN);
            update(null);

            Collection<ISonarMeasure> measures = null;

            if (ProjectProperties.getInstance(element.getProject()).isAnalysedLocally()) {
                // Local mode
                try {
                    measures = (Collection<ISonarMeasure>) element.getResource()
                            .getSessionProperty(SonarCorePlugin.SESSION_PROPERY_MEASURES);
                } catch (CoreException e) {
                    // ignore
                }
            } else {
                // Remote mode
                EclipseSonar index = EclipseSonar.getInstance(element.getProject());
                final SourceCode sourceCode = index.search(element);
                if (sourceCode != null) {
                    measures = getMeasures(index, element);
                }
            }

            if (measures == null) {
                measures = Collections.emptyList();
            }

            final List<ISonarMeasure> favorites = Lists.newArrayList();

            // Group by key and domain
            final Map<String, ISonarMeasure> measuresByKey = Maps.newHashMap();
            final Multimap<String, ISonarMeasure> measuresByDomain = ArrayListMultimap.create();
            for (ISonarMeasure measure : measures) {
                if (SonarUiPlugin.getFavouriteMetricsManager().isFavorite(measure.getMetricDef())) {
                    favorites.add(measure);
                }
                String domain = measure.getMetricDef().getDomain();
                measuresByDomain.put(domain, measure);
                measuresByKey.put(measure.getMetricDef().getKey(), measure);
            }

            MeasuresView.this.measuresByDomain = Maps.newHashMap(measuresByDomain.asMap());
            MeasuresView.this.measuresByKey = measuresByKey;
            if (!favorites.isEmpty()) {
                MeasuresView.this.measuresByDomain.put(FAVORITES_CATEGORY, favorites);
            }
            update(MeasuresView.this.measuresByDomain);

            monitor.done();
            return Status.OK_STATUS;
        }
    };
    IWorkbenchSiteProgressService siteService = (IWorkbenchSiteProgressService) getSite()
            .getAdapter(IWorkbenchSiteProgressService.class);
    siteService.schedule(job);
}

From source file:eu.itesla_project.ucte.network.ext.UcteNetworkExt.java

private void updateSubstation() {
    if (substations == null) {
        LOGGER.trace("Update substations...");
        substations = new ArrayList<>();
        node2voltageLevel = new HashMap<>();
        UndirectedGraph<UcteNodeCode, Object> graph = createSubstationGraph(network);
        for (Set<UcteNodeCode> substationNodes : new ConnectivityInspector<>(graph).connectedSets()) {
            // the main node of the substation is not an xnode and the one with the highest voltage
            // level and the lowest busbar number.
            UcteNodeCode mainNode = substationNodes.stream().sorted((nodeCode1, nodeCode2) -> {
                if (nodeCode1.getUcteCountryCode() == UcteCountryCode.XX
                        && nodeCode2.getUcteCountryCode() != UcteCountryCode.XX) {
                    return 1;
                } else if (nodeCode1.getUcteCountryCode() != UcteCountryCode.XX
                        && nodeCode2.getUcteCountryCode() == UcteCountryCode.XX) {
                    return -1;
                } else {
                    int c = Float.compare(nodeCode2.getVoltageLevelCode().getVoltageLevel(),
                            nodeCode1.getVoltageLevelCode().getVoltageLevel());
                    if (c == 0) {
                        c = nodeCode2.getBusbar().compareTo(nodeCode1.getBusbar());
                    }//from   w w w. j a  v a2s  .c o m
                    return c;
                }
            }).findFirst().get();

            Multimap<UcteVoltageLevelCode, UcteNodeCode> nodesByVoltageLevel = Multimaps.index(substationNodes,
                    nodeCode -> {
                        return nodeCode.getVoltageLevelCode();
                    });

            String substationName = mainNode.getUcteCountryCode().getUcteCode()
                    + mainNode.getGeographicalSpot();
            List<UcteVoltageLevel> voltageLevels = new ArrayList<>();
            UcteSubstation substation = new UcteSubstation(substationName, voltageLevels);
            substations.add(substation);

            LOGGER.trace("Define substation {}", substationName);

            for (Map.Entry<UcteVoltageLevelCode, Collection<UcteNodeCode>> entry : nodesByVoltageLevel.asMap()
                    .entrySet()) {
                UcteVoltageLevelCode vlc = entry.getKey();
                Collection<UcteNodeCode> voltageLevelNodes = entry.getValue();
                String voltageLevelName = mainNode.getUcteCountryCode().getUcteCode()
                        + mainNode.getGeographicalSpot() + vlc.ordinal();
                UcteVoltageLevel voltageLevel = new UcteVoltageLevel(voltageLevelName, substation,
                        voltageLevelNodes);
                voltageLevels.add(voltageLevel);
                for (UcteNodeCode voltageLevelNode : voltageLevelNodes) {
                    node2voltageLevel.put(voltageLevelNode, voltageLevel);
                }

                LOGGER.trace("Define voltage level {} as a group of {} nodes", voltageLevelName,
                        voltageLevelNodes);
            }
        }
    }
}

From source file:org.onosproject.cli.net.ResourcesCommand.java

private void printResource(Resource resource, int level) {
    // workaround to preserve the original behavior of ResourceService#getRegisteredResources
    Set<Resource> children;
    if (resource instanceof DiscreteResource) {
        children = resourceService.getRegisteredResources(((DiscreteResource) resource).id());
    } else {//from w  ww.  java2 s  .c  o  m
        children = Collections.emptySet();
    }

    if (resource.equals(Resource.ROOT)) {
        print("ROOT");
    } else {
        String resourceName = resource.simpleTypeName();
        if (resource instanceof ContinuousResource) {
            print("%s%s: %f", Strings.repeat(" ", level), resourceName,
                    ((ContinuousResource) resource).value());
            // Continuous resource is terminal node, stop here
            return;
        } else {
            String availability = "";
            if (availablesOnly && !children.isEmpty()) {
                // intermediate nodes cannot be omitted, print availability
                if (resourceService.isAvailable(resource)) {
                    availability = " ";
                } else {
                    availability = " ";
                }
            }
            String toString = String.valueOf(resource.valueAs(Object.class).orElse(""));
            if (toString.startsWith(resourceName)) {
                print("%s%s%s", Strings.repeat(" ", level), toString, availability);
            } else {
                print("%s%s: %s%s", Strings.repeat(" ", level), resourceName, toString, availability);
            }
        }
    }

    // Classify children into aggregatable terminal resources and everything else

    Set<Class<?>> aggregatableTypes = ImmutableSet.<Class<?>>builder().add(VlanId.class).add(MplsLabel.class)
            .build();
    // (last() resource name) -> { Resource }
    Multimap<String, Resource> aggregatables = ArrayListMultimap.create();
    List<Resource> nonAggregatable = new ArrayList<>();

    for (Resource r : children) {
        if (!isPrintTarget(r)) {
            continue;
        }

        if (r instanceof ContinuousResource) {
            // non-aggregatable terminal node
            nonAggregatable.add(r);
        } else if (Iterables.any(aggregatableTypes, r::isTypeOf)) {
            // aggregatable & terminal node
            String simpleName = r.simpleTypeName();
            aggregatables.put(simpleName, r);
        } else {
            nonAggregatable.add(r);
        }
    }

    // print aggregated (terminal)
    aggregatables.asMap().entrySet().forEach(e -> {
        // for each type...
        String resourceName = e.getKey();

        RangeSet<Long> rangeSet = TreeRangeSet.create();

        // aggregate into RangeSet
        e.getValue().stream().map(res -> {
            if (res.isTypeOf(VlanId.class)) {
                return (long) res.valueAs(VlanId.class).get().toShort();
            } else if (res.isTypeOf(MplsLabel.class)) {
                return (long) res.valueAs(MplsLabel.class).get().toInt();
            } else if (res.isTypeOf(TributarySlot.class)) {
                return res.valueAs(TributarySlot.class).get().index();
            }
            // TODO support Lambda (OchSignal types)
            return 0L;
        }).map(Range::singleton).map(range -> range.canonical(DiscreteDomain.longs())).forEach(rangeSet::add);

        print("%s%s: %s", Strings.repeat(" ", level + 1), resourceName, rangeSet);
    });

    // print non-aggregatables (recurse)
    if (sort) {
        nonAggregatable.stream().sorted((o1, o2) -> String.valueOf(o1.id()).compareTo(String.valueOf(o2.id())))
                .forEach(r -> printResource(r, level + 1));
    } else {
        nonAggregatable.forEach(r -> printResource(r, level + 1));
    }
}

From source file:org.apache.beam.sdk.options.ProxyInvocationHandler.java

/**
 * Construct a mapping from an option name to its {@link PipelineOptions} interface(s)
 * declarations. An option may be declared in multiple interfaces. If it is overridden in a
 * type hierarchy, only the overriding interface will be included.
 *///w w w .ja v  a2s  .  c o  m
private Multimap<String, PipelineOptionSpec> buildOptionNameToSpecMap(Set<PipelineOptionSpec> props) {

    Multimap<String, PipelineOptionSpec> optionsMap = HashMultimap.create();
    for (PipelineOptionSpec prop : props) {
        optionsMap.put(prop.getName(), prop);
    }

    // Filter out overridden options
    for (Map.Entry<String, Collection<PipelineOptionSpec>> entry : optionsMap.asMap().entrySet()) {

        /* Compare all interfaces for an option pairwise (iface1, iface2) to look for type
         hierarchies. If one is the base-class of the other, remove it from the output and continue
         iterating.
                
         This is an N^2 operation per-option, but the number of interfaces defining an option
         should always be small (usually 1). */
        List<PipelineOptionSpec> specs = Lists.newArrayList(entry.getValue());
        if (specs.size() < 2) {
            // Only one known implementing interface, no need to check for inheritance
            continue;
        }

        for (int i = 0; i < specs.size() - 1; i++) {
            Class<?> iface1 = specs.get(i).getDefiningInterface();
            for (int j = i + 1; j < specs.size(); j++) {
                Class<?> iface2 = specs.get(j).getDefiningInterface();

                if (iface1.isAssignableFrom(iface2)) {
                    optionsMap.remove(entry.getKey(), specs.get(i));
                    specs.remove(i);

                    // Removed element at current "i" index. Set iterators to re-evaluate
                    // new "i" element in outer loop.
                    i--;
                    j = specs.size();
                } else if (iface2.isAssignableFrom(iface1)) {
                    optionsMap.remove(entry.getKey(), specs.get(j));
                    specs.remove(j);

                    // Removed element at current "j" index. Set iterator to re-evaluate
                    // new "j" element in inner-loop.
                    j--;
                }
            }
        }
    }

    return optionsMap;
}

From source file:co.cask.cdap.internal.app.services.ApplicationLifecycleService.java

/**
 * Delete an application specified by appId.
 *
 * @param appId the {@link Id.Application} of the application to be removed
 * @throws Exception//from w  ww . ja  v a2  s. co m
 */
public void removeApplication(final Id.Application appId) throws Exception {
    //Check if all are stopped.
    boolean appRunning = runtimeService.checkAnyRunning(new Predicate<Id.Program>() {
        @Override
        public boolean apply(Id.Program programId) {
            return programId.getApplication().equals(appId);
        }
    }, ProgramType.values());

    if (appRunning) {
        throw new CannotBeDeletedException(appId);
    }

    ApplicationSpecification spec = store.getApplication(appId);
    if (spec == null) {
        throw new NotFoundException(appId);
    }

    //Delete the schedules
    for (WorkflowSpecification workflowSpec : spec.getWorkflows().values()) {
        Id.Program workflowProgramId = Id.Program.from(appId, ProgramType.WORKFLOW, workflowSpec.getName());
        scheduler.deleteSchedules(workflowProgramId, SchedulableProgramType.WORKFLOW);
    }

    deleteMetrics(appId.getNamespaceId(), appId.getId());

    //Delete all preferences of the application and of all its programs
    deletePreferences(appId);

    // Delete all streams and queues state of each flow
    // TODO: This should be unified with the DeletedProgramHandlerStage
    for (FlowSpecification flowSpecification : spec.getFlows().values()) {
        Id.Program flowProgramId = Id.Program.from(appId, ProgramType.FLOW, flowSpecification.getName());

        // Collects stream name to all group ids consuming that stream
        Multimap<String, Long> streamGroups = HashMultimap.create();
        for (FlowletConnection connection : flowSpecification.getConnections()) {
            if (connection.getSourceType() == FlowletConnection.Type.STREAM) {
                long groupId = FlowUtils.generateConsumerGroupId(flowProgramId, connection.getTargetName());
                streamGroups.put(connection.getSourceName(), groupId);
            }
        }
        // Remove all process states and group states for each stream
        String namespace = String.format("%s.%s", flowProgramId.getApplicationId(), flowProgramId.getId());
        for (Map.Entry<String, Collection<Long>> entry : streamGroups.asMap().entrySet()) {
            streamConsumerFactory.dropAll(Id.Stream.from(appId.getNamespaceId(), entry.getKey()), namespace,
                    entry.getValue());
        }

        queueAdmin.dropAllForFlow(Id.Flow.from(appId, flowSpecification.getName()));
    }
    deleteProgramLocations(appId);

    Location appArchive = store.getApplicationArchiveLocation(appId);
    Preconditions.checkNotNull(appArchive, "Could not find the location of application", appId.getId());
    if (!appArchive.delete()) {
        LOG.debug("Could not delete application archive");
    }
    store.removeApplication(appId);

    try {
        usageRegistry.unregister(appId);
    } catch (Exception e) {
        LOG.warn("Failed to unregister usage of app: {}", appId, e);
    }
}

From source file:co.cask.http.BasicHttpResponder.java

@Override
public void sendContent(HttpResponseStatus status, @Nullable ChannelBuffer content, String contentType,
        @Nullable Multimap<String, String> headers) {
    Preconditions.checkArgument(responded.compareAndSet(false, true), "Response has been already sent");
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);

    if (content != null) {
        response.setContent(content);//from  www .  ja  v  a  2 s.  c  o  m
        response.setHeader(HttpHeaders.Names.CONTENT_TYPE, contentType);
        response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    } else {
        response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, 0);
    }

    if (keepAlive) {
        response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Add headers, note will override all headers set by the framework
    if (headers != null) {
        for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) {
            response.setHeader(entry.getKey(), entry.getValue());
        }
    }

    ChannelFuture future = channel.write(response);
    if (!keepAlive || status.getCode() >= 400) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.heliosapm.opentsdb.client.aop.ShorthandScript.java

private void printReflectionsRepo(final Reflections ref) {
    final StringBuilder b = new StringBuilder("\n\t======= Reflections List:");
    for (String s : ref.getStore().keySet()) {
        b.append("\n").append("Scanner:").append(s);
        Multimap<String, String> mm = ref.getStore().get(s);
        for (Map.Entry<String, Collection<String>> entry : mm.asMap().entrySet()) {
            b.append("\n\t").append(entry.getKey());
            for (String n : entry.getValue()) {
                b.append("\n\t\t").append(n);
            }//from w  ww.j ava 2s. c  om
        }
    }
    log(b.toString());
}

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

private void generate(FileWriter writer) throws IOException {
    for (EnumType type : schema.enums()) {
        TypeSpec spec = buildEnum(type);
        JavaFile file = assembleJavaFile(type, spec);
        writer.write(file);//from   ww w .j  av  a  2  s  .c  o  m
    }

    for (StructType struct : schema.structs()) {
        TypeSpec spec = buildStruct(struct);
        JavaFile file = assembleJavaFile(struct, spec);
        writer.write(file);
    }

    for (StructType exception : schema.exceptions()) {
        TypeSpec spec = buildStruct(exception);
        JavaFile file = assembleJavaFile(exception, spec);
        writer.write(file);
    }

    for (StructType union : schema.unions()) {
        TypeSpec spec = buildStruct(union);
        JavaFile file = assembleJavaFile(union, spec);
        writer.write(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);
        writer.write(file);
    }

    for (Service service : schema.services()) {
        TypeSpec spec = serviceBuilder.buildServiceInterface(service);
        JavaFile file = assembleJavaFile(service, spec);
        writer.write(file);

        spec = serviceBuilder.buildService(service, spec);
        file = assembleJavaFile(service, spec);
        writer.write(file);
    }
}

From source file:org.summer.dsl.xbase.scoping.featurecalls.AbstractStaticMethodsFeatureForTypeProvider.java

protected Map<JvmTypeReference, Collection<JvmTypeReference>> getVisibleJvmTypesContainingStaticMethods(
        Iterable<JvmTypeReference> hierarchy) {
    Multimap<JvmTypeReference, JvmTypeReference> result = LinkedListMultimap.create();
    final Map<JvmTypeReference, Collection<String>> staticTypeNames = getVisibleTypesContainingStaticMethods(
            hierarchy);//  w  w w  . ja v  a  2s .c  o  m
    for (final Map.Entry<JvmTypeReference, Collection<String>> e : staticTypeNames.entrySet()) {
        for (final String staticTypeName : e.getValue()) {
            JvmTypeReference staticType = cache.get(Tuples.create(this, staticTypeName), context,
                    new Provider<JvmTypeReference>() {
                        public JvmTypeReference get() {
                            return getTypeReferences().getTypeForName(staticTypeName, context);
                        }
                    });
            if (staticType != null)
                result.put(e.getKey(), staticType);
        }
    }
    return result.asMap();
}