Example usage for com.google.common.collect Table row

List of usage examples for com.google.common.collect Table row

Introduction

In this page you can find the example usage for com.google.common.collect Table row.

Prototype

Map<C, V> row(R rowKey);

Source Link

Document

Returns a view of all mappings that have the given row key.

Usage

From source file:matrix.SparseMatrix.java

/**
 * Construct a sparse matrix/*www . j av a2 s.c o  m*/
 * 
 * @param dataTable
 *            data table
 * @param columnStructure
 *            column structure
 */
private void construct(Table<Integer, Integer, Float> dataTable, Multimap<Integer, Integer> columnStructure) {
    int nnz = dataTable.size();

    // CRS
    rowPtr = new int[numRows + 1];
    colInd = new int[nnz];
    rowData = new float[nnz];

    int j = 0;
    for (int i = 1; i <= numRows; ++i) {
        Set<Integer> cols = dataTable.row(i - 1).keySet();
        rowPtr[i] = rowPtr[i - 1] + cols.size();

        for (int col : cols) {
            colInd[j++] = col;
            if (col < 0 || col >= numColumns)
                throw new IllegalArgumentException(
                        "colInd[" + j + "]=" + col + ", which is not a valid column index");
        }

        Arrays.sort(colInd, rowPtr[i - 1], rowPtr[i]);
    }

    // CCS
    if (columnStructure != null) {
        colPtr = new int[numColumns + 1];
        rowInd = new int[nnz];
        colData = new float[nnz];

        j = 0;
        for (int i = 1; i <= numColumns; ++i) {
            // dataTable.col(i-1) is very time-consuming
            Collection<Integer> rows = columnStructure.get(i - 1);
            colPtr[i] = colPtr[i - 1] + rows.size();

            for (int row : rows) {
                rowInd[j++] = row;
                if (row < 0 || row >= numRows)
                    throw new IllegalArgumentException(
                            "rowInd[" + j + "]=" + row + ", which is not a valid row index");
            }

            Arrays.sort(rowInd, colPtr[i - 1], colPtr[i]);
        }
    }

    // set data
    for (Cell<Integer, Integer, Float> en : dataTable.cellSet()) {
        int row = en.getRowKey();
        int col = en.getColumnKey();
        float val = en.getValue();

        set(row, col, val);
    }
}

From source file:org.caleydo.view.domino.internal.band.ParaBand.java

