Example usage for com.google.common.collect Maps uniqueIndex

List of usage examples for com.google.common.collect Maps uniqueIndex

Introduction

In this page you can find the example usage for com.google.common.collect Maps uniqueIndex.

Prototype

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Returns a map with the given values , indexed by keys derived from those values.

Usage

From source file:org.opennms.netmgt.dao.jaxb.WSManDataCollectionConfigDaoJaxb.java

public List<SystemDefinition> getSystemDefinitionsForCollection(Collection collection) {
    if (collection.getIncludeAllSystemDefinitions() != null) {
        // Return all available system definitions if requested
        return getConfig().getSystemDefinition();
    } else {// w ww .j a v  a  2 s. co m
        // Map all of the available system definitions by name for easy lookup
        final Map<String, SystemDefinition> sysDefsByName = Maps.uniqueIndex(getConfig().getSystemDefinition(),
                sd -> sd.getName());
        // Gather the requested system definitions
        final List<SystemDefinition> sysDefs = Lists.newArrayList();
        for (String sysDefName : collection.getIncludeSystemDefinition()) {
            SystemDefinition sysDef = sysDefsByName.get(sysDefName);
            if (sysDef == null) {
                LOG.warn(
                        "Collection with name {} includes system definition with name {}, but no such definition was found.",
                        collection.getName(), sysDefName);
                continue;
            }
            sysDefs.add(sysDef);
        }
        return sysDefs;
    }
}

From source file:com.github.nyrkovalex.deploy.me.parsing.Parser.java

Set<Server> parse(JsonObject jsonObject, Iterable<Fileset> filesets) {
    Map<String, Fileset> filesetIndex = Maps.uniqueIndex(filesets, Named::name);
    return jsonObject.entrySet().stream()
            .map(entry -> serverParser.parse(entry.getKey(), filesetIndex, entry.getValue())).collect(toSet());
}

From source file:org.opendaylight.sxp.route.core.RouteReactorImpl.java

/**
 * Add all unchanged {@link RoutingDefinition} into provided {@link List}
 *
 * @param routingDifference         contains configuration changes
 * @param outcomingRouteDefinitions where result will be stored
 *//*  www  . j  a v a2  s .c  o  m*/
private void collectUnchanged(final MapDifference<IpAddress, RoutingDefinition> routingDifference,
        final List<RoutingDefinition> outcomingRouteDefinitions) {
    final SxpClusterRoute sxpClusterRouteOper = datastoreAccess.readSynchronous(
            SxpClusterRouteManager.SXP_CLUSTER_ROUTE_CONFIG_PATH, LogicalDatastoreType.OPERATIONAL);

    final ImmutableMap<IpAddress, RoutingDefinition> routingDefinitionMap = Optional
            .ofNullable(sxpClusterRouteOper).map(SxpClusterRoute::getRoutingDefinition)
            .map((routingDefinitions -> Maps.uniqueIndex(routingDefinitions, RoutingDefinition::getIpAddress)))
            .orElse(ImmutableMap.of());

    routingDifference.entriesInCommon().forEach((virtualIface, routingDefinition) -> {
        final RoutingDefinition routingDef = routingDefinitionMap.get(virtualIface);
        if (routingDef != null) {
            outcomingRouteDefinitions.add(routingDef);
        } else {
            LOG.debug("Missing unchainged routing definition in current DS/operational: {}", routingDefinition);
        }
    });
}

From source file:com.b2international.snowowl.core.internal.validation.ValidationBootstrap.java

