Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

In this page you can find the example usage for java.util List retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:org.rhq.enterprise.server.configuration.metadata.ConfigurationMetadataManagerBean.java

/**
 * Return a new List with elements both in first and second passed collection.
 *
 * @param  first  First list//from   w  ww . java 2 s .  co m
 * @param  second Second list
 *
 * @return a new set (depending on input type) with elements in first and second
 */
private <T> List<T> intersection(List<T> first, List<T> second) {
    List<T> result = new ArrayList<T>();

    if ((first != null) && (second != null)) {
        result.addAll(first);
        result.retainAll(second);
    }

    return result;
}

From source file:org.sakaiproject.content.impl.SiteEmailNotificationContent.java

/**
 * Add to the user list any other users who should be notified about this ref's change.
 * /*  w ww  .  java 2  s .c  o  m*/
 * @param users
 *        The user list, already populated based on site visit and resource ability.
 * @param ref
 *        The entity reference.
 */
protected void addSpecialRecipients(List users, Reference ref) {
    // include any users who have AnnouncementService.SECURE_ALL_GROUPS and getResourceAbility() in the context
    String contextRef = SiteService.siteReference(ref.getContext());

    // get the list of users who have SECURE_ALL_GROUPS
    List allGroupUsers = SecurityService.unlockUsers(ContentHostingService.AUTH_RESOURCE_ALL_GROUPS,
            contextRef);

    // filter down by the permission
    if (getResourceAbility() != null) {
        List allGroupUsers2 = SecurityService.unlockUsers(getResourceAbility(), contextRef);
        allGroupUsers.retainAll(allGroupUsers2);
    }

    // remove any in the list already
    allGroupUsers.removeAll(users);

    // combine
    users.addAll(allGroupUsers);
}

From source file:org.silverpeas.components.formsonline.model.DefaultFormsOnlineService.java

@Override
public RequestsByStatus getValidatorRequests(RequestsFilter filter, String userId,
        final PaginationPage paginationPage) throws FormsOnlineDatabaseException {
    final List<String> formIds = getAvailableFormIdsAsReceiver(filter.getComponentId(), userId);

    // limit requests to specified forms
    if (!filter.getFormIds().isEmpty()) {
        formIds.retainAll(filter.getFormIds());
    }//from  ww w  .ja  va  2  s. com
    final List<FormDetail> availableForms = getDAO().getForms(formIds);
    RequestsByStatus requests = new RequestsByStatus(paginationPage);
    for (FormDetail form : availableForms) {
        for (Pair<List<Integer>, BiConsumer<RequestsByStatus, SilverpeasList<FormInstance>>> mergingRuleByStates : RequestsByStatus.MERGING_RULES_BY_STATES) {
            final List<Integer> states = mergingRuleByStates.getLeft();
            final BiConsumer<RequestsByStatus, SilverpeasList<FormInstance>> merge = mergingRuleByStates
                    .getRight();
            final PaginationCriterion paginationCriterion = paginationPage != null
                    ? paginationPage.asCriterion()
                    : null;
            final SilverpeasList<FormInstance> result = getDAO().getReceivedRequests(form.getPK(),
                    filter.isAllRequests(), userId, states, paginationCriterion);
            merge.accept(requests, result.stream().map(l -> {
                l.setForm(form);
                return l;
            }).collect(SilverpeasList.collector(result)));
        }
    }
    return requests;
}

From source file:org.apache.asterix.optimizer.rules.PushFieldAccessRule.java