@Override
protected List<? extends IBandRenderAble> computeGroupDetailRoutes() {
    List<IBandRenderAble> detailRoutes = new ArrayList<>();

    TypedList s = shared.sliceList(sData.getIdType());
    final Multimap<Integer, Integer> slookup = computeLookup(s);
    TypedList t = shared.sliceList(tData.getIdType());
    final Multimap<Integer, Integer> tlookup = computeLookup(tData);

    Table<TypedListGroup, TypedListGroup, NavigableSet<LineAcc>> lines = ArrayTable.create(sData.getGroups(),
            tData.getGroups());// w w  w .  ja  v a2s . c  o  m

    final List<TypedListGroup> sgroups = sData.getGroups();
    final List<TypedListGroup> tgroups = tData.getGroups();
    int i = 0;
    for (int ig = 0; ig < sgroups.size(); ++ig) {
        final TypedListGroup sgroup = sgroups.get(ig);
        Map<TypedListGroup, NavigableSet<LineAcc>> row = lines.row(sgroup);
        for (int ii = 0; ii < sgroup.size(); ++ii, ++i) {
            Integer sId = sgroup.get(ii);
            if (sId.intValue() < 0) {
                continue;
            }
            Collection<Integer> indices = slookup.get(sId);
            if (indices.isEmpty()) { // not shared
                continue;
            }
            GLLocation slocation = locS(EBandMode.DETAIL, i);
            if (!slocation.isDefined()) { // don't know where it is
                continue;
            }
            Vec2f sloc = new Vec2f((float) slocation.getOffset(), (float) slocation.getOffset2());

            for (int sindex : indices) {
                Integer tId = t.get(sindex);
                Collection<Integer> tindices = tlookup.get(tId);
                if (tindices.isEmpty())
                    continue;
                for (int tindex : tindices) {
                    GLLocation tlocation = locT(EBandMode.DETAIL, tindex);
                    if (!tlocation.isDefined())
                        continue;
                    Vec2f tloc = new Vec2f((float) tlocation.getOffset(), (float) tlocation.getOffset2());

                    TypedListGroup tgroup = tData.groupAt(tindex);

                    NavigableSet<LineAcc> stlines = row.get(tgroup);
                    if (stlines == null)
                        row.put(tgroup, stlines = new TreeSet<LineAcc>());

                    final LineAcc l = new LineAcc(sloc, tloc, sId, tId);
                    LineAcc m = stlines.ceiling(l);
                    if (m == null || !m.merge(sloc, tloc, sId, tId))
                        stlines.add(l);
                }
            }
        }
    }

    for (int ig = 0; ig < sgroups.size(); ++ig) {
        final TypedListGroup sgroup = sgroups.get(ig);
        Map<TypedListGroup, NavigableSet<LineAcc>> row = lines.row(sgroup);
        GLLocation gLocation = locS(EBandMode.GROUPS, ig);
        float factor = (float) gLocation.getSize() / sgroup.size();
        int j = 0;
        for (NavigableSet<LineAcc> stlines : row.values()) {
            if (stlines == null)
                continue;
            for (LineAcc line : stlines) {
                line.sGroupOffset = (float) gLocation.getOffset() + factor * j - line.s.x();
                j += line.sIds.size();
            }
        }
    }
    for (int ig = 0; ig < tgroups.size(); ++ig) {
        final TypedListGroup tgroup = tgroups.get(ig);
        Map<TypedListGroup, NavigableSet<LineAcc>> col = lines.column(tgroup);
        GLLocation gLocation = locT(EBandMode.GROUPS, ig);
        float factor = (float) gLocation.getSize() / tgroup.size();
        int j = 0;
        for (NavigableSet<LineAcc> stlines : col.values()) {
            if (stlines == null)
                continue;
            for (LineAcc line : stlines) {
                line.tGroupOffset = (float) gLocation.getOffset() + factor * j - line.t.x();
                j += line.tIds.size();
            }
        }
    }
    {
        IDType sType = this.sData.getIdType();
        IDType tType = this.tData.getIdType();

        for (NavigableSet<LineAcc> stlines : lines.values()) {
            if (stlines == null)
                continue;
            for (LineAcc line : stlines)
                detailRoutes.add(build(line, sType, tType, EBandMode.GROUPED_DETAIL));
        }
    }
    return detailRoutes;
}

From source file:com.torodb.d2r.R2DTranslatorImpl.java

@Override
public List<ToroDocument> translate(Iterator<DocPartResult> docPartResultIt) {
    ImmutableList.Builder<ToroDocument> readedDocuments = ImmutableList.builder();

    Table<TableRef, Integer, Map<String, List<KvValue<?>>>> currentFieldDocPartTable = HashBasedTable
            .<TableRef, Integer, Map<String, List<KvValue<?>>>>create();
    Table<TableRef, Integer, Map<String, List<KvValue<?>>>> childFieldDocPartTable = HashBasedTable
            .<TableRef, Integer, Map<String, List<KvValue<?>>>>create();

    int previousDepth = -1;

    while (docPartResultIt.hasNext()) {
        DocPartResult docPartResult = docPartResultIt.next();
        MetaDocPart metaDocPart = docPartResult.getMetaDocPart();
        TableRef tableRef = metaDocPart.getTableRef();

        if (previousDepth != -1 && previousDepth != tableRef.getDepth()) {
            Table<TableRef, Integer, Map<String, List<KvValue<?>>>> previousFieldChildDocPartTable = childFieldDocPartTable;
            childFieldDocPartTable = currentFieldDocPartTable;
            currentFieldDocPartTable = previousFieldChildDocPartTable;

            if (!tableRef.isRoot()) {
                currentFieldDocPartTable.clear();
            }//from w ww.j a  v a2 s  .c o m
        }
        previousDepth = tableRef.getDepth();

        Map<Integer, Map<String, List<KvValue<?>>>> childFieldDocPartRow = childFieldDocPartTable.row(tableRef);
        Map<Integer, Map<String, List<KvValue<?>>>> currentFieldDocPartRow;

        if (tableRef.isRoot()) {
            currentFieldDocPartRow = null;
        } else {
            currentFieldDocPartRow = currentFieldDocPartTable.row(tableRef.getParent().get());
        }

        readResult(metaDocPart, tableRef, docPartResult, currentFieldDocPartRow, childFieldDocPartRow,
                readedDocuments);
    }

    return readedDocuments.build();
}

