List of usage examples for org.apache.commons.collections CollectionUtils collect
public static Collection collect(Iterator inputIterator, Transformer transformer)
From source file:net.sourceforge.fenixedu.dataTransferObject.InfoMasterDegreeThesisDataVersionWithGuiders.java
/** * @param masterDegreeThesisDataVersion//w ww . ja va2 s. c o m * @return */ private List<InfoTeacher> copyTeachers(Collection<Teacher> teachers) { return (List<InfoTeacher>) CollectionUtils.collect(teachers, new Transformer() { @Override public Object transform(Object arg0) { Teacher teacher = (Teacher) arg0; return InfoTeacher.newInfoFromDomain(teacher); } }); }
From source file:com.googlecode.tapestry5cayenne.services.TestBindingAndGridDataSourceCoercion.java
public void testPersistentClassToGridDataSourceCoercion() { TypeCoercer coercer = registry.getService(TypeCoercer.class); GridDataSource ds = coercer.coerce(Painting.class, GridDataSource.class); List<SortConstraint> constraints = Collections.emptyList(); ds.prepare(0, ds.getAvailableRows() - 1, constraints); final List<Painting> paints = new ArrayList<Painting>(); CollectionUtils.collect(data, new Transformer() { public Object transform(Object input) { paints.addAll(((Artist) input).getPaintingList()); return null; }//from w ww.j av a2 s . c o m }); new Ordering(Painting.TITLE_PROPERTY, SortOrder.ASCENDING).orderList(paints); assertEquals(ds.getAvailableRows(), paints.size()); for (int i = 0; i < paints.size(); i++) { assertEquals(((Painting) ds.getRowValue(i)).getObjectId(), paints.get(i).getObjectId()); } }
From source file:com.fsoft.bn.service.impl.BNJournalArticleLocalServiceImpl.java
@SuppressWarnings("unchecked") public NewsPage getNews(PortletRequest req, String structId, long categoryId, int numPerPage, int currentPageNum, boolean paging, List<KeyValuePair> sortbys) { int totalPageNum = 1; if (currentPageNum < 1) { currentPageNum = 1;//from ww w . jav a 2 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:com.jaspersoft.jasperserver.repository.test.RepositoryServiceDependentResourcesTest.java
@Test public void shouldFindFirstFiveDependantReportsForDataSource() { assertNotNull("RepositoryService service is not wired.", getRepositoryService()); assertNotNull("SearchCriteriaFactory service is not wired.", searchCriteriaFactory); String uri = "/datasources/JServerJNDIDS"; List<ResourceLookup> resources = getRepositoryService().getDependentResources(null, uri, searchCriteriaFactory, 0, 5); assertEquals("Should find 5 dependant resources.", 5, resources.size()); assertEquals("All resources should be lookup's.", 5, CollectionUtils.countMatches(resources, PredicateUtils.instanceofPredicate(ResourceLookup.class))); String sortOrder = ArrayUtils.toString( CollectionUtils.collect(resources, TransformerUtils.invokerTransformer("getURIString")).toArray()); assertEquals("Resources should be sorted in order.", expectedOrderForTopFive, sortOrder); }
From source file:com.base2.kagura.core.ExportHandler.java
/** * Takes the output and transforms it into a csv file. * @param out Output stream.//from w w w .j ava 2 s. co m * @param rows Rows of data from reporting-core * @param columns Columns to list on report */ public void generateCsv(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) { ICsvMapWriter csvWriter = null; try { csvWriter = new CsvMapWriter(new OutputStreamWriter(out), CsvPreference.STANDARD_PREFERENCE); // the header elements are used to map the bean values to each column (names must match) String[] header = new String[] {}; CellProcessor[] processors = new CellProcessor[] {}; if (columns != null) { header = (String[]) CollectionUtils.collect(columns, new Transformer() { @Override public Object transform(Object input) { ColumnDef column = (ColumnDef) input; return column.getName(); } }).toArray(new String[0]); processors = (CellProcessor[]) CollectionUtils.collect(columns, new Transformer() { @Override public Object transform(Object input) { return new Optional(); } }).toArray(new CellProcessor[0]); } else if (rows.size() > 0) { header = new ArrayList<String>(rows.get(0).keySet()).toArray(new String[0]); processors = (CellProcessor[]) CollectionUtils.collect(rows.get(0).keySet(), new Transformer() { @Override public Object transform(Object input) { return new Optional(); } }).toArray(new CellProcessor[0]); } if (header.length > 0) csvWriter.writeHeader(header); if (rows != null) for (Map<String, Object> row : rows) { csvWriter.write(row, header, processors); } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } }
From source file:net.sourceforge.fenixedu.dataTransferObject.guide.reimbursementGuide.InfoReimbursementGuide.java
public void copyFromDomain(ReimbursementGuide reimbursementGuide) { super.copyFromDomain(reimbursementGuide); if (reimbursementGuide != null) { setCreationDate(reimbursementGuide.getCreationDate()); setInfoGuide(InfoGuideWithPersonAndExecutionDegreeAndDegreeCurricularPlanAndDegreeAndContributor .newInfoFromDomain(reimbursementGuide.getGuide())); setNumber(reimbursementGuide.getNumber()); List infoReimbursementGuideEntries = (List) CollectionUtils .collect(reimbursementGuide.getReimbursementGuideEntriesSet(), new Transformer() { @Override/*from www . j a v a 2s . c om*/ public Object transform(Object arg0) { ReimbursementGuideEntry reimbursementGuideEntry = (ReimbursementGuideEntry) arg0; return InfoReimbursementGuideEntry.newInfoFromDomain(reimbursementGuideEntry); } }); setInfoReimbursementGuideEntries(infoReimbursementGuideEntries); List infoReimbursementGuideSituations = (List) CollectionUtils .collect(reimbursementGuide.getReimbursementGuideSituationsSet(), new Transformer() { @Override public Object transform(Object arg0) { ReimbursementGuideSituation reimbursementGuideSituation = (ReimbursementGuideSituation) arg0; return InfoReimbursementGuideSituation.newInfoFromDomain(reimbursementGuideSituation); } }); setInfoReimbursementGuideSituations(infoReimbursementGuideSituations); } }
From source file:com.abiquo.abiserver.pojo.user.User.java
@SuppressWarnings("unchecked") public static User create(final UserDto dto, final Enterprise enterprise, final Role role) { User user = new User(); user.setId(dto.getId());//from w w w. ja v a 2 s . c om user.setEnterprise(enterprise); user.setRole(role); user.setUser(dto.getNick()); user.setName(dto.getName()); user.setSurname(dto.getSurname()); user.setDescription(dto.getDescription()); user.setEmail(dto.getEmail()); user.setLocale(dto.getLocale()); user.setPass(dto.getPassword()); user.setActive(dto.isActive()); user.setAuthType( StringUtils.isBlank(dto.getAuthType()) ? AuthType.ABIQUO : AuthType.valueOf(dto.getAuthType())); if (!StringUtils.isEmpty(dto.getAvailableVirtualDatacenters())) { String[] ids = dto.getAvailableVirtualDatacenters().split(","); Collection<Integer> idsI = CollectionUtils.collect(Arrays.asList(ids), new Transformer() { @Override public Object transform(final Object input) { return Integer.valueOf(input.toString()); } }); user.setAvailableVirtualDatacenters(idsI.toArray(new Integer[idsI.size()])); } else { user.setAvailableVirtualDatacenters(new Integer[] {}); } user.setCreationDate(Calendar.getInstance().getTime()); return user; }
From source file:net.sourceforge.fenixedu.applicationTier.Servico.publico.teachersBody.ReadProfessorshipsAndResponsibilitiesByExecutionDegreeAndExecutionPeriod.java
protected static List getDetailedProfessorships(List professorships, final List responsibleFors, final Integer teacherType) { List detailedProfessorshipList = (List) CollectionUtils.collect(professorships, new Transformer() { @Override// w w w . j a v 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.sourceforge.fenixedu.applicationTier.Servico.resourceAllocationManager.SearchExecutionCourses.java
private List<InfoExecutionCourse> fillInfoExecutionCourses(final AcademicInterval academicInterval, List<ExecutionCourse> executionCourses) { List<InfoExecutionCourse> result; result = (List<InfoExecutionCourse>) CollectionUtils.collect(executionCourses, new Transformer() { @Override//from w ww.j a v a 2 s .co m public Object transform(Object arg0) { InfoExecutionCourse infoExecutionCourse = null; infoExecutionCourse = getOccupancyLevels(arg0); getTeacherReportInformation(infoExecutionCourse, arg0); return infoExecutionCourse; } private void getTeacherReportInformation(InfoExecutionCourse infoExecutionCourse, Object arg0) { ExecutionCourse executionCourse = (ExecutionCourse) arg0; if (executionCourse.getAssociatedCurricularCoursesSet() != null) { InfoSiteEvaluationStatistics infoSiteEvaluationStatistics = new InfoSiteEvaluationStatistics(); int enrolledInCurricularCourse = 0; int evaluated = 0; int approved = 0; Iterator<CurricularCourse> iter = executionCourse.getAssociatedCurricularCoursesSet() .iterator(); while (iter.hasNext()) { CurricularCourse curricularCourse = iter.next(); final List<Enrolment> enroled = curricularCourse .getEnrolmentsByAcademicInterval(academicInterval); enrolledInCurricularCourse += enroled.size(); evaluated = Enrolment.countEvaluated(enroled); approved = Enrolment.countApproved(enroled); } infoSiteEvaluationStatistics.setEnrolled(Integer.valueOf(enrolledInCurricularCourse)); infoSiteEvaluationStatistics.setEvaluated(Integer.valueOf(evaluated)); infoSiteEvaluationStatistics.setApproved(Integer.valueOf(approved)); infoExecutionCourse.setInfoSiteEvaluationStatistics(infoSiteEvaluationStatistics); } } private InfoExecutionCourse getOccupancyLevels(Object arg0) { InfoExecutionCourse infoExecutionCourse; ExecutionCourse executionCourse = (ExecutionCourse) arg0; Integer theoreticalCapacity = Integer.valueOf(0); Integer theoPraticalCapacity = Integer.valueOf(0); Integer praticalCapacity = Integer.valueOf(0); Integer labCapacity = Integer.valueOf(0); Integer doubtsCapacity = Integer.valueOf(0); Integer reserveCapacity = Integer.valueOf(0); Integer semCapacity = Integer.valueOf(0); Integer probCapacity = Integer.valueOf(0); Integer fieldCapacity = Integer.valueOf(0); Integer trainCapacity = Integer.valueOf(0); Integer tutCapacity = Integer.valueOf(0); Set<Shift> shifts = executionCourse.getAssociatedShifts(); Iterator<Shift> iterator = shifts.iterator(); while (iterator.hasNext()) { Shift shift = iterator.next(); if (shift.containsType(ShiftType.TEORICA)) { theoreticalCapacity = Integer .valueOf(theoreticalCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.TEORICO_PRATICA)) { theoPraticalCapacity = Integer .valueOf(theoPraticalCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.DUVIDAS)) { doubtsCapacity = Integer.valueOf(doubtsCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.LABORATORIAL)) { labCapacity = Integer.valueOf(labCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.PRATICA)) { praticalCapacity = Integer .valueOf(praticalCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.RESERVA)) { reserveCapacity = Integer .valueOf(reserveCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.SEMINARY)) { semCapacity = Integer.valueOf(semCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.PROBLEMS)) { probCapacity = Integer.valueOf(probCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.FIELD_WORK)) { fieldCapacity = Integer.valueOf(fieldCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.TRAINING_PERIOD)) { trainCapacity = Integer.valueOf(trainCapacity.intValue() + shift.getLotacao().intValue()); } else if (shift.containsType(ShiftType.TUTORIAL_ORIENTATION)) { tutCapacity = Integer.valueOf(tutCapacity.intValue() + shift.getLotacao().intValue()); } } infoExecutionCourse = InfoExecutionCourse.newInfoFromDomain(executionCourse); List<Integer> capacities = new ArrayList<Integer>(); if (theoreticalCapacity.intValue() != 0) { capacities.add(theoreticalCapacity); } if (theoPraticalCapacity.intValue() != 0) { capacities.add(theoPraticalCapacity); } if (doubtsCapacity.intValue() != 0) { capacities.add(doubtsCapacity); } if (labCapacity.intValue() != 0) { capacities.add(labCapacity); } if (praticalCapacity.intValue() != 0) { capacities.add(praticalCapacity); } if (reserveCapacity.intValue() != 0) { capacities.add(reserveCapacity); } if (semCapacity.intValue() != 0) { capacities.add(semCapacity); } if (probCapacity.intValue() != 0) { capacities.add(probCapacity); } if (fieldCapacity.intValue() != 0) { capacities.add(fieldCapacity); } if (trainCapacity.intValue() != 0) { capacities.add(trainCapacity); } if (tutCapacity.intValue() != 0) { capacities.add(tutCapacity); } int total = 0; if (!capacities.isEmpty()) { total = (Collections.min(capacities)).intValue(); } if (total == 0) { infoExecutionCourse.setOccupancy(Double.valueOf(-1)); } else { infoExecutionCourse.setOccupancy(NumberUtils.formatNumber(Double.valueOf( (Double.valueOf(executionCourse.getAttendsSet().size()).floatValue() * 100 / total)), 1)); } return infoExecutionCourse; } }); return result; }
From source file:de.hybris.platform.integration.cis.payment.cronjob.DefaultCisFraudReportJob.java
@Override public PerformResult perform(final CisFraudReportCronJobModel cronJob) { try {/* w w w .j av a2s .c om*/ final CisFraudReportRequest request = new CisFraudReportRequest(); final Date requestStartTime = getLastCronJobEndTime(); final Date requestEndTime = new Date(); final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, -24); if (requestStartTime.before(calendar.getTime())) { LOG.error("CyberSource report time range is only valid for the past 24 hours"); return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED); } request.setStartDateTime(requestStartTime); request.setEndDateTime(requestEndTime); final RestResponse<CisFraudReportResult> response = getOndemandHystrixCommandFactory().newCommand( getHystrixCommandConfig(), new HystrixExecutable<RestResponse<CisFraudReportResult>>() { @Override public RestResponse<CisFraudReportResult> runEvent() { return getFraudClient().generateFraudReport(cronJob.getCode(), request); } @Override public RestResponse<CisFraudReportResult> fallbackEvent() { return null; } @Override public RestResponse<CisFraudReportResult> defaultEvent() { return null; } }).execute(); if (response != null) { final List<CisFraudTransactionResult> transactionResults = response.getResult().getTransactions(); if (CollectionUtils.isNotEmpty(transactionResults)) { //Retrieve all the transactionIds from each of the transaction results final List<String> transactionIds = (List<String>) CollectionUtils.collect(transactionResults, new Transformer() { @Override public Object transform(final Object o) { final CisFraudTransactionResult result = (CisFraudTransactionResult) o; return result.getClientAuthorizationId(); } }); final List<PaymentTransactionEntryModel> transactionEntries = getPaymentTransactionEntryModels( transactionIds); //For each transaction result, set the transaction from it's corresponding order and fire the business process event for (final CisFraudTransactionResult transactionResult : transactionResults) { final PaymentTransactionEntryModel transactionEntry = (PaymentTransactionEntryModel) CollectionUtils .find(transactionEntries, new Predicate() { @Override public boolean evaluate(final Object o) { return ((PaymentTransactionEntryModel) o).getCode() .equalsIgnoreCase(transactionResult.getClientAuthorizationId()); } }); if (transactionEntry != null && transactionEntry.getPaymentTransaction() != null && transactionEntry.getPaymentTransaction().getOrder() != null) { final PaymentTransactionModel transaction = transactionEntry.getPaymentTransaction(); final String guid = transaction.getOrder().getGuid(); final PaymentTransactionEntryModel newTransactionEntry = getTransactionResultConverter() .convert(transactionResult); getPaymentService().setPaymentTransactionReviewResult(newTransactionEntry, guid); } } } //Set the LastFraudReportEndTime for use the next time this cron job runs cronJob.setLastFraudReportEndTime(requestEndTime); getModelService().save(cronJob); return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED); } return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED); } catch (final Exception e) { LOG.warn(String.format("Error occurred while processing the fraud reports [%s]", e.getLocalizedMessage())); if (LOG.isDebugEnabled()) { LOG.debug("Error occurred while processing the fraud reports", e); } return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED); } }