Example usage for com.google.common.collect Multimap putAll

List of usage examples for com.google.common.collect Multimap putAll

Introduction

In this page you can find the example usage for com.google.common.collect Multimap putAll.

Prototype

boolean putAll(@Nullable K key, Iterable<? extends V> values);

Source Link

Document

Stores a key-value pair in this multimap for each of values , all using the same key, key .

Usage

From source file:org.eclipse.viatra.query.runtime.matchers.psystem.rewriters.PBodyNormalizer.java

/**
 * Inserts "weakened alternative" constraints suggested by the meta context that aid in coming up with a query plan.
 *///from w  w  w  .  j  a v a  2 s .  c o  m
void expandWeakenedAlternativeConstraints(PBody body) {
    Set<TypeJudgement> allJudgements = new HashSet<TypeJudgement>();
    Set<TypeJudgement> newJudgementsToAdd = new HashSet<TypeJudgement>();
    Queue<TypeJudgement> judgementsToProcess = new LinkedList<TypeJudgement>();
    Multimap<TypeJudgement, PConstraint> traceability = HashMultimap.create();

    for (ITypeConstraint typeConstraint : body.getConstraintsOfType(ITypeConstraint.class)) {
        TypeJudgement equivalentJudgement = typeConstraint.getEquivalentJudgement();
        judgementsToProcess.add(equivalentJudgement);
        allJudgements.add(equivalentJudgement);
        traceability.put(equivalentJudgement, typeConstraint);
    }

    while (!judgementsToProcess.isEmpty()) {
        TypeJudgement judgement = judgementsToProcess.poll();
        for (TypeJudgement alternativeJudgement : judgement.getWeakenedAlternativeJudgements(context)) {
            if (allJudgements.add(alternativeJudgement)) {
                newJudgementsToAdd.add(alternativeJudgement);
                judgementsToProcess.add(alternativeJudgement);
                traceability.putAll(alternativeJudgement, traceability.get(judgement));
            }
        }
    }

    for (TypeJudgement typeJudgement : newJudgementsToAdd) {
        PConstraint newConstraint = typeJudgement.createConstraintFor(body);
        for (PConstraint source : traceability.get(typeJudgement)) {
            addTrace(source, newConstraint);
        }
    }
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

private void renderParameters(List<Parameter> _parameters, MarkdownBuilder markdownBuilder) {
    Multimap<ParameterIn, String> parameterGroups = ArrayListMultimap.create();

    if (_parameters == null || _parameters.isEmpty()) {
        return;//from   w w w . jav  a  2  s.c  o m
    }

    _parameters.forEach(p -> {
        ParameterIn parameterIn;
        try {
            parameterIn = ParameterIn.valueOf(p.getIn().toUpperCase(Locale.ENGLISH));
        } catch (IllegalArgumentException e) {
            throw new UnsupportedOperationException(
                    format("Parameter type '%s' not supported yet.", p.getIn()));
        }

        parameterGroups.putAll(parameterIn, renderParameter(parameterIn, p));
    });

    parameterGroups.keySet().forEach(key -> {
        List<String> group = new ArrayList<>();
        group.add("Parameter|Required|Type|Description");
        group.addAll(parameterGroups.get(key));

        markdownBuilder.sectionTitleLevel2(key.getQuery() + " Parameters");
        markdownBuilder.tableWithHeaderRow(group);
    });
}

From source file:com.pidoco.juri.JURI.java

public JURI replaceQueryParametersMulti(Map<String, Collection<String>> params) {
    startChange();// w ww.ja  v a2s  .c o  m

    Multimap<String, String> queryParameters = getQueryParametersMultimap();
    for (Map.Entry<String, Collection<String>> entry : params.entrySet()) {
        queryParameters.removeAll(entry.getKey());
        queryParameters.putAll(entry.getKey(), entry.getValue());
    }

    changed();
    return this;
}

From source file:grakn.core.graql.reasoner.atom.binary.RelationAtom.java

/**
 * @return a map of relations and corresponding roles that could be played by this atom
 *//*from   w ww.  ja va 2s  .co  m*/
private Multimap<RelationType, Role> inferPossibleRelationConfigurations(ConceptMap sub) {
    Set<Role> roles = getExplicitRoles().filter(r -> !Schema.MetaSchema.isMetaLabel(r.label()))
            .collect(toSet());
    SetMultimap<Variable, Type> varTypeMap = getParentQuery().getVarTypeMap(sub);
    Set<Type> types = getRolePlayers().stream().filter(varTypeMap::containsKey)
            .flatMap(v -> varTypeMap.get(v).stream()).collect(toSet());

    if (roles.isEmpty() && types.isEmpty()) {
        RelationType metaRelationType = tx().getMetaRelationType();
        Multimap<RelationType, Role> compatibleTypes = HashMultimap.create();
        metaRelationType.subs().filter(rt -> !rt.equals(metaRelationType))
                .forEach(rt -> compatibleTypes.putAll(rt, rt.roles().collect(toSet())));
        return compatibleTypes;
    }

    //intersect relation types from roles and types
    Multimap<RelationType, Role> compatibleTypes;

    Multimap<RelationType, Role> compatibleTypesFromRoles = ReasonerUtils
            .compatibleRelationTypesWithRoles(roles, new RoleConverter());
    Multimap<RelationType, Role> compatibleTypesFromTypes = ReasonerUtils
            .compatibleRelationTypesWithRoles(types, new TypeConverter());

    if (roles.isEmpty()) {
        compatibleTypes = compatibleTypesFromTypes;
    }
    //no types from roles -> roles correspond to mutually exclusive relations
    else if (compatibleTypesFromRoles.isEmpty() || types.isEmpty()) {
        compatibleTypes = compatibleTypesFromRoles;
    } else {
        compatibleTypes = ReasonerUtils.multimapIntersection(compatibleTypesFromTypes,
                compatibleTypesFromRoles);
    }
    return compatibleTypes;
}

From source file:org.sosy_lab.cpachecker.util.predicates.AssignmentToPathAllocator.java

private ConcreteState createSingleConcreteState(CFAEdge cfaEdge, SSAMap ssaMap,
        Map<String, Assignment> variableEnvoirment, Map<LeftHandSide, Object> variables,
        Multimap<String, Assignment> functionEnvoirment, Map<String, Map<Address, Object>> memory,
        Map<LeftHandSide, Address> addressOfVariables, Collection<AssignableTerm> terms, Model pModel,
        MachineModel pMachineModel, Multimap<CFAEdge, AssignableTerm> usedAssignableTerms) {

    Set<Assignment> termSet = new HashSet<>();

    createAssignments(pModel, terms, termSet, variableEnvoirment, variables, functionEnvoirment, memory);

    removeDeallocatedVariables(ssaMap, variableEnvoirment);

    Map<String, Memory> allocatedMemory = createAllocatedMemory(memory);

    ConcreteState concreteState = new ConcreteState(variables, allocatedMemory, addressOfVariables, memoryName);

    // for legacy functionality, remember used assignable terms per cfa edge.
    usedAssignableTerms.putAll(cfaEdge, terms);

    return concreteState;
}

From source file:forge.game.phase.PhaseHandler.java

private void declareAttackersTurnBasedAction() {
    final Player whoDeclares = playerDeclaresAttackers == null || playerDeclaresAttackers.hasLost() ? playerTurn
            : playerDeclaresAttackers;//from w w  w .  ja va 2s  .com

    if (CombatUtil.canAttack(playerTurn)) {
        boolean success = false;
        do {
            if (game.isGameOver()) { // they just like to close window at any moment
                return;
            }

            whoDeclares.getController().declareAttackers(playerTurn, combat);
            combat.removeAbsentCombatants();

            success = CombatUtil.validateAttackers(combat);
            if (!success) {
                whoDeclares.getController().notifyOfValue(null, null, "Attack declaration invalid");
                continue;
            }

            for (final Card attacker : combat.getAttackers()) {
                final boolean shouldTapForAttack = !attacker.hasKeyword("Vigilance")
                        && !attacker.hasKeyword("Attacking doesn't cause CARDNAME to tap.");
                if (shouldTapForAttack) {
                    // set tapped to true without firing triggers because it may affect propaganda costs
                    attacker.setTapped(true);
                }

                final boolean canAttack = CombatUtil.checkPropagandaEffects(game, attacker, combat);
                attacker.setTapped(false);

                if (canAttack) {
                    if (shouldTapForAttack) {
                        attacker.tap();
                    }
                } else {
                    combat.removeFromCombat(attacker);
                    success = CombatUtil.validateAttackers(combat);
                    if (!success) {
                        break;
                    }
                }
            }

        } while (!success);
    }

    if (game.isGameOver()) { // they just like to close window at any moment
        return;
    }

    nCombatsThisTurn++;

    // Prepare and fire event 'attackers declared'
    Multimap<GameEntity, Card> attackersMap = ArrayListMultimap.create();
    for (GameEntity ge : combat.getDefenders()) {
        attackersMap.putAll(ge, combat.getAttackersOf(ge));
    }
    game.fireEvent(new GameEventAttackersDeclared(playerTurn, attackersMap));

    // This Exalted handler should be converted to script
    if (combat.getAttackers().size() == 1) {
        final Player attackingPlayer = combat.getAttackingPlayer();
        final Card attacker = combat.getAttackers().get(0);
        for (Card card : attackingPlayer.getCardsIn(ZoneType.Battlefield)) {
            int exaltedMagnitude = card.getAmountOfKeyword("Exalted");

            for (int i = 0; i < exaltedMagnitude; i++) {
                String abScript = String.format(
                        "AB$ Pump | Cost$ 0 | Defined$ CardUID_%d | NumAtt$ +1 | NumDef$ +1 | StackDescription$ Exalted for attacker {c:CardUID_%d} (Whenever a creature you control attacks alone, that creature gets +1/+1 until end of turn).",
                        attacker.getId(), attacker.getId());
                SpellAbility ability = AbilityFactory.getAbility(abScript, card);
                ability.setActivatingPlayer(card.getController());
                ability.setDescription(ability.getStackDescription());
                ability.setTrigger(true);

                game.getStack().addSimultaneousStackEntry(ability);
            }
        }
    }

    // fire AttackersDeclared trigger
    if (!combat.getAttackers().isEmpty()) {
        List<GameEntity> attackedTarget = new ArrayList<GameEntity>();
        for (final Card c : combat.getAttackers()) {
            attackedTarget.add(combat.getDefenderByAttacker(c));
        }
        final HashMap<String, Object> runParams = new HashMap<String, Object>();
        runParams.put("Attackers", combat.getAttackers());
        runParams.put("AttackingPlayer", combat.getAttackingPlayer());
        runParams.put("AttackedTarget", attackedTarget);
        game.getTriggerHandler().runTrigger(TriggerType.AttackersDeclared, runParams, false);
    }

    for (final Card c : combat.getAttackers()) {
        CombatUtil.checkDeclaredAttacker(game, c, combat);
    }

    game.getTriggerHandler().resetActiveTriggers();
    game.updateCombatForView();
    game.fireEvent(new GameEventCombatChanged());
}

From source file:org.obiba.onyx.quartz.editor.openAnswer.validation.ValidationDataSourceWindow.java

public ValidationDataSourceWindow(String id, IModel<ComparingDataSource> model,
        final IModel<Question> questionModel, final IModel<Questionnaire> questionnaireModel,
        final DataType dataType, final ModalWindow modalWindow) {
    super(id, model);
    this.dataType = dataType;

    final ValueType valueType = VariableUtils.convertToValueType(dataType);

    add(CSSPackageResource.getHeaderContribution(ValidationDataSourceWindow.class,
            "ValidationDataSourceWindow.css"));

    variableWindow = new ModalWindow("variableWindow");
    variableWindow.setCssClassName("onyx");
    variableWindow.setInitialWidth(950);
    variableWindow.setInitialHeight(540);
    variableWindow.setResizable(true);/*ww w  . ja  v  a  2 s  . c o m*/
    variableWindow.setTitle(new ResourceModel("Variable"));
    add(variableWindow);

    final Questionnaire questionnaire = questionnaireModel.getObject();

    final OpenAnswerValidator validator = new OpenAnswerValidator();
    if (model.getObject() != null) {
        ComparingDataSource comparingDataSource = model.getObject();
        validator.setOperator(comparingDataSource.getComparisonOperator());
        IDataSource dataSourceRight = comparingDataSource.getDataSourceRight();
        if (dataSourceRight instanceof VariableDataSource) {
            VariableDataSource variableDataSource = (VariableDataSource) dataSourceRight;
            if (questionnaire.getName().equals(variableDataSource.getTableName())) {
                try {
                    validator.setVariable(questionnaire.getVariable(variableDataSource.getVariableName()));
                    validator.setType(Type.VARIABLE);
                } catch (IllegalArgumentException e) {
                    // not found in this questionnaire
                }
            }
            if (validator.getType() == null) { // not found yet
                Variable variable = variableUtils.findVariable(variableDataSource);
                if (variable != null) {
                    try {
                        validator.setVariable(questionnaire.getVariable(variable.getName()));
                        validator.setType(Type.VARIABLE);
                    } catch (IllegalArgumentException e) {
                        // not found
                        Question question = VariableUtils.findQuestion(variable,
                                QuestionnaireFinder.getInstance(questionnaire));
                        validator.setType(Type.QUESTION_CATEGORY);
                        validator.setQuestion(question);
                        Category category = VariableUtils.findCategory(variable, question);
                        validator.setCategory(category);
                        validator.setOpenAnswer(VariableUtils.findOpenAnswer(variable, category));
                    }
                }
            }
        } else if (dataSourceRight instanceof JavascriptDataSource) {
            JavascriptDataSource javascriptDataSource = (JavascriptDataSource) dataSourceRight;
            validator.setType(JAVASCRIPT);
            validator.setScript(javascriptDataSource.getScript());
        }
    }

    feedbackPanel = new FeedbackPanel("content");
    feedbackWindow = new FeedbackWindow("feedback");
    feedbackWindow.setOutputMarkupId(true);

    add(feedbackWindow);

    add(form = new Form<OpenAnswerValidator>("form", new Model<OpenAnswerValidator>(validator)));
    form.setMultiPart(false);

    IChoiceRenderer<ComparisonOperator> operatorRenderer = new IChoiceRenderer<ComparisonOperator>() {
        @Override
        public String getIdValue(ComparisonOperator operator, int index) {
            return operator.name();
        }

        @Override
        public Object getDisplayValue(ComparisonOperator operator) {
            return new StringResourceModel("Operator." + operator, ValidationDataSourceWindow.this, null)
                    .getString();
        }
    };

    List<ComparisonOperator> comparisonOperatorAsList = null;
    if (dataType == DataType.TEXT) {
        comparisonOperatorAsList = Arrays.asList(ComparisonOperator.eq, ComparisonOperator.ne,
                ComparisonOperator.in);
    } else {
        comparisonOperatorAsList = Arrays.asList(ComparisonOperator.values());
    }
    final DropDownChoice<ComparisonOperator> operator = new DropDownChoice<ComparisonOperator>("operator",
            new PropertyModel<ComparisonOperator>(form.getModel(), "operator"), comparisonOperatorAsList,
            operatorRenderer);
    form.add(operator.setLabel(new ResourceModel("Operator")).setRequired(true))
            .add(new SimpleFormComponentLabel("operatorLabel", operator));

    final RadioGroup<Type> validationType = new RadioGroup<Type>("validationType",
            new PropertyModel<Type>(form.getModel(), "type"));
    form.add(validationType.setLabel(new ResourceModel("Variable")).setRequired(true));

    final Radio<Type> questionType = new Radio<Type>("questionType", new Model<Type>(QUESTION_CATEGORY));
    questionType.setLabel(new ResourceModel("QuestionType"));
    validationType.add(questionType).add(new SimpleFormComponentLabel("questionTypeLabel", questionType));

    final WebMarkupContainer questionTypeContainer = new WebMarkupContainer("questionTypeContainer");
    questionTypeContainer.setOutputMarkupId(true);
    validationType.add(questionTypeContainer);

    final WebMarkupContainer questionConditionContainer = new WebMarkupContainer("questionConditionContainer");
    questionConditionContainer.setVisible(validator.getType() == QUESTION_CATEGORY);
    questionTypeContainer.add(questionConditionContainer);

    if (questionnaire.getQuestionnaireCache() == null) {
        QuestionnaireFinder.getInstance(questionnaire).buildQuestionnaireCache();
    }

    List<Question> questions = new ArrayList<Question>(
            questionnaire.getQuestionnaireCache().getQuestionCache().values());
    Collections.sort(questions, new QuestionnaireElementComparator());
    final Multimap<Question, Category> questionCategories = LinkedHashMultimap.create();
    final Multimap<Category, OpenAnswerDefinition> categoryOpenAnswer = LinkedHashMultimap.create();
    for (Question q : questions) {
        if (!q.equals(questionModel.getObject()) && q.getType() != QuestionType.BOILER_PLATE) {
            final List<Category> findCategories = findCategories(q);
            for (Category category : findCategories) {
                categoryOpenAnswer.putAll(category, category.getOpenAnswerDefinitionsByName().values());
            }
            questionCategories.putAll(q, findCategories);
        }
    }

    final DropDownChoice<Question> questionName = new DropDownChoice<Question>("question",
            new PropertyModel<Question>(form.getModel(), "question"),
            new ArrayList<Question>(questionCategories.keySet()), new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };

    questionName.setLabel(new ResourceModel("Question"));
    questionConditionContainer.add(questionName)
            .add(new SimpleFormComponentLabel("questionLabel", questionName));

    final List<Category> categories = questionName.getModelObject() == null ? new ArrayList<Category>()
            : new ArrayList<Category>(questionCategories.get(questionName.getModelObject()));

    final DropDownChoice<Category> categoryName = new DropDownChoice<Category>("category",
            new PropertyModel<Category>(form.getModel(), "category"), categories,
            new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };
    categoryName.setLabel(new ResourceModel("Category"));
    questionConditionContainer.add(categoryName)
            .add(new SimpleFormComponentLabel("categoryLabel", categoryName));

    final List<OpenAnswerDefinition> openAnswers = categoryName.getModelObject() == null
            ? new ArrayList<OpenAnswerDefinition>()
            : new ArrayList<OpenAnswerDefinition>(categoryOpenAnswer.get(categoryName.getModelObject()));

    final DropDownChoice<OpenAnswerDefinition> openAnswerName = new DropDownChoice<OpenAnswerDefinition>(
            "openAnswer", new PropertyModel<OpenAnswerDefinition>(form.getModel(), "openAnswer"), openAnswers,
            new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };

    questionName.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            categories.clear();
            openAnswers.clear();
            categories.addAll(questionName.getModelObject() == null ? new ArrayList<Category>()
                    : new ArrayList<Category>(questionCategories.get(questionName.getModelObject())));
            openAnswers.addAll(categories.isEmpty() ? new ArrayList<OpenAnswerDefinition>()
                    : new ArrayList<OpenAnswerDefinition>(categoryOpenAnswer.get(categories.get(0))));
            target.addComponent(categoryName);
            target.addComponent(openAnswerName);
        }
    });

    categoryName.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            openAnswers.clear();
            openAnswers.addAll(categoryName.getModelObject() == null ? new ArrayList<OpenAnswerDefinition>()
                    : new ArrayList<OpenAnswerDefinition>(
                            categoryOpenAnswer.get(categoryName.getModelObject())));
            target.addComponent(openAnswerName);
        }
    });

    openAnswerName.setLabel(new ResourceModel("OpenAnswer"));
    questionConditionContainer.add(openAnswerName)
            .add(new SimpleFormComponentLabel("openAnswerLabel", openAnswerName));

    Radio<Type> variableType = new Radio<Type>("variableType", new Model<Type>(VARIABLE));
    variableType.setLabel(new ResourceModel("Variable"));
    validationType.add(variableType).add(new SimpleFormComponentLabel("variableTypeLabel", variableType));

    final WebMarkupContainer variableTypeContainer = new WebMarkupContainer("variableTypeContainer");
    variableTypeContainer.setOutputMarkupId(true);
    validationType.add(variableTypeContainer);

    final WebMarkupContainer variableContainer = new WebMarkupContainer("variableContainer");
    variableContainer.setVisible(validator.getType() == VARIABLE);
    variableTypeContainer.add(variableContainer);

    final List<Variable> variables = new ArrayList<Variable>(
            Collections2.filter(questionnaire.getVariables(), new Predicate<Variable>() {
                @Override
                public boolean apply(Variable v) {
                    // Filter for text when the operator is 'IN'
                    if (validator.getOperator() != null
                            && validator.getOperator().equals(ComparisonOperator.in)) {
                        return v.getValueType().equals(VariableUtils.convertToValueType(DataType.TEXT));
                    }
                    return v.getValueType().equals(valueType);
                }
            }));

    final DropDownChoice<Variable> variableDropDown = new DropDownChoice<Variable>("variable",
            new PropertyModel<Variable>(form.getModel(), "variable"), variables, new VariableRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == VARIABLE;
        }
    };
    variableDropDown.setLabel(new ResourceModel("Variable")).setOutputMarkupId(true);
    variableContainer.add(variableDropDown);

    final WebMarkupContainer previewVariableVisibility = new WebMarkupContainer("previewVariableVisibility");
    variableContainer.add(previewVariableVisibility.setOutputMarkupId(true));

    final Image previewVariable = new Image("previewVariable", Images.ZOOM);
    previewVariable.add(new AttributeModifier("title", true, new ResourceModel("Preview")));
    previewVariable.setVisible(variableDropDown.getModelObject() != null);
    previewVariableVisibility.add(previewVariable);

    final Label previewScript = new Label("previewScript", variableDropDown.getModelObject() == null ? ""
            : variableDropDown.getModelObject().getAttributeStringValue("script"));
    previewScript.add(new SyntaxHighlighterBehavior());
    previewScript.add(new AttributeAppender("style", true, new Model<String>("display: none;"), " "));
    previewVariableVisibility.add(previewScript);

    final Map<String, Object> tooltipCfg = new HashMap<String, Object>();
    tooltipCfg.put("delay", 100);
    tooltipCfg.put("showURL", false);
    tooltipCfg.put("top", -30);
    tooltipCfg.put("bodyHandler",
            "function() { return $(\"#" + previewScript.getMarkupId(true) + "\").html(); }");
    previewVariable.add(new TooltipBehavior(null, tooltipCfg));

    variableContainer.add(new AjaxLink<Void>("newVariable") {
        @Override
        public void onClick(AjaxRequestTarget target) {

            @SuppressWarnings({ "rawtypes", "unchecked" })
            VariablePanel variablePanel = new VariablePanel("content", new Model(null), questionnaireModel,
                    valueType) {
                @Override
                public void onSave(@SuppressWarnings("hiding") AjaxRequestTarget target,
                        Variable createdVariable) {
                    variables.add(createdVariable);
                    questionnaire.addVariable(createdVariable);
                    variableDropDown.setModelObject(createdVariable);
                    previewVariable.setVisible(true);
                    previewScript.setDefaultModelObject(createdVariable.getAttributeStringValue("script"));
                    variableWindow.close(target);
                    target.addComponent(variableDropDown);
                    target.addComponent(previewVariableVisibility);
                }

                @Override
                public void onCancel(@SuppressWarnings("hiding") AjaxRequestTarget target) {
                    variableWindow.close(target);
                }
            };
            variableWindow.setContent(variablePanel);
            variableWindow.show(target);
        }
    }.add(new Image("newVariableImg", Images.ADD))
            .add(new AttributeModifier("title", true, new ResourceModel("NewVariable"))));

    variableDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Variable variable = variableDropDown.getModelObject();
            previewVariable.setVisible(variable != null);
            previewScript.setDefaultModelObject(
                    variable == null ? null : variable.getAttributeStringValue("script"));
            target.addComponent(previewVariableVisibility);
        }
    });

    Radio<Type> javascriptType = new Radio<Type>("javascriptType", new Model<Type>(JAVASCRIPT));
    javascriptType.setLabel(new ResourceModel("JavascriptType"));
    validationType.add(javascriptType).add(new SimpleFormComponentLabel("javascriptTypeLabel", javascriptType));

    final TextArea<String> javascriptField = new TextArea<String>("javascriptField",
            new PropertyModel<String>(validator, "script"));
    javascriptField.setOutputMarkupPlaceholderTag(true);
    javascriptField.setVisible(validator.getType() == JAVASCRIPT);
    validationType.add(javascriptField);

    javascriptField.add(new IValidator<String>() {

        @Override
        public void validate(final IValidatable<String> validatable) {
            JavascriptUtils.compile(validatable.getValue(), questionModel.getObject().getName(),
                    ValidationDataSourceWindow.this, form);
        }
    });

    validationType.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Type type = validationType.getModelObject();
            switch (type) {
            case QUESTION_CATEGORY:
                variableDropDown.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case VARIABLE:
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                openAnswerName.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case JAVASCRIPT:
                variableDropDown.setModelObject(null);
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                openAnswerName.setModelObject(null);
                break;
            }
            questionConditionContainer.setVisible(type == QUESTION_CATEGORY);
            variableContainer.setVisible(type == VARIABLE);
            javascriptField.setVisible(type == JAVASCRIPT);
            target.addComponent(questionTypeContainer);
            target.addComponent(variableTypeContainer);
            target.addComponent(javascriptField);
        }
    });

    form.add(new SaveCancelPanel("saveCancel", form) {
        @Override
        protected void onSave(AjaxRequestTarget target, Form<?> form1) {

            IDataSource dataSource = null;
            switch (validator.getType()) {
            case QUESTION_CATEGORY:
                Question question = validator.getQuestion();
                OpenAnswerDefinition openAnswer = validator.getOpenAnswer();
                String variableName = openAnswer.getVariableName(question.getName());
                if (StringUtils.isNotBlank(variableName)) {
                    dataSource = new VariableDataSource(questionnaire.getName() + ":" + variableName);
                } else {
                    dataSource = new VariableDataSource(questionnaire.getName() + ":" + question.getName() + "."
                            + validator.getCategory().getName() + "." + openAnswer.getName());
                }
                break;
            case VARIABLE:
                dataSource = new VariableDataSource(
                        questionnaire.getName() + ":" + validator.getVariable().getName());
                break;
            case JAVASCRIPT:
                dataSource = new JavascriptDataSource(validator.getScript(),
                        VariableUtils.convertToValueType(dataType).getName(), questionnaire.getName());
                ((JavascriptDataSource) dataSource)
                        .setSequence(validator.getOperator() == ComparisonOperator.in);
                break;
            }

            ComparingDataSource comparingDataSource = new ComparingDataSource(null, validator.getOperator(),
                    dataSource);
            ValidationDataSourceWindow.this.onSave(target, comparingDataSource);
            modalWindow.close(target);
        }

        @Override
        protected void onCancel(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            modalWindow.close(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            feedbackWindow.setContent(feedbackPanel);
            feedbackWindow.show(target);
        }
    });

}

