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

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

Introduction

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

Prototype

Multiset<K> keys();

Source Link

Document

Returns a view collection containing the key from each key-value pair in this multimap, without collapsing duplicates.

Usage

From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java

/**
 * Produce a valid ordering of the properties by using the given dependency information.
 *
 * <p>/*w  w w.j ava 2 s  .com*/
 *     This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering.
 * </p>
 */
private ImmutableList<VarAndProperty> sortProperties() {
    ImmutableList.Builder<VarAndProperty> sorted = ImmutableList.builder();

    // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified
    // we should always also modify invertedDependencies (and vice-versa).
    Multimap<VarAndProperty, VarAndProperty> dependencies = HashMultimap.create(this.dependencies);
    Multimap<VarAndProperty, VarAndProperty> invertedDependencies = HashMultimap.create();
    Multimaps.invertFrom(dependencies, invertedDependencies);

    Queue<VarAndProperty> propertiesWithoutDependencies = new ArrayDeque<>(
            Sets.filter(properties, property -> dependencies.get(property).isEmpty()));

    VarAndProperty property;

    // Retrieve the next property without any dependencies
    while ((property = propertiesWithoutDependencies.poll()) != null) {
        sorted.add(property);

        // We copy this into a new list because the underlying collection gets modified during iteration
        Collection<VarAndProperty> dependents = Lists.newArrayList(invertedDependencies.get(property));

        for (VarAndProperty dependent : dependents) {
            // Because the property has been removed, the dependent no longer needs to depend on it
            dependencies.remove(dependent, property);
            invertedDependencies.remove(property, dependent);

            boolean hasNoDependencies = dependencies.get(dependent).isEmpty();

            if (hasNoDependencies) {
                propertiesWithoutDependencies.add(dependent);
            }
        }
    }

    if (!dependencies.isEmpty()) {
        // This means there must have been a loop. Pick an arbitrary remaining var to display
        Var var = dependencies.keys().iterator().next().var();
        throw GraqlQueryException.insertRecursive(printableRepresentation(var));
    }

    return sorted.build();
}

From source file:com.flexive.core.search.genericSQL.GenericSQLDataFilter.java

/**
 * Builds an 'AND' condition.// w ww .  java 2  s. c  o  m
 *
 * @param sb the StringBuilder to use
 * @param br the brace
 * @throws FxSqlSearchException if the build failed
 */
private void buildAnd(StringBuilder sb, Brace br) throws FxSqlSearchException {
    // Start AND
    if (br.size() > 1) {
        final Multimap<String, ConditionTableInfo> tables = getUsedContentTables(br, true);
        // for "AND" we can only optimize when ALL flatstorage conditions are not multi-lang and on the same level,
        // i.e. that table must have exactly one flat-storage entry, and we cannot optimize if an IS NULL is present
        if (tables.size() == 1 && tables.values().iterator().next().isFlatStorage()
                && !tables.values().iterator().next().isMultiLang() && !containsIsNullCondition(br)) {
            sb.append(getOptimizedFlatStorageSubquery(br, tables.keySet().iterator().next(), true));
            return;
        }
        if (tables.size() == 1 && tables.keys().iterator().next().equals(DatabaseConst.TBL_CONTENT)) {
            // combine main table selects into a single one
            sb.append("(SELECT id,ver," + getEmptyLanguage() + " as lang FROM " + DatabaseConst.TBL_CONTENT
                    + " cd" + " WHERE " + getOptimizedMainTableConditions(br, "cd") + ")");
            return;
        }
        // check if there are two or more flat storage queries in the same level that can be grouped
        try {
            final Brace grouped = br.groupConditions(new Brace.GroupFunction() {
                @Override
                public Object apply(Condition cond) {
                    try {
                        return getPropertyInfo(cond);
                    } catch (FxSqlSearchException e) {
                        throw e.asRuntimeException();
                    }
                }
            });
            if (grouped != br) {
                // reorg happened - process new version
                if (LOG.isTraceEnabled()) {
                    LOG.trace("AND statement reorganized, new statement: " + grouped);
                }
                buildAnd(sb, grouped);
                return;
            }
        } catch (SqlParserException e) {
            throw new FxSqlSearchException(e);
        }
    }
    int pos = 0;
    final StringBuilder combinedConditions = new StringBuilder();
    int firstId = -1;
    for (BraceElement be : br.getElements()) {
        if (pos == 0) {
            firstId = be.getId();
            // TODO: do we need .lang here?
            sb.append(("(SELECT tbl" + firstId + ".id,tbl" + firstId + ".ver,tbl" + firstId + ".lang FROM\n"));
        } else {
            sb.append(",");
            combinedConditions.append((pos > 1) ? " AND " : " ").append("tbl").append(firstId).append(".id=tbl")
                    .append(be.getId()).append(".id AND ").append("tbl").append(firstId).append(".ver=tbl")
                    .append(be.getId()).append(".ver AND ").append("(tbl").append(firstId)
                    .append(".lang=0 or tbl").append(firstId).append(".lang IS NULL OR ").append("tbl")
                    .append(be.getId()).append(".lang=0 OR tbl").append(be.getId()).append(".lang IS NULL OR ")
                    .append("tbl").append(firstId).append(".lang=tbl").append(be.getId()).append(".lang)");
        }

        if (be instanceof Condition) {
            sb.append(getConditionSubQuery(br.getStatement(), (Condition) be));
        } else if (be instanceof Brace) {
            build(sb, (Brace) be);
        } else {
            throw new FxSqlSearchException(LOG, "ex.sqlSearch.filter.invalidBrace", be);
        }
        sb.append(" tbl").append(be.getId()).append("\n");
        pos++;
    }
    // Where links the tables together
    sb.append(" WHERE ");
    sb.append(combinedConditions);
    // Close AND
    sb.append(")");
}

