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

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

Introduction

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

Prototype

public static Collection collect(Iterator inputIterator, Transformer transformer) 

Source Link

Document

Transforms all elements from the inputIterator with the given transformer and adds them to the outputCollection.

Usage

From source file:org.squashtest.tm.service.internal.advancedsearch.AdvancedSearchServiceImpl.java

private void secureProjectCriteria(AdvancedSearchModel model) {

    // Issue #5079 again
    // first task is to locate which name has the project criteria because it may differ depending on the interface
    // (test case, requirement, test-case-through-requirements
    String key = null;/*from w w  w  .  j  a  va  2 s . co  m*/
    Set<String> keys = model.getFields().keySet();
    for (String k : keys) {
        if (k.contains(PROJECT_CRITERIA_NAME)) {
            key = k;
            break;
        }
    }
    // if no projectCriteria was set -> nothing to do
    if (key == null) {
        return;
    }

    AdvancedSearchListFieldModel projectCriteria = (AdvancedSearchListFieldModel) model.getFields().get(key);

    List<String> approvedIds;
    List<String> selectedIds = projectCriteria.getValues();

    // case 1 : no project is selected
    if (selectedIds == null || selectedIds.isEmpty()) {
        List<Project> ps = projectFinder.findAllReadable();
        approvedIds = (List<String>) CollectionUtils.collect(ps, new Transformer() {
            @Override
            public Object transform(Object project) {
                return ((Identified) project).getId().toString();
            }
        });
    }
    // case 2 : some projects were selected
    else {
        approvedIds = new ArrayList<>();
        for (String id : selectedIds) {
            if (permissionService.hasRoleOrPermissionOnObject("ROLE_ADMIN", "READ", Long.valueOf(id),
                    Project.class.getName())) {
                approvedIds.add(id);
            } else {
                LOGGER.info("AdvancedSearchService : removed element '" + id
                        + "' from criteria 'project.id' because the user is not approved for 'READ' operation on it");
            }
        }
    }

    projectCriteria.setValues(approvedIds);

}

From source file:org.squashtest.tm.service.internal.batchimport.Model.java

/**
 * substitutes the value of the name attribute of NamedReference so that it
 * becomes a path instead.<br/>/*from  ww  w . ja  v  a 2 s.c o  m*/
 * All references are supposed to exist in the database that's foul play but
 * saves more bloat
 */
@SuppressWarnings("unchecked")
private void swapNameForPath(Collection<SimpleNode<NamedReference>> references) {

    // first ensures that the references will be iterated in a constant
    // order
    List<SimpleNode<NamedReference>> listedRefs = new ArrayList<>(references);

    // now collect the ids. Node : the javadoc claims that the result is a
    // new list.
    List<Long> ids = (List<Long>) CollectionUtils.collect(listedRefs, NamedReferenceIdCollector.INSTANCE);

    List<String> paths = finderService.getPathsAsString(ids);

    for (int i = 0; i < paths.size(); i++) {
        SimpleNode<NamedReference> currentNode = listedRefs.get(i);
        Long id = ids.get(i);
        String path = paths.get(i);
        currentNode.setKey(new NamedReference(id, path));
    }

}

From source file:org.squashtest.tm.service.internal.chart.ColumnPrototypeModification.java

@SuppressWarnings("unchecked")
private Set<EntityType> findTypeToRemove(Entry<Long, List<CustomFieldBinding>> entry) {

    List<CustomFieldBinding> allBinding = cufBindingDao
            .findAllByCustomFieldIdOrderByPositionAsc(entry.getKey());
    allBinding.removeAll(entry.getValue());

    Set<EntityType> remainingType = CollectionUtils.isEmpty(allBinding) ? EnumSet.noneOf(EntityType.class)
            : EnumSet.copyOf(CollectionUtils.collect(allBinding, TYPE_COLLECTOR));

    Set<EntityType> typeToRemove = EnumSet.copyOf(CollectionUtils.collect(entry.getValue(), TYPE_COLLECTOR));

    typeToRemove.removeAll(remainingType);

    return typeToRemove;
}

