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:io.druid.indexing.overlord.RemoteTaskRunner.java

/**
 * Ensures no workers are already running a task before assigning the task to a worker.
 * It is possible that a worker is running a task that the RTR has no knowledge of. This occurs when the RTR
 * needs to bootstrap after a restart./* www.j a  va 2  s.  c  om*/
 *
 * @param taskRunnerWorkItem - the task to assign
 *
 * @return true iff the task is now assigned
 */
private boolean tryAssignTask(final Task task, final RemoteTaskRunnerWorkItem taskRunnerWorkItem)
        throws Exception {
    Preconditions.checkNotNull(task, "task");
    Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem");
    Preconditions.checkArgument(task.getId().equals(taskRunnerWorkItem.getTaskId()), "task id != workItem id");

    if (runningTasks.containsKey(task.getId()) || findWorkerRunningTask(task.getId()) != null) {
        log.info("Task[%s] already running.", task.getId());
        return true;
    } else {
        // Nothing running this task, announce it in ZK for a worker to run it
        WorkerBehaviorConfig workerConfig = workerConfigRef.get();
        WorkerSelectStrategy strategy;
        if (workerConfig == null || workerConfig.getSelectStrategy() == null) {
            log.warn("No worker selections strategy set. Using default.");
            strategy = WorkerBehaviorConfig.DEFAULT_STRATEGY;
        } else {
            strategy = workerConfig.getSelectStrategy();
        }
        final Optional<ImmutableZkWorker> immutableZkWorker = strategy.findWorkerForTask(config,
                ImmutableMap.copyOf(Maps.transformEntries(
                        Maps.filterEntries(zkWorkers, new Predicate<Map.Entry<String, ZkWorker>>() {
                            @Override
                            public boolean apply(Map.Entry<String, ZkWorker> input) {
                                return !lazyWorkers.containsKey(input.getKey());
                            }
                        }), new Maps.EntryTransformer<String, ZkWorker, ImmutableZkWorker>() {
                            @Override
                            public ImmutableZkWorker transformEntry(String key, ZkWorker value) {
                                return value.toImmutable();
                            }
                        })),
                task);
        if (immutableZkWorker.isPresent()) {
            final ZkWorker zkWorker = zkWorkers.get(immutableZkWorker.get().getWorker().getHost());
            return announceTask(task, zkWorker, taskRunnerWorkItem);
        } else {
            log.debug("Worker nodes %s do not have capacity to run any more tasks!", zkWorkers.values());
            return false;
        }
    }
}

From source file:org.apache.abdera2.activities.extra.Extra.java

/**
 * Two ASObject's are considered equivalent in identity if 
 * they share the same objectType and id property
 * values. Note: This implementation does not yet take 
 * the downstreamDuplicates and upstreamDuplicates properties
 * into account when determining equivalence.
 *//*from  ww  w . j  a v a2 s . c o  m*/
public static <X extends ASObject> Equivalence<X> identity() {
    return new Equivalence<X>() {
        protected boolean doEquivalent(X a, X b) {
            Selector<Map.Entry<String, Object>> filter = ASBase.withFields("id", "alias", "objectType",
                    "displayName");
            Map<String, Object> map1 = Maps.transformEntries(a.toMap(filter), lower_val);
            Map<String, Object> map2 = Maps.transformEntries(b.toMap(filter), lower_val);
            MapDifference<String, Object> diff = Maps.difference(map1, map2);
            return ((diff.entriesInCommon().containsKey("alias") || diff.entriesInCommon().containsKey("id")
                    || diff.entriesInCommon().containsKey("displayName"))
                    && !diff.entriesDiffering().containsKey("objectType")
                    && !diff.entriesDiffering().containsKey("id") && !diff.entriesOnlyOnLeft().containsKey("id")
                    && !diff.entriesOnlyOnRight().containsKey("id"));
        }

        protected int doHash(ASObject t) {
            return MoreFunctions.genHashCode(1, t.getId(), t.getProperty("alias"), t.getObjectType());
        }
    };
}

From source file:com.android.tools.idea.avdmanager.AvdOptionsModel.java