@Override
public void preRun(SnowOwlConfiguration configuration, Environment env) throws Exception {
    if (env.isEmbedded() || env.isServer()) {
        final ObjectMapper mapper = env.service(ObjectMapper.class);
        final Index validationIndex = Indexes.createIndex("validations", mapper,
                new Mappings(ValidationIssue.class, ValidationRule.class, ValidationWhiteList.class),
                env.service(IndexSettings.class));

        final ValidationRepository repository = new ValidationRepository(validationIndex);
        env.services().registerService(ValidationRepository.class, repository);

        // register always available validation rule evaluators
        ValidationRuleEvaluator.Registry
                .register(new GroovyScriptValidationRuleEvaluator(env.getConfigDirectory().toPath()));

        // initialize validation thread pool
        final ValidationConfiguration validationConfig = configuration
                .getModuleConfig(ValidationConfiguration.class);

        int numberOfValidationThreads = validationConfig.getNumberOfValidationThreads();
        int maxConcurrentExpensiveJobs = validationConfig.getMaxConcurrentExpensiveJobs();
        int maxConcurrentNormalJobs = validationConfig.getMaxConcurrentNormalJobs();

        env.services().registerService(ValidationConfiguration.class, validationConfig);
        env.services().registerService(ValidationThreadPool.class, new ValidationThreadPool(
                numberOfValidationThreads, maxConcurrentExpensiveJobs, maxConcurrentNormalJobs));

        final List<File> listOfFiles = Arrays.asList(env.getConfigDirectory().listFiles());
        final Set<File> validationRuleFiles = Sets.newHashSet();
        final Pattern validationFilenamePattern = Pattern.compile("(validation-rules)-(\\w+).(json)");
        for (File file : listOfFiles) {
            final String fileName = file.getName();
            final Matcher match = validationFilenamePattern.matcher(fileName);
            if (match.matches()) {
                validationRuleFiles.add(file);
            }/* w  w  w . ja  v a  2  s .c o m*/
        }

        final List<ValidationRule> availableRules = Lists.newArrayList();
        for (File validationRulesFile : validationRuleFiles) {
            LOG.info("Synchronizing validation rules from file: " + validationRulesFile);
            availableRules
                    .addAll(mapper.readValue(validationRulesFile, new TypeReference<List<ValidationRule>>() {
                    }));
        }

        repository.write(writer -> {
            final Map<String, ValidationRule> existingRules = Maps.uniqueIndex(
                    ValidationRequests.rules().prepareSearch().all().buildAsync().getRequest().execute(env),
                    ValidationRule::getId);

            // index all rules from the file, this will update existing rules as well
            final Set<String> ruleIds = newHashSet();
            for (ValidationRule rule : availableRules) {
                writer.put(rule.getId(), rule);
                ruleIds.add(rule.getId());
            }

            // delete rules and associated issues
            Set<String> rulesToDelete = Sets.difference(existingRules.keySet(), ruleIds);
            if (!rulesToDelete.isEmpty()) {
                final Set<String> issuesToDelete = newHashSet(writer.searcher().search(Query
                        .select(String.class).from(ValidationIssue.class).fields(ValidationIssue.Fields.ID)
                        .where(Expressions.builder()
                                .filter(Expressions.matchAny(ValidationIssue.Fields.RULE_ID, rulesToDelete))
                                .build())
                        .limit(Integer.MAX_VALUE).build()).getHits());
                writer.removeAll(ImmutableMap.<Class<?>, Set<String>>of(ValidationRule.class, rulesToDelete,
                        ValidationIssue.class, issuesToDelete));
            }

            writer.commit();
            return null;
        });

    }
}

From source file:de.metas.ui.web.window.datatypes.json.JSONDocumentBase.java

public final void setFields(final Collection<JSONDocumentField> fields) {
    setFields(fields == null ? null : Maps.uniqueIndex(fields, (field) -> field.getField()));
}

From source file:org.apache.aurora.scheduler.async.preemptor.PendingTaskProcessor.java