From source file:com.flexive.core.search.PropertyEntry.java

/**
 * Create a new instance based on the given (search) property.
 *
 * @param searchProperty the search property
 * @param storage        the storage instance
 * @param ignoreCase     whether case should be ignored for this column
 * @throws FxSqlSearchException if the entry could not be created
 *///from w w w .  j  av a2s. c om
public PropertyEntry(Property searchProperty, ContentStorage storage, boolean ignoreCase)
        throws FxSqlSearchException {
    this.type = Type.PROPERTY_REF;
    this.environment = CacheAdmin.getEnvironment();
    if (searchProperty.isAssignment()) {
        try {
            if (StringUtils.isNumeric(searchProperty.getPropertyName())) {
                //#<id>
                assignment = (FxPropertyAssignment) environment
                        .getAssignment(Long.valueOf(searchProperty.getPropertyName()));
            } else {
                //XPath
                assignment = (FxPropertyAssignment) environment.getAssignment(searchProperty.getPropertyName());
            }
        } catch (ClassCastException ce) {
            throw unknownAssignmentException(searchProperty, ce);
        } catch (FxRuntimeException e) {
            if (e.getConverted() instanceof FxNotFoundException) {
                throw unknownAssignmentException(searchProperty, e);
            } else {
                throw new FxSqlSearchException(LOG, e, "ex.sqlSearch.query.failedToResolveAssignment",
                        searchProperty.getPropertyName(), e.getMessage());
            }
        }
        this.property = assignment.getProperty();
    } else {
        this.property = environment.getProperty(searchProperty.getPropertyName());

        // check if all assignments of the property are in the same table
        final List<FxPropertyAssignment> assignments = environment.getPropertyAssignments(property.getId(),
                false);
        final Multimap<String, FxPropertyAssignment> storageCounts = HashMultimap.create();
        boolean hasFlatStorageAssignments = false;
        for (FxPropertyAssignment pa : assignments) {
            if (pa.isFlatStorageEntry()) {
                hasFlatStorageAssignments = true;
                final FxFlatStorageMapping mapping = pa.getFlatStorageMapping();
                // group assignments by table, column, and level
                storageCounts.put(mapping.getStorage() + "." + mapping.getColumn() + "." + mapping.getLevel(),
                        pa);
            } else {
                storageCounts.put(storage.getTableName(property), pa);
            }
        }

        if (storageCounts.size() > 1 || hasFlatStorageAssignments) {
            // more than one storage, or only flat storage assignments

            // find the table with most occurances
            final List<Multiset.Entry<String>> tables = newArrayList(storageCounts.keys().entrySet());
            Collections.sort(tables, new Comparator<Multiset.Entry<String>>() {
                @Override
                public int compare(Multiset.Entry<String> o1, Multiset.Entry<String> o2) {
                    return FxSharedUtils.compare(o2.getCount(), o1.getCount());
                }
            });
            final String key = tables.get(0).getElement();
            final FxPropertyAssignment pa = storageCounts.get(key).iterator().next();
            if (pa.isFlatStorageEntry()) {
                // use assignment search. All assignments share the same flat storage table,
                // column and level, thus the "normal" assignment search can be used.
                assignment = pa;
            } else {
                assignment = null; // use "real" property search in the CONTENT_DATA table
                if (hasFlatStorageAssignments && LOG.isWarnEnabled()) {
                    // only write warning to log for now
                    LOG.warn(new FxExceptionMessage("ex.sqlSearch.err.select.propertyWithFlat",
                            this.property.getName(),
                            Iterables.filter(assignments, new Predicate<FxPropertyAssignment>() {
                                @Override
                                public boolean apply(FxPropertyAssignment input) {
                                    return input.isFlatStorageEntry();
                                }
                            })).getLocalizedMessage(FxContext.get().getLanguage()));
                }
            }
        } else {
            assignment = null; // nothing to do, use normal property search
        }
    }

    if (assignment != null && assignment.isFlatStorageEntry()) {
        // flat storage assignment search
        this.tableName = assignment.getFlatStorageMapping().getStorage();
        this.tbl = PropertyResolver.Table.T_CONTENT_DATA_FLAT;
    } else {
        // content_data assignment or property search
        this.tableName = storage.getTableName(property);
        if (this.tableName.equalsIgnoreCase(DatabaseConst.TBL_CONTENT)) {
            this.tbl = PropertyResolver.Table.T_CONTENT;
        } else if (this.tableName.equalsIgnoreCase(DatabaseConst.TBL_CONTENT_DATA)) {
            this.tbl = PropertyResolver.Table.T_CONTENT_DATA;
        } else {
            throw new FxSqlSearchException(LOG, "ex.sqlSearch.err.unknownPropertyTable", searchProperty,
                    this.tableName);
        }
    }

    this.readColumns = getReadColumns(storage, property);

    if (assignment != null && assignment.isFlatStorageEntry()) {
        final String column = StorageManager.getStorageImpl()
                .escapeFlatStorageColumn(assignment.getFlatStorageMapping().getColumn());
        this.filterColumn = !ignoreCase
                || assignment.getOption(FxStructureOption.OPTION_IN_UPPERCASE).isValueTrue()
                || (this.property.getDataType() != FxDataType.String1024
                        && this.property.getDataType() != FxDataType.Text
                        && this.property.getDataType() != FxDataType.HTML) ? column
                                // calculate upper-case function for text queries
                                : "UPPER(" + column + ")";
        this.flatColumnIndex = FxFlatStorageManager.getInstance().getColumnDataIndex(assignment);
        if (this.flatColumnIndex == -1) {
            throw new FxSqlSearchException(LOG, "ex.sqlSearch.init.flatMappingIndex", searchProperty);
        }
    } else {
        String fcol = ignoreCase
                && !this.property.getOption(FxStructureOption.OPTION_IN_UPPERCASE).isValueTrue()
                        ? storage.getQueryUppercaseColumn(this.property)
                        : this.readColumns[0];
        if (fcol == null) {
            fcol = this.readColumns == null ? null : this.readColumns[0];
        }
        this.filterColumn = fcol;
        this.flatColumnIndex = -1;
    }

    if (this.filterColumn == null) {
        throw new FxSqlSearchException(LOG, "ex.sqlSearch.init.propertyDoesNotHaveColumnMapping",
                searchProperty.getPropertyName());
    }

    if (this.tbl == PropertyResolver.Table.T_CONTENT_DATA) {
        switch (this.property.getDataType()) {
        case Number:
        case SelectMany:
            this.dataColumn = "FBIGINT";
            break;
        default:
            this.dataColumn = "FINT";
            break;
        }
    } else {
        this.dataColumn = null;
    }

    this.multilanguage = this.property.isMultiLang();
    this.functions.addAll(searchProperty.getFunctions());
    if (this.functions.size() > 0) {
        // use outmost function result type
        this.overrideDataType = this.functions.get(0).getOverrideDataType();
    }
}