@SuppressWarnings("unchecked")
private boolean propagateFieldAccessRec(Mutable<ILogicalOperator> opRef, IOptimizationContext context,
        String finalAnnot) throws AlgebricksException {
    AssignOperator access = (AssignOperator) opRef.getValue();
    Mutable<ILogicalOperator> opRef2 = access.getInputs().get(0);
    AbstractLogicalOperator op2 = (AbstractLogicalOperator) opRef2.getValue();
    // If it's not an indexed field, it is pushed so that scan can be
    // rewritten into index search.
    if (op2.getOperatorTag() == LogicalOperatorTag.PROJECT || context.checkAndAddToAlreadyCompared(access, op2)
            && !(op2.getOperatorTag() == LogicalOperatorTag.SELECT
                    && isAccessToIndexedField(access, context))) {
        return false;
    }//from w  ww.ja  v  a 2  s  .  co m
    if (!OperatorPropertiesUtil.isMovable(op2)) {
        return false;
    }
    if (tryingToPushThroughSelectionWithSameDataSource(access, op2)) {
        return false;
    }
    if (testAndModifyRedundantOp(access, op2)) {
        propagateFieldAccessRec(opRef2, context, finalAnnot);
        return true;
    }
    List<LogicalVariable> usedInAccess = new LinkedList<>();
    VariableUtilities.getUsedVariables(access, usedInAccess);

    List<LogicalVariable> produced2 = new LinkedList<>();
    if (op2.getOperatorTag() == LogicalOperatorTag.GROUP) {
        VariableUtilities.getLiveVariables(op2, produced2);
    } else {
        VariableUtilities.getProducedVariables(op2, produced2);
    }
    boolean pushItDown = false;
    List<LogicalVariable> inter = new ArrayList<>(usedInAccess);
    if (inter.isEmpty()) { // ground value
        return false;
    }
    inter.retainAll(produced2);
    if (inter.isEmpty()) {
        pushItDown = true;
    } else if (op2.getOperatorTag() == LogicalOperatorTag.GROUP) {
        GroupByOperator g = (GroupByOperator) op2;
        List<Pair<LogicalVariable, LogicalVariable>> varMappings = new ArrayList<>();
        for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : g.getDecorList()) {
            ILogicalExpression e = p.second.getValue();
            if (e.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
                LogicalVariable decorVar = GroupByOperator.getDecorVariable(p);
                if (inter.contains(decorVar)) {
                    inter.remove(decorVar);
                    LogicalVariable v1 = ((VariableReferenceExpression) e).getVariableReference();
                    varMappings.add(new Pair<>(decorVar, v1));
                }
            }
        }
        if (inter.isEmpty()) {
            boolean changed = false;
            for (Pair<LogicalVariable, LogicalVariable> m : varMappings) {
                LogicalVariable v2 = context.newVar();
                LogicalVariable oldVar = access.getVariables().get(0);
                g.getDecorList().add(new Pair<LogicalVariable, Mutable<ILogicalExpression>>(oldVar,
                        new MutableObject<ILogicalExpression>(new VariableReferenceExpression(v2))));
                changed = true;
                access.getVariables().set(0, v2);
                VariableUtilities.substituteVariables(access, m.first, m.second, context);
            }
            if (changed) {
                context.computeAndSetTypeEnvironmentForOperator(g);
            }
            usedInAccess.clear();
            VariableUtilities.getUsedVariables(access, usedInAccess);
            pushItDown = true;
        }
    }
    if (pushItDown) {
        if (op2.getOperatorTag() == LogicalOperatorTag.NESTEDTUPLESOURCE) {
            Mutable<ILogicalOperator> childOfSubplan = ((NestedTupleSourceOperator) op2)
                    .getDataSourceReference().getValue().getInputs().get(0);
            pushAccessDown(opRef, op2, childOfSubplan, context, finalAnnot);
            return true;
        }
        if (op2.getInputs().size() == 1 && !op2.hasNestedPlans()) {
            pushAccessDown(opRef, op2, op2.getInputs().get(0), context, finalAnnot);
            return true;
        } else {
            for (Mutable<ILogicalOperator> inp : op2.getInputs()) {
                HashSet<LogicalVariable> v2 = new HashSet<>();
                VariableUtilities.getLiveVariables(inp.getValue(), v2);
                if (v2.containsAll(usedInAccess)) {
                    pushAccessDown(opRef, op2, inp, context, finalAnnot);
                    return true;
                }
            }
        }
        if (op2.hasNestedPlans()) {
            AbstractOperatorWithNestedPlans nestedOp = (AbstractOperatorWithNestedPlans) op2;
            for (ILogicalPlan plan : nestedOp.getNestedPlans()) {
                for (Mutable<ILogicalOperator> root : plan.getRoots()) {
                    HashSet<LogicalVariable> v2 = new HashSet<>();
                    VariableUtilities.getLiveVariables(root.getValue(), v2);
                    if (v2.containsAll(usedInAccess)) {
                        pushAccessDown(opRef, op2, root, context, finalAnnot);
                        return true;
                    }
                }
            }
        }
        throw new AlgebricksException("Field access " + access.getExpressions().get(0).getValue()
                + " does not correspond to any input of operator " + op2);
    } else {
        // Check if the accessed field is not one of the partitioning key
        // fields. If yes, we can equate the two variables.
        if (op2.getOperatorTag() == LogicalOperatorTag.DATASOURCESCAN) {
            DataSourceScanOperator scan = (DataSourceScanOperator) op2;
            int n = scan.getVariables().size();
            LogicalVariable scanRecordVar = scan.getVariables().get(n - 1);
            AbstractFunctionCallExpression accessFun = (AbstractFunctionCallExpression) access.getExpressions()
                    .get(0).getValue();
            ILogicalExpression e0 = accessFun.getArguments().get(0).getValue();
            LogicalExpressionTag tag = e0.getExpressionTag();
            if (tag == LogicalExpressionTag.VARIABLE) {
                VariableReferenceExpression varRef = (VariableReferenceExpression) e0;
                if (varRef.getVariableReference() == scanRecordVar) {
                    ILogicalExpression e1 = accessFun.getArguments().get(1).getValue();
                    if (e1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
                        IDataSource<AqlSourceId> dataSource = (IDataSource<AqlSourceId>) scan.getDataSource();
                        byte dsType = ((AqlDataSource) dataSource).getDatasourceType();
                        if (dsType == AqlDataSourceType.FEED || dsType == AqlDataSourceType.LOADABLE) {
                            return false;
                        }
                        AqlSourceId asid = dataSource.getId();
                        AqlMetadataProvider mp = (AqlMetadataProvider) context.getMetadataProvider();
                        Dataset dataset = mp.findDataset(asid.getDataverseName(), asid.getDatasourceName());
                        if (dataset == null) {
                            throw new AlgebricksException(
                                    "Dataset " + asid.getDatasourceName() + " not found.");
                        }
                        if (dataset.getDatasetType() != DatasetType.INTERNAL) {
                            setAsFinal(access, context, finalAnnot);
                            return false;
                        }
                        ConstantExpression ce = (ConstantExpression) e1;
                        IAObject obj = ((AsterixConstantValue) ce.getValue()).getObject();
                        String fldName;
                        if (obj.getType().getTypeTag() == ATypeTag.STRING) {
                            fldName = ((AString) obj).getStringValue();
                        } else {
                            int pos = ((AInt32) obj).getIntegerValue();
                            String tName = dataset.getItemTypeName();
                            IAType t = mp.findType(dataset.getItemTypeDataverseName(), tName);
                            if (t.getTypeTag() != ATypeTag.RECORD) {
                                return false;
                            }
                            ARecordType rt = (ARecordType) t;
                            if (pos >= rt.getFieldNames().length) {
                                setAsFinal(access, context, finalAnnot);
                                return false;
                            }
                            fldName = rt.getFieldNames()[pos];
                        }
                        int p = DatasetUtils.getPositionOfPartitioningKeyField(dataset, fldName);
                        if (p < 0) { // not one of the partitioning fields
                            setAsFinal(access, context, finalAnnot);
                            return false;
                        }
                        LogicalVariable keyVar = scan.getVariables().get(p);
                        access.getExpressions().get(0).setValue(new VariableReferenceExpression(keyVar));
                        return true;
                    }
                }
            }
        }
        setAsFinal(access, context, finalAnnot);
        return false;
    }
}