@Override
public void run() {
    metrics.recordTaskProcessorRun();// w  w w.  j  a  v  a  2  s.  com
    storage.read(new Storage.Work.Quiet<Void>() {
        @Override
        public Void apply(StoreProvider store) {
            Multimap<String, PreemptionVictim> slavesToActiveTasks = clusterState.getSlavesToActiveTasks();

            if (slavesToActiveTasks.isEmpty()) {
                // No preemption victims to consider.
                return null;
            }

            // Group the offers by slave id so they can be paired with active tasks from the same slave.
            Map<String, HostOffer> slavesToOffers = Maps.uniqueIndex(offerManager.getOffers(),
                    OFFER_TO_SLAVE_ID);

            Set<String> allSlaves = Sets
                    .newHashSet(Iterables.concat(slavesToOffers.keySet(), slavesToActiveTasks.keySet()));

            // The algorithm below attempts to find a reservation for every task group by matching
            // it against all available slaves until a preemption slot is found. Groups are evaluated
            // in a round-robin fashion to ensure fairness (e.g.: G1, G2, G3, G1, G2).
            // A slave is removed from further matching once a reservation is made. Similarly, all
            // identical task group instances are removed from further iteration if none of the
            // available slaves could yield a preemption proposal. A consuming iterator is used for
            // task groups to ensure iteration order is preserved after a task group is removed.
            LoadingCache<IJobKey, AttributeAggregate> jobStates = attributeCache(store);
            List<TaskGroupKey> pendingGroups = fetchIdlePendingGroups(store);
            Iterator<TaskGroupKey> groups = Iterators.consumingIterator(pendingGroups.iterator());
            while (!pendingGroups.isEmpty()) {
                boolean matched = false;
                TaskGroupKey group = groups.next();
                ITaskConfig task = group.getTask();

                metrics.recordPreemptionAttemptFor(task);
                Iterator<String> slaveIterator = allSlaves.iterator();
                while (slaveIterator.hasNext()) {
                    String slaveId = slaveIterator.next();
                    Optional<ImmutableSet<PreemptionVictim>> candidates = preemptionVictimFilter
                            .filterPreemptionVictims(task, slavesToActiveTasks.get(slaveId),
                                    jobStates.getUnchecked(task.getJob()),
                                    Optional.fromNullable(slavesToOffers.get(slaveId)), store);

                    metrics.recordSlotSearchResult(candidates, task);
                    if (candidates.isPresent()) {
                        // Slot found -> remove slave to avoid multiple task reservations.
                        slaveIterator.remove();
                        slotCache.put(new PreemptionProposal(candidates.get(), slaveId), group);
                        matched = true;
                        break;
                    }
                }
                if (!matched) {
                    // No slot found for the group -> remove group and reset group iterator.
                    pendingGroups.removeAll(ImmutableSet.of(group));
                    groups = Iterators.consumingIterator(pendingGroups.iterator());
                }
            }
            return null;
        }
    });
}

From source file:org.apache.aurora.scheduler.updater.JobDiff.java

/**
 * Calculates the diff necessary to change the current state of a job to the proposed state.
 *
 * @param taskStore Store to fetch the job's current state from.
 * @param job Job being diffed.//from  ww  w  . j a  v a  2 s  .co m
 * @param proposedState Proposed state to move the job towards.
 * @param scope Instances to limit the diff to.
 * @return A diff of the current state compared with {@code proposedState}, within {@code scope}.
 */
public static JobDiff compute(TaskStore taskStore, IJobKey job, Map<Integer, ITaskConfig> proposedState,
        Set<IRange> scope) {

    Map<Integer, ITaskConfig> currentState = ImmutableMap.copyOf(Maps.transformValues(
            Maps.uniqueIndex(taskStore.fetchTasks(Query.jobScoped(job).active()), Tasks::getInstanceId),
            Tasks::getConfig));

    JobDiff diff = computeUnscoped(currentState, job, proposedState);
    if (scope.isEmpty()) {
        return diff;
    } else {
        Set<Integer> limit = Numbers.rangesToInstanceIds(scope);
        Map<Integer, ITaskConfig> replaced = ImmutableMap
                .copyOf(Maps.filterKeys(diff.getReplacedInstances(), Predicates.in(limit)));
        Set<Integer> replacements = ImmutableSet
                .copyOf(Sets.intersection(diff.getReplacementInstances(), limit));

        Set<Integer> unchangedIds = ImmutableSet.copyOf(Sets.difference(
                ImmutableSet.copyOf(Sets.difference(currentState.keySet(), replaced.keySet())), replacements));
        Map<Integer, ITaskConfig> unchanged = ImmutableMap
                .copyOf(Maps.filterKeys(currentState, Predicates.in(unchangedIds)));

        return new JobDiff(replaced, replacements, unchanged);
    }
}

