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

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

Introduction

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

Prototype

Map<R, Map<C, V>> rowMap();

Source Link

Document

Returns a view that associates each row key with the corresponding map from column keys to values.

Usage

From source file:eu.itesla_project.modules.offline.CsvMetricsDb.java

@Override
public synchronized void exportCsv(String workflowId, Writer writer, char delimiter) {
    Objects.requireNonNull(workflowId);
    Objects.requireNonNull(writer);
    try {/*w ww  . j  a  va2  s.  co  m*/
        flush(workflowId);

        Table<String, String, String> table = HashBasedTable.create();
        try (BufferedReader metricsReader = Files.newBufferedReader(toMetricsCsvFile(workflowId),
                StandardCharsets.UTF_8)) {
            String line;
            while ((line = metricsReader.readLine()) != null) {
                String[] tokens = line.split(Character.toString(CSV_SEPARATOR));
                if (tokens.length != 4) {
                    LOGGER.warn("Invalid line '{}'", line);
                    continue;
                }
                String target = tokens[0];
                String moduleName = tokens[1];
                String metricName = tokens[2];
                String metricValue = tokens[3];
                table.put(target, (moduleName.length() > 0 ? moduleName + ":" : "") + metricName, metricValue);
            }
        }
        writer.write("target");
        writer.write(delimiter);
        List<String> columnKeys = new ArrayList<>(new TreeSet<>(table.columnKeySet()));
        for (String columnKey : columnKeys) {
            writer.write(columnKey);
            writer.write(delimiter);
        }
        writer.write("\n");
        for (Map.Entry<String, Map<String, String>> entry : table.rowMap().entrySet()) {
            String target = entry.getKey();
            Map<String, String> metrics = entry.getValue();
            writer.write(target);
            writer.write(delimiter);
            for (String columnKey : columnKeys) {
                String value = metrics.get(columnKey);
                if (value != null) {
                    writer.write(value);
                }
                writer.write(delimiter);
            }
            writer.write("\n");
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java

/**
 * Generic implementation for finding all the Services or Operations that have ALL the given types as inputs or outputs.
 *
 * @param entityType   the MSM URI of the type of entity we are looking for. Only supports Service and Operation.
 * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput.
 * @param types        the input/output types (modelReferences that is) we are looking for
 * @return a Map mapping operation/services URIs to MatchResults.
 *//*  ww w.j  a v a2  s  .  c  o m*/
private Map<URI, MatchResult> findAll(URI entityType, URI relationship, Set<URI> types) {

    // Ensure that we have been given correct parameters
    if (types == null || types.isEmpty()
            || (!entityType.toASCIIString().equals(MSM.Service.getURI())
                    && !entityType.toASCIIString().equals(MSM.Operation.getURI()))
            || (!relationship.toASCIIString().equals(MSM.hasInput.getURI())
                    && !entityType.toASCIIString().equals(MSM.hasOutput.getURI())
                    && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) {

        return ImmutableMap.of();
    }

    // Expand the input types to get all that match enough to be consumed
    // The structure is: <OriginalType, MatchingType, MatchResult>
    Table<URI, URI, MatchResult> expandedTypes;
    if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
        expandedTypes = HashBasedTable.create();
        for (URI type : types) {
            expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type),
                    LogicConceptMatchType.Subsume));
            expandedTypes.putAll(
                    this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact));
        }
    } else {
        expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin);
    }

    // Track all the results in a multimap to push the details up the stack
    ListMultimap<URI, MatchResult> result = ArrayListMultimap.create();

    // Do the intersection of those operations that can consume each of the inputs separately
    boolean firstTime = true;
    Map<URI, MatchResult> intermediateMatches;
    Map<URI, Map<URI, MatchResult>> rowMap = expandedTypes.rowMap();
    // For each original type
    for (URI inputType : rowMap.keySet()) {
        // obtain those entities that match any of the expanded matching types
        intermediateMatches = findSome(entityType, relationship, rowMap.get(inputType).keySet());
        if (firstTime) {
            // Add all entries
            firstTime = false;
            for (Map.Entry<URI, MatchResult> entry : intermediateMatches.entrySet()) {
                result.put(entry.getKey(), entry.getValue());
            }
        } else {
            // Put all the values from the intersection
            Set<URI> intersection = Sets.intersection(result.keySet(), intermediateMatches.keySet());
            for (URI opUri : intersection) {
                result.put(opUri, intermediateMatches.get(opUri));
            }

            // Drop all the values from the difference
            // Use an immutable copy since the views will be changed
            Set<URI> difference = Sets.difference(result.keySet(), intermediateMatches.keySet())
                    .immutableCopy();
            for (URI opUri : difference) {
                result.removeAll(opUri);
            }
        }
    }

    // Merge the results into a single map using Union
    return Maps.transformValues(result.asMap(), MatchResultsMerger.INTERSECTION);

}

