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

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

Introduction

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

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterEntries(BiMap<K, V> unfiltered,
        Predicate<? super Entry<K, V>> entryPredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered that satisfy a predicate.

Usage

From source file:org.opentestsystem.authoring.testauth.service.impl.ScoringRuleHelper.java

protected List<BlueprintElement> findBlueprintElementsMissingScoringRule(final String assessmentId) {
    final Assessment assessment = this.assessmentRepository.findOne(assessmentId);
    final List<Segment> segmentList = this.sharedPublisherHelper.retrieveSegmentList(assessmentId);
    final List<BlueprintElement> blueprintElementList = this.sharedPublisherHelper
            .getActiveBlueprintElements(assessmentId);
    final List<AffinityGroup> affinityGroupList = this.sharedPublisherHelper
            .getActiveAffinityGroups(assessmentId);
    final Map<BlueprintReferenceType, Map<String, String>> blueprintReferenceMap = this.sharedPublisherHelper
            .buildBlueprintReferenceMap(assessment, segmentList, blueprintElementList, affinityGroupList);
    final List<ScoringRule> scoringRuleList = this.sharedPublisherHelper.retrieveScoringRules(assessmentId);
    final ScoringRuleData scoringRuleData = this.sharedPublisherHelper.setupScoringRuleData(assessmentId,
            blueprintReferenceMap, scoringRuleList, blueprintElementList, false);
    final List<String> blueprintElementStandardKeysCoveredByScoringRule = Lists
            .transform(scoringRuleData.getComputationRuleList(), COMPRULE_BPE_ID_TRANSFORMER);

    final Map<String, BlueprintElement> bpElementMap = Maps.uniqueIndex(blueprintElementList,
            BPELEMENT_STANDARD_KEY_TRANSFORMER);

    final List<BlueprintElement> blueprintElementsNotCoveredByScoringRule = Lists.newArrayList(Maps
            .filterEntries(bpElementMap,
                    BPE_WITHOUT_SCORULE_FILTER.getInstance(blueprintElementStandardKeysCoveredByScoringRule))
            .values());/*  w  ww . ja  va 2s. c om*/
    return blueprintElementsNotCoveredByScoringRule;
}

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./*from   w w w.  j  a  v a  2  s  . co  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) {
            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:com.qcadoo.view.internal.components.grid.GridComponentPattern.java

public Map<String, GridComponentColumn> getColumns() {
    // FIXME MAKU -> KRNA: I think we should return an unmodifable (immutable) map or (if mutability were intended) pack them
    // into SynchronizedMap.
    return Maps.filterEntries(columns,
            Predicates.compose(COLUMNS_VISIBLE_FOR_TENANT_PREDICATE, VALUE_FROM_MAP_ENTRY_FUNCTION));
}

From source file:org.eclipse.acceleo.engine.internal.evaluation.AcceleoEvaluationContext.java

/**
 * This will be called by the generation engine once all evaluations are finished for this generation. It
 * will be used to call for the current generation strategy's global handlers.
 *//*from   ww  w .j  ava  2  s  . com*/
public void hookGenerationEnd() {
    final Map<String, Map<String, String>> lostCode = new HashMap<String, Map<String, String>>();
    for (Map.Entry<Writer, Map<String, String>> entry : userCodeBlocks.entrySet()) {
        if (!entry.getValue().isEmpty()) {
            final String filePath = ((AbstractAcceleoWriter) entry.getKey()).getTargetPath();
            lostCode.put(filePath, entry.getValue());
        }
    }
    if (!lostCode.isEmpty()) {
        strategy.createLostFiles(lostCode);
    }
    try {
        strategy.flushWriters(generationPreview);
    } catch (IOException e) {
        throw new AcceleoEvaluationException(
                AcceleoEngineMessages.getString("AcceleoEvaluationContext.WriteError"), e); //$NON-NLS-1$
    }

    Map<String, Integer> filteredFiles = Maps.filterEntries(generateFiles,
            new Predicate<Map.Entry<String, Integer>>() {
                public boolean apply(Map.Entry<String, Integer> input) {
                    return input.getValue().intValue() > 1;
                }
            });

    if (!filteredFiles.isEmpty()) {
        final StringBuilder message = new StringBuilder(
                AcceleoEngineMessages.getString("AcceleoEvaluationContext.OverrodeFiles")); //$NON-NLS-1$
        message.append('\n').append('\n');
        for (Map.Entry<String, Integer> file : filteredFiles.entrySet()) {
            message.append(file.getKey() + " : " + file.getValue().toString() + " times" + '\n'); //$NON-NLS-1$ //$NON-NLS-2$
        }
        AcceleoEnginePlugin.log(message.toString(), false);
    }
}

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;/*from w ww  .  ja  v a2 s .co  m*/

    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.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./*from w  w w .  j  ava2s  .co  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:org.elasticsearch.test.InternalTestCluster.java

private synchronized Set<String> nRandomDataNodes(int numNodes) {
    assert size() >= numNodes;
    NavigableMap<String, NodeAndClient> dataNodes = Maps.filterEntries(nodes,
            new EntryNodePredicate(new DataNodePredicate()));
    return Sets.newHashSet(Iterators.limit(dataNodes.keySet().iterator(), numNodes));
}

From source file:org.opentestsystem.delivery.testadmin.scheduling.SchedulerHelper.java

private boolean studentsStillToBeScheduled(final Map<String, ScheduledStudent> studentsToBeScheduled,
        final Assessment assessment) {

    final Map<String, ScheduledStudent> filtered = Maps.filterEntries(studentsToBeScheduled,
            new Predicate<Map.Entry<String, ScheduledStudent>>() {
                @Override/*from w ww .j a  v a  2 s . c o  m*/
                public boolean apply(final Map.Entry<String, ScheduledStudent> entry) {

                    if (entry.getValue().isEligibleForAssessment(assessment)
                            && !entry.getValue().isStudentScheduled(assessment)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });

    return !filtered.isEmpty();
}

From source file:org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.java

private static Map<ConfigElement.PathIdentifier, Object> getGlobalSubset(
        Map<ConfigElement.PathIdentifier, Object> m) {
    return Maps.filterEntries(m, new Predicate<Map.Entry<ConfigElement.PathIdentifier, Object>>() {
        @Override// w  w  w  . j ava  2  s. co  m
        public boolean apply(@Nullable Map.Entry<ConfigElement.PathIdentifier, Object> entry) {
            assert entry.getKey().element.isOption();
            return ((ConfigOption) entry.getKey().element).isGlobal();
        }
    });
}

From source file:org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.java

private static Map<ConfigElement.PathIdentifier, Object> getLocalSubset(
        Map<ConfigElement.PathIdentifier, Object> m) {
    return Maps.filterEntries(m, new Predicate<Map.Entry<ConfigElement.PathIdentifier, Object>>() {
        @Override/*  ww  w .  j a  v  a  2 s. c om*/
        public boolean apply(@Nullable Map.Entry<ConfigElement.PathIdentifier, Object> entry) {
            assert entry.getKey().element.isOption();
            return ((ConfigOption) entry.getKey().element).isLocal();
        }
    });
}