Example usage for org.apache.commons.collections Transformer Transformer

List of usage examples for org.apache.commons.collections Transformer Transformer

Introduction

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

Prototype

Transformer

Source Link

Usage

From source file:com.alkacon.opencms.v8.list.CmsListConfiguration.java

/**
 * Returns a lazy initialized map with the mapped entries of the collected resources.<p>
 * /*from w ww. j a  va 2s .  co m*/
 * @return a lazy initialized map
 */
@SuppressWarnings("unchecked")
public Map<Object, CmsListEntry> getMappedEntry() {

    if (m_mappedEntries == null) {
        m_mappedEntries = LazyMap.decorate(new HashMap<Object, CmsListEntry>(), new Transformer() {

            /**
             * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
             */
            public Object transform(Object input) {

                CmsListEntry entry = null;

                try {
                    CmsXmlContent content;
                    if (input instanceof CmsXmlContent) {
                        content = (CmsXmlContent) input;
                    } else {
                        CmsResource resource = (CmsResource) input;
                        content = CmsXmlContentFactory.unmarshal(getCmsObject(),
                                getCmsObject().readFile(resource));
                    }

                    if (getMapping() != null) {
                        entry = getMapping().getEntryFromXmlContent(getCmsObject(), content,
                                getRequestContext().getLocale());
                    }
                } catch (CmsException ex) {
                    // noop
                }

                return entry;
            }
        });
    }
    return m_mappedEntries;
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.coordinator.degreeCurricularPlanManagement.ReadCurriculumHistoryByCurricularCourseCodeAndExecutionYearName.java

private static InfoCurriculum createInfoCurriculum(Curriculum curriculum, List allCurricularCourseScopes,
        List allExecutionCourses) {

    InfoCurriculum infoCurriculum = InfoCurriculumWithInfoCurricularCourse.newInfoFromDomain(curriculum);

    List scopes = new ArrayList();
    CollectionUtils.collect(allCurricularCourseScopes, new Transformer() {
        @Override/*from   w ww.  j a  v  a2s . c o m*/
        public Object transform(Object arg0) {
            CurricularCourseScope curricularCourseScope = (CurricularCourseScope) arg0;

            return InfoCurricularCourseScope.newInfoFromDomain(curricularCourseScope);
        }
    }, scopes);
    infoCurriculum.getInfoCurricularCourse().setInfoScopes(scopes);

    List<InfoExecutionCourse> infoExecutionCourses = new ArrayList<InfoExecutionCourse>();
    Iterator iterExecutionCourses = allExecutionCourses.iterator();
    while (iterExecutionCourses.hasNext()) {
        ExecutionCourse executionCourse = (ExecutionCourse) iterExecutionCourses.next();
        infoExecutionCourses.add(InfoExecutionCourse.newInfoFromDomain(executionCourse));
    }
    infoCurriculum.getInfoCurricularCourse().setInfoAssociatedExecutionCourses(infoExecutionCourses);
    return infoCurriculum;
}

From source file:info.magnolia.freemarker.models.ContentModel.java

@Override
public TemplateCollectionModel keys() throws TemplateModelException {
    final Iterator it = IteratorUtils.transformedIterator(content.getNodeDataCollection().iterator(),
            new Transformer() {
                @Override//from  w w w  .  j  a v  a 2 s.  c o  m
                public Object transform(Object input) {
                    return ((NodeData) input).getName();
                }
            });
    return new SimpleCollection(it);
}

From source file:com.base2.kagura.core.ExportHandler.java

/**
 * Takes the output and transforms it into a csv file.
 * @param out Output stream./*ww  w .j  a  va2s . c o 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: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());/*  w w w. java 2 s . c  o m*/
    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.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// w  w w . ja v a2s .c o  m
                    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.projity.util.DataUtils.java

public static String stringList(Collection collection) {
    return StringList.list(collection, new Transformer() {
        public Object transform(Object arg0) {
            return "" + ((HasKey) arg0).getId();
        }/*w  w  w. ja  v a2  s.  c om*/
    });
}

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//from   www.j  ava2  s  .com
        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 w w.j  av  a2s .c om*/
        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 {/*  www .ja v a  2 s.c o  m*/
        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);
    }
}