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:com.abiquo.server.core.cloud.VirtualApplianceDAO.java

@SuppressWarnings("unchecked")
private static Collection<Integer> availableVdsToUser(final User user) {
    Collection<String> idsStrings = Arrays.asList(user.getAvailableVirtualDatacenters().split(","));

    return CollectionUtils.collect(idsStrings, new Transformer() {
        @Override/*from   w w  w. j  a  v a2 s.c  om*/
        public Object transform(final Object input) {
            return Integer.valueOf(input.toString());
        }
    });
}

From source file:com.epam.cme.core.services.impl.DefaultCompatibilityServiceIntegrationTest.java

protected void assertCompatibileListIsCorrect(final List<? extends ProductModel> returnedProducts,
        final Set<String> expectedCodes) {
    Assert.assertEquals(expectedCodes.size(), returnedProducts.size());
    final List<String> returnedCodes = (List<String>) CollectionUtils.collect(returnedProducts,
            new Transformer() {

                @Override/* ww w  .j a v a2 s  . c om*/
                public Object transform(final Object product) {
                    final String productCode = ((ProductModel) product).getCode();
                    return productCode;
                }

            });

    Assert.assertTrue(CollectionUtils.isEqualCollection(expectedCodes, returnedCodes));
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.teacher.onlineTests.ReadDistributedTestMarksToString.java

protected String run(String executionCourseId, String[] distributedTestCodes) throws FenixServiceException {
    StringBuilder result = new StringBuilder();
    result.append(BundleUtil.getString(Bundle.APPLICATION, "label.username")).append("\t");
    result.append(BundleUtil.getString(Bundle.APPLICATION, "label.number")).append("\t");
    result.append(BundleUtil.getString(Bundle.APPLICATION, "label.name")).append("\t");

    ExecutionCourse executionCourse = FenixFramework.getDomainObject(executionCourseId);
    List<Registration> studentsFromAttendsList = (List) CollectionUtils.collect(executionCourse.getAttendsSet(),
            new Transformer() {

                @Override/*from  w w w. ja  v  a  2  s .  co m*/
                public Object transform(Object input) {
                    return ((Attends) input).getRegistration();
                }
            });

    final Set<Registration> students = new HashSet<Registration>();
    for (final String distributedTestCode : distributedTestCodes) {
        final DistributedTest distributedTest = FenixFramework.getDomainObject(distributedTestCode);
        students.addAll(distributedTest.findStudents());
    }

    List<Registration> studentList = concatStudentsLists(studentsFromAttendsList, students);
    Double[] maxValues = new Double[distributedTestCodes.length];

    for (int i = 0; i < distributedTestCodes.length; i++) {
        DistributedTest distributedTest = FenixFramework.getDomainObject(distributedTestCodes[i]);
        if (distributedTest == null) {
            throw new InvalidArgumentsServiceException();
        }
        maxValues[i] = distributedTest.calculateMaximumDistributedTestMark();
        result.append(distributedTest.getTitle());
        result.append("\t");
        if (maxValues[i].doubleValue() > 0) {
            result.append("%\t");
        }
    }

    for (Registration registration : studentList) {
        result.append("\n");
        result.append(registration.getPerson().getUsername());
        result.append("\t");
        result.append(registration.getNumber());
        result.append("\t");
        result.append(registration.getPerson().getName());
        result.append("\t");

        for (int i = 0; i < distributedTestCodes.length; i++) {

            Double finalMark = new Double(0);
            DecimalFormat df = new DecimalFormat("#0.##");
            DecimalFormat percentageFormat = new DecimalFormat("#%");

            final DistributedTest distributedTest = FenixFramework.getDomainObject(distributedTestCodes[i]);
            finalMark = distributedTest.calculateTestFinalMarkForStudent(registration);

            if (finalMark == null) {
                result.append("NA\t");
                if (maxValues[i].doubleValue() > 0) {
                    result.append("NA\t");
                }
            } else {
                if (finalMark.doubleValue() < 0) {
                    result.append("0\t");
                } else {
                    result.append(df.format(finalMark.doubleValue()));
                    result.append("\t");
                }
                if (maxValues[i].doubleValue() > 0) {
                    double finalMarkPercentage = finalMark.doubleValue()
                            * java.lang.Math.pow(maxValues[i].doubleValue(), -1);
                    if (finalMarkPercentage < 0) {
                        result.append("0%\t");
                    } else {
                        result.append(percentageFormat.format(finalMarkPercentage));
                        result.append("\t");
                    }
                }
            }
        }
    }
    return result.toString();
}

From source file:edu.buffalo.fusim.FusionGene.java

private void setIds() {
    this.geneId = StringUtils.join(CollectionUtils.collect(this.genes, new Transformer() {
        public Object transform(Object g) {
            return ((TranscriptRecord) g).getGeneId();
        }/*from   w w  w  .  j a  v a 2s.c  o m*/
    }), "-");

    this.transcriptId = StringUtils.join(CollectionUtils.collect(this.genes, new Transformer() {
        public Object transform(Object g) {
            return ((TranscriptRecord) g).getTranscriptId();
        }
    }), "-");
}

From source file:com.fsoft.bn.service.impl.BNJournalArticleLocalServiceImpl.java

@SuppressWarnings("unchecked")
public NewsPage getNews(PortletRequest req, String structId, long categoryId, String cateName, int numPerPage,
        int currentPageNum, boolean paging, List<KeyValuePair> sortbys) {
    int totalPageNum = 1;
    if (currentPageNum < 1) {
        currentPageNum = 1;//from  ww  w  .  j  a  v  a2  s .c o  m
    }
    if (numPerPage < 1) {
        numPerPage = CONFIG_DEFAULT_VALUE.NUM_PER_PAGE;
    }

    long groupId = PortalUtil.getGroupId(req);
    List<JournalArticle> news;
    if (paging) {
        int newsCount = BNJournalArticleFinderUtil.countNews(groupId, structId, categoryId);
        if (newsCount == 0) {
            return new NewsPage();
        }
        totalPageNum = CommonUtil.getNumberOfPage(newsCount, numPerPage);

        if (currentPageNum > totalPageNum)
            throw new RuntimeException("can not get page number :" + currentPageNum
                    + " exceed total number of page" + totalPageNum);

        news = BNJournalArticleFinderUtil.getNews(groupId, structId, categoryId,
                (currentPageNum - 1) * numPerPage, currentPageNum * numPerPage, sortbys);
    } else {
        news = BNJournalArticleFinderUtil.getNews(groupId, structId, categoryId, 0, numPerPage, sortbys);
    }

    List<News> items = (List<News>) CollectionUtils.collect(news,
            new JournalArticle2NewsTransformer(req, structId));
    return new NewsPage(req, totalPageNum, currentPageNum, numPerPage, items);
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.publico.teachersBody.ReadProfessorshipsAndResponsibilitiesByDepartmentAndExecutionPeriod.java

protected static List getDetailedProfessorships(List professorships, final List responsibleFors,
        final Integer teacherType) {

    List detailedProfessorshipList = (List) CollectionUtils.collect(professorships, new Transformer() {

        @Override//from w  w  w.  j  av a2 s .  c o m
        public Object transform(Object input) {

            Professorship professorship = (Professorship) input;

            InfoProfessorship infoProfessorShip = InfoProfessorship.newInfoFromDomain(professorship);

            List executionCourseCurricularCoursesList = getInfoCurricularCourses(
                    professorship.getExecutionCourse());

            DetailedProfessorship detailedProfessorship = new DetailedProfessorship();

            Boolean isResponsible = Boolean.valueOf(professorship.getResponsibleFor());

            if ((teacherType.intValue() == 1) && (!isResponsible.booleanValue())) {
                return null;
            }

            detailedProfessorship.setResponsibleFor(isResponsible);

            detailedProfessorship.setInfoProfessorship(infoProfessorShip);
            detailedProfessorship.setExecutionCourseCurricularCoursesList(executionCourseCurricularCoursesList);

            return detailedProfessorship;
        }

        private List getInfoCurricularCourses(ExecutionCourse executionCourse) {

            List infoCurricularCourses = (List) CollectionUtils
                    .collect(executionCourse.getAssociatedCurricularCoursesSet(), new Transformer() {

                        @Override
                        public Object transform(Object input) {

                            CurricularCourse curricularCourse = (CurricularCourse) input;

                            InfoCurricularCourse infoCurricularCourse = InfoCurricularCourse
                                    .newInfoFromDomain(curricularCourse);
                            return infoCurricularCourse;
                        }
                    });
            return infoCurricularCourses;
        }
    });

    return detailedProfessorshipList;
}

From source file:net.sf.wickedshell.facade.descriptor.ExtensionShellDescriptor.java

/**
 * Constructor for ExtensionShellDescriptor.
 * // w  w w. ja  va  2s .  c  o  m
 * @param extension
 *            The <code>IConfigurationElement</code> representing the
 *            <code>IShellDescriptor</code>
 */
@SuppressWarnings("unchecked")
public ExtensionShellDescriptor(IConfigurationElement configurationElement) {
    super();
    shellName = configurationElement.getAttribute(SHELL_NAME_ATTRIBUTE);
    shellExecutable = configurationElement.getAttribute(EXECUTABLE_ATTRIBUTE);
    characterEncoding = configurationElement.getAttribute(CHARACTER_ENCODING_ATTRIBUTE);
    String lineFeed = configurationElement.getAttribute(LINE_FEED_ATTRIBUTE);
    StringBuffer buffer = new StringBuffer();
    if (lineFeed.equals(DomainID.CR_LF_VALUE)) {
        buffer.append(SWT.CR);
    }
    buffer.append(SWT.LF);
    lineFeedString = buffer.toString();
    pathDelimiter = configurationElement.getAttribute(PATH_DELIMITER_ATTRIBUTE).replace(BLANK_SUBSTITUTE, ' ');

    String pathSeparatorDefinition = configurationElement.getAttribute(PATH_SEPARATOR_ATTRIBUTE);
    if (pathSeparatorDefinition.equals(DomainID.SLASH_VALUE)) {
        pathSeparator = "/";
    } else {
        pathSeparator = "\\";
    }
    systemPathSeparator = configurationElement.getAttribute(SYSTEM_PATH_SEPARATOR_ATTRIBUTE);
    hasCustomRoot = Boolean.valueOf(configurationElement.getAttribute(HAS_CUSTOM_ROOT_ATTRIBUTE))
            .booleanValue();
    if (hasCustomRoot) {
        binariesDirectory = configurationElement.getAttribute(BINARIES_DIRECTORY_ATTRIBUTE);
    } else {
        binariesDirectory = new String();
    }
    commandDelimiter = configurationElement.getAttribute(COMMAND_DELIMITER_ATTRIBUTE);
    isUILineFeedProvided = Boolean
            .valueOf(configurationElement.getAttribute(IS_UI_LINE_FEED_PROVIDED_ATTRIBUTE)).booleanValue();
    isExecutedComandProvided = Boolean
            .valueOf(configurationElement.getAttribute(IS_EXECUTED_COMMAND_PROVIDED_ATTIBUTE)).booleanValue();
    id = configurationElement.getAttribute(SHELL_ID_ATTRIBUTE);
    executableFiles = (IExecutableFile[]) CollectionUtils.collect(
            Arrays.asList(configurationElement.getChildren(EXECUTABLE_FILES_ATTRIBUTE)), new Transformer() {
                /**
                * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
                */
                public Object transform(Object object) {
                    IConfigurationElement executableFileElement = (IConfigurationElement) object;
                    String extension = executableFileElement.getAttribute(EXTENSION_ATTRIBUTE);
                    String description = executableFileElement.getAttribute(DESCRIPTION_ATTRIBUTE);
                    Boolean isBatchFile = Boolean
                            .valueOf(executableFileElement.getAttribute(IS_BATCH_FILE_ATTRIBUTE));
                    return IExecutableFile.Factory.newInstance(description, extension,
                            isBatchFile.booleanValue());
                }
            }).toArray(new IExecutableFile[0]);
    supportingOperatingSystems = (String[]) CollectionUtils.collect(
            Arrays.asList(configurationElement.getChildren(SUPPORTING_OS_ATTRIBUTE)), new Transformer() {
                /**
                * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
                */
                public Object transform(Object object) {
                    IConfigurationElement executableFileElement = (IConfigurationElement) object;
                    return executableFileElement.getAttribute(OS_NAME_ATTRIBUTE);
                }
            }).toArray(new String[0]);
    externalShellInvoker = null;
    if (configurationElement.getAttribute(EXTERNAL_SHELL_INVOKER_ATTRIBUTE) != null) {
        try {
            externalShellInvoker = (IExternalShellInvoker) configurationElement
                    .createExecutableExtension(EXTERNAL_SHELL_INVOKER_ATTRIBUTE);
        } catch (CoreException exception) {
            shellLogger.error(exception.getMessage(), exception);
        }
    }
    environmentalValueProvider = null;
    if (configurationElement.getAttribute(ENVIRONMENTAL_VALUE_PROVIDER_ATTRIBUTE) != null) {
        try {
            environmentalValueProvider = (IEnvironmentalValueProvider) configurationElement
                    .createExecutableExtension(ENVIRONMENTAL_VALUE_PROVIDER_ATTRIBUTE);
        } catch (CoreException exception) {
            shellLogger.error(exception.getMessage(), exception);
        }
    }
    commandProvider = null;
    if (configurationElement.getAttribute(COMMAND_PROVIDER_ATTRIBUTE) != null) {
        try {
            commandProvider = (ICommandProvider) configurationElement
                    .createExecutableExtension(COMMAND_PROVIDER_ATTRIBUTE);
        } catch (CoreException exception) {
            shellLogger.error(exception.getMessage(), exception);
        }
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.service.StudySiteService.java

@SuppressWarnings({ "unchecked" })
public List<List<StudySite>> refreshStudySitesForStudies(final List<Study> studies) {
    if (studies == null) {
        throw new IllegalArgumentException(STUDY_IS_NULL);
    }/*www.j  a va 2 s  . c o  m*/

    List<List<StudySite>> refreshed = new ArrayList<List<StudySite>>();

    final Map<String, List<Site>> sites = buildProvidedSiteMap();
    List<List<StudySite>> allProvided = studySiteConsumer.refreshSites(studies);

    for (int i = 0; i < studies.size(); i++) {
        final Study study = studies.get(i);
        List<StudySite> provided = allProvided.get(i);
        if (provided == null) {
            provided = EMPTY_LIST;
        }

        Collection<StudySite> qualifying = CollectionUtils.select(provided, new Predicate() {
            public boolean evaluate(Object o) {
                StudySite potential = (StudySite) o;

                // Verify Study Provider and StudySite Provider Are Equal
                if (study.getProvider() == null || !study.getProvider().equals(potential.getProvider())) {
                    return false;
                }

                // Verify Site Provider and StudySite Provider Are Equal (And Site Exists)
                List<Site> providerSpecific = sites.get(potential.getProvider());
                if (providerSpecific == null || !providerSpecific.contains(potential.getSite())) {
                    return false;
                }

                // Verify new study site
                Site site = providerSpecific.get(providerSpecific.indexOf(potential.getSite()));
                if (StudySite.findStudySite(study, site) != null) {
                    return false;
                }

                return true;
            }
        });

        logger.debug("Found " + qualifying.size() + " new study sites from the provider.");
        for (StudySite u : qualifying) {
            logger.debug("- " + u);
        }

        // StudySites returned from provider are proxied by CGLIB.  This causes problems when saving,
        // so we want to create a fresh StudySite instance. Also, we want to populate the site with a
        // valid Site from SiteService.
        Collection<StudySite> enhanced = CollectionUtils.collect(qualifying, new Transformer() {
            public Object transform(Object o) {
                StudySite s = (StudySite) o;
                List<Site> providerSpecific = sites.get(s.getProvider());
                Site site = providerSpecific.get(providerSpecific.indexOf(s.getSite()));

                StudySite e = new StudySite(study, site);
                e.getStudy().addStudySite(e);
                e.getSite().addStudySite(e);
                e.setProvider(s.getProvider());
                e.setLastRefresh(s.getLastRefresh());
                return e;
            }
        });

        for (StudySite s : enhanced) {
            studySiteDao.save(s);
        }

        refreshed.add(study.getStudySites());
    }

    return refreshed;
}

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

/**
 * @see eionet.meta.dao.ISchemaDAO#listForSchemaSets(List<SchemaSets>)
 *//*www  .  j  a  v  a  2  s  .  co m*/
@Override
public List<Schema> listForSchemaSets(List<SchemaSet> schemaSets) {

    Map<String, Object> params = new HashMap<String, Object>();
    StringBuilder sql = new StringBuilder("select SCHEMA_ID from T_SCHEMA ");
    if (schemaSets != null && schemaSets.size() > 0) {
        sql.append("where SCHEMA_SET_ID IN ( :schemaSetIds) ");
        params.put("schemaSetIds",
                CollectionUtils.collect(schemaSets, new BeanToPropertyValueTransformer("id")));
    }
    sql.append("order by FILENAME");

    List<Integer> schemaIdList = getNamedParameterJdbcTemplate().queryForList(sql.toString(), params,
            Integer.class);

    return getSchemas(schemaIdList);
}

From source file:com.denimgroup.threadfix.service.DefaultConfigServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public List<String> getDisplayNamesFromExportFields(List<CSVExportField> exportFields) {

    return (List<String>) CollectionUtils.collect(exportFields,
            new BeanToPropertyValueTransformer("displayName"));

}