Example usage for com.google.common.collect SetMultimap put

List of usage examples for com.google.common.collect SetMultimap put

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap put.

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:lu.list.itis.dkd.aig.process.ClozeCreationProcess.java

/** {@inheritDoc} */
@Override/*  w  w w.  j  a va 2 s  .co  m*/
public void initializeVariables(final Map<String, String> input, final SetMultimap<URI, Variable> variables)
        throws TemplateConsistencyException, ResolutionException {

    configureClozeGenerator();

    ClozeText clozeText = null;
    ClozeItems clozeItems = null;

    clozeText = new ClozeText(input.get("text"), "body", Language.EN, approach, numberOfDistractors, //$NON-NLS-1$
            skipFirstSentence);

    storeOntology(clozeText);

    clozeItems = new ClozeItems(clozeText, clozeText.getNumberOfDistractors(), difficulty);

    for (final ClozeItem clozeItem : clozeItems.getClozeItems()) {

        final Element clozeBlock = clozeItem.getClozeBlock();
        final List<Element> correctResponses = clozeItem.getCorrectResponseBlocks();
        final List<Element> outcomeDeclarations = clozeItem.getOutcomeDeclarationBlocks(generateFeedback);
        final Element responseProcessingBlock = clozeItem.getResponseProcessingBlock(generateFeedback);
        final List<Element> modalFeedbackBlocks = clozeItem.getModalFeedbackBlocks(generateFeedback);

        // There should only be one outcome: clozeText
        Variable outcomeVariable = null;
        try {
            outcomeVariable = VariableBuilder
                    .getVariableFromBlueprint(Strings.nullToEmpty(outcomeIdentifiers.get(0)));
        } catch (final TemplateParseException e) {
            throw new ResolutionException(e);
        }

        for (final Value value : outcomeVariable.getValues(ValueType.TEXT)) {
            switch (value.getIdentifier().toString()) {
            case "http://list.lu/responseProcessingBlock":
                value.setInnerValueTo(outputter.outputString(responseProcessingBlock));
                break;
            case "http://list.lu/outcomeDeclarationBlock":
                value.setInnerValueTo(outputter.outputString(outcomeDeclarations));
                break;
            case "http://list.lu/clozeBlock":
                value.setInnerValueTo(outputter.outputString(clozeBlock));
                break;
            case "http://list.lu/correctResponseBlock":
                value.setInnerValueTo(outputter.outputString(correctResponses));
                break;
            case "http://list.lu/modalFeedbackBlock":
                value.setInnerValueTo(outputter.outputString(modalFeedbackBlocks));
                break;
            default:
                break;
            }

        }
        variables.put(outcomeVariable.getIdentifier(), outcomeVariable);
    }

}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Prepare to remove links between the targeted model objects and the remainder of the model object graph.
 * @param isUnlinkIncludeFromExclude if {@link Action#EXCLUDE} objects must be unlinked from {@link Action#INCLUDE} objects
 * and vice versa/* w w w  .j  a  va 2  s.c  o m*/
 * @return the actual unlinker for the targeted model objects, to be used by the caller
 * @throws GraphException if the user does not have permission to unlink the targets
 */
public PlanExecutor unlinkTargets(boolean isUnlinkIncludeFromExclude) throws GraphException {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    /* accumulate plan for unlinking included/deleted from others */
    final SetMultimap<CP, Long> toNullByCP = HashMultimap.create();
    final Map<CP, SetMultimap<Long, Entry<String, Long>>> linkerToIdToLinked = new HashMap<CP, SetMultimap<Long, Entry<String, Long>>>();
    for (final CI object : planning.included) {
        for (final String superclassName : model.getSuperclassesOfReflexive(object.className)) {
            for (final Entry<String, String> forwardLink : model.getLinkedTo(superclassName)) {
                final CP linkProperty = new CP(superclassName, forwardLink.getValue());
                final boolean isCollection = model.getPropertyKind(linkProperty.className,
                        linkProperty.propertyName) == PropertyKind.COLLECTION;
                final CPI linkSource = linkProperty.toCPI(object.id);
                for (final CI linked : planning.forwardLinksCached.get(linkSource)) {
                    final Action linkedAction = getAction(linked);
                    if (linkedAction == Action.DELETE
                            || isUnlinkIncludeFromExclude && linkedAction == Action.EXCLUDE) {
                        /* INCLUDE is linked to EXCLUDE or DELETE, so unlink */
                        if (isCollection) {
                            addRemoval(linkerToIdToLinked, linkProperty.toCPI(object.id), linked);
                        } else {
                            toNullByCP.put(linkProperty, object.id);
                        }
                    }
                }
            }
            if (isUnlinkIncludeFromExclude) {
                for (final Entry<String, String> backwardLink : model.getLinkedBy(superclassName)) {
                    final CP linkProperty = new CP(backwardLink.getKey(), backwardLink.getValue());
                    final boolean isCollection = model.getPropertyKind(linkProperty.className,
                            linkProperty.propertyName) == PropertyKind.COLLECTION;
                    final CPI linkTarget = linkProperty.toCPI(object.id);
                    for (final CI linker : planning.backwardLinksCached.get(linkTarget)) {
                        final Action linkerAction = getAction(linker);
                        if (linkerAction == Action.EXCLUDE) {
                            /* EXCLUDE is linked to INCLUDE, so unlink */
                            if (isCollection) {
                                addRemoval(linkerToIdToLinked, linkProperty.toCPI(linker.id), object);
                            } else {
                                toNullByCP.put(linkProperty, linker.id);
                            }
                        }
                    }
                }
            }
        }
    }
    for (final CI object : planning.deleted) {
        for (final String superclassName : model.getSuperclassesOfReflexive(object.className)) {
            for (final Entry<String, String> backwardLink : model.getLinkedBy(superclassName)) {
                final CP linkProperty = new CP(backwardLink.getKey(), backwardLink.getValue());
                final boolean isCollection = model.getPropertyKind(linkProperty.className,
                        linkProperty.propertyName) == PropertyKind.COLLECTION;
                final CPI linkTarget = linkProperty.toCPI(object.id);
                for (final CI linker : planning.backwardLinksCached.get(linkTarget)) {
                    final Action linkerAction = getAction(linker);
                    if (linkerAction != Action.DELETE) {
                        /* EXCLUDE, INCLUDE or OUTSIDE is linked to DELETE, so unlink */
                        if (isCollection) {
                            addRemoval(linkerToIdToLinked, linkProperty.toCPI(linker.id), object);
                        } else {
                            toNullByCP.put(linkProperty, linker.id);
                        }
                    }
                }
            }
        }
    }
    /* note unlink included/deleted by nulling properties */
    final Map<CP, Collection<Long>> eachToNullByCP = toNullByCP.asMap();
    for (final Entry<CP, Collection<Long>> nullCurr : eachToNullByCP.entrySet()) {
        final CP linker = nullCurr.getKey();
        if (unnullable.get(linker.className).contains(linker.propertyName)
                || model.getPropertyKind(linker.className, linker.propertyName) == PropertyKind.REQUIRED) {
            throw new GraphException("cannot null " + linker);
        }
        final Collection<Long> allIds = nullCurr.getValue();
        assertMayBeUpdated(linker.className, allIds);
    }
    /* note unlink included/deleted by removing from collections */
    for (final Entry<CP, SetMultimap<Long, Entry<String, Long>>> removeCurr : linkerToIdToLinked.entrySet()) {
        final CP linker = removeCurr.getKey();
        final Collection<Long> allIds = removeCurr.getValue().keySet();
        assertMayBeUpdated(linker.className, allIds);
        throw new GraphException("cannot remove elements from collection " + linker);
    }
    return new PlanExecutor() {
        @Override
        public void execute() throws GraphException {
            if (progress.contains(Milestone.UNLINKED)) {
                throw new IllegalStateException("model objects already unlinked");
            }
            /* actually do the noted unlinking */
            for (final Entry<CP, Collection<Long>> nullCurr : eachToNullByCP.entrySet()) {
                final CP linker = nullCurr.getKey();
                final Collection<Long> allIds = nullCurr.getValue();
                for (final List<Long> ids : Iterables.partition(allIds, BATCH_SIZE)) {
                    processor.nullProperties(linker.className, linker.propertyName, ids);
                }
            }
            progress.add(Milestone.UNLINKED);
        }
    };
}

From source file:lu.list.itis.dkd.aig.process.SemanticRetrievalProcess.java

/**
 * {@inheritDoc}<br>//from  w w w. java  2s .  c  om
 *
 * The method will execute a query to Jena, encoding key variables as
 * necessary. The latter will be stored in a local {@link BiMap} for easy
 * referencing. The query solution is then
 *
 * @throws ResolutionException
 *
 * @throws TemplateConsistencyException
 *             Thrown when one or more variables, respectively their values,
 *             were found in the query that could not be identified, i.e.
 *             their identifier was not a valid URI or not mapped due to
 *             variable definitions containing errors.
 */
@SuppressWarnings("null")
@Override
public void initializeVariables(final Map<String, String> input, final SetMultimap<URI, Variable> variables)
        throws ResolutionException, TemplateConsistencyException {

    if (datasourceIsIdentifier) {
        //Variable datasourceVariable;
        String datasourceFromVariables = null;
        try {
            for (Map.Entry<URI, Variable> entry : variables.entries()) {
                Variable variable = entry.getValue();
                Value value = variable.getValueByIdentifier(datasource);
                if (value != null) {
                    datasourceFromVariables = (String) value.getValue();
                }
            }
            if (datasourceFromVariables == null) {
                throw new NoSuchElementException("cannot find corresponding variable for: " + datasource); //$NON-NLS-1$
            }
            //datasourceVariable = VariableBuilder.getVariableFromBlueprintWithValueIdentifier(new URI(datasource));
            //datasourceVariable = variables.get(new URI(datasource)).iterator().next();
        } catch (NoSuchElementException e) {
            throw new ResolutionException("cannot find corresponding variable for: " + datasource, e); //$NON-NLS-1$
        }

        datasource = datasourceFromVariables;
        //Variable datasourceVariable = VariableBuilder.getVariableFromBlueprint(outcomeVariablesByValueKey.get(datasource));
        //datasource = (String)datasourceVariable.getValueByIdentifier(datasource).getValue();
    }
    logger.info("datasource: " + datasource);

    Query query = QueryFactory.create(resolveQueryInput(queryString, input, variables));
    logger.info("query:" + query.toString());

    final QueryExecution queryExecution;

    if (null == graph) {
        queryExecution = QueryExecutionFactory.sparqlService(datasource, query);
    } else { // graph cannot be null in the else-clause.
        queryExecution = QueryExecutionFactory.sparqlService(datasource, query, graph.toString());
    }
    encodedKeyToVariableKey = variableKeyToEncodedKey.inverse();

    ResultSet result = null;
    try {
        result = queryExecution.execSelect();
    } catch (final HttpException e) {
        throw new ResolutionException("The remote resource used to initialize variables is not accessible!", e); //$NON-NLS-1$
    }
    while ((result != null) && result.hasNext()) {
        final QuerySolution solution = result.nextSolution();
        System.out.println("Solution: " + solution.toString());
        // Retrieve variables in solution
        final Map<URI, Variable> solutionVariables = fetchSolutionVariables(result.getResultVars());
        System.out.println("Solutions: " + solutionVariables.toString());

        for (final String queryResultVariable : result.getResultVars()) {
            final Value value = getValueFromVariables(solutionVariables, decode(queryResultVariable));
            final String object = solution.get(queryResultVariable).toString()
                    .replace(Externalization.AMPERSAND, Externalization.AMPERSAND_ENCODED)
                    .replaceAll(Externalization.REGEX_LANGUAGE_TAG, new String());

            if ((null == value) || (null == object)) {
                throw new ResolutionException(
                        "The query result could not be mapped to a value as there was no value for the query result \"" //$NON-NLS-1$
                                + queryResultVariable + "\" defined!"); //$NON-NLS-1$
            }

            value.setInnerValueTo(object);
        }
        solutionVariables.forEach((k, v) -> System.out.println("forEach: " + k + " - " + v.toString()));
        solutionVariables.forEach((k, v) -> variables.put(k, v));
    }
    queryExecution.close();
}

From source file:com.zimbra.cs.db.DbMailItem.java

public static SetMultimap<MailItem.Type, Integer> getIndexDeferredIds(DbConnection conn, Mailbox mbox)
        throws ServiceException {
    SetMultimap<MailItem.Type, Integer> result = Multimaps.newSetMultimap(
            new EnumMap<MailItem.Type, Collection<Integer>>(MailItem.Type.class), new Supplier<Set<Integer>>() {
                @Override/*from  ww w  .j av  a2  s  .  c  o  m*/
                public Set<Integer> get() {
                    return new HashSet<Integer>();
                }
            });

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try { // from MAIL_ITEM table
        stmt = conn.prepareStatement("SELECT type, id FROM " + getMailItemTableName(mbox, false) + " WHERE "
                + IN_THIS_MAILBOX_AND + "index_id <= 1"); // 0: deferred, 1: stale
        setMailboxId(stmt, mbox, 1);
        rs = stmt.executeQuery();
        while (rs.next()) {
            result.put(MailItem.Type.of(rs.getByte(1)), rs.getInt(2));
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("Failed to query index deferred IDs", e);
    } finally {
        conn.closeQuietly(rs);
        conn.closeQuietly(stmt);
    }

    if (mbox.dumpsterEnabled()) {
        try { // also from MAIL_ITEM_DUMPSTER table
            stmt = conn.prepareStatement("SELECT type, id FROM " + getMailItemTableName(mbox, true) + " WHERE "
                    + IN_THIS_MAILBOX_AND + "index_id <= 1");
            setMailboxId(stmt, mbox, 1);
            rs = stmt.executeQuery();
            while (rs.next()) {
                result.put(MailItem.Type.of(rs.getByte(1)), rs.getInt(2));
            }
        } catch (SQLException e) {
            throw ServiceException.FAILURE("Failed to query index deferred IDs from dumpster", e);
        } finally {
            conn.closeQuietly(rs);
            conn.closeQuietly(stmt);
        }
    }
    return result;
}