From source file:org.ow2.authzforce.core.pdp.impl.policy.CoreRefPolicyProvider.java

/**
 * Creates an instance from policy locations
 *
 * @param policyURLs/*w  w  w  . ja va  2  s. c om*/
 *            location of Policy(Set) elements (JAXB) to be parsed for future reference by Policy(Set)IdReferences
 * @param ignoreOldPolicyVersions
 *            for any given policy ID, ignore all versions except the last one if there are multiple versions of the policy
 * @param xacmlParserFactory
 *            XACML parser factory for parsing any XACML Policy(Set)
 * @param maxPolicySetRefDepth
 *            maximum allowed depth of PolicySet reference chain (via PolicySetIdReference): PolicySet1 -> PolicySet2 -> ...; a strictly negative value means no limit
 * @param combiningAlgRegistry
 *            registry of policy/rule combining algorithms
 * @param expressionFactory
 *            Expression factory for parsing Expressions used in the policy(set)
 * @return instance of this class
 * @throws java.lang.IllegalArgumentException
 *             if {@code policyURLs == null || policyURLs.length == 0 || xacmlParserFactory == null || expressionFactory == null || combiningAlgRegistry == null}; or one of {@code policyURLs} is
 *             null or is not a valid XACML Policy(Set) or conflicts with another because it has same Policy(Set)Id and Version. Beware that the Policy(Set)Issuer is ignored from this check!
 */