From source file:es.uam.eps.bmi.recommendation.data.MovieRatingData.java

/**
 * Load the data from file./*from   w w w .ja va  2 s .  co  m*/
 *
 * @param dataPath Path to the file to be read.
 * @throws java.io.IOException
 */
@Override
public void load(String dataPath) throws IOException {
    // Table for reading
    Table<Integer, Integer, Double> table = HashBasedTable.create();

    // Read the file.
    BufferedReader reader = new BufferedReader(new FileReader(new File(dataPath)));

    // Read the first line
    String line = reader.readLine();
    // Get headers
    if (line != null) {
        line = reader.readLine();
    }

    // Array indexes
    ArrayList<Integer> userArray = new ArrayList<>();
    ArrayList<Integer> movieArray = new ArrayList<>();
    int userIndex = 0, movieIndex = 0;

    // Read file
    while (line != null) {
        // Split data
        String[] split = line.split("\t");
        // Get data
        int user = Integer.valueOf(split[0]);
        int movie = Integer.valueOf(split[1]);
        double rating = Double.valueOf(split[2]);

        // Store rows and columns IDs.
        if (!userMap.containsKey(user)) {
            userArray.add(user);
            userMap.put(user, userIndex++);
        }
        if (!movieMap.containsKey(movie)) {
            movieArray.add(movie);
            movieMap.put(movie, movieIndex++);
        }

        // Add data
        table.put(user, movie, rating);
        // Read next line
        line = reader.readLine();
    }

    // Create sparse matrix
    this.userID = userArray.toArray(new Integer[userIndex]);
    this.movieID = movieArray.toArray(new Integer[movieIndex]);
    this.ratingData = new SparseDoubleMatrix2D(userIndex, movieIndex);

    // Fill sparse matrix
    table.rowMap().forEach((Integer row, Map<Integer, Double> rowVector) -> {
        rowVector.forEach((Integer column, Double cellData) -> {
            ratingData.set(userMap.get(row), movieMap.get(column), cellData);
        });
    });

    table.clear();
}

From source file:org.pau.assetmanager.viewmodel.chart.ChartDataModel.java

/**
 * Returns the total balance along one year in a monthly basis.
 * /*from www .j a  va 2  s. c  o m*/
 * @param year
 *            the balance
 * @param yearToAnnotationMultimap
 *            year --> annotations multimap
 * @param selectedBook
 *            book selected for the balance
 * @param bookSelectionType
 *            type of book
 * @return
 */