From source file:com.google.gerrit.server.notedb.ChangeRebuilderImpl.java

private void buildUpdates(NoteDbUpdateManager manager, ChangeBundle bundle) throws IOException, OrmException {
    manager.setCheckExpectedState(false);
    Change change = new Change(bundle.getChange());
    PatchSet.Id currPsId = change.currentPatchSetId();
    // We will rebuild all events, except for draft comments, in buckets based
    // on author and timestamp.
    List<Event> events = new ArrayList<>();
    Multimap<Account.Id, PatchLineCommentEvent> draftCommentEvents = ArrayListMultimap.create();

    events.addAll(getHashtagsEvents(change, manager));

    // Delete ref only after hashtags have been read
    deleteChangeMetaRef(change, manager.getChangeRepo().cmds);
    deleteDraftRefs(change, manager.getAllUsersRepo());

    Integer minPsNum = getMinPatchSetNum(bundle);
    Set<PatchSet.Id> psIds = Sets.newHashSetWithExpectedSize(bundle.getPatchSets().size());

    for (PatchSet ps : bundle.getPatchSets()) {
        if (ps.getId().get() > currPsId.get()) {
            log.info("Skipping patch set {}, which is higher than current patch set {}", ps.getId(), currPsId);
            continue;
        }/* w w w.  j a  v a  2 s .  c  om*/
        psIds.add(ps.getId());
        events.add(new PatchSetEvent(change, ps, manager.getChangeRepo().rw));
        for (PatchLineComment c : getPatchLineComments(bundle, ps)) {
            PatchLineCommentEvent e = new PatchLineCommentEvent(c, change, ps, patchListCache);
            if (c.getStatus() == Status.PUBLISHED) {
                events.add(e);
            } else {
                draftCommentEvents.put(c.getAuthor(), e);
            }
        }
    }

    for (PatchSetApproval psa : bundle.getPatchSetApprovals()) {
        if (psIds.contains(psa.getPatchSetId())) {
            events.add(new ApprovalEvent(psa, change.getCreatedOn()));
        }
    }

    for (Table.Cell<ReviewerStateInternal, Account.Id, Timestamp> r : bundle.getReviewers().asTable()
            .cellSet()) {
        events.add(new ReviewerEvent(r, change.getCreatedOn()));
    }

    Change noteDbChange = new Change(null, null, null, null, null);
    for (ChangeMessage msg : bundle.getChangeMessages()) {
        if (msg.getPatchSetId() == null || psIds.contains(msg.getPatchSetId())) {
            events.add(new ChangeMessageEvent(msg, noteDbChange, change.getCreatedOn()));
        }
    }

    sortAndFillEvents(change, noteDbChange, events, minPsNum);

    EventList<Event> el = new EventList<>();
    for (Event e : events) {
        if (!el.canAdd(e)) {
            flushEventsToUpdate(manager, el, change);
            checkState(el.canAdd(e));
        }
        el.add(e);
    }
    flushEventsToUpdate(manager, el, change);

    EventList<PatchLineCommentEvent> plcel = new EventList<>();
    for (Account.Id author : draftCommentEvents.keys()) {
        for (PatchLineCommentEvent e : EVENT_ORDER.sortedCopy(draftCommentEvents.get(author))) {
            if (!plcel.canAdd(e)) {
                flushEventsToDraftUpdate(manager, plcel, change);
                checkState(plcel.canAdd(e));
            }
            plcel.add(e);
        }
        flushEventsToDraftUpdate(manager, plcel, change);
    }
}