From source file:com.b2international.snowowl.snomed.reasoner.server.classification.EquivalentConceptMerger.java

/**
 * Resolves the equivalency {@link Map} to a {@link Map} that contains only
 * {@link Concept} instances. The returned {@link Map} is contains value
 * {@link Concept}s as replacement for the key {@link Concept}s.
 * /* www. j a va2  s.co  m*/
 * @param equivalencies
 * @param results
 * @param helper
 * @return
 */
private Multimap<Concept, Concept> resolveEquivalencies() {
    final Multimap<Concept, Concept> processedEquivalencies = HashMultimap.create();

    for (final LongCollection equivalentSet : equivalenciesToFix) {

        final List<Concept> conceptsToRemove = Lists.newArrayList();

        for (final LongIterator itr = equivalentSet.iterator(); itr.hasNext(); /* empty */) {
            final long conceptId = itr.next();
            final Concept concept = editingContext.lookup(Long.toString(conceptId), Concept.class);
            conceptsToRemove.add(concept);
        }

        final Concept conceptToKeep = Ordering.natural().onResultOf(new Function<Concept, Long>() {
            @Override
            public Long apply(Concept input) {
                return CDOIDUtil.getLong(input.cdoID());
            }
        }).min(conceptsToRemove);

        conceptsToRemove.remove(conceptToKeep);
        processedEquivalencies.putAll(conceptToKeep, conceptsToRemove);
    }

    return processedEquivalencies;
}