From source file:ubic.BAMSandAllen.MatrixPairs.ConnectivityAndAllenDataPair.java

/**
 * removes all or retains only the connections to and from the Bed nuclei of the stria terminalis
 * /*from   ww w. ja  va2  s .c o  m*/
 * @param inverse true to retain the connections, false to remove
 * @param leaveCols true to leave the columns of the matrix untouched
 */
public void removeBedNucleiStria(boolean inverse, boolean leaveCols) {
    BAMSDataLoader BAMSData = new BAMSDataLoader();
    boolean indirect = true;
    Set<String> bedNuclei = BAMSData.getChildren("Bed nuclei of the stria terminalis", indirect);
    bedNuclei.add("Bed nuclei of the stria terminalis");

    log.info("Bed nuclei:" + bedNuclei);
    log.info("Bed nuclei terms:" + bedNuclei.size());

    List<String> connectionRows = new LinkedList<String>(matrixA.getRowNames());
    if (inverse) {
        connectionRows.removeAll(bedNuclei);
    } else {
        connectionRows.retainAll(bedNuclei);
    }
    log.info("Bed nuclei rows removed:" + connectionRows.size());
    matrixA = matrixA.removeRows(connectionRows);

    if (!leaveCols) {
        Set<String> connectionCols = new HashSet<String>(matrixA.getColNames());
        if (inverse) {
            // do nothing
        } else {
            connectionCols.retainAll(bedNuclei);
            log.info("Bed nuclei cols removed:" + connectionCols.size());
            matrixA = matrixA.removeColumns(connectionCols);
            if (isInSameSpace) {
                // remove from matrix B too
                log.info("MatrixB before:" + matrixB.columns());
                matrixB = matrixB.removeColumns(connectionCols);
                log.info("MatrixB after:" + matrixB.columns());
            } else {
                // if it's not in the same space then it will fail to map it to a BAMS region, and will be removed
            }
        }
    }
}

