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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformEntries(NavigableMap<K, V1> fromMap,
        EntryTransformer<? super K, ? super V1, V2> transformer) 

Source Link

Document

Returns a view of a navigable map whose values are derived from the original navigable map's entries.

Usage

From source file:org.onosproject.store.primitives.resources.impl.AtomixLeaderElectorService.java

/**
 * Applies an {@link AtomixLeaderElectorOperations#GET_ALL_LEADERSHIPS} commit.
 * @param commit GetAllLeaderships commit
 * @return topic to leader mapping/*from w  w  w  . ja  v a  2s .  co m*/
 */
public Map<String, Leadership> allLeaderships(Commit<Void> commit) {
    Map<String, Leadership> result = new HashMap<>();
    try {
        result.putAll(Maps.transformEntries(elections, (k, v) -> leadership(k)));
        return result;
    } catch (Exception e) {
        logger().error("State machine operation failed", e);
        throw new IllegalStateException(e);
    }
}

From source file:biz.dfch.j.graylog.plugin.alarm.dfchBizClickatellAlarm.java

@Override
public Map<String, Object> getAttributes() {
    return Maps.transformEntries(configuration.getSource(),
            new Maps.EntryTransformer<String, Object, Object>() {
                @Override//from   w w w.  j a  v a 2  s.  c  o m
                public Object transformEntry(String key, Object value) {
                    return key + "-" + value;
                }
            });
}

From source file:org.apache.druid.indexing.overlord.hrtr.HttpRemoteTaskRunner.java

private ImmutableWorkerInfo findWorkerToRunTask(Task task) {
    WorkerBehaviorConfig workerConfig = workerConfigRef.get();
    WorkerSelectStrategy strategy;// w w w.ja v a 2s.  co  m
    if (workerConfig == null || workerConfig.getSelectStrategy() == null) {
        strategy = WorkerBehaviorConfig.DEFAULT_STRATEGY;
        log.debug("No worker selection strategy set. Using default of [%s]",
                strategy.getClass().getSimpleName());
    } else {
        strategy = workerConfig.getSelectStrategy();
    }

    return strategy.findWorkerForTask(config, ImmutableMap.copyOf(
            Maps.transformEntries(Maps.filterEntries(workers, new Predicate<Map.Entry<String, WorkerHolder>>() {
                @Override
                public boolean apply(Map.Entry<String, WorkerHolder> input) {
                    return !lazyWorkers.containsKey(input.getKey())
                            && !workersWithUnacknowledgedTask.containsKey(input.getKey())
                            && !blackListedWorkers.containsKey(input.getKey());
                }
            }), new Maps.EntryTransformer<String, WorkerHolder, ImmutableWorkerInfo>() {
                @Override
                public ImmutableWorkerInfo transformEntry(String key, WorkerHolder value) {
                    return value.toImmutable();
                }
            })), task);
}

From source file:org.locationtech.geogig.storage.postgresql.PGObjectStore.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from  w w w .  j  a  va  2 s. co  m
public <T extends RevObject> Iterator<T> getAll(Iterable<ObjectId> ids, BulkOpListener listener,
        Class<T> type) {

    checkNotNull(ids, "ids is null");
    checkNotNull(listener, "listener is null");
    checkNotNull(type, "type is null");
    checkState(isOpen(), "Database is closed");
    config.checkRepositoryExists();

    final Set<ObjectId> queryIds = ids instanceof Set ? (Set<ObjectId>) ids : Sets.newHashSet(ids);

    ImmutableMap<ObjectId, byte[]> cached = byteCache.getAllPresent(queryIds);

    Iterator<T> hits = Collections.emptyIterator();
    Iterator<T> stream = Collections.emptyIterator();

    if (!cached.isEmpty()) {

        Map<ObjectId, T> cachedObjects = Maps.transformEntries(cached, (id, bytes) -> {
            RevObject o = encoder.decode(id, bytes);
            if (type.isAssignableFrom(o.getClass())) {
                listener.found(id, Integer.valueOf(bytes.length));
                return type.cast(o);
            }
            listener.notFound(id);
            return null;
        });

        hits = Iterators.filter(cachedObjects.values().iterator(), Predicates.notNull());
    }
    if (queryIds.size() > cached.size()) {
        Set<ObjectId> misses = Sets.difference(queryIds, cached.keySet());
        stream = new GetAllIterator(dataSource, misses.iterator(), type, listener, this);
    }

    return Iterators.concat(hits, stream);
}