From source file:org.squashtest.tm.service.internal.customfield.AbstractCustomFieldHelper.java

/**
 * Return the CustomFields referenced by the CustomFieldBindings for the given project and BindableEntity type,
 * ordered by their position. The location argument is optional, if set then only the custom fields that are
 * rendered in at least one of these locations will be returned.
 *
 * @param projectId/*from ww  w.  j a v  a  2 s .co m*/
 * @param entityType
 * @return
 */
@SuppressWarnings("unchecked")
protected final List<CustomField> findCustomFields(long projectId, BindableEntity entityType,
        Collection<RenderingLocation> optionalLocations) {

    List<CustomFieldBinding> bindings = cufBindingService.findCustomFieldsForProjectAndEntity(projectId,
            entityType);

    Collections.sort(bindings, new BindingSorter());

    if (optionalLocations != null && !optionalLocations.isEmpty()) {
        CollectionUtils.filter(bindings, new BindingLocationFilter(optionalLocations));
    }

    return (List<CustomField>) CollectionUtils.collect(bindings, new BindingFieldCollector());

}

From source file:org.squashtest.tm.service.internal.customfield.CustomFieldBindingModificationServiceImpl.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww.ja va 2s  .c o  m*/
@PreAuthorize("hasRole('ROLE_TM_PROJECT_MANAGER')" + OR_HAS_ROLE_ADMIN)
// TODO add check for permission MANAGEMENT on the project id
public void removeCustomFieldBindings(Long projectId) {
    List<CustomFieldBinding> bindings = customFieldBindingDao.findAllForGenericProject(projectId);
    List<Long> bindingIds = new LinkedList<>(CollectionUtils.collect(bindings, BINDING_ID_COLLECTOR));
    removeCustomFieldBindings(bindingIds);
}

From source file:org.squashtest.tm.service.internal.customfield.CustomFieldHelperImpl.java

@Override
@SuppressWarnings("unchecked")
protected void initCustomFields() {
    if (!entities.isEmpty()) {

        // restrict the number of queries we must perform : 1 per pair of (project, bindableentity)
        Collection<BindingTarget> targets = CollectionUtils.collect(entities, new BindingTargetCollector());
        retainUniques(targets);/* w  ww  .  ja v  a2  s .c  o  m*/

        customFields = new ArrayList<>();

        // collect the result
        for (BindingTarget target : targets) {
            customFields = getAddingStrategy().add(customFields,
                    findCustomFields(target.getProjectId(), target.getBindableEntity(), getLocations()));

        }

        // eliminate multiple occurences
        retainUniques(customFields);
    } else {
        customFields = Collections.emptyList();
    }
}

From source file:org.squashtest.tm.service.internal.deletion.AbstractNodeDeletionHandler.java

/**
 * <p>Accepts a list of ids and returns themselves and their children as a list of pairs, each pair being an array of long (node ids) such as [ parent.id, child.id ].
 * see {@link FolderDao#findPairedContentForList(List)} for details. The nodes input nodes will be paired with null (no parents), and the leaves will be be paired with null (for children).
 *  </p>/*from  w w  w.  j a va 2 s  .c  o  m*/
 *
 * @param rootNodesIds the ids defining the upper level of the hierarchy.
 * @return the rootNodeIds and the ids of their children, paired together as described above.
 */
/*
 * TODO : refactor and make profit of the tables [TC,R,C]LN_RELATIONSHIP_CLOSURE]
 */