From source file:edu.uci.ics.asterix.optimizer.rules.PushFieldAccessRule.java

@SuppressWarnings("unchecked")
private boolean propagateFieldAccessRec(Mutable<ILogicalOperator> opRef, IOptimizationContext context,
        String finalAnnot) throws AlgebricksException {
    AssignOperator access = (AssignOperator) opRef.getValue();
    Mutable<ILogicalOperator> opRef2 = access.getInputs().get(0);
    AbstractLogicalOperator op2 = (AbstractLogicalOperator) opRef2.getValue();
    // If it's not an indexed field, it is pushed so that scan can be
    // rewritten into index search.
    if (op2.getOperatorTag() == LogicalOperatorTag.PROJECT || context.checkAndAddToAlreadyCompared(access, op2)
            && !(op2.getOperatorTag() == LogicalOperatorTag.SELECT
                    && isAccessToIndexedField(access, context))) {
        return false;
    }//from  w ww. j  av a  2s  .c om
    if (tryingToPushThroughSelectionWithSameDataSource(access, op2)) {
        return false;
    }
    if (testAndModifyRedundantOp(access, op2)) {
        propagateFieldAccessRec(opRef2, context, finalAnnot);
        return true;
    }
    List<LogicalVariable> usedInAccess = new LinkedList<LogicalVariable>();
    VariableUtilities.getUsedVariables(access, usedInAccess);
    List<LogicalVariable> produced2 = new LinkedList<LogicalVariable>();
    if (op2.getOperatorTag() == LogicalOperatorTag.GROUP) {
        VariableUtilities.getLiveVariables(op2, produced2);
    } else {
        VariableUtilities.getProducedVariables(op2, produced2);
    }
    boolean pushItDown = false;
    List<LogicalVariable> inter = new ArrayList<LogicalVariable>(usedInAccess);
    if (inter.isEmpty()) { // ground value
        return false;
    }
    inter.retainAll(produced2);
    if (inter.isEmpty()) {
        pushItDown = true;
    } else if (op2.getOperatorTag() == LogicalOperatorTag.GROUP) {
        GroupByOperator g = (GroupByOperator) op2;
        List<Pair<LogicalVariable, LogicalVariable>> varMappings = new ArrayList<Pair<LogicalVariable, LogicalVariable>>();
        for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : g.getDecorList()) {
            ILogicalExpression e = p.second.getValue();
            if (e.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
                LogicalVariable decorVar = GroupByOperator.getDecorVariable(p);
                if (inter.contains(decorVar)) {
                    inter.remove(decorVar);
                    LogicalVariable v1 = ((VariableReferenceExpression) e).getVariableReference();
                    varMappings.add(new Pair<LogicalVariable, LogicalVariable>(decorVar, v1));
                }
            }
        }
        if (inter.isEmpty()) {
            boolean changed = false;
            for (Pair<LogicalVariable, LogicalVariable> m : varMappings) {
                LogicalVariable v2 = context.newVar();
                LogicalVariable oldVar = access.getVariables().get(0);
                g.getDecorList().add(new Pair<LogicalVariable, Mutable<ILogicalExpression>>(oldVar,
                        new MutableObject<ILogicalExpression>(new VariableReferenceExpression(v2))));
                changed = true;
                access.getVariables().set(0, v2);
                VariableUtilities.substituteVariables(access, m.first, m.second, context);
            }
            if (changed) {
                context.computeAndSetTypeEnvironmentForOperator(g);
            }
            usedInAccess.clear();
            VariableUtilities.getUsedVariables(access, usedInAccess);
            pushItDown = true;
        }
    }
    if (pushItDown) {
        if (op2.getOperatorTag() == LogicalOperatorTag.NESTEDTUPLESOURCE) {
            Mutable<ILogicalOperator> childOfSubplan = ((NestedTupleSourceOperator) op2)
                    .getDataSourceReference().getValue().getInputs().get(0);
            pushAccessDown(opRef, op2, childOfSubplan, context, finalAnnot);
            return true;
        }
        if (op2.getInputs().size() == 1 && !op2.hasNestedPlans()) {
            pushAccessDown(opRef, op2, op2.getInputs().get(0), context, finalAnnot);
            return true;
        } else {
            for (Mutable<ILogicalOperator> inp : op2.getInputs()) {
                HashSet<LogicalVariable> v2 = new HashSet<LogicalVariable>();
                VariableUtilities.getLiveVariables(inp.getValue(), v2);
                if (v2.containsAll(usedInAccess)) {
                    pushAccessDown(opRef, op2, inp, context, finalAnnot);
                    return true;
                }
            }
        }
        if (op2.hasNestedPlans()) {
            AbstractOperatorWithNestedPlans nestedOp = (AbstractOperatorWithNestedPlans) op2;
            for (ILogicalPlan plan : nestedOp.getNestedPlans()) {
                for (Mutable<ILogicalOperator> root : plan.getRoots()) {
                    HashSet<LogicalVariable> v2 = new HashSet<LogicalVariable>();
                    VariableUtilities.getLiveVariables(root.getValue(), v2);
                    if (v2.containsAll(usedInAccess)) {
                        pushAccessDown(opRef, op2, root, context, finalAnnot);
                        return true;
                    }
                }
            }
        }
        throw new AsterixRuntimeException("Field access " + access.getExpressions().get(0).getValue()
                + " does not correspond to any input of operator " + op2);
    } else {
        // Check if the accessed field is not one of the partitioning key
        // fields. If yes, we can equate the two variables.
        if (op2.getOperatorTag() == LogicalOperatorTag.DATASOURCESCAN) {
            DataSourceScanOperator scan = (DataSourceScanOperator) op2;
            int n = scan.getVariables().size();
            LogicalVariable scanRecordVar = scan.getVariables().get(n - 1);
            AbstractFunctionCallExpression accessFun = (AbstractFunctionCallExpression) access.getExpressions()
                    .get(0).getValue();
            ILogicalExpression e0 = accessFun.getArguments().get(0).getValue();
            LogicalExpressionTag tag = e0.getExpressionTag();
            if (tag == LogicalExpressionTag.VARIABLE) {
                VariableReferenceExpression varRef = (VariableReferenceExpression) e0;
                if (varRef.getVariableReference() == scanRecordVar) {
                    ILogicalExpression e1 = accessFun.getArguments().get(1).getValue();
                    if (e1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
                        IDataSource<AqlSourceId> dataSource = (IDataSource<AqlSourceId>) scan.getDataSource();
                        AqlDataSourceType dsType = ((AqlDataSource) dataSource).getDatasourceType();
                        if (dsType == AqlDataSourceType.FEED || dsType == AqlDataSourceType.LOADABLE) {
                            return false;
                        }
                        AqlSourceId asid = dataSource.getId();
                        AqlMetadataProvider mp = (AqlMetadataProvider) context.getMetadataProvider();
                        Dataset dataset = mp.findDataset(asid.getDataverseName(), asid.getDatasourceName());
                        if (dataset == null) {
                            throw new AlgebricksException(
                                    "Dataset " + asid.getDatasourceName() + " not found.");
                        }
                        if (dataset.getDatasetType() != DatasetType.INTERNAL) {
                            setAsFinal(access, context, finalAnnot);
                            return false;
                        }
                        ConstantExpression ce = (ConstantExpression) e1;
                        IAObject obj = ((AsterixConstantValue) ce.getValue()).getObject();
                        String fldName;
                        if (obj.getType().getTypeTag() == ATypeTag.STRING) {
                            fldName = ((AString) obj).getStringValue();
                        } else {
                            int pos = ((AInt32) obj).getIntegerValue();
                            String tName = dataset.getItemTypeName();
                            IAType t = mp.findType(dataset.getDataverseName(), tName);
                            if (t.getTypeTag() != ATypeTag.RECORD) {
                                return false;
                            }
                            ARecordType rt = (ARecordType) t;
                            if (pos >= rt.getFieldNames().length) {
                                setAsFinal(access, context, finalAnnot);
                                return false;
                            }
                            fldName = rt.getFieldNames()[pos];
                        }
                        int p = DatasetUtils.getPositionOfPartitioningKeyField(dataset, fldName);
                        if (p < 0) { // not one of the partitioning fields
                            setAsFinal(access, context, finalAnnot);
                            return false;
                        }
                        LogicalVariable keyVar = scan.getVariables().get(p);
                        access.getExpressions().get(0).setValue(new VariableReferenceExpression(keyVar));
                        return true;
                    }
                }
            }
        }
        setAsFinal(access, context, finalAnnot);
        return false;
    }
}