public static DefaultCategoryDataset getBalance(Integer year,
        Multimap<Integer, Annotation> yearToAnnotationMultimap, BookSelection bookSelection,
        Boolean includePurchasedStocks, Optional<String> optionalStockLabel) {
    Book selectedBook = bookSelection.getSelectedBook();
    Double previousYearsTotals = 0.0;
    for (Integer currentYear : yearToAnnotationMultimap.keySet()) {
        if (currentYear < year) {
            for (Annotation currentAnnotation : yearToAnnotationMultimap.get(currentYear)) {
                previousYearsTotals += currentAnnotation.getSignedAmount();
            }
        }
    }
    Set<StocksBook> stockBooks = new HashSet<StocksBook>();
    Map<String, Double> totalData = new HashMap<String, Double>();
    for (int month = 0; month < 12; month++) {
        Calendar currentcalendar = GregorianCalendar.getInstance();
        currentcalendar.set(Calendar.MONTH, month);
        currentcalendar.set(Calendar.YEAR, year);
        currentcalendar.set(Calendar.DAY_OF_MONTH, 1);
        String mainLabel = getTimeLabel(currentcalendar.getTime());
        totalData.put(mainLabel, 0.0);
        Collection<Annotation> annotations = yearToAnnotationMultimap.get(year);
        if (annotations != null) {
            for (Annotation annotation : annotations) {
                String currentAnnotationLabel = getTimeLabel(annotation.getDate());
                if (currentAnnotationLabel.equals(mainLabel)) {
                    if (annotation.getBook() instanceof StocksBook) {
                        stockBooks.add((StocksBook) annotation.getBook());
                    }
                    totalData.put(mainLabel, totalData.get(mainLabel) + annotation.getSignedAmount());
                }
            }
        }
    }

    DefaultCategoryDataset model = new DefaultCategoryDataset();
    List<String> listOfLabels = getListOfMonthTimeLabelsForYear(year);

    Map<String, Double> labelToToalCumulativeMap = new HashMap<String, Double>();

    Double total = 0.0;
    for (String currentLabel : listOfLabels) {
        Double currentValue = totalData.get(currentLabel);
        if (currentValue != null) {
            total += currentValue;
        }
        labelToToalCumulativeMap.put(currentLabel, total + previousYearsTotals);
    }

    for (String currentLabel : listOfLabels) {
        model.addValue(labelToToalCumulativeMap.get(currentLabel), TOTAL_CUMULATIVE, currentLabel);
    }

    // add stock information in case it is necessary
    if ((selectedBook instanceof StocksBook) && includePurchasedStocks) {
        Table<Integer, Integer, Set<StockState>> historicalStockBalanceStateTable = HistoricalStockBalanceState
                .getConiniousHistoricalStockBalanceStateTable(bookSelection, year, optionalStockLabel);
        Collection<Annotation> annotationsForYear = yearToAnnotationMultimap.get(year);
        if (annotationsForYear == null) {
            annotationsForYear = Lists.newLinkedList();
        }
        Collection<Annotation> movementAnnotationsForYear = Collections2.filter(annotationsForYear,
                new Predicate<Annotation>() {
                    @Override
                    public boolean apply(Annotation input) {
                        return input instanceof MovementExpensesAnnotation
                                || input instanceof MovementIncomeAnnotation;
                    }
                });
        movementAnnotationsForYear = Collections2.filter(movementAnnotationsForYear,
                new Predicate<Annotation>() {
                    @Override
                    public boolean apply(Annotation input) {
                        return input instanceof MovementExpensesAnnotation
                                || input instanceof MovementIncomeAnnotation;
                    }
                });
        final Calendar currentcalendar = GregorianCalendar.getInstance();
        Multimap<Integer, Annotation> monthToAnnotationMultimap = Multimaps.index(movementAnnotationsForYear,
                new Function<Annotation, Integer>() {
                    @Override
                    public Integer apply(Annotation input) {
                        currentcalendar.setTime(input.getDate());
                        return currentcalendar.get(Calendar.MONTH);
                    }
                });

        Double movementBalance = getAllPreviousMovementCumulative(yearToAnnotationMultimap, year);
        if (historicalStockBalanceStateTable != null) {
            Map<Integer, Set<StockState>> historyForYear = historicalStockBalanceStateTable.rowMap().get(year);
            for (Integer currentMonth = 0; currentMonth <= 11; currentMonth++) {
                Double balance = 0.0;
                if (historyForYear != null && historyForYear.get(currentMonth) != null) {
                    for (StockState currentStockState : historyForYear.get(currentMonth)) {
                        balance += currentStockState.getVirtualBalanceForForcedYearAndMonth(year, currentMonth);
                    }
                } else {
                    balance = getYearBeforeFinalVirtualStockBalance(year, historicalStockBalanceStateTable);
                }
                if (monthToAnnotationMultimap.get(currentMonth) != null) {
                    for (Annotation movementAnnotation : monthToAnnotationMultimap.get(currentMonth)) {
                        movementBalance += movementAnnotation.getSignedAmount();
                    }
                }
                model.addValue(balance, TOTAL_CUMULATIVE_STOCKS_PURCHASED, listOfLabels.get(currentMonth));
                Double cumulativeBalance = labelToToalCumulativeMap.get(listOfLabels.get(currentMonth));

                model.addValue(balance + cumulativeBalance - movementBalance, TOTAL_CUMULATIVE_STOCKS_COMBINED,
                        listOfLabels.get(currentMonth));
            }

        }
    }

    return model;
}