@Override
protected void handleFinished() {
    // By this point we should have both a Device and a SystemImage
    Device device = myDevice.getValue();
    SystemImageDescription systemImage = mySystemImage.getValue();

    Map<String, String> hardwareProperties = DeviceManager.getHardwareProperties(device);
    Map<String, Object> userEditedProperties = generateUserEditedPropertiesMap();

    // Remove the SD card setting that we're not using
    String sdCard = null;/*  w  w w  . j a v a  2s .com*/

    boolean useExisting = myUseExternalSdCard.get();
    if (!useExisting) {
        if (sdCardStorage().get().isPresent() && myOriginalSdCard != null
                && sdCardStorage().getValue().equals(myOriginalSdCard.get())) {
            // unchanged, use existing card
            useExisting = true;
        }
    }

    boolean hasSdCard = false;
    if (!useExisting) {

        userEditedProperties.remove(AvdWizardUtils.EXISTING_SD_LOCATION);
        Storage storage = null;
        myOriginalSdCard = new ObjectValueProperty<>(mySdCardStorage.getValue());
        if (mySdCardStorage.get().isPresent()) {
            storage = mySdCardStorage.getValue();
            sdCard = toIniString(storage, false);
        }
        hasSdCard = storage != null && storage.getSize() > 0;
    } else if (!Strings.isNullOrEmpty(existingSdLocation.get())) {
        sdCard = existingSdLocation.get();
        userEditedProperties.remove(AvdWizardUtils.SD_CARD_STORAGE_KEY);
        hasSdCard = true;
    }
    hardwareProperties.put(HardwareProperties.HW_SDCARD, toIniString(hasSdCard));
    // Remove any internal keys from the map
    userEditedProperties = Maps.filterEntries(userEditedProperties,
            input -> !input.getKey().startsWith(AvdWizardUtils.WIZARD_ONLY) && input.getValue() != null);

    // Call toIniString() on all remaining values
    hardwareProperties.putAll(Maps.transformEntries(userEditedProperties, (key, value) -> {
        if (value instanceof Storage) {
            if (key.equals(AvdWizardUtils.RAM_STORAGE_KEY) || key.equals(AvdWizardUtils.VM_HEAP_STORAGE_KEY)) {
                return toIniString((Storage) value, true);
            } else {
                return toIniString((Storage) value, false);
            }
        } else if (value instanceof Boolean) {
            return toIniString((Boolean) value);
        } else if (value instanceof File) {
            return toIniString((File) value);
        } else if (value instanceof Double) {
            return toIniString((Double) value);
        } else if (value instanceof GpuMode) {
            return ((GpuMode) value).getGpuSetting();
        } else {
            return value.toString();
        }
    }));

    File skinFile = (myAvdDeviceData.customSkinFile().get().isPresent())
            ? myAvdDeviceData.customSkinFile().getValue()
            : AvdWizardUtils.resolveSkinPath(device.getDefaultHardware().getSkinFile(), systemImage,
                    FileOpUtils.create());

    if (myBackupSkinFile.get().isPresent()) {
        hardwareProperties.put(AvdManager.AVD_INI_BACKUP_SKIN_PATH, myBackupSkinFile.getValue().getPath());
    }

    // Add defaults if they aren't already set differently
    if (!hardwareProperties.containsKey(AvdManager.AVD_INI_SKIN_DYNAMIC)) {
        hardwareProperties.put(AvdManager.AVD_INI_SKIN_DYNAMIC, toIniString(true));
    }
    if (!hardwareProperties.containsKey(HardwareProperties.HW_KEYBOARD)) {
        hardwareProperties.put(HardwareProperties.HW_KEYBOARD, toIniString(false));
    }

    boolean isCircular = myAvdDeviceData.isScreenRound().get();

    String tempAvdName = myAvdId.get();
    final String avdName = tempAvdName.isEmpty() ? calculateAvdName(myAvdInfo, hardwareProperties, device)
            : tempAvdName;

    // If we're editing an AVD and we downgrade a system image, wipe the user data with confirmation
    if (myAvdInfo != null) {
        ISystemImage image = myAvdInfo.getSystemImage();
        if (image != null) {
            int oldApiLevel = image.getAndroidVersion().getFeatureLevel();
            int newApiLevel = systemImage.getVersion().getFeatureLevel();
            final String oldApiName = image.getAndroidVersion().getApiString();
            final String newApiName = systemImage.getVersion().getApiString();
            if (oldApiLevel > newApiLevel || (oldApiLevel == newApiLevel
                    && image.getAndroidVersion().isPreview() && !systemImage.getVersion().isPreview())) {
                final AtomicReference<Boolean> shouldContinue = new AtomicReference<>();
                ApplicationManager.getApplication().invokeAndWait(() -> {
                    String message = String.format(Locale.getDefault(),
                            "You are about to downgrade %1$s from API level %2$s to API level %3$s.\n"
                                    + "This requires a wipe of the userdata partition of the AVD.\nDo you wish to "
                                    + "continue with the data wipe?",
                            avdName, oldApiName, newApiName);
                    int result = Messages.showYesNoDialog((Project) null, message, "Confirm Data Wipe",
                            AllIcons.General.QuestionDialog);
                    shouldContinue.set(result == Messages.YES);
                }, ModalityState.any());
                if (shouldContinue.get()) {
                    AvdManagerConnection.getDefaultAvdManagerConnection().wipeUserData(myAvdInfo);
                } else {
                    return;
                }
            }
        }
    }

    AvdManagerConnection connection = AvdManagerConnection.getDefaultAvdManagerConnection();
    myCreatedAvd = connection.createOrUpdateAvd(myAvdInfo, avdName, device, systemImage,
            mySelectedAvdOrientation.get(), isCircular, sdCard, skinFile, hardwareProperties, false);
    if (myCreatedAvd == null) {
        ApplicationManager.getApplication().invokeAndWait(() -> Messages.showErrorDialog((Project) null,
                "An error occurred while creating the AVD. See idea.log for details.", "Error Creating AVD"),
                ModalityState.any());
    }
}