From source file:au.org.ala.delta.intkey.ui.TaxonKeywordSelectionDialog.java

@Override
protected void listBtnPressed() {
    // List button will only be enabled if a single taxon is selected.
    if (_list.getSelectedValue() != null) {

        List<Item> taxa = new ArrayList<Item>();
        String selectedKeyword = (String) _list.getSelectedValue();

        // do nothing if the "specimen" keyword is selected - this is not a
        // real taxon keyword.
        if (selectedKeyword.equals(IntkeyContext.SPECIMEN_KEYWORD)) {
            return;
        }/*from  ww  w  .j av  a  2 s .co  m*/

        taxa.addAll(_context.getTaxaForKeyword(selectedKeyword));

        if (_selectFromIncluded) {
            taxa.retainAll(_includedTaxa);
        }

        if (taxa.isEmpty()) {
            JOptionPane.showMessageDialog(this, allTaxaInSelectedSetExcludedCaption, title,
                    JOptionPane.ERROR_MESSAGE);
        } else {
            TaxonSelectionDialog taxonDlg = new TaxonSelectionDialog(this, taxa, _directiveName,
                    selectedKeyword, _context.displayNumbering(), false, _context, _includeSpecimenAsOption,
                    _specimenSelectedReturnValue);
            taxonDlg.setVisible(true);

            List<Item> taxaSelectedInDlg = taxonDlg.getSelectedTaxa();
            if (taxaSelectedInDlg != null && taxaSelectedInDlg.size() > 0) {
                if (_selectedTaxa == null) {
                    _selectedTaxa = new ArrayList<Item>();
                }
                _selectedTaxa.clear();
                _selectedTaxa.addAll(taxaSelectedInDlg);
                this.setVisible(false);
            }
        }
    }
}