From source file:uk.ac.york.mondo.integration.hawk.emf.impl.HawkResourceImpl.java

protected void setEffectiveMetamodelOptions(final HawkQueryOptions opts, final EffectiveMetamodelRuleset emm) {
    final Table<String, String, ImmutableSet<String>> inclusionRules = emm.getInclusionRules();
    final Table<String, String, ImmutableSet<String>> exclusionRules = emm.getExclusionRules();
    if (!inclusionRules.isEmpty()) {
        // The rowMap points to ImmutableSet<String>, which is compatible with
        // Set<String>, but the Java compiler is not smart enough to accept this.
        // Here we use a cast to work around this, which is cheaper than doing a
        // full copy.
        @SuppressWarnings({ "unchecked", "rawtypes" })
        final Map<String, Map<String, Set<String>>> inclusionMap = (Map) inclusionRules.rowMap();
        opts.setEffectiveMetamodelIncludes(inclusionMap);
    }//  ww w  .j av a2s  .co  m
    if (!exclusionRules.isEmpty()) {
        // See comment above.
        @SuppressWarnings({ "unchecked", "rawtypes" })
        final Map<String, Map<String, Set<String>>> exclusionMap = (Map) exclusionRules.rowMap();
        opts.setEffectiveMetamodelExcludes(exclusionMap);
    }
}

From source file:com.google.errorprone.bugpatterns.DeduplicateConstants.java

@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
    Table<VarSymbol, Tree, SuggestedFix> fixes = HashBasedTable.create();
    new TreeScanner<Void, Scope>() {

        @Override/*from w  w w . j a  v a  2  s. c  o  m*/
        public Void visitBlock(BlockTree tree, Scope scope) {
            // enter a new block scope (includes block trees for method and class bodies)
            return super.visitBlock(tree, scope.enter());
        }

        @Override
        public Void visitVariable(VariableTree tree, Scope scope) {
            // record that this variables hides previous declarations before entering its initializer
            scope.remove(ASTHelpers.getSymbol(tree));
            scan(tree.getInitializer(), scope);
            saveConstValue(tree, scope);
            return null;
        }

        @Override
        public Void visitLiteral(LiteralTree tree, Scope scope) {
            replaceLiteral(tree, scope, state);
            return super.visitLiteral(tree, scope);
        }

        private void replaceLiteral(LiteralTree tree, Scope scope, VisitorState state) {
            Object value = ASTHelpers.constValue(tree);
            if (value == null) {
                return;
            }
            VarSymbol sym = scope.get(state.getSourceForNode(tree));
            if (sym == null) {
                return;
            }
            SuggestedFix fix = SuggestedFix.replace(tree, sym.getSimpleName().toString());
            fixes.put(sym, tree, fix);
        }

        private void saveConstValue(VariableTree tree, Scope scope) {
            VarSymbol sym = ASTHelpers.getSymbol(tree);
            if (sym == null) {
                return;
            }
            if ((sym.flags() & (Flags.EFFECTIVELY_FINAL | Flags.FINAL)) == 0) {
                return;
            }
            // heuristic: long string constants are generally more interesting than short ones, or
            // than non-string constants (e.g. `""`, `0`, or `false`).
            String constValue = ASTHelpers.constValue(tree.getInitializer(), String.class);
            if (constValue == null || constValue.length() <= 1) {
                return;
            }
            scope.put(state.getSourceForNode(tree.getInitializer()), sym);
        }
    }.scan(tree, new Scope(null));
    for (Map.Entry<VarSymbol, Map<Tree, SuggestedFix>> entries : fixes.rowMap().entrySet()) {
        Map<Tree, SuggestedFix> occurrences = entries.getValue();
        if (occurrences.size() < 2) {
            // heuristic: only de-duplicate when there are two or more occurrences
            continue;
        }
        // report the finding on each occurrence, but provide a fix for all related occurrences,
        // so it works better on changed-lines only
        SuggestedFix fix = mergeFix(occurrences.values());
        occurrences.keySet().forEach(t -> state.reportMatch(describeMatch(t, fix)));
    }
    return Description.NO_MATCH;
}

