Example usage for java.util Collection remove

List of usage examples for java.util Collection remove

Introduction

In this page you can find the example usage for java.util Collection remove.

Prototype

boolean remove(Object o);

Source Link

Document

Removes a single instance of the specified element from this collection, if it is present (optional operation).

Usage

From source file:org.castor.cpa.test.test88.TestLazyLoading.java

public void testGeneral() throws PersistenceException {
    LOG.info("Running testGeneral...");

    Calendar cal = Calendar.getInstance();
    Identity fullname = new Identity("First", "Person");
    LazyEmployee loadPerson;/*from  w w  w .  j av  a 2s .com*/

    _db.begin();
    loadPerson = _db.load(LazyEmployee.class, fullname);

    cal.set(1922, 2, 2, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    if (loadPerson.getBirthday().equals(cal.getTime()) && loadPerson.getFirstName().equals("First")
            && loadPerson.getLastName().equals("Person")) {
        LOG.info("OK: Employee is valid");

        Collection<LazyAddress> address = loadPerson.getAddress();
        Iterator<LazyAddress> itor = address.iterator();
        LazyAddress[] addresses = { null, null, null };
        LazyAddress addr;
        while (itor.hasNext()) {
            addr = itor.next();
            if ((addr.getId() < 1) || (addr.getId() > 3)) {
                LOG.error("Error: Address id is incorrect");
                _db.rollback();
                fail("address id is incorrect");
            }
            addresses[addr.getId() - 1] = addr;
        }

        if ((addresses[0] == null) || !addresses[0].getStreet().equals("#1 Address Street")
                || !addresses[0].getCity().equals("First City") || !addresses[0].getState().equals("AB")
                || !addresses[0].getZip().equals("10000") || (addresses[0].getPerson() != loadPerson)) {
            LOG.error("Error: Address 1 is incorrect: " + addresses[0]);
            _db.rollback();
            fail("address 1 is incorrect");
        }
        LOG.info("OK: Address 1 are valid");

        if ((addresses[1] == null) || !addresses[1].getStreet().equals("2nd Ave")
                || !addresses[1].getCity().equals("Second City") || !addresses[1].getState().equals("BC")
                || !addresses[1].getZip().equals("22222") || (addresses[1].getPerson() != loadPerson)) {
            LOG.error("Error: Address 2 is incorrect");
            _db.rollback();
            fail("address 2 is incorrect");
        }
        LOG.info("OK: Address 2 are valid");

        checkGeneral(loadPerson);

        // now modified the object and store it
        address.remove(addresses[0]);
        addresses[1].setStreet("New Second Street");
    } else {
        LOG.error("Error: FirstName, LastName or Birthday is incorrect!");
        _db.rollback();
        fail("FirstName, LastName or Birthday is incorrect!");
    }
    _db.commit();

    // test and see if changes made succeed
    _db.begin();
    loadPerson = _db.load(LazyEmployee.class, fullname);

    cal.set(1922, 2, 2, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    if (loadPerson.getBirthday().equals(cal.getTime()) && loadPerson.getFirstName().equals("First")
            && loadPerson.getLastName().equals("Person")) {
        LOG.info("OK: Employee is valid");

        Collection<LazyAddress> address = loadPerson.getAddress();
        Iterator<LazyAddress> itor = address.iterator();
        LazyAddress[] addresses = { null, null, null };
        LazyAddress addr;
        while (itor.hasNext()) {
            addr = itor.next();
            if ((addr.getId() < 1) || (addr.getId() > 3)) {
                LOG.error("Error: Address id is incorrect");
                _db.rollback();
                fail("address id is incorrect");
            }
            addresses[addr.getId() - 1] = addr;
        }

        if (addresses[0] != null) {
            LOG.error("Error: Address 1 is not deleted: " + addresses[0]);
            fail("address 1 is not deleted");
        }
        LOG.info("OK: Address 1 is deleted");

        if ((addresses[1] == null) || !addresses[1].getStreet().equals("New Second Street")
                || !addresses[1].getCity().equals("Second City") || !addresses[1].getState().equals("BC")
                || !addresses[1].getZip().equals("22222") || (addresses[1].getPerson() != loadPerson)) {
            LOG.error("Error: Address 2 is incorrect");
            _db.rollback();
            fail("address 2 is incorrect");
        }
        LOG.info("OK: Address 2 are valid: " + addresses[1]);

        checkGeneral(loadPerson);
    } else {
        LOG.error("Error: FirstName, LastName or Birthday is incorrect!");
        _db.rollback();
        fail("FirstName, LastName or Birthday is incorrect!");
    }
    _db.commit();
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.xml.converter.util.PsiConverterUtils.java

private static void populateXref(AnnotatedObject<?, ?> annotatedObject, XrefContainer xrefContainer,
        AbstractIntactPsiConverter converter) {

    // ac - create a xref to the institution db
    String ac = annotatedObject.getAc();
    boolean containsAcXref = false;
    DbReference acRef = null;//from   ww  w. ja v  a  2  s .co m

    if (ac != null) {
        for (uk.ac.ebi.intact.model.Xref xref : IntactCore.ensureInitializedXrefs(annotatedObject)) {
            if (annotatedObject.getAc().equals(xref.getPrimaryId())) {
                containsAcXref = true;
                break;
            }
        }

        if (!containsAcXref) {
            String dbMi = null;
            String db = null;

            // calculate the owner of the interaction, based on the AC prefix first,
            // then in the defaultInstitutionForACs if passed to the ConverterContext or,
            // finally to the Institution in the source section of the PSI-XML
            if (ac.startsWith("EBI")) {
                dbMi = Institution.INTACT_REF;
                db = Institution.INTACT.toLowerCase();
            } else if (ac.startsWith("MINT")) {
                dbMi = Institution.MINT_REF;
                db = Institution.MINT.toLowerCase();
            } else if (ConverterContext.getInstance().getDefaultInstitutionForAcs() != null) {
                Institution defaultInstitution = ConverterContext.getInstance().getDefaultInstitutionForAcs();
                dbMi = converter.calculateInstitutionPrimaryId(defaultInstitution);
                db = defaultInstitution.getShortLabel().toLowerCase();
            } else {
                dbMi = converter.getInstitutionPrimaryId();
                db = converter.getInstitution().getShortLabel().toLowerCase();
            }

            // the ref is identity!!!!
            acRef = new DbReference(db, dbMi, ac, CvXrefQualifier.IDENTITY, CvXrefQualifier.IDENTITY_MI_REF);
        }
    }

    if (acRef == null && annotatedObject.getXrefs().isEmpty()) {
        return;
    }

    Xref xref = xrefContainer.getXref();

    if (xref == null) {
        xref = new Xref();
    }

    Collection<DbReference> dbRefs = toDbReferences(annotatedObject,
            IntactCore.ensureInitializedXrefs(annotatedObject));

    // normally the primary reference is the identity reference, but for bibliographic references
    // it is the primary-reference and it does not contain secondary refs
    if (xrefContainer instanceof Bibref) {
        final DbReference primaryPubmedRef = getPrimaryReference(dbRefs, CvDatabase.PUBMED_MI_REF);

        if (primaryPubmedRef != null) {
            xref.setPrimaryRef(primaryPubmedRef);
        } else {
            final DbReference primaryDoiRef = getPrimaryReference(dbRefs, CvDatabase.DOI_MI_REF);

            if (primaryDoiRef != null) {
                xref.setPrimaryRef(primaryDoiRef);

                if (log.isWarnEnabled())
                    log.warn("Primary-reference (refTypeAc=" + CvXrefQualifier.PRIMARY_REFERENCE_MI_REF + ") "
                            + " found in " + xrefContainer.getClass().getSimpleName() + ": " + xrefContainer
                            + ", located at: "
                            + ConverterContext.getInstance().getLocation().getCurrentLocation()
                                    .pathFromRootAsString()
                            + " is neither a reference to Pubmed (dbAc=" + CvDatabase.PUBMED_MI_REF
                            + ") nor a DOI (dbAc=" + CvDatabase.DOI_MI_REF + ")");

            } else {
                final DbReference primaryRef = getPrimaryReference(dbRefs);

                if (primaryRef != null) {
                    xref.setPrimaryRef(primaryRef);
                } else {
                    if (log.isWarnEnabled())
                        log.warn("No primary-reference (refTypeAc=" + CvXrefQualifier.PRIMARY_REFERENCE_MI_REF
                                + ") " + " could be found in " + xrefContainer.getClass().getSimpleName() + ": "
                                + xrefContainer + ", located at: " + ConverterContext.getInstance()
                                        .getLocation().getCurrentLocation().pathFromRootAsString());
                }
            }
        }
    } else {

        // remove the primary ref from the collection if it is a experiment
        // so we don't have the same ref in the bibref and the xref sections
        if (annotatedObject instanceof Experiment) {
            final DbReference bibref = getPrimaryReference(dbRefs, CvDatabase.PUBMED_MI_REF);

            if (bibref != null) {
                dbRefs.remove(bibref);
            }
        }

        DbReference primaryRef = getIdentity(dbRefs, acRef);
        xref.setPrimaryRef(primaryRef);

        // remove the primary ref
        // from the collection and add the rest as secondary refs
        dbRefs.remove(primaryRef);

        for (DbReference secDbRef : dbRefs) {
            if (!xref.getSecondaryRef().contains(secDbRef)) {
                xref.getSecondaryRef().add(secDbRef);
            }
        }
    }

    if (xref.getPrimaryRef() != null) {
        xrefContainer.setXref(xref);
    }
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.storage.ZkOffsetStorage.java

@Override
public void commitOffset(final String group, final Collection<TopicPartitionRegInfo> infoList) {
    if (this.zkClient == null || infoList == null || infoList.isEmpty()) {
        return;/* w  ww  . j a v a 2s .com*/
    }
    List<TopicPartitionRegInfo> shouldDeleteList = new ArrayList<TopicPartitionRegInfo>();

    for (final TopicPartitionRegInfo info : infoList) {
        final String topic = info.getTopic();
        final ZKGroupTopicDirs topicDirs = this.metaZookeeper.new ZKGroupTopicDirs(topic, group);
        long newOffset = -1;
        long msgId = -1;
        // ???msgIdoffset
        synchronized (info) {
            // ??
            if (!info.isModified()) {
                continue;
            }
            newOffset = info.getOffset().get();
            msgId = info.getMessageId();
            // false
            info.setModified(false);
        }
        try {

            if (!ZkUtils.pathExists(this.zkClient,
                    topicDirs.consumerOffsetDir + "/" + info.getPartition().toString())) {
                Partition partition = info.getPartition();
                int brokerId = partition.getBrokerId();
                String brokerTopicPath = this.metaZookeeper.brokerTopicsPathOf(topic, brokerId, -1);
                if (!ZkUtils.pathExists(this.zkClient, brokerTopicPath)) {
                    shouldDeleteList.add(info);
                    continue;
                }
            }
            // zk?msgId-offset
            // ?offset1.4msgId-offset,??
            ZkUtils.updatePersistentPath(this.zkClient,
                    topicDirs.consumerOffsetDir + "/" + info.getPartition().toString(),
                    msgId + "-" + newOffset);
        } catch (final Throwable t) {
            log.error("exception during commitOffsets", t);
        }
        if (log.isDebugEnabled()) {
            log.debug("Committed offset " + newOffset + " for topic " + info.getTopic());
        }

    }
    if (shouldDeleteList.size() > 0) {
        for (TopicPartitionRegInfo deleteInfo : shouldDeleteList) {
            log.warn(deleteInfo.getTopic() + " remove form borked[" + deleteInfo.getPartition().getBrokerId()
                    + "]");
        }
        infoList.remove(shouldDeleteList);
    }
}

From source file:org.nuclos.client.wizard.steps.NuclosEntitySQLLayoutStep.java

private List<MasterDataVO> searchParentLayouts() {
    List<MasterDataVO> layoutToChange = new ArrayList<MasterDataVO>();
    for (Attribute attr : model.getAttributeModel().getRemoveAttributes()) {
        for (String sParentEntity : searchParentEntity(model.getEntityName())) {
            Set<Integer> lstLayouts = new HashSet<Integer>();
            CollectableComparison compare = SearchConditionUtils.newComparison(
                    NuclosEntity.LAYOUTUSAGE.getEntityName(), "entity", ComparisonOperator.EQUAL,
                    sParentEntity);/*from w  ww  . j a v  a  2  s.  c  om*/
            for (MasterDataVO layout : MasterDataDelegate.getInstance()
                    .getMasterData(NuclosEntity.LAYOUTUSAGE.getEntityName(), compare)) {
                lstLayouts.add((Integer) layout.getField("layoutId"));
            }
            for (Integer iLayoutId : lstLayouts) {
                try {
                    MasterDataVO voLayout = MasterDataDelegate.getInstance()
                            .get(NuclosEntity.LAYOUT.getEntityName(), iLayoutId);

                    String sLayout = (String) voLayout.getField("layoutML");

                    WYSIWYGLayoutControllingPanel ctrlPanel = new WYSIWYGLayoutControllingPanel(
                            new WYSIWYGMetaInformation());
                    CollectableEntity entity = NuclosCollectableEntityProvider.getInstance()
                            .getCollectableEntity(sParentEntity);
                    ctrlPanel.getMetaInformation().setCollectableEntity(entity);
                    ctrlPanel.setLayoutML(sLayout);

                    if (attr.getField() != null
                            && NuclosWizardUtils.searchParentEntity(getModel().getEntityName()).size() < 1) {
                        List<WYSIWYGComponent> allCollectables = new ArrayList<WYSIWYGComponent>();
                        ctrlPanel.getEditorPanel().getWYSIWYGComponents(WYSIWYGComponent.class,
                                ctrlPanel.getEditorPanel().getMainEditorPanel(), allCollectables);
                        for (WYSIWYGComponent collectable : allCollectables) {
                            if (collectable.getLayoutMLRulesIfCapable() == null)
                                continue;
                            Collection<LayoutMLRule> copyOfRules = new ArrayList<LayoutMLRule>();
                            copyOfRules.addAll(collectable.getLayoutMLRulesIfCapable().getRules());
                            for (LayoutMLRule rule : collectable.getLayoutMLRulesIfCapable().getRules()) {
                                for (LayoutMLRuleAction action : rule.getLayoutMLRuleActions()
                                        .getSingleActions()) {
                                    if (action.getEntity() != null
                                            && action.getEntity().equals(model.getEntityName())) {
                                        if (action.getTargetComponent().equals(attr.getInternalName())) {
                                            copyOfRules.remove(rule);
                                        }
                                    }
                                }
                            }
                            collectable.getLayoutMLRulesIfCapable().clearRulesForComponent();
                            for (LayoutMLRule rule : copyOfRules) {
                                collectable.getLayoutMLRulesIfCapable().addRule(rule);
                            }
                        }

                        List<WYSIWYGSubForm> allSubForms = new ArrayList<WYSIWYGSubForm>();
                        ctrlPanel.getEditorPanel().getWYSIWYGComponents(WYSIWYGSubForm.class,
                                ctrlPanel.getEditorPanel().getMainEditorPanel(), allSubForms);
                        for (WYSIWYGSubForm collectable : allSubForms) {
                            Collection<WYSIWYGSubFormColumn> copyOfColumns = new ArrayList<WYSIWYGSubFormColumn>(
                                    collectable.getColumns());
                            for (WYSIWYGSubFormColumn col : copyOfColumns) {
                                CollectableEntityField field = col.getEntityField();
                                if (field.getName().equals(attr.getInternalName())) {
                                    collectable.removeColumn(col.getName());
                                }

                                if (col.getLayoutMLRulesIfCapable() == null)
                                    continue;
                                Collection<LayoutMLRule> copyOfRules = new ArrayList<LayoutMLRule>();
                                copyOfRules.addAll(col.getLayoutMLRulesIfCapable().getRules());
                                for (LayoutMLRule rule : col.getLayoutMLRulesIfCapable().getRules()) {
                                    for (LayoutMLRuleAction action : rule.getLayoutMLRuleActions()
                                            .getSingleActions()) {
                                        if (action.getEntity() != null
                                                && action.getEntity().equals(model.getEntityName())) {
                                            if (action.getTargetComponent().equals(attr.getInternalName())) {
                                                copyOfRules.remove(rule);
                                            }
                                        }
                                    }
                                }
                                col.getLayoutMLRulesIfCapable().clearRulesForComponent();
                                for (LayoutMLRule rule : copyOfRules) {
                                    col.getLayoutMLRulesIfCapable().addRule(rule);
                                }
                            }
                        }
                    } else if (NuclosWizardUtils.searchParentEntity(getModel().getEntityName()).size() > 0) {
                        List<WYSIWYGSubForm> allSubForms = new ArrayList<WYSIWYGSubForm>();
                        ctrlPanel.getEditorPanel().getWYSIWYGComponents(WYSIWYGSubForm.class,
                                ctrlPanel.getEditorPanel().getMainEditorPanel(), allSubForms);
                        for (WYSIWYGSubForm collectable : allSubForms) {
                            String sSubFormEntity = collectable.getEntityName();
                            if (getModel().getEntityName().equals(sSubFormEntity) && ((attr.getMetaVO() != null
                                    && attr.getMetaVO().getEntity().equals(sParentEntity))
                                    || (attr.getLookupMetaVO() != null
                                            && attr.getLookupMetaVO().getEntity().equals(sParentEntity)))) {
                                ctrlPanel.getEditorPanel().getTableLayoutUtil()
                                        .removeComponentFromLayout(collectable);
                            }

                            Collection<WYSIWYGSubFormColumn> copyOfColumns = new ArrayList<WYSIWYGSubFormColumn>(
                                    collectable.getColumns());
                            for (WYSIWYGSubFormColumn col : copyOfColumns) {
                                CollectableEntityField field = col.getEntityField();
                                if (field.getName().equals(attr.getInternalName())) {
                                    collectable.removeColumn(col.getName());
                                }

                                if (col.getLayoutMLRulesIfCapable() == null)
                                    continue;
                                Collection<LayoutMLRule> copyOfRules = new ArrayList<LayoutMLRule>();
                                copyOfRules.addAll(col.getLayoutMLRulesIfCapable().getRules());
                                for (LayoutMLRule rule : col.getLayoutMLRulesIfCapable().getRules()) {
                                    for (LayoutMLRuleAction action : rule.getLayoutMLRuleActions()
                                            .getSingleActions()) {
                                        if (action.getEntity() != null
                                                && action.getEntity().equals(model.getEntityName())) {
                                            if (action.getTargetComponent().equals(attr.getInternalName())) {
                                                copyOfRules.remove(rule);
                                            }
                                        }
                                    }
                                }
                                col.getLayoutMLRulesIfCapable().clearRulesForComponent();
                                for (LayoutMLRule rule : copyOfRules) {
                                    col.getLayoutMLRulesIfCapable().addRule(rule);
                                }
                            }
                        }
                    }

                    sLayout = ctrlPanel.getLayoutML();

                    voLayout.setField("layoutML", sLayout);
                    layoutToChange.add(voLayout);
                } catch (Exception e) {
                    // don't modify layout
                    LOG.info("searchParentLayouts failed: " + e);
                }
            }
        }
    }

    return layoutToChange;
}

From source file:com.evolveum.midpoint.model.impl.lens.projector.focus.InboundProcessor.java

private <V extends PrismValue, D extends ItemDefinition> DeltaSetTriple<ItemValueWithOrigin<V, D>> consolidateTriples(
        DeltaSetTriple<ItemValueWithOrigin<V, D>> originTriples, AssignmentPolicyEnforcementType enforcement) {
    // Meaning of the resulting triple:
    // values in PLUS set will be added (valuesToAdd in delta)
    // values in MINUS set will be removed (valuesToDelete in delta)
    // values in ZERO set will be compared with existing values in
    // user property
    // the differences will be added to delta

    Collection<ItemValueWithOrigin<V, D>> consolidatedZeroSet = new HashSet<>();
    Collection<ItemValueWithOrigin<V, D>> consolidatedPlusSet = new HashSet<>();
    Collection<ItemValueWithOrigin<V, D>> consolidatedMinusSet = new HashSet<>();

    if (originTriples != null) {
        if (originTriples.hasPlusSet()) {
            Collection<ItemValueWithOrigin<V, D>> plusSet = originTriples.getPlusSet();
            LOGGER.trace("Consolidating plusSet from origin:\n {}", DebugUtil.debugDumpLazily(plusSet));

            for (ItemValueWithOrigin<V, D> plusValue : plusSet) {
                boolean consolidated = false;
                if (originTriples.hasMinusSet()) {
                    for (ItemValueWithOrigin<V, D> minusValue : originTriples.getMinusSet()) {
                        if (minusValue.getItemValue().equalsRealValue(plusValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from minus set -> moved to the zero, becuase the same value present in plus and minus set at the same time",
                                    minusValue.debugDumpLazily());
                            consolidatedMinusSet.remove(minusValue);
                            consolidatedPlusSet.remove(plusValue);
                            consolidatedZeroSet.add(minusValue);
                            consolidated = true;
                        }/*  ww  w .j a v  a2 s.c  o  m*/
                    }
                }

                if (originTriples.hasZeroSet()) {
                    for (ItemValueWithOrigin<V, D> zeroValue : originTriples.getZeroSet()) {
                        if (zeroValue.getItemValue().equalsRealValue(plusValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from plus set -> moved to the zero, becuase the same value present in plus and minus set at the same time",
                                    zeroValue.debugDumpLazily());
                            consolidatedPlusSet.remove(plusValue);
                            consolidated = true;
                        }
                    }
                }
                if (!consolidated) { //&& !PrismValue.containsRealValue(consolidatedPlusSet, plusValue)) {
                    consolidatedPlusSet.add(plusValue);
                }
            }

        }

        if (originTriples.hasZeroSet()) {
            Collection<ItemValueWithOrigin<V, D>> zeroSet = originTriples.getZeroSet();
            LOGGER.trace("Consolidating zero set from origin:\n {}", DebugUtil.debugDumpLazily(zeroSet));

            for (ItemValueWithOrigin<V, D> zeroValue : zeroSet) {
                boolean consolidated = false;
                if (originTriples.hasMinusSet()) {
                    for (ItemValueWithOrigin<V, D> minusValue : originTriples.getMinusSet()) {
                        if (minusValue.getItemValue().equalsRealValue(zeroValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from minus set -> moved to the zero, becuase the same value present in zero and minus set at the same time",
                                    minusValue.debugDumpLazily());
                            consolidatedMinusSet.remove(minusValue);
                            consolidatedZeroSet.add(minusValue);
                            consolidated = true;
                        }
                    }

                }

                if (originTriples.hasPlusSet()) {
                    for (ItemValueWithOrigin<V, D> plusValue : originTriples.getPlusSet()) {
                        if (plusValue.getItemValue().equalsRealValue(zeroValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from plus set -> moved to the zero, becuase the same value present in zero and plus set at the same time",
                                    plusValue.debugDumpLazily());
                            consolidatedPlusSet.remove(plusValue);
                            consolidatedZeroSet.add(plusValue);
                            consolidated = true;
                        }
                    }

                }
                if (!consolidated) {// && !PrismValue.containsRealValue(consolidatedZeroSet, zeroValue)) {
                    consolidatedZeroSet.add(zeroValue);
                }
            }

        }

        if (originTriples.hasMinusSet()) {
            Collection<ItemValueWithOrigin<V, D>> minusSet = originTriples.getMinusSet();
            LOGGER.trace("Consolidating minus set from origin:\n {}", DebugUtil.debugDumpLazily(minusSet));

            for (ItemValueWithOrigin<V, D> minusValue : minusSet) {
                boolean consolidated = false;
                if (originTriples.hasPlusSet()) {
                    for (ItemValueWithOrigin<V, D> plusValue : originTriples.getPlusSet()) {
                        if (plusValue.getItemValue().equalsRealValue(minusValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from minus set -> moved to the zero, becuase the same value present in plus and minus set at the same time",
                                    plusValue.debugDumpLazily());
                            consolidatedPlusSet.remove(plusValue);
                            consolidatedMinusSet.remove(minusValue);
                            consolidatedZeroSet.add(minusValue);
                            consolidated = true;
                        }
                    }
                }

                if (originTriples.hasZeroSet()) {
                    for (ItemValueWithOrigin<V, D> zeroValue : originTriples.getZeroSet()) {
                        if (zeroValue.getItemValue().equalsRealValue(minusValue.getItemValue())) {
                            LOGGER.trace(
                                    "Removing value {} from minus set -> moved to the zero, becuase the same value present in plus and minus set at the same time",
                                    zeroValue.debugDumpLazily());
                            consolidatedMinusSet.remove(minusValue);
                            consolidatedZeroSet.add(zeroValue);
                            consolidated = true;
                        }
                    }
                }

                if (!consolidated) { // && !PrismValue.containsRealValue(consolidatedMinusSet, minusValue)) {
                    consolidatedMinusSet.add(minusValue);
                }

            }

        }
    }

    DeltaSetTriple<ItemValueWithOrigin<V, D>> consolidatedTriples = new DeltaSetTriple<>();
    consolidatedTriples.addAllToMinusSet(consolidatedMinusSet);
    consolidatedTriples.addAllToPlusSet(consolidatedPlusSet);
    consolidatedTriples.addAllToZeroSet(consolidatedZeroSet);
    return consolidatedTriples;
}

From source file:org.rhq.enterprise.server.resource.group.definition.GroupDefinitionManagerBean.java

@RequiredPermission(Permission.MANAGE_INVENTORY)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
// required for the recalculation thread
public void calculateGroupMembership(Subject subject, int groupDefinitionId)
        throws ResourceGroupDeleteException, GroupDefinitionDeleteException, GroupDefinitionNotFoundException,
        InvalidExpressionException, ResourceGroupUpdateException {
    /*// w ww  . j a  v  a2 s .  com
     * even though this method declares to throw it, it should never generate an InvalidExpressionException because
     * the definition's expression set was validated before it was persisted.  conceivably, if the group definition
     * is persisted without being passed to the validating updateGroupDefinition( GroupDefinition ) method, then it
     * could throw a validation exception.
     *
     * so, callers to this method should catch InvalidExpressionException just in case, and give the user a chance to
     * correct the expression set before attempting to calculate the effective group again.
     */

    long startTime = System.currentTimeMillis();

    GroupDefinition groupDefinition = getById(groupDefinitionId);
    groupDefinition.setLastCalculationTime(System.currentTimeMillis()); // we're calculating now

    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    for (String expression : groupDefinition.getExpressionAsList()) {
        evaluator.addExpression(expression);
    }

    Collection<Integer> doomedResourceGroupIds = new ArrayList<Integer>();
    for (Integer managedGroupId : getManagedResourceGroupIdsForGroupDefinition(groupDefinitionId)) {
        doomedResourceGroupIds.add(managedGroupId);
    }

    for (ExpressionEvaluator.Result result : evaluator) {
        if (result == null) {
            /*
             * skip null result elements, which represent queries that returned some null element -- this could be
             * remedied by supporting "IS NULL" for parameter-replacement aside from just "= :bindArg" syntax
             */
            continue;
        }

        /*
         * do one group at a time, to help prevent xaction timeouts
         *
         * note: we don't need to pass the overlord here because all group definition / dynagroup functionality
         *       is hidden behind the MANAGE_INVENTORY permission, which is sufficient for all operations on a
         *       resource group including creation, deletion, and membership changes
         */
        Integer nextResourceGroupId = groupDefinitionManager.calculateGroupMembership_helper(subject,
                groupDefinitionId, result);

        /*
         * as a result of recalculation, the membership may have changed such that a group which was previously
         * marked as compatible now becomes a mixed group.  if that happens, then the GroupCategory needs to be
         * updated and any compatible group constructs need to be removed from this group.  the following method
         * will achieve both of those goals
         */
        resourceGroupManager.setResourceType(nextResourceGroupId);

        /*
         * remove all ids returned from the helper.  by the time we're done looping over all
         * ExpressionEvaluator.Result objects, the remaining objects in managedResourceGroupIds should represent
         * groups that no longer managed by this definition (either due to an inventory or expression change), and
         * are thus doomed
         */
        doomedResourceGroupIds.remove(nextResourceGroupId);
    }

    /*
     * and ids that are left over are doomed, but since deleting a resource group is related to the size of the
     * group, remove each group in it's own transaction
     *
     * note: we don't need to pass the overlord here because all group definition / dynagroup functionality
     *       is hidden behind the MANAGE_INVENTORY permission, which is sufficient for all operations on a
     *       resource group including creation, deletion, and membership changes
     */
    for (Integer doomedGroupId : doomedResourceGroupIds) {
        groupDefinitionManager.removeManagedResource_helper(subject, groupDefinitionId, doomedGroupId);
    }

    long endTime = System.currentTimeMillis();

    log.debug("calculateGroupMembership took " + (endTime - startTime) + " millis");
}

From source file:com.wavemaker.tools.data.DataModelConfiguration.java

private Map<String, ColumnInfo> initColumns(String entity) {

    Map<String, ColumnInfo> pkCols = new HashMap<String, ColumnInfo>();
    Map<String, ColumnInfo> fkCols = new HashMap<String, ColumnInfo>();

    Collection<ColumnInfo> allColumns = new LinkedHashSet<ColumnInfo>();

    for (PropertyInfo p : getProperties(entity)) {
        if (p.getIsRelated() && p.getIsInverse()) {
            continue;
        }// w ww . j  a v  a 2  s .  com
        for (ColumnInfo ci : p.allColumns()) {
            allColumns.add(ci);
            if (ci.getIsPk()) {
                pkCols.put(ci.getName(), ci);
            }
            if (ci.getIsFk()) {
                fkCols.put(ci.getName(), ci);
            }
        }
    }

    for (ColumnInfo fk : fkCols.values()) {
        if (pkCols.containsKey(fk.getName())) {
            ColumnInfo pk = pkCols.get(fk.getName());
            pk.setIsFk(true);
            allColumns.remove(fk);
        }
    }

    Map<String, ColumnInfo> rtn = new LinkedHashMap<String, ColumnInfo>(allColumns.size());

    for (ColumnInfo ci : allColumns) {
        rtn.put(ci.getName(), ci);
    }

    return rtn;
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.xml.converter.util.PsiConverterUtils.java

public static void populateXref(AnnotatedObject<?, ?> annotatedObject, XrefContainer xrefContainer,
        XrefConverter converter) {//  w  w  w .ja v  a2s  . com

    // ac - create a xref to the institution db
    String ac = annotatedObject.getAc();
    boolean containsAcXref = false;
    DbReference acRef = null;

    Collection<? extends uk.ac.ebi.intact.model.Xref> xrefs;
    if (converter.isCheckInitializedCollections()) {
        xrefs = IntactCore.ensureInitializedXrefs(annotatedObject);
    } else {
        xrefs = annotatedObject.getXrefs();
    }

    if (ac != null) {
        for (uk.ac.ebi.intact.model.Xref xref : xrefs) {
            if (annotatedObject.getAc().equals(xref.getPrimaryId())) {
                containsAcXref = true;
                break;
            }
        }

        if (!containsAcXref) {
            String dbMi = null;
            String db = null;

            // calculate the owner of the interaction, based on the AC prefix first,
            // then in the defaultInstitutionForACs if passed to the ConverterContext or,
            // finally to the Institution in the source section of the PSI-XML
            if (ac.startsWith("EBI")) {
                dbMi = Institution.INTACT_REF;
                db = Institution.INTACT.toLowerCase();
            } else if (ac.startsWith("MINT")) {
                dbMi = Institution.MINT_REF;
                db = Institution.MINT.toLowerCase();
            } else if (ConverterContext.getInstance().getDefaultInstitutionForAcs() != null) {
                Institution defaultInstitution = ConverterContext.getInstance().getDefaultInstitutionForAcs();
                dbMi = converter.calculateInstitutionPrimaryId(defaultInstitution);
                db = defaultInstitution.getShortLabel().toLowerCase();
            } else {
                dbMi = converter.getInstitutionPrimaryId();
                db = converter.getInstitution().getShortLabel().toLowerCase();
            }

            acRef = new DbReference(db, dbMi, ac, CvXrefQualifier.IDENTITY, CvXrefQualifier.IDENTITY_MI_REF);
        }
    }

    if (acRef == null && xrefs.isEmpty()) {
        return;
    }

    Xref xref = xrefContainer.getXref();

    if (xref == null) {
        xref = new Xref();
    }

    Collection<DbReference> dbRefs = toDbReferences(annotatedObject, xrefs, converter);

    // normally the primary reference is the identity reference, but for bibliographic references
    // it is the primary-reference and it does not contain secondary refs
    if (xrefContainer instanceof Bibref) {
        DbReference primaryRef = getPrimaryReference(dbRefs, CvDatabase.PUBMED_MI_REF);

        if (primaryRef != null) {
            xref.setPrimaryRef(primaryRef);
        } else {
            primaryRef = getPrimaryReference(dbRefs, CvDatabase.DOI_MI_REF);

            if (primaryRef != null) {
                xref.setPrimaryRef(primaryRef);

                if (log.isWarnEnabled())
                    log.warn("Primary-reference (refTypeAc=" + CvXrefQualifier.PRIMARY_REFERENCE_MI_REF + ") "
                            + " found in " + xrefContainer.getClass().getSimpleName() + ": " + xrefContainer
                            + ", located at: "
                            + ConverterContext.getInstance().getLocation().getCurrentLocation()
                                    .pathFromRootAsString()
                            + " is neither a reference to Pubmed (dbAc=" + CvDatabase.PUBMED_MI_REF
                            + ") nor a DOI (dbAc=" + CvDatabase.DOI_MI_REF + ")");

            } else {
                primaryRef = getPrimaryReference(dbRefs);

                if (primaryRef != null) {
                    xref.setPrimaryRef(primaryRef);
                } else {
                    if (log.isWarnEnabled())
                        log.warn("No primary-reference (refTypeAc=" + CvXrefQualifier.PRIMARY_REFERENCE_MI_REF
                                + ") " + " could be found in " + xrefContainer.getClass().getSimpleName() + ": "
                                + xrefContainer + ", located at: " + ConverterContext.getInstance()
                                        .getLocation().getCurrentLocation().pathFromRootAsString());
                }
            }

            // add the secondary xrefs
            xref.getSecondaryRef().addAll(CollectionUtils.subtract(dbRefs, Arrays.asList(primaryRef)));
        }
    } else {
        // remove the primary ref from the collection if it is a experiment
        // so we don't have the same ref in the bibref and the xref sections
        if (annotatedObject instanceof Experiment) {
            DbReference bibref = getPrimaryReference(dbRefs, CvDatabase.PUBMED_MI_REF);

            if (bibref == null) {
                bibref = getPrimaryReference(dbRefs, CvDatabase.DOI_MI_REF);
            }

            if (bibref != null) {
                dbRefs.remove(bibref);
            }
        }

        DbReference primaryRef = getIdentity(dbRefs, acRef);

        if (primaryRef == null) {
            primaryRef = getPrimaryReference(dbRefs);
        }

        xref.setPrimaryRef(primaryRef);

        // remove the primary ref
        // from the collection and add the rest as secondary refs
        dbRefs.remove(primaryRef);

        for (DbReference secDbRef : dbRefs) {
            if (!xref.getSecondaryRef().contains(secDbRef)) {
                xref.getSecondaryRef().add(secDbRef);
            }
        }
    }

    if (xref.getPrimaryRef() != null) {
        xrefContainer.setXref(xref);
    }
}

From source file:org.pentaho.ui.xul.swt.tags.SwtTree.java

private void removeItem(Object parent, String childrenMethodProperty, Object toRemove, DropEvent event) {
    Collection children = getChildCollection(parent, childrenMethodProperty);
    if (children == null) {
        return;/*from   w  w  w. j av  a 2  s  .  c o m*/
    }
    Iterator iter = children.iterator();
    int pos = 0;
    while (iter.hasNext()) {
        Object next = iter.next();
        if (next == toRemove) {
            // check to see if DnD is same origin, if so index needs to be adjusted
            if (event.getDropParent() == children && event.getDropIndex() > pos) {
                event.setDropIndex(event.getDropIndex() - 1);
            }
            children.remove(toRemove);
            return;
        }
        removeItem(next, childrenMethodProperty, toRemove, event);
        pos++;
    }
}

From source file:jetbrains.exodus.entitystore.PersistentEntityStoreImpl.java

@Override
public void updateUniqueKeyIndices(@NotNull final Iterable<Index> indices) {
    environment.suspendGC();/*from   w w w .  j av  a2 s.  c o m*/
    try {
        executeInTransaction(new StoreTransactionalExecutable() {
            @Override
            public void execute(@NotNull StoreTransaction txn) {
                final PersistentStoreTransaction t = (PersistentStoreTransaction) txn;
                final PersistentStoreTransaction snapshot = t.getSnapshot();
                try {
                    final Collection<String> indexNames = new HashSet<>();
                    for (final String dbName : environment.getAllStoreNames(t.getEnvironmentTransaction())) {
                        if (namingRulez.isUniqueKeyIndexName(dbName)) {
                            indexNames.add(dbName);
                        }
                    }
                    for (final Index index : indices) {
                        final String indexName = getUniqueKeyIndexName(index);
                        if (indexNames.contains(indexName)) {
                            indexNames.remove(indexName);
                        } else {
                            createUniqueKeyIndex(t, snapshot, index);
                        }
                    }
                    // remove obsolete indices
                    for (final String indexName : indexNames) {
                        removeObsoleteUniqueKeyIndex(t, indexName);
                    }
                    if (log.isTraceEnabled()) {
                        log.trace("Flush index persistent transaction " + t);
                    }
                    t.flush();
                } finally {
                    snapshot.abort(); // reading snapshot is obsolete now
                }
            }
        });
    } finally {
        environment.resumeGC();
    }
}