From source file:org.apache.syncope.core.util.ContentExporter.java

private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames)
        throws SQLException {

    Set<MultiParentNode<String>> roots = new HashSet<MultiParentNode<String>>();

    final DatabaseMetaData meta = conn.getMetaData();

    final Map<String, MultiParentNode<String>> exploited = new TreeMap<String, MultiParentNode<String>>(
            String.CASE_INSENSITIVE_ORDER);

    final Set<String> pkTableNames = new HashSet<String>();

    for (String tableName : tableNames) {
        MultiParentNode<String> node = exploited.get(tableName);
        if (node == null) {
            node = new MultiParentNode<String>(tableName);
            roots.add(node);//from  w w  w  .  j a  v  a 2 s.c om
            exploited.put(tableName, node);
        }

        pkTableNames.clear();

        ResultSet rs = null;
        try {
            rs = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName);

            // this is to avoid repetition
            while (rs.next()) {
                pkTableNames.add(rs.getString("PKTABLE_NAME"));
            }
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    LOG.error("While closing tables result set", e);
                }
            }
        }

        for (String pkTableName : pkTableNames) {
            if (!tableName.equalsIgnoreCase(pkTableName)) {
                MultiParentNode<String> pkNode = exploited.get(pkTableName);
                if (pkNode == null) {
                    pkNode = new MultiParentNode<String>(pkTableName);
                    roots.add(pkNode);
                    exploited.put(pkTableName, pkNode);
                }

                pkNode.addChild(node);

                if (roots.contains(node)) {
                    roots.remove(node);
                }
            }
        }
    }

    final List<String> sortedTableNames = new ArrayList<String>(tableNames.size());
    MultiParentNodeOp.traverseTree(roots, sortedTableNames);

    // remove from sortedTableNames any table possibly added during lookup 
    // but matching some item in this.tablePrefixesToBeExcluded
    sortedTableNames.retainAll(tableNames);

    LOG.debug("Tables after retainAll {}", sortedTableNames);

    Collections.reverse(sortedTableNames);

    return sortedTableNames;
}

From source file:fr.mcc.ginco.services.ConceptHierarchicalRelationshipServiceUtil.java