From source file:org.apache.stanbol.client.enhancer.model.EnhancementStructure.java

/**
 * Returns the best {@link EntityAnnotation}s (those with the highest
 * confidence value) for each extracted {@link TextAnnotation}
 *
 * @return best annotations/*from w w w  . ja  va  2  s.  c  o  m*/
 */
public Multimap<TextAnnotation, EntityAnnotation> getBestAnnotations() {

    final Ordering<EntityAnnotation> o = new Ordering<EntityAnnotation>() {
        @Override
        public int compare(final EntityAnnotation left, final EntityAnnotation right) {
            return Doubles.compare(left.getConfidence(), right.getConfidence());
        }
    }.reverse();

    final Multimap<TextAnnotation, EntityAnnotation> result = ArrayListMultimap.create();
    for (final TextAnnotation ta : getTextAnnotations()) {
        final List<EntityAnnotation> eas = o.sortedCopy(getEntityAnnotations(ta));
        if (!eas.isEmpty()) {
            final Collection<EntityAnnotation> highest = Sets.newHashSet();
            final Double confidence = eas.get(0).getConfidence();
            for (final EntityAnnotation ea : eas) {
                if (ea.getConfidence() < confidence) {
                    break;
                } else {
                    highest.add(ea);
                }
            }
            result.putAll(ta, highest);
        }
    }

    return result;
}

