Example usage for org.apache.commons.collections CollectionUtils forAllDo

List of usage examples for org.apache.commons.collections CollectionUtils forAllDo

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils forAllDo.

Prototype

public static void forAllDo(Collection collection, Closure closure) 

Source Link

Document

Executes the given closure on each element in the collection.

Usage

From source file:com.rubenlaguna.en4j.mainmodule.NoteListTopComponent.java

private RepeatableTask createUpdateAllNotesTask() {
    Runnable runnable = new Runnable() {

        @Override//from   w ww. j a v a 2s .  com
        @SuppressWarnings(value = "SleepWhileHoldingLock")
        public void run() {
            updateAllNotes();
            NoteListTopComponent.this.refresh();
        }

        private void updateAllNotes() {
            final Collection<Note> allNotesInDb = getAllNotesInDb();
            LOG.info("clear and repopulate allNotes list");

            final Collection<Note> toRemove = CollectionUtils.subtract(allNotes, allNotesInDb);
            final Collection<Note> toAdd = CollectionUtils.subtract(allNotesInDb, allNotes);

            long startLockList = System.currentTimeMillis();
            //allNotes.getReadWriteLock().writeLock().lock();
            try {
                // avoid removeAll as it would block allNotes for too long
                CollectionUtils.forAllDo(toRemove, new Closure() {
                    @Override
                    @SuppressWarnings("element-type-mismatch")
                    public void execute(Object input) {
                        allNotes.remove(input);
                    }
                });
                //avoid allNotes.addAll it could block allNotes for too long
                CollectionUtils.addAll(allNotes, toAdd.iterator());
            } finally {
                //allNotes.getReadWriteLock().writeLock().unlock();
            }
            long deltaListLock = System.currentTimeMillis() - startLockList;
            LOG.log(Level.INFO, "We locked the eventlist for {0} ms", deltaListLock);
            LOG.log(Level.INFO, "allNotes size: {0}  allNotesInDb size: {1}",
                    new Object[] { allNotes.size(), allNotesInDb.size() });
        }
    };
    return new RepeatableTask(runnable, 4000);
}

From source file:com.redhat.rhn.domain.monitoring.TemplateProbe.java

private void forAllProbes(String setter, Class valueClass, Object value) {
    Closure c = ClosureUtils.invokerClosure(setter, new Class[] { valueClass }, new Object[] { value });
    CollectionUtils.forAllDo(getServerProbes(), c);
}

From source file:de.berlios.gpon.persistence.GponDataDaoImpl.java

public void updateItem(final Item item, List associationList) {

    Set newAssociations = new HashSet();

    // union//from   ww w  .  jav a  2s .  c o m
    Set allAssoc = new HashSet();
    if (item.getAssociationsA() != null) {
        allAssoc.addAll(item.getAssociationsA());
    }
    if (item.getAssociationsB() != null) {
        allAssoc.addAll(item.getAssociationsB());
    }

    Iterator currentAssocIterator = allAssoc.iterator();

    // remove all unused associations 
    while (currentAssocIterator.hasNext()) {
        Association assoc = (Association) currentAssocIterator.next();

        if (associationList == null || !associationList.contains(assoc)) {
            if (item.getId().equals(assoc.getItemA().getId())) {
                item.getAssociationsA().remove(assoc);
            } else {
                item.getAssociationsB().remove(assoc);
            }
        }
    }

    getHibernateTemplate().flush();

    if (associationList != null) {
        Iterator newAssocIterator = associationList.iterator();

        while (newAssocIterator.hasNext()) {
            Association assoc = (Association) newAssocIterator.next();

            if (!allAssoc.contains(assoc)) {
                // keep track of obsolete associations
                newAssociations.add(assoc);
            }
        }
    }

    // TODO: dissociateIfNecessary has to be a configurable
    // strategy
    checkAssociationConstraints(item, newAssociations, true);

    getHibernateTemplate().flush();

    if (newAssociations != null) {
        CollectionUtils.forAllDo(newAssociations, new Closure() {
            public void execute(Object o) {
                Association assoc = (Association) o;

                if (item.getId().equals(assoc.getItemA())) {
                    if (item.getAssociationsA() == null) {
                        item.setAssociationsA(new HashSet());
                    }

                    item.getAssociationsA().add(assoc);
                } else {
                    if (item.getAssociationsB() == null) {
                        item.setAssociationsB(new HashSet());
                    }

                    item.getAssociationsB().add(assoc);
                }
            }
        });
    }

    this.updateItem(item);

    try {
        getHibernateTemplate().flush();
    } catch (RuntimeException rex) {
        // TODO: handle constraint violations
        log.error("Error while flushing session to db.", rex);
        throw rex;
    }
}