public static CoreRefPolicyProvider getInstance(final Collection<URL> policyURLs,
        final boolean ignoreOldPolicyVersions, final XmlnsFilteringParserFactory xacmlParserFactory,
        final int maxPolicySetRefDepth, final ExpressionFactory expressionFactory,
        final CombiningAlgRegistry combiningAlgRegistry) throws IllegalArgumentException {
    if (policyURLs == null || policyURLs.isEmpty()) {
        throw ILLEGAL_POLICY_URLS_ARGUMENT_EXCEPTION;
    }

    if (xacmlParserFactory == null) {
        throw ILLEGAL_XACML_PARSER_FACTORY_ARGUMENT_EXCEPTION;
    }

    if (expressionFactory == null) {
        throw ILLEGAL_EXPRESSION_FACTORY_ARGUMENT_EXCEPTION;
    }

    if (combiningAlgRegistry == null) {
        throw ILLEGAL_COMBINING_ALG_REGISTRY_ARGUMENT_EXCEPTION;
    }

    final XmlnsFilteringParser xacmlParser;
    try {
        xacmlParser = xacmlParserFactory.getInstance();
    } catch (final JAXBException e) {
        throw new IllegalArgumentException("Failed to create JAXB unmarshaller for XML Policy(Set)", e);
    }

    final Table<String, PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicyTable = HashBasedTable
            .create();
    final Table<String, PolicyVersion, PolicyWithNamespaces<PolicySet>> updatablePolicySetTable = HashBasedTable
            .create();
    int policyUrlIndex = 0;
    for (final URL policyURL : policyURLs) {
        if (policyURL == null) {
            throw new IllegalArgumentException("policyURL #" + policyUrlIndex + " undefined");
        }

        final Object jaxbPolicyOrPolicySetObj;
        try {
            jaxbPolicyOrPolicySetObj = xacmlParser.parse(policyURL);
        } catch (final JAXBException e) {
            throw new IllegalArgumentException(
                    "Failed to unmarshall Policy(Set) XML document from policy location: " + policyURL, e);
        }

        final Map<String, String> nsPrefixUriMap = xacmlParser.getNamespacePrefixUriMap();
        if (jaxbPolicyOrPolicySetObj instanceof Policy) {
            final Policy jaxbPolicy = (Policy) jaxbPolicyOrPolicySetObj;
            final String policyId = jaxbPolicy.getPolicyId();
            final String policyVersionStr = jaxbPolicy.getVersion();
            final PolicyVersion policyVersion = new PolicyVersion(policyVersionStr);

            if (ignoreOldPolicyVersions) {
                final Map<PolicyVersion, StaticTopLevelPolicyElementEvaluator> policyVersions = updatablePolicyTable
                        .row(policyId);
                if (policyVersions != null) {
                    final boolean isOld = policyVersions.keySet().parallelStream()
                            .anyMatch(v -> policyVersion.compareTo(v) <= 0);
                    if (isOld) {
                        // skip
                        continue;
                    }

                    /*
                     * Else replace/overwrite with this new version (make sure it is the only one), so empty the row first
                     */
                    policyVersions.clear();
                }
            }

            final StaticTopLevelPolicyElementEvaluator policyEvaluator;
            try {
                policyEvaluator = PolicyEvaluators.getInstance(jaxbPolicy, null, nsPrefixUriMap,
                        expressionFactory, combiningAlgRegistry);
            } catch (final IllegalArgumentException e) {
                throw new IllegalArgumentException(
                        "Invalid Policy with PolicyId=" + policyId + ", Version=" + policyVersionStr, e);
            }

            final StaticTopLevelPolicyElementEvaluator previousValue = updatablePolicyTable.put(policyId,
                    policyVersion, policyEvaluator);
            if (previousValue != null) {
                throw new IllegalArgumentException("Policy conflict: two policies with same PolicyId="
                        + policyId + ", Version=" + policyVersionStr);
            }

        } else if (jaxbPolicyOrPolicySetObj instanceof PolicySet) {
            final PolicySet jaxbPolicySet = (PolicySet) jaxbPolicyOrPolicySetObj;
            final String policyId = jaxbPolicySet.getPolicySetId();
            final String policyVersionStr = jaxbPolicySet.getVersion();
            final PolicyVersion policyVersion = new PolicyVersion(policyVersionStr);

            if (ignoreOldPolicyVersions) {
                final Map<PolicyVersion, PolicyWithNamespaces<PolicySet>> policyVersions = updatablePolicySetTable
                        .row(policyId);
                if (policyVersions != null) {
                    final boolean isOld = policyVersions.keySet().parallelStream()
                            .anyMatch(v -> policyVersion.compareTo(v) <= 0);
                    if (isOld) {
                        // skip
                        continue;
                    }

                    /*
                     * Else replace/overwrite with this new version (make sure it is the only one), so empty the row first
                     */
                    policyVersions.clear();
                }
            }

            final PolicyWithNamespaces<PolicySet> previousValue = updatablePolicySetTable.put(policyId,
                    policyVersion, new PolicyWithNamespaces<>(jaxbPolicySet, nsPrefixUriMap));
            if (previousValue != null) {
                throw new IllegalArgumentException("Policy conflict: two PolicySets with same PolicySetId="
                        + policyId + ", Version=" + policyVersionStr);
            }

            /*
             * PolicySets cannot be parsed before we have collected them all, because each PolicySet may refer to others via PolicySetIdReferences
             */
        } else {
            throw new IllegalArgumentException("Unexpected element found as root of the policy document: "
                    + jaxbPolicyOrPolicySetObj.getClass().getSimpleName());
        }

        policyUrlIndex++;
    }

    final PolicyMap<StaticTopLevelPolicyElementEvaluator> policyMap = new PolicyMap<>(
            updatablePolicyTable.rowMap());
    final PolicyMap<PolicyWithNamespaces<PolicySet>> policySetMap = new PolicyMap<>(
            updatablePolicySetTable.rowMap());
    return new CoreRefPolicyProvider(policyMap, policySetMap, maxPolicySetRefDepth, expressionFactory,
            combiningAlgRegistry);
}

From source file:librec.data.SparseMatrix.java

/**
 * Construct a sparse matrix/*from  ww w .  j av a 2  s  .com*/
 * 
 * @param dataTable
 *            data table
 * @param columnStructure
 *            column structure
 */