From source file:org.terasology.documentation.apiScraper.CompleteApiScraper.java

/**
 *
 * @return Project's Packages, Interfaces, Classes and Methods
 * @throws Exception if the module environment cannot be loaded
 *///from  w  w  w.  j a  va  2s .  c om
static StringBuffer getApi() throws Exception {
    ModuleManager moduleManager = ModuleManagerFactory.create();
    ModuleEnvironment environment = moduleManager.getEnvironment();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    Multimap<String, String> api = Multimaps.newMultimap(new HashMap<String, Collection<String>>(),
            ArrayList::new);

    for (Class<?> apiClass : environment.getTypesAnnotatedWith(API.class)) {
        boolean isPackage = apiClass.isSynthetic();
        URL location;
        String category;
        String apiPackage = "";
        if (isPackage) {
            apiPackage = apiClass.getPackage().getName();
            location = classLoader.getResource(apiPackage.replace('.', '/'));
        } else {

            location = apiClass.getResource('/' + apiClass.getName().replace('.', '/') + ".class");
        }

        if (location == null) {
            logger.error("Failed to get a class/package location, skipping " + apiClass);
            continue;
        }

        switch (location.getProtocol()) {
        case "jar":

            // Find out what jar it came from and consider that the category
            String categoryFragment = location.getPath();

            int bang = categoryFragment.lastIndexOf("!");
            int hyphen = categoryFragment.lastIndexOf("-", bang);
            int slash = categoryFragment.lastIndexOf("/", hyphen);
            category = categoryFragment.substring(slash + 1, hyphen);

            if (isPackage) {
                api.put(category, apiPackage + " (PACKAGE)");
            } else {
                addToApi(category, apiClass, api);
            }
            break;

        case "file":
            // If file based we know it is local so organize it like that
            category = TERASOLOGY_API_CLASS_CATEGORY;
            if (isPackage) {
                api.put(category, apiPackage + " (PACKAGE)");
            } else {
                addToApi(category, apiClass, api);
            }
            break;

        default:
            logger.error("Unknown protocol for: " + apiClass + ", came from " + location);
        }
    }
    api.putAll(EXTERNAL, ExternalApiWhitelist.CLASSES.stream().map(clazz -> clazz.getName() + " (CLASS)")
            .collect(Collectors.toSet()));
    api.putAll(EXTERNAL, ExternalApiWhitelist.PACKAGES.stream().map(packagee -> packagee + " (PACKAGE)")
            .collect(Collectors.toSet()));

    //Puts the information in the StringBuffer
    StringBuffer stringApi = new StringBuffer();
    stringApi.append("# Modding API:\n");
    for (String key : api.keySet()) {
        stringApi.append("## ");
        stringApi.append(key);
        stringApi.append("\n");
        for (String value : api.get(key)) {
            stringApi.append("* ");
            stringApi.append(value);
            stringApi.append("\n");
        }
        stringApi.append("\n");
    }
    return stringApi;
}