From source file:com.projity.configuration.FieldDictionary.java

private static void fieldsToHtmlTable(final StringBuffer result, String title, Collection fields) {
    result.append("<p><b>").append(title).append("</b><br />");
    result.append("<table border='1'>");
    tabbedStringToHtmlRow(result, Field.getMetadataStringHeader(), true);
    CollectionUtils.forAllDo(FieldDictionary.getInstance().getProjectFields(), new Closure() {
        public void execute(Object arg0) {
            tabbedStringToHtmlRow(result, ((Field) arg0).getMetadataString(), false);
        }//  ww  w.  j  a  va  2  s .  c o  m
    });
    result.append("</table>");
    result.append("</p>");
}

From source file:ar.com.zauber.commons.test.SpringHibernateRepositoryTest.java

/** test */
public final void testActualizarEliminarColeccion() {
    final Query<PersonaDummy> query = new SimpleQuery<PersonaDummy>(PersonaDummy.class,
            new EqualsPropertyFilter("numeroFiscal", new SimpleValue(new Integer(55555))), null, null);

    final PersonaDummy personaDummy = new PersonaDummy(55555, "Martin Contini", "Descripcion Martin Contini",
            crearGuardarDosDirecciones());

    // prueba actualizacion
    repository.saveOrUpdate(personaDummy);

    CollectionUtils.forAllDo(personaDummy.getDirecciones(),
            new BeanPropertyValueChangeClosure("codpostal", CODIGO_POSTAL_3));

    List<PersonaDummy> personas = repository.find(query);

    for (final Persistible persistible : personas) {
        final PersonaDummy persona = (PersonaDummy) persistible;
        for (final DireccionDummy direccion : persona.getDirecciones()) {
            Assert.assertEquals(CODIGO_POSTAL_3, direccion.getCodpostal());
        }/*from  w w  w.  j av a  2  s .  c  o  m*/
    }

    // prueba eliminacion
    personaDummy.getDirecciones().removeAll(personaDummy.getDirecciones());
    repository.saveOrUpdate(personaDummy);

    personas = repository.find(query);

    Assert.assertEquals(0, (personas.get(0)).getDirecciones().size());
}

From source file:de.berlios.gpon.persistence.GponDataDaoImpl.java

private void checkAssociationConstraints(final Item item, Set newAssociations, boolean dissociateIfNecessary) {

    final Set associationsToBeRemoved = new HashSet();

    CollectionUtils.forAllDo(newAssociations, new Closure() {
        public void execute(Object o) {

            Association assoc = (Association) o;

            // we will be connected to a new 'Many' side item 
            // in a 1:M association. let's become the one and only and disconnect it 
            // from other 'One'-side items
            if (assoc.getAssociationType().getMultiplicity().equals(MultiplicityConstants.ONE_TO_MANY)
                    && assoc.getItemA().equals(item)) {
                Item manySideItem = assoc.getItemB();

                List associations = manySideItem.getAssociationsByTypeAndSide(assoc.getAssociationType(), "b");
                if (associations != null && associations.size() > 0) {
                    associationsToBeRemoved.addAll(associations /* should be only 1 */);
                    manySideItem.getAssociationsB().removeAll(associations);
                    updateItem(manySideItem);
                }/*from  w w  w.  j a  v  a 2  s. c  o m*/

            }

        }
    });
}

From source file:com.projity.pm.task.Project.java