From source file:springfox.documentation.schema.property.field.FieldModelPropertyProvider.java

@Override
public List<ModelProperty> propertiesFor(ResolvedType type, ModelContext givenContext) {

    List<ModelProperty> serializationCandidates = newArrayList();
    BeanDescription beanDescription = beanDescription(type, givenContext);
    Map<String, BeanPropertyDefinition> propertyLookup = Maps.uniqueIndex(beanDescription.findProperties(),
            BeanPropertyDefinitions.beanPropertyByInternalName());

    for (ResolvedField childField : fieldProvider.in(type)) {
        LOG.debug("Reading property {}", childField.getName());
        if (propertyLookup.containsKey(childField.getName())) {
            BeanPropertyDefinition propertyDefinition = propertyLookup.get(childField.getName());
            Optional<BeanPropertyDefinition> jacksonProperty = BeanPropertyDefinitions
                    .jacksonPropertyWithSameInternalName(beanDescription, propertyDefinition);
            AnnotatedMember member = propertyDefinition.getField();
            serializationCandidates.addAll(
                    newArrayList(serializationCandidates(member, childField, jacksonProperty, givenContext)));
        }/*from  w  ww.java 2s.c o m*/
    }
    return serializationCandidates;
}

From source file:org.sonar.server.qualityprofile.ws.CompareAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    String leftKey = request.mandatoryParam(PARAM_LEFT_KEY);
    String rightKey = request.mandatoryParam(PARAM_RIGHT_KEY);

    try (DbSession dbSession = dbClient.openSession(false)) {
        QualityProfileDto left = dbClient.qualityProfileDao().selectByKey(dbSession, leftKey);
        checkArgument(left != null, "Could not find left profile '%s'", leftKey);
        QualityProfileDto right = dbClient.qualityProfileDao().selectByKey(dbSession, rightKey);
        checkArgument(right != null, "Could not find right profile '%s'", rightKey);

        checkArgument(Objects.equals(left.getOrganizationUuid(), right.getOrganizationUuid()),
                "Cannot compare quality profiles of different organizations. Quality profile left with key '%s' belongs to organization '%s', "
                        + "quality profile right with key '%s' belongs to organization '%s'.",
                leftKey, left.getOrganizationUuid(), rightKey, right.getOrganizationUuid());

        QProfileComparisonResult result = comparator.compare(dbSession, left, right);

        List<RuleDefinitionDto> referencedRules = dbClient.ruleDao().selectDefinitionByKeys(dbSession,
                new ArrayList<>(result.collectRuleKeys()));
        Map<RuleKey, RuleDefinitionDto> rulesByKey = Maps.uniqueIndex(referencedRules,
                RuleDefinitionDto::getKey);
        Map<String, RuleRepositoryDto> repositoriesByKey = Maps
                .uniqueIndex(dbClient.ruleRepositoryDao().selectAll(dbSession), RuleRepositoryDto::getKey);
        writeResult(response.newJsonWriter(), result, rulesByKey, repositoriesByKey);
    }//w  w  w .ja va  2  s.co m
}

From source file:com.offbytwo.jenkins.JenkinsServer.java

/**
 * Get a list of all the defined jobs on the server (at the specified view
 * level and in the specified folder)//from   ww w . j a v  a 2 s  .  com
 *
 * @return list of defined jobs (view level, for details @see Job#details
 * @throws IOException
 */
public Map<String, Job> getJobs(FolderJob folder, String view) throws IOException {
    String path = "/";
    if (folder != null) {
        path = folder.getUrl();
    }
    Class<? extends MainView> viewClass = MainView.class;
    if (view != null) {
        path = path + "view/" + EncodingUtils.encode(view) + "/";
        viewClass = View.class;
    }
    List<Job> jobs = client.get(path, viewClass).getJobs();
    return Maps.uniqueIndex(jobs, new Function<Job, String>() {
        @Override
        public String apply(Job job) {
            job.setClient(client);
            return job.getName();
        }
    });
}