@Override
public ThesaurusConcept saveHierarchicalRelationship(ThesaurusConcept conceptToUpdate,
        List<ConceptHierarchicalRelationship> hierarchicalRelationships,
        List<ThesaurusConcept> allRecursiveParents, List<ThesaurusConcept> allRecursiveChilds,
        List<ThesaurusConcept> childrenConceptToDetach, List<ThesaurusConcept> childrenConceptToAttach) {

    // We update the modified relations, and we delete the relations that
    // have been removed
    List<String> oldParentConceptIds = new ArrayList<String>();
    if (!conceptToUpdate.getParentConcepts().isEmpty()) {
        oldParentConceptIds = ThesaurusConceptUtils
                .getIdsFromConceptList(new ArrayList<ThesaurusConcept>(conceptToUpdate.getParentConcepts()));
    }// w w  w  . j  av a  2s  .c om

    List<String> newParentConceptIds = new ArrayList<String>();
    for (ConceptHierarchicalRelationship relation : hierarchicalRelationships) {
        newParentConceptIds.add(relation.getIdentifier().getParentconceptid());
    }

    List<String> newChildConceptIds = new ArrayList<String>();
    for (ThesaurusConcept newChild : childrenConceptToAttach) {
        newChildConceptIds.add(newChild.getIdentifier());
    }
    // Check loops
    for (ThesaurusConcept childConcept : allRecursiveChilds) {
        if (newParentConceptIds.contains(childConcept.getIdentifier())) {
            throw new BusinessException("A parent concept cannot be the child of the same concept",
                    "hierarchical-loop-violation");
        }
    }
    // Check loops
    for (ThesaurusConcept parentConcept : allRecursiveParents) {
        if (newChildConceptIds.contains(parentConcept.getIdentifier())) {
            throw new BusinessException("A child concept cannot be the parent of the same concept",
                    "hierarchical-loop-violation");
        }
    }

    // Verify if the concept doesn't have one of its brothers as parent
    for (String currentParentId : newParentConceptIds) {
        List<String> childrenOfCurrentParentIds = ThesaurusConceptUtils
                .getIdsFromConceptList(thesaurusConceptDAO.getChildrenConcepts(currentParentId, 0, null));
        List<String> commonIds = new ArrayList<String>(newParentConceptIds);
        // Compare both lists and see which elements are in common.
        // Those elements are both parents and brothers to the considered concept.
        commonIds.retainAll(childrenOfCurrentParentIds);

        if (!commonIds.isEmpty()) {
            String commonPreferedTerms = "";
            for (String conceptId : commonIds) {
                if (commonIds.indexOf(conceptId) != 0) {
                    commonPreferedTerms += ", ";
                }
                commonPreferedTerms += thesaurusTermDAO.getConceptPreferredTerm(conceptId).getLexicalValue();
            }
            throw new BusinessException(
                    "A concept cannot have one of its brother (" + commonPreferedTerms + ") as a parent",
                    "hierarchical-brotherIsParent-violation", new Object[] { commonPreferedTerms });
        }
    }
    List<String> brotherIds = new ArrayList<String>();
    for (ThesaurusConcept parentConcept : conceptToUpdate.getParentConcepts()) {
        brotherIds.addAll(ThesaurusConceptUtils.getIdsFromConceptList(
                thesaurusConceptDAO.getChildrenConcepts(parentConcept.getIdentifier(), 0, null)));
    }
    // Verify if the concept doesn't have one of its brothers as child
    for (String currentChildId : newChildConceptIds) {
        if (brotherIds.contains(currentChildId)) {
            List<String> commonIds = new ArrayList<String>(newChildConceptIds);
            String commonPreferedTerms = "";
            for (String conceptId : commonIds) {
                if (commonIds.indexOf(conceptId) != 0) {
                    commonPreferedTerms += ", ";
                }
                commonPreferedTerms += thesaurusTermDAO.getConceptPreferredTerm(conceptId).getLexicalValue();
            }
            throw new BusinessException(
                    "A concept cannot have one of its brother (" + commonPreferedTerms + ") as a parent",
                    "hierarchical-brotherIsParent-violation", new Object[] { commonPreferedTerms });
        }
    }

    List<String> addedParentConceptIds = ListUtils.subtract(newParentConceptIds, oldParentConceptIds);
    List<String> removedParentConceptIds = ListUtils.subtract(oldParentConceptIds, newParentConceptIds);

    List<ThesaurusConcept> addedParentConcepts = new ArrayList<ThesaurusConcept>();
    for (String id : addedParentConceptIds) {
        addedParentConcepts.add(thesaurusConceptDAO.getById(id));
    }

    List<ThesaurusConcept> removedParentConcepts = new ArrayList<ThesaurusConcept>();
    for (String id : removedParentConceptIds) {
        removedParentConcepts.add(thesaurusConceptDAO.getById(id));
    }

    if (!addedParentConcepts.isEmpty() || !removedParentConcepts.isEmpty()) {
        // Treatment in case of modified hierarchy (both add or remove)

        // We remove this concept in all array it belongs
        List<ThesaurusArrayConcept> arrays = thesaurusArrayConceptDAO.getArraysOfConcept(conceptToUpdate);
        for (ThesaurusArrayConcept thesaurusArrayConcept : arrays) {
            thesaurusArrayConceptDAO.delete(thesaurusArrayConcept);
        }

        // We remove all removed parents
        if (!removedParentConcepts.isEmpty()) {
            removeParents(conceptToUpdate, removedParentConcepts);
        }

        // We set all added parents
        Set<ThesaurusConcept> addedParentsSet = new HashSet<ThesaurusConcept>();
        for (ThesaurusConcept addedParentId : addedParentConcepts) {
            addedParentsSet.add(addedParentId);
        }

        if (!addedParentConcepts.isEmpty()) {
            conceptToUpdate.getParentConcepts().addAll(addedParentsSet);
            conceptToUpdate.setTopConcept(false);
        }

        if (!conceptToUpdate.getThesaurus().isPolyHierarchical()
                && conceptToUpdate.getParentConcepts().size() > 1) {
            throw new BusinessException(
                    "Thesaurus is monohierarchical, but some concepts have multiple parents!",
                    "monohierarchical-violation");
        }

        // We calculate the rootconcepts for the concept to update
        conceptToUpdate.setRootConcepts(new HashSet<ThesaurusConcept>(getRootConcepts(conceptToUpdate)));

        // We launch an async method to calculate new root concept for the
        // children of the concept we update
        calculateChildrenRoots(conceptToUpdate.getIdentifier(), conceptToUpdate.getIdentifier());
    }

    // We process children delete
    addChildren(conceptToUpdate, childrenConceptToAttach);
    removeChildren(conceptToUpdate, childrenConceptToDetach);

    thesaurusConceptDAO.update(conceptToUpdate);
    thesaurusConceptDAO.flush();
    saveRoleOfHierarchicalRelationship(hierarchicalRelationships);

    return conceptToUpdate;
}