public void saveCurrentToSnapshot(Object snapshotId, boolean entireProject, List selection, boolean undo) {
    if (entireProject)
        forTasks(new SnapshottableImpl.SaveCurrentToSnapshotClosure(snapshotId));
    else//from w  ww  .  ja  v  a  2  s .  co  m
        CollectionUtils.forAllDo(selection, new SnapshottableImpl.SaveCurrentToSnapshotClosure(snapshotId));

    fireBaselineChanged(this, null, (Integer) snapshotId, true);

    if (undo) {
        UndoableEditSupport undoableEditSupport = getUndoController().getEditSupport();
        if (undoableEditSupport != null) {
            undoableEditSupport.postEdit(new SaveSnapshotEdit(this, snapshotId, entireProject, selection));
        }
    }

}

From source file:com.projity.pm.task.Project.java

public void clearSnapshot(final Object snapshotId, boolean entireProject, List selection, boolean undo) {
    Iterator i;/*from   w w  w.  j a v a2  s  .c om*/
    if (entireProject)
        i = getTaskOutlineIterator();
    else
        i = selection == null ? null : selection.iterator();

    final Collection snapshotDetails;
    final boolean[] foundSnapshot = new boolean[1]; //no undo edit of there is no snapshot
    if (undo && i != null && i.hasNext()) {
        snapshotDetails = new ArrayList();
        while (i.hasNext()) {
            NormalTask t = (NormalTask) i.next();
            TaskBackup taskBackup = (TaskBackup) t.backupDetail(snapshotId);
            if (taskBackup.snapshot != null)
                foundSnapshot[0] = true;
            snapshotDetails.add(taskBackup);
        }
    } else
        snapshotDetails = null;

    if (entireProject)
        forTasks(new SnapshottableImpl.ClearSnapshotClosure(snapshotId));
    else
        CollectionUtils.forAllDo(selection, new SnapshottableImpl.ClearSnapshotClosure(snapshotId));
    //      FieldEvent.fire(this, Configuration.getFieldFromId("Field.baseline" + snapshotId + "Cost"), null);
    fireBaselineChanged(this, null, (Integer) snapshotId, false);

    if (foundSnapshot[0]) {
        UndoableEditSupport undoableEditSupport = getUndoController().getEditSupport();
        if (undoableEditSupport != null) {
            undoableEditSupport.postEdit(
                    new ClearSnapshotEdit(this, snapshotId, entireProject, selection, snapshotDetails));
        }
    }

}

From source file:com.projity.pm.task.Task.java

/**
 * Percent complete is calculated based on assignments
 *///  www  . ja va  2  s  . c o m
public double getPercentComplete() {
    boolean parent = isWbsParent();
    DivisionSummaryVisitor divisionClosure = ScheduleUtil.percentCompleteClosureInstance(parent);
    Project proj = (Project) (getMasterDocument() == null ? getProject() : getMasterDocument());
    NodeModel nodeModel = proj.getTaskOutline();
    if (isWbsParent()) {
        try {
            LeafWalker.recursivelyTreatBranch(nodeModel, this, divisionClosure);
        } catch (NullPointerException n) {
            ErrorLogger.logOnce("getPercentComplete",
                    "getPercentComplete() Task: " + this + " Project " + project, n);
            return 0; // better this than crashing
        }
    } else {
        CollectionUtils.forAllDo(((NormalTask) this).getAssignments(), divisionClosure);
    }
    double val = divisionClosure.getValue();
    if (val >= COMPLETE_THRESHOLD) // adjust for rounding
        val = 1.0D;
    return val;
}

From source file:com.projity.server.data.Serializer.java

public static void forProjectDataDo(ProjectData project, Closure c) {
    c.execute(project);//from  w w  w  .  j  a v a  2 s  . co m
    if (project.getCalendar() != null) {
        c.execute(project.getCalendar());
        //base calendars to handle?
    }
    for (Iterator i = project.getResources().iterator(); i.hasNext();) {
        ResourceData r = (ResourceData) i.next();
        c.execute(r);
        c.execute(r.getEnterpriseResource());
        //calendars?
    }
    for (Iterator i = project.getTasks().iterator(); i.hasNext();) {
        TaskData t = (TaskData) i.next();
        c.execute(t);
        CollectionUtils.forAllDo(t.getAssignments(), c);
        CollectionUtils.forAllDo(t.getPredecessors(), c);
        //calendars?
    }
}