From source file:org.apache.twill.yarn.YarnTwillPreparer.java

private TwillRuntimeSpecification saveSpecification(TwillSpecification spec, Path targetFile)
        throws IOException {
    final Multimap<String, LocalFile> runnableLocalFiles = populateRunnableLocalFiles(spec);

    // Rewrite LocalFiles inside twillSpec
    Map<String, RuntimeSpecification> runtimeSpec = Maps.transformEntries(spec.getRunnables(),
            new Maps.EntryTransformer<String, RuntimeSpecification, RuntimeSpecification>() {
                @Override/* w ww .  j ava2 s . co m*/
                public RuntimeSpecification transformEntry(String key, RuntimeSpecification value) {
                    return new DefaultRuntimeSpecification(value.getName(), value.getRunnableSpecification(),
                            value.getResourceSpecification(), runnableLocalFiles.get(key));
                }
            });

    // Serialize into a local temp file.
    LOG.debug("Creating {}", targetFile);
    try (Writer writer = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8)) {
        EventHandlerSpecification eventHandler = spec.getEventHandler();
        if (eventHandler == null) {
            eventHandler = new LogOnlyEventHandler().configure();
        }
        TwillSpecification newTwillSpec = new DefaultTwillSpecification(spec.getName(), runtimeSpec,
                spec.getOrders(), spec.getPlacementPolicies(), eventHandler);
        Map<String, String> configMap = Maps.newHashMap();
        for (Map.Entry<String, String> entry : config) {
            if (entry.getKey().startsWith("twill.")) {
                configMap.put(entry.getKey(), entry.getValue());
            }
        }

        TwillRuntimeSpecification twillRuntimeSpec = new TwillRuntimeSpecification(newTwillSpec,
                appLocation.getLocationFactory().getHomeLocation().getName(), appLocation.toURI(),
                zkConnectString, runId, twillSpec.getName(), config.get(YarnConfiguration.RM_SCHEDULER_ADDRESS),
                logLevels, maxRetries, configMap, runnableConfigs);
        TwillRuntimeSpecificationAdapter.create().toJson(twillRuntimeSpec, writer);
        LOG.debug("Done {}", targetFile);
        return twillRuntimeSpec;
    }
}

From source file:org.apache.druid.indexing.overlord.RemoteTaskRunner.java

/**
 * Ensures no workers are already running a task before assigning the task to a worker.
 * It is possible that a worker is running a task that the RTR has no knowledge of. This occurs when the RTR
 * needs to bootstrap after a restart.//  w  w w .j  a va2s .  c  o m
 *
 * @param taskRunnerWorkItem - the task to assign
 *
 * @return true iff the task is now assigned
 */