From source file:co.cask.cdap.app.mapreduce.LocalMRJobInfoFetcher.java

/**
 * @param runId for which information will be returned.
 * @return a {@link MRJobInfo} containing information about a particular MapReduce program run.
 *//*from   w  w  w.  j  a  v a  2  s. com*/
public MRJobInfo getMRJobInfo(Id.Run runId) throws Exception {
    Preconditions.checkArgument(ProgramType.MAPREDUCE.equals(runId.getProgram().getType()));

    // baseTags has tag keys: ns.app.mr.runid
    Map<String, String> baseTags = Maps.newHashMap();
    baseTags.put(Constants.Metrics.Tag.NAMESPACE, runId.getNamespace().getId());
    baseTags.put(Constants.Metrics.Tag.APP, runId.getProgram().getApplicationId());
    baseTags.put(Constants.Metrics.Tag.MAPREDUCE, runId.getProgram().getId());
    baseTags.put(Constants.Metrics.Tag.RUN_ID, runId.getId());

    Map<String, String> mapTags = Maps.newHashMap(baseTags);
    mapTags.put(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Mapper.getId());

    Map<String, String> reduceTags = Maps.newHashMap(baseTags);
    reduceTags.put(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Reducer.getId());

    // map from RunId -> (CounterName -> CounterValue)
    Table<String, String, Long> mapTaskMetrics = HashBasedTable.create();
    Table<String, String, Long> reduceTaskMetrics = HashBasedTable.create();

    // Populate mapTaskMetrics and reduce Task Metrics via MetricStore. Used to construct MRTaskInfo below.
    Map<String, String> metricNamesToCounters = Maps.newHashMap();
    metricNamesToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_INPUT_RECORDS),
            TaskCounter.MAP_INPUT_RECORDS.name());
    metricNamesToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_OUTPUT_RECORDS),
            TaskCounter.MAP_OUTPUT_RECORDS.name());
    metricNamesToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_BYTES),
            TaskCounter.MAP_OUTPUT_BYTES.name());
    metricNamesToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_COMPLETION),
            MapReduceMetrics.METRIC_TASK_COMPLETION);

    // get metrics grouped by instance-id for the map tasks
    queryGroupedAggregates(mapTags, mapTaskMetrics, metricNamesToCounters);

    Map<String, Long> mapProgress = Maps.newHashMap();
    if (mapTaskMetrics.columnMap().containsKey(MapReduceMetrics.METRIC_TASK_COMPLETION)) {
        mapProgress = Maps
                .newHashMap(mapTaskMetrics.columnMap().remove(MapReduceMetrics.METRIC_TASK_COMPLETION));
    }

    Map<String, String> reduceMetricsToCounters = Maps.newHashMap();
    reduceMetricsToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_INPUT_RECORDS),
            TaskCounter.REDUCE_INPUT_RECORDS.name());
    reduceMetricsToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_OUTPUT_RECORDS),
            TaskCounter.REDUCE_OUTPUT_RECORDS.name());
    reduceMetricsToCounters.put(prependSystem(MapReduceMetrics.METRIC_TASK_COMPLETION),
            MapReduceMetrics.METRIC_TASK_COMPLETION);

    // get metrics grouped by instance-id for the map tasks
    queryGroupedAggregates(reduceTags, reduceTaskMetrics, reduceMetricsToCounters);

    Map<String, Long> reduceProgress = Maps.newHashMap();
    if (reduceTaskMetrics.columnMap().containsKey(MapReduceMetrics.METRIC_TASK_COMPLETION)) {
        reduceProgress = Maps
                .newHashMap(reduceTaskMetrics.columnMap().remove(MapReduceMetrics.METRIC_TASK_COMPLETION));
    }

    // Construct MRTaskInfos from the information we can get from Metric system.
    List<MRTaskInfo> mapTaskInfos = Lists.newArrayList();
    for (Map.Entry<String, Map<String, Long>> taskEntry : mapTaskMetrics.rowMap().entrySet()) {
        String mapTaskId = taskEntry.getKey();
        mapTaskInfos.add(new MRTaskInfo(mapTaskId, null, null, null, mapProgress.get(mapTaskId) / 100.0F,
                taskEntry.getValue()));
    }

    List<MRTaskInfo> reduceTaskInfos = Lists.newArrayList();
    for (Map.Entry<String, Map<String, Long>> taskEntry : reduceTaskMetrics.rowMap().entrySet()) {
        String reduceTaskId = taskEntry.getKey();
        reduceTaskInfos.add(new MRTaskInfo(reduceTaskId, null, null, null,
                reduceProgress.get(reduceTaskId) / 100.0F, taskEntry.getValue()));
    }

    return getJobCounters(mapTags, reduceTags, mapTaskInfos, reduceTaskInfos);
}

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