@SuppressWarnings("unchecked")
protected List<Long[]> findPairedNodeHierarchy(List<Long> rootNodeIds) {

    if (rootNodeIds.isEmpty()) {
        return new ArrayList<>();
    }

    List<Long[]> nodeHierarchy = new ArrayList<>();

    for (Long id : rootNodeIds) {
        nodeHierarchy.add(new Long[] { null, id });
    }

    //now we loop over the folder structure.
    List<Long> currentLayer = rootNodeIds;

    //let's loop
    while (!currentLayer.isEmpty()) {
        List<Long[]> nextPairedLayer = getFolderDao().findPairedContentForList(currentLayer);

        nodeHierarchy.addAll(nextPairedLayer);

        currentLayer = new LinkedList<>(CollectionUtils.collect(nextPairedLayer, new Transformer() {
            @Override
            public Object transform(Object input) {
                return ((Object[]) input)[1];
            }
        }));
    }

    return nodeHierarchy;
}

From source file:org.squashtest.tm.service.internal.denormalizedField.PrivateDenormalizedFieldValueServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public List<DenormalizedFieldValue> findAllForEntities(Collection<DenormalizedFieldHolder> entities,
        Collection<RenderingLocation> nullOrLocations) {
    if (entities.isEmpty()) {
        return Collections.emptyList();
    } else {//from w w  w . ja v a2 s  .  c o m
        DenormalizedFieldHolderType type = entities.iterator().next().getDenormalizedFieldHolderType();

        Collection<Long> entityIds = CollectionUtils.collect(entities, new Transformer() {
            @Override
            public Object transform(Object input) {
                return ((DenormalizedFieldHolder) input).getDenormalizedFieldHolderId();
            }
        });

        if (nullOrLocations == null) {
            return denormalizedFieldValueDao.findDFVForEntities(type, entityIds);
        } else {
            return denormalizedFieldValueDao.findDFVForEntitiesAndLocations(type, entityIds, nullOrLocations);
        }
    }
}

From source file:org.squashtest.tm.service.internal.milestone.CustomMilestoneBindingServiceImpl.java

private void unbindMilestonesFromProject(GenericProject project, List<Milestone> milestones) {

    project.unbindMilestones(milestones);

    // Remove the project in different for loop because milestoneDao.unbindAllObjectsForProject may clear the
    // session//  w ww  .jav a2s .c  om
    for (Milestone milestone : milestones) {
        milestone.removeProjectFromPerimeter(project);
    }

    // save the test case and requirement ids for reindexation later
    Collection<Long> milestoneIds = CollectionUtils.collect(milestones, ID_COLLECTOR);

    Collection<Long> tcIds = milestoneDao.findTestCaseIdsBoundToMilestones(milestoneIds);
    Collection<Long> reqIds = milestoneDao.findRequirementVersionIdsBoundToMilestones(milestoneIds);

    for (Milestone milestone : milestones) {
        // that thing will probably clear the session, be careful
        milestoneDao.unbindAllObjectsForProject(milestone.getId(), project.getId());
    }

    // reindex
    indexService.batchReindexTc(tcIds);
    indexService.batchReindexReqVersion(reqIds);
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateDeletionDao.java

@Override
@SuppressWarnings("unchecked")
public void removeAttachmentsLists(final List<Long> attachmentListIds) {

    List<Object[]> attachmentContentIds;

    if (attachmentListIds.isEmpty()) {
        return;/*from www . j a  va2s .c om*/
    }

    // we handle the cascade ourselves to make sure that the deletion is carried properly
    attachmentContentIds = executeSelectNamedQuery("attachment.getAttachmentAndContentIdsFromList", "listIds",
            attachmentListIds);

    // due to foreign key constraints and the like, the following
    // operations
    // must be carried in that order :

    if (!attachmentContentIds.isEmpty()) {

        Collection<Long> attachIds = CollectionUtils.collect(attachmentContentIds, new CellTableTransformer(0));

        Collection<Long> contentIds = CollectionUtils.collect(attachmentContentIds,
                new CellTableTransformer(1));

        executeDeleteNamedQuery("attachment.removeAttachments", "attachIds", attachIds);
        executeDeleteNamedQuery("attachment.removeContents", "contentIds", contentIds);
    }

    executeDeleteNamedQuery("attachment.deleteAttachmentLists", "listIds", attachmentListIds);

}