From source file:uk.nhs.cfh.dsp.snomed.dao.impl.SnomedConceptDatabaseDAO.java

/**
 * Sets the relationships.// w  w  w.  ja v  a 2s. c o m
 *
 * @param concept the new relationships
 * @throws SQLException the SQL exception
 */
private synchronized void setRelationships(SnomedConcept concept) throws SQLException {

    String conceptID = concept.getConceptID();
    // get relationships
    Collection<SnomedRelationship> relationships = new ArrayList<SnomedRelationship>();
    Multimap<String, SnomedRelationship> roleGroupsMap = new HashMultimap();

    String relID = "";
    String sourceConceptID = "";
    String relationshipType = "";
    String targetConceptID = "";
    String relationshipGroup = "";
    String relSource = "";

    // set conceptID  in getRelationshipsForConceptIDStatement  and execute it
    getRelationshipsForConceptIDStatement.setString(1, conceptID);
    ResultSet relResultSet = getRelationshipsForConceptIDStatement.executeQuery();

    while (relResultSet.next()) {
        /*
        Retrieval using column name is expensive but does the conversion for us...
         */
        relID = relResultSet.getString(1);
        sourceConceptID = relResultSet.getString(2);
        relationshipType = relResultSet.getString(3);
        targetConceptID = relResultSet.getString(4);
        int characteristicType = relResultSet.getInt(5);
        int refinability = relResultSet.getInt(6);
        relationshipGroup = relResultSet.getString(7);
        relSource = relResultSet.getString(8);

        // process refinability and characteristic type returned.
        SnomedRelationship.Refinability relationshipRefinability = null;
        SnomedRelationship.RelationshipType type = null;

        // set value based on value passed
        if (refinability == 0) {
            relationshipRefinability = SnomedRelationship.Refinability.NOT_REFINABLE;
        } else if (refinability == 1) {
            relationshipRefinability = SnomedRelationship.Refinability.OPTIONAL;
        } else if (refinability == 2) {
            relationshipRefinability = SnomedRelationship.Refinability.MANDATORY;

        } else {
            logger.warn("Unknown refinability value : " + refinability);
        }

        // set characteristic type value based on value passed
        if (characteristicType == 0) {
            type = SnomedRelationship.RelationshipType.DEFINING;
        } else if (characteristicType == 1) {
            type = SnomedRelationship.RelationshipType.QUALIFIER;
        } else if (characteristicType == 2) {
            type = SnomedRelationship.RelationshipType.HISTORICAL;
        } else if (characteristicType == 3) {
            type = SnomedRelationship.RelationshipType.ADDITIONAL;
        } else {
            logger.warn("Unknown characteristic type passed : " + characteristicType);
        }

        // add relationship name
        String relationshipName = null;
        getPreferredTermStatement.setString(1, relationshipType);
        ResultSet rs = getPreferredTermStatement.executeQuery();
        while (rs.next()) {
            relationshipName = rs.getString(1);
        }

        // close result set
        rs.close();

        // create new relationship
        SnomedRelationship relationship = new SnomedRelationshipImpl(relID, sourceConceptID, relationshipType,
                targetConceptID, type, relationshipRefinability, relationshipGroup, relSource);

        if (relationshipName != null) {
            relationship.setName(relationshipName);
        }

        if (conceptID.equalsIgnoreCase(relationship.getSourceConceptID())) {
            concept.getSourceRelationships().add(relationship);
            // add relationship to concept
            concept.getRelationships().add(relationship);

            // check if relationship type is 'is a'
            if (ConceptType.ATTRIBUTE_IS_A.getID().equals(relationship.getRelationshipType())) {
                // we know this is a parent child relationship, so we add to children
                concept.getParentIDSet().add(relationship.getTargetConceptID());
            }

            // add defining and refining relationships
            if (relationship.isDefiningRelation()) {
                /*
                we need to check that the relationship is a defining relationship and does not have
                a relationshipgroup of 0. Any defining relationship without any any relationship with others
                is assigned the default value of 0.
                */
                if (!"0".equalsIgnoreCase(relationship.getRelationshipGroup())) {
                    // add relationship to rolegroups map
                    roleGroupsMap.put(relationshipGroup, relationship);
                } else {
                    concept.getDefiningRelationships().add(relationship);
                }
            }

            if (relationship.isQualifyingRelation()) {
                concept.getRefiningRelationships().add(relationship);
            }

            if (relationship.isMandatory()) {
                concept.getMandatoryRelationships().add(relationship);
            }

            if (relationship.isOptional()) {
                concept.getOptionalRelationships().add(relationship);
            }
        }
    }
    relResultSet.close();

    // get child relationship ids
    getChildRelationshipsForConceptIDStatement.setString(1, conceptID);
    ResultSet childrenSet = getChildRelationshipsForConceptIDStatement.executeQuery();
    Collection<String> childIds = new HashSet<String>();
    while (childrenSet.next()) {
        // add to concept's childIdSet
        childIds.add(childrenSet.getString(1));
    }
    // close result set
    childrenSet.close();

    concept.setChildIDSet(childIds);

    // add role groups
    Collection<SnomedRoleGroup> roleGroups = new ArrayList<SnomedRoleGroup>();
    // loop through role group map and generate role groups as needed
    for (String relationshipGroupId : roleGroupsMap.keys()) {
        Collection<SnomedRelationship> rels = roleGroupsMap.get(relationshipGroupId);
        // create rolegroup with relationships
        SnomedRoleGroup roleGroup = new SnomedRoleGroupImpl();
        roleGroup.setRelationships(new HashSet<SnomedRelationship>(rels));
        // set relationship group id for role group
        roleGroup.setRelationshipGroupId(relationshipGroupId);
        // add to roleGroups
        roleGroups.add(roleGroup);
    }

    concept.setRoleGroups(roleGroups);
}