private void construct(Table<Integer, Integer, ? extends Number> dataTable,
        Multimap<Integer, Integer> columnStructure) {
    int nnz = dataTable.size();

    // CRS
    rowPtr = new int[numRows + 1];
    colInd = new int[nnz];
    rowData = new double[nnz];

    int j = 0;
    for (int i = 1; i <= numRows; ++i) {
        Set<Integer> cols = dataTable.row(i - 1).keySet();
        rowPtr[i] = rowPtr[i - 1] + cols.size();

        for (int col : cols) {
            colInd[j++] = col;
            if (col < 0 || col >= numColumns)
                throw new IllegalArgumentException(
                        "colInd[" + j + "]=" + col + ", which is not a valid column index");
        }

        Arrays.sort(colInd, rowPtr[i - 1], rowPtr[i]);
    }

    // CCS
    colPtr = new int[numColumns + 1];
    rowInd = new int[nnz];
    colData = new double[nnz];

    j = 0;
    for (int i = 1; i <= numColumns; ++i) {
        // dataTable.col(i-1) is more time-consuming than columnStructure.get(i-1)
        Collection<Integer> rows = columnStructure != null ? columnStructure.get(i - 1)
                : dataTable.column(i - 1).keySet();
        colPtr[i] = colPtr[i - 1] + rows.size();

        for (int row : rows) {
            rowInd[j++] = row;
            if (row < 0 || row >= numRows)
                throw new IllegalArgumentException(
                        "rowInd[" + j + "]=" + row + ", which is not a valid row index");
        }

        Arrays.sort(rowInd, colPtr[i - 1], colPtr[i]);
    }

    // set data
    for (Cell<Integer, Integer, ? extends Number> en : dataTable.cellSet()) {
        int row = en.getRowKey();
        int col = en.getColumnKey();
        double val = en.getValue().doubleValue();

        set(row, col, val);
    }
}

From source file:es.upm.dit.xsdinferencer.merge.mergerimpl.TypeMergerImpl.java

private void removedUnusedSchemaElements(Schema schema) {
    boolean changed = true;
    Table<String, String, SchemaElement> schemaElements = schema.getElements();
    mainLoop: while (changed) {
        changed = false;/*w ww  . j av  a  2  s .  c  o m*/
        for (String namespaceURI : schemaElements.rowKeySet()) {
            elementInnerLoop: for (String key : schemaElements.row(namespaceURI).keySet()) {
                SchemaElement currentSchemaElement = schemaElements.get(namespaceURI, key);
                if (currentSchemaElement.isValidRoot())
                    continue elementInnerLoop;
                for (ComplexType complexType : schema.getComplexTypes().values()) {
                    if (complexType.getAutomaton().containsNode(currentSchemaElement))
                        continue elementInnerLoop;
                }
                //If no complex type contains it and it is not a valid root, we delete it
                schemaElements.remove(namespaceURI, key);
                changed = true;
                continue mainLoop;
            }
        }
    }
}

From source file:de.blizzy.rust.lootconfig.LootConfigDump.java