private CoreRefPolicyProvider(final PolicyMap<StaticTopLevelPolicyElementEvaluator> policyMap,
        final PolicyMap<PolicyWithNamespaces<PolicySet>> jaxbPolicySetMap, final int maxPolicySetRefDepth,
        final ExpressionFactory expressionFactory, final CombiningAlgRegistry combiningAlgRegistry)
        throws IllegalArgumentException {
    super(maxPolicySetRefDepth);
    assert policyMap != null && jaxbPolicySetMap != null && expressionFactory != null
            && combiningAlgRegistry != null;

    this.policyEvaluatorMap = policyMap;
    final Table<String, PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicySetEvaluatorTable = HashBasedTable
            .create();/*from   ww  w  . j  av  a  2 s .  c  o  m*/
    /*
     * Ref policy Provider module used only for initialization, more particularly for parsing the PolicySets when they are referred to by others (in PolicySetIdReferences)
     */
    try (final InitOnlyRefPolicyProvider bootstrapRefPolicyProvider = new InitOnlyRefPolicyProvider(
            this.policyEvaluatorMap, jaxbPolicySetMap, updatablePolicySetEvaluatorTable, maxPolicySetRefDepth,
            expressionFactory, combiningAlgRegistry)) {
        for (final Entry<String, PolicyVersions<PolicyWithNamespaces<PolicySet>>> jaxbPolicySetWithNsEntry : jaxbPolicySetMap
                .entrySet()) {
            final String policySetId = jaxbPolicySetWithNsEntry.getKey();
            // instantiate all policy versions for this policyId now
            final PolicyVersions<PolicyWithNamespaces<PolicySet>> jaxbPolicySetVersions = jaxbPolicySetWithNsEntry
                    .getValue();
            for (final Entry<PolicyVersion, PolicyWithNamespaces<PolicySet>> jaxbPolicySetEntry : jaxbPolicySetVersions) {

                final PolicyVersion policySetVersion = jaxbPolicySetEntry.getKey();
                /*
                 * Check corresponding PolicySet evaluator in policySetEvaluatorTable to check whether it is not already there, i.e. already instantiated by refPolicyProvider.get(...) because of
                 * Policy references in previously instantiated policies (when calling PolicyEvaluators.getInstanceStatic() down below)
                 */
                final StaticTopLevelPolicyElementEvaluator old = updatablePolicySetEvaluatorTable
                        .get(policySetId, policySetVersion);
                if (old == null) {
                    // no policyset with such ID/Version instantiated yet
                    // do it now
                    final PolicyWithNamespaces<PolicySet> jaxbPolicySetWithNs = jaxbPolicySetEntry.getValue();
                    final StaticTopLevelPolicyElementEvaluator newPolicySetEvaluator;
                    try {
                        newPolicySetEvaluator = PolicyEvaluators.getInstanceStatic(jaxbPolicySetWithNs.policy,
                                null, jaxbPolicySetWithNs.nsPrefixUriMap, expressionFactory,
                                combiningAlgRegistry, bootstrapRefPolicyProvider, null);
                    } catch (final IllegalArgumentException e) {
                        throw new IllegalArgumentException("Invalid PolicySet with PolicySetId='" + policySetId
                                + "', Version=" + policySetVersion, e);
                    }

                    updatablePolicySetEvaluatorTable.put(policySetId, policySetVersion, newPolicySetEvaluator);
                }
            }
        }
    }

    this.policySetEvaluatorMap = new PolicyMap<>(updatablePolicySetEvaluatorTable.rowMap());
}

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

/**
 * Creates an instance from policy locations
 *
 * @param policyURLs//from  www  . jav a2  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);
}