From source file:com.continuuity.weave.yarn.YarnWeavePreparer.java

private Closeable saveWeaveSpec(WeaveSpecification spec, final Multimap<String, LocalFile> localFiles,
        Map<String, LocalResource> localResources) throws IOException {
    // Rewrite LocalFiles inside weaveSpec
    Map<String, RuntimeSpecification> runtimeSpec = Maps.transformEntries(spec.getRunnables(),
            new Maps.EntryTransformer<String, RuntimeSpecification, RuntimeSpecification>() {
                @Override//from   ww  w  .j  a  va 2s .com
                public RuntimeSpecification transformEntry(String key, RuntimeSpecification value) {
                    return new DefaultRuntimeSpecification(value.getName(), value.getRunnableSpecification(),
                            value.getResourceSpecification(), localFiles.get(key));
                }
            });

    // Serialize into a local temp file.
    LOG.debug("Create and copy weaveSpec.json");
    Location location = createTempLocation("weaveSpec", ".json");
    Writer writer = new OutputStreamWriter(location.getOutputStream(), Charsets.UTF_8);
    try {
        WeaveSpecificationAdapter.create()
                .toJson(new DefaultWeaveSpecification(spec.getName(), runtimeSpec, spec.getOrders()), writer);
    } finally {
        writer.close();
    }
    LOG.debug("Done weaveSpec.json");
    localResources.put("weaveSpec.json", YarnUtils.createLocalResource(location));

    // Delete the file when the closeable is invoked.
    return getCloseable(location);
}

From source file:com.continuuity.weave.yarn.YarnWeavePreparer.java

private Closeable saveLocalFiles(Map<String, LocalResource> localResources, Set<String> keys)
        throws IOException {
    Map<String, LocalFile> localFiles = Maps.transformEntries(
            Maps.filterKeys(localResources, Predicates.in(keys)),
            new Maps.EntryTransformer<String, LocalResource, LocalFile>() {
                @Override//from  w ww.j  ava2s  .  c o m
                public LocalFile transformEntry(String key, LocalResource value) {
                    try {
                        return new DefaultLocalFile(key,
                                ConverterUtils.getPathFromYarnURL(value.getResource()).toUri(),
                                value.getTimestamp(), value.getSize(),
                                value.getType() != LocalResourceType.FILE, value.getPattern());
                    } catch (URISyntaxException e) {
                        throw Throwables.propagate(e);
                    }
                }
            });

    LOG.debug("Create and copy localFiles.json");
    Location location = createTempLocation("localFiles", ".json");
    Writer writer = new OutputStreamWriter(location.getOutputStream(), Charsets.UTF_8);
    try {
        new GsonBuilder().registerTypeAdapter(LocalFile.class, new LocalFileCodec()).create()
                .toJson(localFiles.values(), new TypeToken<List<LocalFile>>() {
                }.getType(), writer);
    } finally {
        writer.close();
    }
    LOG.debug("Done localFiles.json");
    localResources.put("localFiles.json", YarnUtils.createLocalResource(location));
    return getCloseable(location);
}

From source file:com.twitter.aurora.scheduler.thrift.SchedulerThriftInterface.java

@Override
public Response getJobs(@Nullable String maybeNullRole) {
    Optional<String> ownerRole = Optional.fromNullable(maybeNullRole);

    // Ensure we only return one JobConfiguration for each JobKey.
    Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap();

    // Query the task store, find immediate jobs, and synthesize a JobConfiguration for them.
    // This is necessary because the ImmediateJobManager doesn't store jobs directly and
    // ImmediateJobManager#getJobs always returns an empty Collection.
    Query.Builder scope = ownerRole.isPresent() ? Query.roleScoped(ownerRole.get()) : Query.unscoped();
    Multimap<IJobKey, IScheduledTask> tasks = Tasks
            .byJobKey(Storage.Util.weaklyConsistentFetchTasks(storage, scope.active()));

    jobs.putAll(Maps.transformEntries(tasks.asMap(),
            new Maps.EntryTransformer<IJobKey, Collection<IScheduledTask>, IJobConfiguration>() {
                @Override//from ww w  .  j a va2s. c o m
                public IJobConfiguration transformEntry(IJobKey jobKey, Collection<IScheduledTask> tasks) {

                    // Pick an arbitrary task for each immediate job. The chosen task might not be the most
                    // recent if the job is in the middle of an update or some shards have been selectively
                    // created.
                    TaskConfig firstTask = tasks.iterator().next().getAssignedTask().getTask().newBuilder();
                    return IJobConfiguration.build(
                            new JobConfiguration().setKey(jobKey.newBuilder()).setOwner(firstTask.getOwner())
                                    .setTaskConfig(firstTask).setInstanceCount(tasks.size()));
                }
            }));

    // Get cron jobs directly from the manager. Do this after querying the task store so the real
    // template JobConfiguration for a cron job will overwrite the synthesized one that could have
    // been created above.
    Predicate<IJobConfiguration> configFilter = ownerRole.isPresent()
            ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys.CONFIG_TO_ROLE)
            : Predicates.<IJobConfiguration>alwaysTrue();
    jobs.putAll(Maps.uniqueIndex(FluentIterable.from(cronJobManager.getJobs()).filter(configFilter),
            JobKeys.FROM_CONFIG));

    return new Response().setResponseCode(OK).setResult(Result
            .getJobsResult(new GetJobsResult().setConfigs(IJobConfiguration.toBuildersSet(jobs.values()))));
}