private void run() throws IOException {
    LootConfig config = loadConfig(configFile);

    Table<LootContainer, Category, Multiset<Float>> dropChances = HashBasedTable.create();

    Collection<LootContainer> lootContainers = config.LootContainers.values();
    config.Categories.values().stream().filter(Category::hasItemsOrBlueprints).forEach(category -> {
        lootContainers.forEach(lootContainer -> {
            Multiset<Float> categoryInContainerDropChances = getItemCategoryDropChances(category,
                    lootContainer);// w  w  w .ja  v a2  s  .  co m
            if (!categoryInContainerDropChances.isEmpty()) {
                dropChances.put(lootContainer, category, categoryInContainerDropChances);
            }
        });
    });

    dropChances.rowKeySet().stream()
            .filter(lootContainer -> SHOW_DMLOOT || !lootContainer.name.contains("dmloot"))
            .sorted((lootContainer1, lootContainer2) -> Collator.getInstance().compare(lootContainer1.name,
                    lootContainer2.name))
            .forEach(lootContainer -> {
                System.out.printf("%s (blueprint fragments: %s)", lootContainer,
                        lootContainer.DistributeFragments ? "yes" : "no").println();
                Map<Category, Multiset<Float>> lootContainerDropChances = dropChances.row(lootContainer);
                AtomicDouble lootContainerDropChancesSum = new AtomicDouble();
                AtomicInteger categoriesCount = new AtomicInteger();
                lootContainerDropChances.entrySet().stream().sorted(this::compareByChances).limit(7)
                        .forEach(categoryDropChancesEntry -> {
                            Category category = categoryDropChancesEntry.getKey();
                            Multiset<Float> categoryDropChances = categoryDropChancesEntry.getValue();
                            float categoryDropChancesSum = sum(categoryDropChances);
                            lootContainerDropChancesSum.addAndGet(categoryDropChancesSum);
                            System.out.printf("  %s %s%s%s", formatPercent(categoryDropChancesSum), category,
                                    (category.Items.size() > 0) ? " (" + formatItems(category) + ")" : "",
                                    (category.Blueprints.size() > 0) ? " [" + formatBlueprints(category) + "]"
                                            : "")
                                    .println();
                            categoriesCount.incrementAndGet();
                        });
                if (categoriesCount.get() < lootContainerDropChances.size()) {
                    System.out.printf("  %s other (%d)",
                            formatPercent(1f - (float) lootContainerDropChancesSum.get()),
                            lootContainerDropChances.size() - categoriesCount.get()).println();
                }
            });
}

From source file:structure.matrix.SparseMatrix.java

/**
 * Construct a sparse matrix//from www  .  j  ava2 s . c o m
 * 
 * @param dataTable
 *            data table
 * @param columnStructure
 *            column structure
 */
private void construct(Table<Integer, Integer, ? extends Number> dataTable,
        Multimap<Integer, Integer> columnStructure) {
    int nnz = dataTable.size();

    // CRS
    rowPtr = new int[numRows + 1];
    colInd = new int[nnz];
    rowData = new double[nnz];

    int j = 0;
    for (int i = 1; i <= numRows; ++i) {
        Set<Integer> cols = dataTable.row(i - 1).keySet();
        rowPtr[i] = rowPtr[i - 1] + cols.size();

        for (int col : cols) {
            colInd[j++] = col;
            if (col < 0 || col >= numColumns)
                throw new IllegalArgumentException(
                        "colInd[" + j + "]=" + col + ", which is not a valid column index");
        }

        Arrays.sort(colInd, rowPtr[i - 1], rowPtr[i]);
    }

    // CCS
    colPtr = new int[numColumns + 1];
    rowInd = new int[nnz];
    colData = new double[nnz];

    j = 0;
    for (int i = 1; i <= numColumns; ++i) {
        // dataTable.col(i-1) is more time-consuming than
        // columnStructure.get(i-1)
        Collection<Integer> rows = columnStructure != null ? columnStructure.get(i - 1)
                : dataTable.column(i - 1).keySet();
        colPtr[i] = colPtr[i - 1] + rows.size();

        for (int row : rows) {
            rowInd[j++] = row;
            if (row < 0 || row >= numRows)
                throw new IllegalArgumentException(
                        "rowInd[" + j + "]=" + row + ", which is not a valid row index");
        }

        Arrays.sort(rowInd, colPtr[i - 1], colPtr[i]);
    }

    // set data
    for (Cell<Integer, Integer, ? extends Number> en : dataTable.cellSet()) {
        int row = en.getRowKey();
        int col = en.getColumnKey();
        double val = en.getValue().doubleValue();

        set(row, col, val);
    }
}

From source file:org.eclipse.viatra.query.runtime.base.core.NavigationHelperContentAdapter.java

/**
 * Maintains subtype hierarchy//from   w  ww .  j  av a2 s  .  co m
 * 
 * @param subClassKey
 *            EClass or String id of subclass
 * @param superClassKey
 *            EClass or String id of superclass
 */