From source file:org.eclipse.jubula.client.core.communication.AUTConnection.java

/**
 * Query the AUTServer for all supported components.
 * <code>listener.componentInfo()</code> will be called when the answer
 * receives./*from  w w  w  .j av  a2  s .  c  om*/
 * 
 * @param command
 *            the command to execute as a callback
 * 
 * @throws CommunicationException
 *             if an error occurs while communicating with the AUT.
 */
private void getAllComponentsFromAUT(AUTStartedCommand command) throws CommunicationException {

    LOG.info(Messages.GettingAllComponentsFromAUT);

    try {
        SendAUTListOfSupportedComponentsMessage message = MessageFactory
                .getSendAUTListOfSupportedComponentsMessage();
        // Send the supported components and their implementation classes
        // to the AUT server to get registered.
        CompSystem compSystem = ComponentBuilder.getInstance().getCompSystem();
        IAUTMainPO connectedAut = TestExecution.getInstance().getConnectedAut();
        String autToolkitId = connectedAut.getToolkit();
        List<Component> components = compSystem.getComponents(autToolkitId, true);

        // optimization: only concrete components need to be registered,
        // as abstract components do not have a corresponding tester class
        components.retainAll(compSystem.getConcreteComponents());
        message.setComponents(components);

        Profile profile = new Profile();
        IObjectMappingProfilePO profilePo = connectedAut.getObjMap().getProfile();
        profile.setNameFactor(profilePo.getNameFactor());
        profile.setPathFactor(profilePo.getPathFactor());
        profile.setContextFactor(profilePo.getContextFactor());
        profile.setThreshold(profilePo.getThreshold());

        message.setProfile(profile);

        int timeoutToUse = AUTStateCommand.AUT_COMPONENT_RETRIEVAL_TIMEOUT;
        request(message, command, timeoutToUse);

        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() <= startTime + timeoutToUse && !command.wasExecuted()
                && isConnected()) {
            TimeUtil.delay(500);
        }
        if (!command.wasExecuted() && isConnected()) {
            IAUTInfoListener listener = command.getListener();
            if (listener != null) {
                listener.error(IAUTInfoListener.ERROR_COMMUNICATION);
            }
            throw new CommunicationException(Messages.CouldNotRequestComponentsFromAUT,
                    IAUTInfoListener.ERROR_COMMUNICATION);
        }
    } catch (UnknownMessageException ume) {
        ClientTestFactory.getClientTest().fireAUTServerStateChanged(new AUTServerEvent(ume.getErrorId()));
    }
}