private boolean tryAssignTask(final Task task, final RemoteTaskRunnerWorkItem taskRunnerWorkItem)
        throws Exception {
    Preconditions.checkNotNull(task, "task");
    Preconditions.checkNotNull(taskRunnerWorkItem, "taskRunnerWorkItem");
    Preconditions.checkArgument(task.getId().equals(taskRunnerWorkItem.getTaskId()), "task id != workItem id");

    if (runningTasks.containsKey(task.getId()) || findWorkerRunningTask(task.getId()) != null) {
        log.info("Task[%s] already running.", task.getId());
        return true;
    } else {
        // Nothing running this task, announce it in ZK for a worker to run it
        WorkerBehaviorConfig workerConfig = workerConfigRef.get();
        WorkerSelectStrategy strategy;
        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();
        }

        ZkWorker assignedWorker = null;
        final ImmutableWorkerInfo immutableZkWorker;
        try {
            synchronized (workersWithUnacknowledgedTask) {
                immutableZkWorker = strategy.findWorkerForTask(config,
                        ImmutableMap.copyOf(Maps.transformEntries(
                                Maps.filterEntries(zkWorkers, new Predicate<Map.Entry<String, ZkWorker>>() {
                                    @Override
                                    public boolean apply(Map.Entry<String, ZkWorker> input) {
                                        return !lazyWorkers.containsKey(input.getKey())
                                                && !workersWithUnacknowledgedTask.containsKey(input.getKey())
                                                && !blackListedWorkers.contains(input.getValue());
                                    }
                                }), new Maps.EntryTransformer<String, ZkWorker, ImmutableWorkerInfo>() {
                                    @Override
                                    public ImmutableWorkerInfo transformEntry(String key, ZkWorker value) {
                                        return value.toImmutable();
                                    }
                                })),
                        task);

                if (immutableZkWorker != null && workersWithUnacknowledgedTask
                        .putIfAbsent(immutableZkWorker.getWorker().getHost(), task.getId()) == null) {
                    assignedWorker = zkWorkers.get(immutableZkWorker.getWorker().getHost());
                }
            }

            if (assignedWorker != null) {
                return announceTask(task, assignedWorker, taskRunnerWorkItem);
            } else {
                log.debug(
                        "Unsuccessful task-assign attempt for task [%s] on workers [%s]. Workers to ack tasks are [%s].",
                        task.getId(), zkWorkers.values(), workersWithUnacknowledgedTask);
            }

            return false;
        } finally {
            if (assignedWorker != null) {
                workersWithUnacknowledgedTask.remove(assignedWorker.getWorker().getHost());
                //if this attempt won the race to run the task then other task might be able to use this worker now after task ack.
                runPendingTasks();
            }
        }
    }
}

From source file:com.b2international.snowowl.snomed.reasoner.server.normalform.RelationshipNormalFormGenerator.java

private Iterable<Group> toGroups(final boolean preserveNumbers,
        final Collection<StatementFragment> nonIsARelationshipFragments) {

    final Map<Integer, Collection<StatementFragment>> relationshipsByGroupId = Multimaps
            .index(nonIsARelationshipFragments, new Function<StatementFragment, Integer>() {
                @Override/*w  ww  . j a v  a2  s  . c  om*/
                public Integer apply(final StatementFragment input) {
                    return input.getGroup();
                }
            }).asMap();

    final Collection<Collection<Group>> groups = Maps.transformEntries(relationshipsByGroupId,
            new EntryTransformer<Integer, Collection<StatementFragment>, Collection<Group>>() {
                @Override
                public Collection<Group> transformEntry(final Integer key,
                        final Collection<StatementFragment> values) {
                    final Iterable<UnionGroup> unionGroups = toUnionGroups(preserveNumbers, values);
                    final Iterable<UnionGroup> disjointUnionGroups = getDisjointComparables(unionGroups);

                    if (key == 0) {
                        // Relationships in group 0 form separate groups
                        return ImmutableList.copyOf(toZeroGroups(preserveNumbers, disjointUnionGroups));
                    } else {
                        // Other group numbers produce a single group from all fragments
                        return ImmutableList.of(toNonZeroGroup(preserveNumbers, key, disjointUnionGroups));
                    }
                }
            }).values();

    return Iterables.concat(groups);
}

From source file:com.b2international.snowowl.snomed.reasoner.server.normalform.RelationshipNormalFormGenerator.java

private Iterable<UnionGroup> toUnionGroups(final boolean preserveNumbers,
        final Collection<StatementFragment> values) {
    final Map<Integer, Collection<StatementFragment>> relationshipsByUnionGroupId = Multimaps
            .index(values, new Function<StatementFragment, Integer>() {
                @Override//from  www .  j a  v a 2 s  .  c  om
                public Integer apply(final StatementFragment input) {
                    return input.getUnionGroup();
                }
            }).asMap();

    final Collection<Collection<UnionGroup>> unionGroups = Maps.transformEntries(relationshipsByUnionGroupId,
            new EntryTransformer<Integer, Collection<StatementFragment>, Collection<UnionGroup>>() {
                @Override
                public Collection<UnionGroup> transformEntry(final Integer key,
                        final Collection<StatementFragment> values) {
                    if (key == 0) {
                        // Relationships in union group 0 form separate union groups
                        return ImmutableList.copyOf(toZeroUnionGroups(values));
                    } else {
                        // Other group numbers produce a single union group from all fragments
                        return ImmutableList.of(toNonZeroUnionGroup(preserveNumbers, key, values));
                    }
                }
            }).values();

    return Iterables.concat(unionGroups);
}