private void maintainTypeHierarhyInternal(final Object subClassKey, final Object superClassKey) {
    // update observed class and instance listener tables according to new subtype information
    if (navigationHelper.directlyObservedClasses.contains(superClassKey)) {
        navigationHelper.getAllObservedClassesInternal().add(subClassKey);
    }
    final Table<Object, InstanceListener, Set<EClass>> instanceListeners = navigationHelper
            .peekInstanceListeners();
    if (instanceListeners != null) { // table already constructed
        for (final Entry<InstanceListener, Set<EClass>> entry : instanceListeners.row(superClassKey)
                .entrySet()) {
            final InstanceListener listener = entry.getKey();
            for (final EClass subscriptionType : entry.getValue()) {
                navigationHelper.addInstanceListenerInternal(listener, subscriptionType, subClassKey);
            }
        }
    }

    // update subtype maps
    Set<Object> subTypes = subTypeMap.get(superClassKey);
    if (subTypes == null) {
        subTypes = new HashSet<Object>();
        subTypeMap.put(superClassKey, subTypes);
    }
    subTypes.add(subClassKey);
    Set<Object> superTypes = superTypeMap.get(subClassKey);
    if (superTypes == null) {
        superTypes = new HashSet<Object>();
        superTypeMap.put(subClassKey, superTypes);
    }
    superTypes.add(superClassKey);
}

From source file:co.cask.cdap.internal.app.runtime.flow.FlowletProgramRunner.java

private OutputEmitterFactory outputEmitterFactory(final BasicFlowletContext flowletContext,
        final String flowletName, final QueueClientFactory queueClientFactory,
        final ImmutableList.Builder<ProducerSupplier> producerBuilder,
        final Table<Node, String, Set<QueueSpecification>> queueSpecs) {
    return new OutputEmitterFactory() {
        @Override/*from  w w  w.  ja v  a2 s  . c  o  m*/
        public <T> OutputEmitter<T> create(String outputName, TypeToken<T> type) {
            try {
                // first iterate over all queue specifications to find the queue name and all consumer flowlet ids
                QueueName queueName = null;
                List<String> consumerFlowlets = Lists.newLinkedList();
                Node flowlet = Node.flowlet(flowletName);
                Schema schema = schemaGenerator.generate(type.getType());
                for (Map.Entry<String, Set<QueueSpecification>> entry : queueSpecs.row(flowlet).entrySet()) {
                    for (QueueSpecification queueSpec : entry.getValue()) {
                        if (queueSpec.getQueueName().getSimpleName().equals(outputName)
                                && queueSpec.getOutputSchema().equals(schema)) {

                            queueName = queueSpec.getQueueName();
                            consumerFlowlets.add(entry.getKey());
                            break;
                        }
                    }
                }
                if (queueName == null) {
                    throw new IllegalArgumentException(
                            String.format("No queue specification found for %s, %s", flowletName, type));
                }

                // create a metric collector for this queue, and also one for each consumer flowlet
                final MetricsContext metrics = flowletContext.getProgramMetrics()
                        .childContext(Constants.Metrics.Tag.FLOWLET_QUEUE, outputName);
                final MetricsContext producerMetrics = metrics.childContext(Constants.Metrics.Tag.PRODUCER,
                        flowletContext.getFlowletId());
                final Iterable<MetricsContext> consumerMetrics = Iterables.transform(consumerFlowlets,
                        new Function<String, MetricsContext>() {
                            @Override
                            public MetricsContext apply(String consumer) {
                                return producerMetrics.childContext(Constants.Metrics.Tag.CONSUMER, consumer);
                            }
                        });

                // create a queue metrics emitter that emit to all of the above collectors
                ProducerSupplier producerSupplier = new ProducerSupplier(queueName, queueClientFactory,
                        new QueueMetrics() {
                            @Override
                            public void emitEnqueue(int count) {
                                metrics.increment("process.events.out", count);
                                for (MetricsContext collector : consumerMetrics) {
                                    collector.increment("queue.pending", count);
                                }
                            }

                            @Override
                            public void emitEnqueueBytes(int bytes) {
                                // no-op
                            }
                        });
                producerBuilder.add(producerSupplier);
                return new DatumOutputEmitter<>(producerSupplier, schema,
                        datumWriterFactory.create(type, schema));
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };
}