From source file:com.gnapse.common.math.Factorization.java

private static <T> String toString(Map<T, Integer> map, final Function<T, String> itemsToString,
        final int signum) {
    final EntryTransformer<T, Integer, String> transformer = new Maps.EntryTransformer<T, Integer, String>() {
        @Override//from  w  w  w  . j a v a  2s .  co  m
        public String transformEntry(T key, Integer value) {
            final String keyString = itemsToString.apply(key);
            return value.intValue() == signum ? keyString : String.format("%s^%s", keyString, signum * value);
        }
    };
    final Collection<String> items = Maps.transformEntries(map, transformer).values();

    if (items.isEmpty()) {
        return "1";
    }
    if (items.size() == 1) {
        return items.iterator().next();
    }

    return joiner.join(items);
}

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

private Map<IJobKey, IJobConfiguration> getJobs(Optional<String> ownerRole,
        Multimap<IJobKey, IScheduledTask> tasks) {

    // We need to synthesize the JobConfiguration from the the current tasks because the
    // ImmediateJobManager doesn't store jobs directly and ImmediateJobManager#getJobs always
    // returns an empty Collection.
    Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap();

    jobs.putAll(Maps.transformEntries(tasks.asMap(), (jobKey, tasks1) -> {

        // Pick the latest transitioned task for each immediate job since the job can be in the
        // middle of an update or some shards have been selectively created.
        TaskConfig mostRecentTaskConfig = Tasks.getLatestActiveTask(tasks1).getAssignedTask().getTask()
                .newBuilder();/*from   ww  w.j  a  v a 2s  .  co m*/

        return IJobConfiguration.build(
                new JobConfiguration().setKey(jobKey.newBuilder()).setOwner(mostRecentTaskConfig.getOwner())
                        .setTaskConfig(mostRecentTaskConfig).setInstanceCount(tasks1.size()));
    }));

    // Get cron jobs directly from the manager. Do this after querying the task store so the real
    // template JobConfiguration for a cron job will overwrite the synthesized one that could have
    // been created above.
    Predicate<IJobConfiguration> configFilter = ownerRole.isPresent()
            ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys::getRole)
            : Predicates.alwaysTrue();
    jobs.putAll(Maps.uniqueIndex(FluentIterable.from(Storage.Util.fetchCronJobs(storage)).filter(configFilter),
            IJobConfiguration::getKey));

    return jobs;
}

From source file:edu.buaa.satla.analysis.cfa.CProgramScope.java

private static Map<String, CSimpleDeclaration> extractUniqueSimpleDeclarations(
        Map<String, CSimpleDeclaration> pQualifiedDeclarations) {
    return Maps
            .transformEntries(Maps.filterEntries(from(pQualifiedDeclarations.values()).index(GET_NAME).asMap(),
                    new Predicate<Map.Entry<String, Collection<CSimpleDeclaration>>>() {

                        @Override
                        public boolean apply(Entry<String, Collection<CSimpleDeclaration>> pArg0) {
                            return pArg0.getValue().size() == 1;
                        }/*from  w ww.j  ava  2s .c  o m*/

                    }),
                    new Maps.EntryTransformer<String, Collection<CSimpleDeclaration>, CSimpleDeclaration>() {

                        @Override
                        public CSimpleDeclaration transformEntry(String pArg0,
                                @Nonnull Collection<CSimpleDeclaration> pArg1) {
                            return pArg1.iterator().next();
                        }

                    });
}