From source file:org.kie.workbench.common.screens.projecteditor.client.editor.ProjectScreenPresenter.java

@Override
public void triggerBuildAndDeploy() {
    specManagementService.call(new RemoteCallback<Collection<ServerTemplate>>() {
        @Override//from  ww w . j  av a  2s  .  c o m
        public void callback(final Collection<ServerTemplate> serverTemplates) {
            //TODO use config for using defaults or not
            final String defaultContainerId = project.getPom().getGav().getArtifactId() + "_"
                    + project.getPom().getGav().getVersion();
            final String defaultContainerAlias = project.getPom().getGav().getArtifactId();
            final boolean defaultStartContainer = true;
            if (serverTemplates.isEmpty()) {
                getSafeExecutedCommand(getBuildDeployCommand(DeploymentMode.VALIDATED)).execute();
            } else if (serverTemplates.size() == 1) {
                final ServerTemplate serverTemplate = serverTemplates.iterator().next();
                final Set<String> existingContainers = FluentIterable.from(serverTemplate.getContainersSpec())
                        .transform(s -> s.getId()).toSet();
                if (existingContainers.contains(defaultContainerId) == false) {
                    getSafeExecutedCommand(
                            getBuildDeployProvisionCommand(DeploymentMode.VALIDATED, defaultContainerId,
                                    defaultContainerAlias, serverTemplate.getId(), defaultStartContainer))
                                            .execute();
                } else {
                    deploymentScreenPopupView.setValidateExistingContainerCallback(
                            containerName -> existingContainers.contains(containerName));
                    deploymentScreenPopupView.setContainerId(defaultContainerId);
                    deploymentScreenPopupView.setContainerAlias(defaultContainerAlias);
                    deploymentScreenPopupView.setStartContainer(defaultStartContainer);
                    deploymentScreenPopupView.configure(new com.google.gwt.user.client.Command() {
                        @Override
                        public void execute() {
                            final String containerId = deploymentScreenPopupView.getContainerId();
                            final String containerAlias = deploymentScreenPopupView.getContainerAlias();
                            final boolean startContainer = deploymentScreenPopupView.getStartContainer();

                            getSafeExecutedCommand(getBuildDeployProvisionCommand(DeploymentMode.VALIDATED,
                                    containerId, containerAlias, serverTemplate.getId(), startContainer))
                                            .execute();

                            deploymentScreenPopupView.hide();
                        }
                    });
                    deploymentScreenPopupView.show();
                }
            } else {
                final Map<String, ServerTemplate> serverTemplatesIds = Maps.uniqueIndex(serverTemplates,
                        s -> s.getId());
                final Map<String, Set<String>> containerNames = Maps.transformEntries(serverTemplatesIds,
                        (id, server) -> FluentIterable.from(server.getContainersSpec())
                                .transform(c -> c.getContainerName()).toSet());
                deploymentScreenPopupView.addServerTemplates(FluentIterable.from(serverTemplatesIds.keySet())
                        .toSortedSet(String.CASE_INSENSITIVE_ORDER));
                deploymentScreenPopupView.setValidateExistingContainerCallback(containerName -> FluentIterable
                        .from(containerNames.get(deploymentScreenPopupView.getServerTemplate()))
                        .contains(containerName));
                deploymentScreenPopupView.setContainerId(defaultContainerId);
                deploymentScreenPopupView.setContainerAlias(defaultContainerAlias);
                deploymentScreenPopupView.setStartContainer(defaultStartContainer);
                deploymentScreenPopupView.configure(new com.google.gwt.user.client.Command() {
                    @Override
                    public void execute() {
                        final String containerId = deploymentScreenPopupView.getContainerId();
                        final String containerAlias = deploymentScreenPopupView.getContainerAlias();
                        final String serverTemplate = deploymentScreenPopupView.getServerTemplate();
                        final boolean startContainer = deploymentScreenPopupView.getStartContainer();

                        getSafeExecutedCommand(getBuildDeployProvisionCommand(DeploymentMode.VALIDATED,
                                containerId, containerAlias, serverTemplate, startContainer)).execute();

                        deploymentScreenPopupView.hide();
                    }
                });
                deploymentScreenPopupView.show();
            }
        }
    }).listServerTemplates();

}