Example usage for org.hibernate.criterion Projections distinct

List of usage examples for org.hibernate.criterion Projections distinct

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections distinct.

Prototype

public static Projection distinct(Projection projection) 

Source Link

Document

Create a distinct projection from a projection.

Usage

From source file:eu.jangos.manager.controller.AccountService.java

License:Apache License

/**
 * Provides access to the list of all accounts matching the parameters.
 *
 * The DateFilter works the same way: - NONE does not apply any filter. -
 * BEFORE & AFTER uses only the "From" date as filter. - BETWEEN uses both
 * "From" & "To" dates as filters./*w w w .  ja  v  a2s  . co m*/
 *
 * @param name The name of the accounts to be found. Can contain %.
 * @param createdFilter The filter type for the creation date.
 * @param createdFrom The first creation date filter.
 * @param createdTo The second creation date filter.
 * @param loginFilter The filter type for the login date.
 * @param loginFrom The first login date filter.
 * @param loginTo The second login date filter.
 * @param locked The filter type for the lock value.
 * @param banned The filter type for the ban value.
 * @param online The filter type for the online value.
 * @param locale The locale on which this search must filter.
 * @param realm The locale on which this search must filter.
 * @return A List of Accounts matching the criterias.
 */
public List<Account> getAllAccounts(String name, DateType createdFilter, Date createdFrom, Date createdTo,
        DateType loginFilter, Date loginFrom, Date loginTo, BooleanType locked, BooleanType banned,
        BooleanType online, Locale locale, Realm realm) {

    boolean error = false;
    String message = "You must enter the following parameters:\n";

    // Checking name input.
    if (name == null || name.isEmpty()) {
        logger.error("The parameter name is null or empty");
        message += "- A name\n";
        error = true;
    }

    // Checking dates input.
    if ((createdFilter != DateType.NONE && createdFrom == null)
            || (createdFilter == DateType.BETWEEN && createdTo == null)
            || (loginFilter != DateType.NONE && loginFrom == null)
            || (loginFilter == DateType.BETWEEN && loginTo == null)) {
        logger.error("A date filter has been requested while the date values are incorrect");
        message += "- Valid dates when selecting a date filter\n";
        error = true;
    }

    if (error) {
        throw new IllegalArgumentException(message);
    }

    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Criteria query = session.createCriteria(Account.class, "acc");

        query.setFetchMode("locale", FetchMode.JOIN);
        query.setFetchMode("realm", FetchMode.JOIN);

        query.add(Restrictions.like("name", name));

        // This ban check is generating 2 SQL queries while, in SQL, you could do it in one.
        // Limitations of the criteria API.
        switch (banned) {
        case TRUE:
            // First, we get the list of IDs for the accounts that are banned.
            Criteria getBannedQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.eq("ban.active", true));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getBannedQuery.list()));
            break;
        case FALSE:
            // First, we get the list of ID for the accounts that are not banned.
            Criteria getNotBanQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.or(Restrictions.eq("ban.active", false),
                            Restrictions.isNull("ban.active")));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getNotBanQuery.list()));
            break;
        }

        // We add the realm restrictions, if it applies.
        if (!realm.getName().equals("ALL")) {
            query.add(Restrictions.eq("realm", realm));
        }

        // We add the locale restrictions, if it applies.
        if (!locale.getLocale().equals("ALL")) {
            query.add(Restrictions.eq("locale", locale));
        }

        query = Utils.applyDateFilter(query, "creation", createdFilter, createdFrom, createdTo);
        query = Utils.applyDateFilter(query, "lastlogin", loginFilter, loginFrom, loginTo);
        query = Utils.applyBooleanFilter(query, "locked", locked);
        query = Utils.applyBooleanFilter(query, "online", online);

        return query.list();
    } catch (HibernateException he) {
        logger.error("There was an error connecting to the database.");
        return null;
    }
}

From source file:eu.optimis.common.trec.db.ip.TrecIP2SPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<SpInfo> getDistinctSpIDs() throws Exception {
    Session session = null;/*w w w .jav  a2  s  .c  o m*/
    List<SpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(IpToSp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("spInfo"))));
        //         criteria.setMaxResults(MAX_RESULTS);
        results = (List<SpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:eu.optimis.common.trec.db.ip.TrecSP2IPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IpInfo> getDistinctIpIDs() throws Exception {
    Session session = null;//from  w ww.  j  a va2s .c  om
    List<IpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(SpToIp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("ipInfo"))));
        results = (List<IpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:eu.optimis.common.trec.db.sp.TrecSP2IPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IpInfo> getDistinctIpIDs() throws Exception {
    Session session = null;/*  ww w  . java  2  s .c  o  m*/
    List<IpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(SpToIp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("ipInfo"))));
        //         criteria.setMaxResults(MAX_RESULTS);
        results = (List<IpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:fr.insalyon.creatis.vip.application.server.dao.hibernate.SimulationStatsData.java

License:Open Source License

@Override
public List<String> getClasses(List<String> workflowsId) throws WorkflowsDBDAOException {
    List<String> result = new ArrayList<String>();
    try {//w ww.ja v a  2s  .c o m
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Workflow.class);
        criteria.add(Restrictions.in("id", workflowsId));
        criteria.setProjection(Projections.distinct(Projections.property("applicationClass")));
        result = (List<String>) criteria.list();
        session.getTransaction().commit();
        session.close();
        return result;
    } catch (HibernateException ex) {
        throw new WorkflowsDBDAOException(ex);
    }

}

From source file:fsl.ta.toms.roms.dao.impl.ReportDAOImpl.java

@SuppressWarnings("unchecked")
@Override/*from  www  . j a v  a 2 s  .  c o  m*/
public RoadOperationsStatisticsReportBO performanceSaisticsReport(
        PerformanceStatisticsReportCriteriaBO reportCriteria, String userName, String userRegion,
        ReportDisplayInformationDAOImpl reportDisplayInformation) {
    /* Specify search criteria for report */
    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(RoadOperationDO.class, "roadOp");

    /* List of all aliases used */
    criteria.createAlias("roadOp.category", "category");

    /* _______________________ */

    /* Apply filters to search results */
    Criterion mainCriteron = Restrictions.or(
            Restrictions.between("roadOp.scheduledStartDtime",
                    DateUtils.searchDateFormater(reportCriteria.getStartDate(), DateUtils.SEARCHDATETYPE.START),
                    DateUtils.searchDateFormater(reportCriteria.getEndDate(), DateUtils.SEARCHDATETYPE.END)),
            Restrictions.between("roadOp.scheduledEndDtime",
                    DateUtils.searchDateFormater(reportCriteria.getStartDate(), DateUtils.SEARCHDATETYPE.START),
                    DateUtils.searchDateFormater(reportCriteria.getEndDate(), DateUtils.SEARCHDATETYPE.END)));

    if (StringUtil.isSet(reportCriteria.getTAOfficeRegion())) {
        mainCriteron = Restrictions.and(mainCriteron,
                Restrictions.eq("roadOp.officeLocCode", reportCriteria.getTAOfficeRegion().trim()));
    }

    if (StringUtil.isSet(reportCriteria.getOperationCategory())) {
        mainCriteron = Restrictions.and(mainCriteron,
                Restrictions.eq("category.categoryId", reportCriteria.getOperationCategory().trim()));
    }

    if (reportCriteria.getTeamLeadId() != null && !reportCriteria.getTeamLeadId().isEmpty()) {
        List<Integer> roadOpIds = this.getListOfRoadOpIdsBasedOnTeamLead(reportCriteria.getTeamLeadId());

        if (roadOpIds != null)
            mainCriteron = Restrictions.and(mainCriteron, Restrictions.in("roadOp.roadOperationId", roadOpIds));
    }

    if (StringUtil.isSet(reportCriteria.getTeamLeadTRN())) {
        List<Integer> roadOpIds = this.getListOfRoadOpIdsBasedOnTeamLeadTRN(reportCriteria.getTeamLeadTRN());

        if (roadOpIds != null)
            mainCriteron = Restrictions.and(mainCriteron, Restrictions.in("roadOp.roadOperationId", roadOpIds));
    }

    if (StringUtil.isSet(reportCriteria.getRoadOperationName())) {
        mainCriteron = Restrictions.and(mainCriteron,
                Restrictions
                        .like("roadOp.operationName", reportCriteria.getRoadOperationName(), MatchMode.ANYWHERE)
                        .ignoreCase());
    }

    if (reportCriteria.getRoadOperationId() != null && reportCriteria.getRoadOperationId() > 0) {
        mainCriteron = Restrictions.and(mainCriteron,
                Restrictions.eq("roadOp.roadOperationId", reportCriteria.getRoadOperationId()));
    }

    if (StringUtil.isSet(reportCriteria.getTAStaffId()) || StringUtil.isSet(reportCriteria.getTAStaffTRN())) {
        Criteria criteriaTA = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                .createCriteria(TAStaffDO.class, "ta");

        criteriaTA.createAlias("ta.person", "taPerson");

        if (StringUtil.isSet(reportCriteria.getTAStaffId()))
            criteriaTA.add(Restrictions.eq("ta.staffId", reportCriteria.getTAStaffId().trim()));

        if (StringUtil.isSet(reportCriteria.getTAStaffTRN()))
            criteriaTA.add(Restrictions.eq("taPerson.trnNbr", reportCriteria.getTAStaffTRN().trim()));

        TAStaffDO taStaff = null;

        List<TAStaffDO> staffList = criteriaTA.list();

        if (!staffList.isEmpty())
            taStaff = staffList.get(0);

        if (taStaff != null) {

            /* Get a list of all assigned persons for a road operation. */
            Criteria criteriaAssignedPersons = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                    .createCriteria(AssignedPersonDO.class, "assignedP");

            criteriaAssignedPersons.add(Restrictions.sqlRestriction("{alias}.person_id = ?",
                    taStaff.getPerson().getPersonId(), Hibernate.INTEGER));

            List<Integer> roadOpsWithTAStaff = new ArrayList<Integer>();

            for (AssignedPersonDO assignee : (List<AssignedPersonDO>) criteriaAssignedPersons.list()) {
                roadOpsWithTAStaff
                        .add(assignee.getAssignedPersonKey().getTeam().getRoadOperation().getRoadOperationId());
            }

            mainCriteron = Restrictions.and(mainCriteron,
                    Restrictions.in("roadOp.roadOperationId", roadOpsWithTAStaff));
        } else {
            return null;
        }
    }

    /* ______________________________ */

    /*** Check which road operations employ the strategies selected ****/
    if (reportCriteria.getStrategyIds() != null && !reportCriteria.getStrategyIds().isEmpty()) {
        //
        Criteria criteriaStrategies = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                .createCriteria(OperationStrategyDO.class, "opStrat");

        // criteriaStrategies.createAlias("opStrat.operationStrategyKey.roadOperation",
        // "roadOp");
        // criteriaStrategies.createAlias("opStrat.operationStrategyKey.strategy",
        // "strat");

        criteriaStrategies.setProjection(Projections
                .distinct(Projections.property("opStrat.operationStrategyKey.roadOperation.roadOperationId")));

        criteriaStrategies.add(Restrictions.in("opStrat.operationStrategyKey.strategy.strategyId",
                reportCriteria.getStrategyIds()));

        List<Integer> roadOpWithStratsList = criteriaStrategies.list();

        if (roadOpWithStratsList != null && !roadOpWithStratsList.isEmpty()) {
            mainCriteron = Restrictions.and(mainCriteron,
                    Restrictions.in("roadOp.roadOperationId", roadOpWithStratsList));
        } else {
            return null;
        }
    }
    /* ______________________________________________________________ */

    /*
     * Create Return objects which are going to be filled during report
     * processing.
     */

    String stringStartDate = "";
    String stringEndDate = "";
    try {
        stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getStartDate());
        stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getEndDate());
    } catch (Exception exe) {

    }

    /* Get report criteria names and descriptions */
    reportCriteria
            .setTAOfficeDescription(this.getTAOfficeRegionDescription(reportCriteria.getTAOfficeRegion()));
    reportCriteria.setOperationCategoryDescription(
            this.getOperationCategoryDesc(reportCriteria.getOperationCategory()));

    if (StringUtil.isSet(reportCriteria.getTAStaffId()))
        reportCriteria.setTAStaffName(this.getTAStaffName(reportCriteria.getTAStaffId()));
    else if (StringUtil.isSet(reportCriteria.getTAStaffTRN()))
        reportCriteria.setTAStaffName(this.getPersonName(reportCriteria.getTAStaffTRN()));

    if (StringUtil.isSet(reportCriteria.getTeamLeadId()))
        reportCriteria.setTeamLeadName(this.getTAStaffName(reportCriteria.getTeamLeadId()));
    else if (StringUtil.isSet(reportCriteria.getTeamLeadTRN()))
        reportCriteria.setTeamLeadName(this.getPersonName(reportCriteria.getTeamLeadTRN()));

    if (reportCriteria.getStrategyIds() != null && !reportCriteria.getStrategyIds().isEmpty()) {
        StringBuilder strategyDescriptions = new StringBuilder("");

        for (Integer strategyId : reportCriteria.getStrategyIds()) {
            StrategyDO strategyDO = this.hibernateTemplate.get(StrategyDO.class, strategyId);

            if (strategyDO != null) {
                if (!strategyDescriptions.toString().isEmpty())
                    strategyDescriptions.append(", ");

                strategyDescriptions.append(strategyDO.getDescription());
            }
        }

        reportCriteria.setStrategyDescriptions(strategyDescriptions.toString());
    }

    RoadOperationsStatisticsReportBO roadOpReportStatsOuput = new RoadOperationsStatisticsReportBO(userName,
            userRegion, reportDisplayInformation.applicationName,
            reportDisplayInformation.getPerformanceStatisticsReportTitle() + stringStartDate + " TO "
                    + stringEndDate,
            reportCriteria.getStartDate(), reportCriteria.getEndDate(),
            reportCriteria.getSearchCriteriaString(), this.getTAOfficeRegionDescription(userRegion));

    List<RegionStatisticsBO> regionStats = new ArrayList<RegionStatisticsBO>();

    RegionStatisticsBO currentRegionStats = null;
    OperationSummaryReportCriteriaBO reportCriteriaForRoadOps = null;

    roadOpReportStatsOuput.setRegionStatistics(regionStats);

    /* ____________________________________ */

    /* Loop through list of road operations and get statistics for persons. */
    criteria.add(mainCriteron);
    criteria.addOrder(Order.asc("roadOp.officeLocCode"));
    criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

    List criteriaList = criteria.list();

    Iterator iterator = criteriaList.iterator();

    while (iterator.hasNext()) {
        Map map = (Map) iterator.next();

        final RoadOperationDO roadOpDO = (RoadOperationDO) map.get("roadOp");
        // TAStaffDO teamLead = (TAStaffDO)map.get("teamLead");

        if (currentRegionStats == null) {

            /* Create List of RoadOperationSummaryBO */
            reportCriteriaForRoadOps = new OperationSummaryReportCriteriaBO(reportCriteria.getStartDate(),
                    reportCriteria.getEndDate(), new ArrayList<String>() {
                        {
                            add(roadOpDO.getOfficeLocCode());

                        }
                    }, this.getTeamLeadIdsForRoadOp(roadOpDO.getRoadOperationId()),
                    roadOpDO.getCategory().getCategoryId(), roadOpDO.getRoadOperationId());

            currentRegionStats = new RegionStatisticsBO(roadOpDO.getOfficeLocCode(),
                    this.getTAOfficeRegionDescription(roadOpDO.getOfficeLocCode()));

            currentRegionStats.setRoadOpSummary(this.operationSummaryReport(reportCriteriaForRoadOps, userName,
                    userRegion, reportDisplayInformation).getResults());

            List<RoadOperationSummaryResultsBO> roadOpSummary = this.operationSummaryReport(
                    reportCriteriaForRoadOps, userName, userRegion, reportDisplayInformation).getResults();

            currentRegionStats.setRoadOpSummary(roadOpSummary);

            currentRegionStats.setRoadOperationStatistics(new ArrayList<RoadOperationStatisticsBO>());

            roadOpReportStatsOuput.getRegionStatistics().add(currentRegionStats);

        } else if (!currentRegionStats.getOfficeLocCode().equalsIgnoreCase(roadOpDO.getOfficeLocCode())) {

            reportCriteriaForRoadOps = new OperationSummaryReportCriteriaBO(reportCriteria.getStartDate(),
                    reportCriteria.getEndDate(), new ArrayList<String>() {
                        {
                            add(roadOpDO.getOfficeLocCode());

                        }
                    }, null, roadOpDO.getCategory().getCategoryId(), null);

            currentRegionStats = new RegionStatisticsBO(roadOpDO.getOfficeLocCode(),
                    this.getTAOfficeRegionDescription(roadOpDO.getOfficeLocCode()));
            ;

            currentRegionStats.setRoadOpSummary(this.operationSummaryReport(reportCriteriaForRoadOps, userName,
                    userRegion, reportDisplayInformation).getResults());

            List<RoadOperationSummaryResultsBO> roadOpSummary = this.operationSummaryReport(
                    reportCriteriaForRoadOps, userName, userRegion, reportDisplayInformation).getResults();

            currentRegionStats.setRoadOpSummary(roadOpSummary);

            currentRegionStats.setRoadOperationStatistics(new ArrayList<RoadOperationStatisticsBO>());

            roadOpReportStatsOuput.getRegionStatistics().add(currentRegionStats);
        }

        RoadOperationStatisticsBO roadOpStats = new RoadOperationStatisticsBO(
                getListOfTeamLeadNamesBasedOnRoadOpId(roadOpDO.getRoadOperationId()),
                roadOpDO.getOperationName());

        roadOpStats.setITAExaminerSummary(new ArrayList<ITAExaminerStatisticsBO>());
        roadOpStats.setJPSummary(new ArrayList<JPStatisticsBO>());
        roadOpStats.setPoliceOfficerSummary(new ArrayList<PoliceOfficerStatisticsBO>());
        roadOpStats.setTAOfficerSummary(new ArrayList<TAOfficerStatisticsBO>());
        /* Get a list of all assigned persons for a road operation. */
        Criteria criteriaAssignedPersons = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                .createCriteria(AssignedPersonDO.class, "assignedP");

        // criteriaAssignedPersons.add(Restrictions.sqlRestriction("{alias}.road_operation_id = ?",
        // roadOpDO.getRoadOperationId(), Hibernate.INTEGER));

        List<Integer> teamIds = this.getTeamIdsForRoadOp(roadOpDO.getRoadOperationId());

        if (teamIds != null && teamIds.size() > 0)
            criteriaAssignedPersons.add(Restrictions.in("assignedPersonKey.team.teamId", teamIds));

        if (StringUtil.isSet(reportCriteria.getTAStaffId())) {
            TAStaffDO taStaff = (TAStaffDO) this.hibernateTemplate.getSessionFactory().getCurrentSession()
                    .get(TAStaffDO.class, reportCriteria.getTAStaffId().trim());

            if (taStaff != null) {

                criteriaAssignedPersons.add(Restrictions.sqlRestriction("{alias}.person_id = ?",
                        taStaff.getPerson().getPersonId(), Hibernate.INTEGER));
            } else {
                return null;
            }
        }

        for (AssignedPersonDO assignedPerson : (List<AssignedPersonDO>) criteriaAssignedPersons.list()) {
            /* Looping through a list of persons based on road operation id. */

            PersonDO person = assignedPerson.getAssignedPersonKey().getPerson();
            CDPersonTypeDO personType = assignedPerson.getAssignedPersonKey().getPersonType();

            if (personType.getPersonTypeId().toLowerCase().equalsIgnoreCase(Constants.PersonType.JP)) {
                /* Get Statistics for JP Person */
                Criteria criteriaJP = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                        .createCriteria(JPDO.class);
                criteriaJP.add(Restrictions.eq("person.personId", person.getPersonId()));

                JPDO jp = (JPDO) criteriaJP.uniqueResult();

                JPStatisticsBO jpStatsBO = new JPStatisticsBO(
                        NameUtil.getName(person.getFirstName(), person.getLastName())/* fullName */,
                        jp.getRegNumber()/* regNumber */,
                        this.summonsCount(roadOpDO.getRoadOperationId(), person.getPersonId(),
                                Constants.PersonType.JP)/* countSummonsSigned */,
                        assignedPerson.getAttended()/* attended */);

                roadOpStats.getJPSummary().add(jpStatsBO);

            } else if (personType.getPersonTypeId().equalsIgnoreCase(Constants.PersonType.TA_STAFF)) {
                /* Get Statistics for TA Staff. */
                Criteria criteriaTA = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                        .createCriteria(TAStaffDO.class);
                criteriaTA.add(Restrictions.eq("person.personId", person.getPersonId()));
                //System.out.println("Person ID is " + person.getPersonId());
                TAStaffDO ta = (TAStaffDO) criteriaTA.uniqueResult();

                TAOfficerStatisticsBO taStatsBO = new TAOfficerStatisticsBO(
                        NameUtil.getName(person.getFirstName(), person.getLastName())/* fullName */,
                        ta.getStaffTypeCode()/* staffType */,
                        this.complianceCount(roadOpDO.getRoadOperationId(), person.getPersonId(),
                                personType.getPersonTypeId())/* countCompliancyChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(),
                                Constants.RoadCheckType.MOTOR_VEHICLE, person.getPersonId(),
                                personType.getPersonTypeId())/* countMVChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(),
                                Constants.RoadCheckType.DRIVERS_LICENCE, person.getPersonId(),
                                personType.getPersonTypeId())/* countDLChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(), Constants.RoadCheckType.BADGE,
                                person.getPersonId(), personType.getPersonTypeId())/* countBadgeChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(), Constants.RoadCheckType.CITATION,
                                person.getPersonId(), personType.getPersonTypeId())/* countCitationChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(),
                                Constants.RoadCheckType.ROAD_LICENCE, person.getPersonId(),
                                personType.getPersonTypeId())/* countRLChecks */,
                        this.roadCheckTypeCount(roadOpDO.getRoadOperationId(), Constants.RoadCheckType.OTHER,
                                person.getPersonId(), personType.getPersonTypeId())/* countOtherChecks */,
                        this.warningNoticeCount(roadOpDO.getRoadOperationId(), person.getPersonId(),
                                personType.getPersonTypeId())/* countWarningNoticesIssued */,
                        this.summonsCount(roadOpDO.getRoadOperationId(), person.getPersonId(),
                                personType.getPersonTypeId())/* countSummonsIssued */,
                        this.roadCheckOutcomeCount(roadOpDO.getRoadOperationId(),
                                Constants.OutcomeType.VEHICLE_SEIZURE, person.getPersonId(),
                                personType.getPersonTypeId())/* countVehiclesSeized */,
                        assignedPerson.getAttended()/* attended */,
                        this.roadCheckOutcomeCount(roadOpDO.getRoadOperationId(),
                                Constants.OutcomeType.REMOVE_PLATES, person.getPersonId(),
                                personType.getPersonTypeId())/* countPlatesRemoved */,
                        this.roadCheckOutcomeCount(roadOpDO.getRoadOperationId(),
                                Constants.OutcomeType.WARNED_FOR_PROSECUTION, person.getPersonId(),
                                personType.getPersonTypeId())/* warningsForProcecution */,
                        this.roadCheckOutcomeCount(roadOpDO.getRoadOperationId(),
                                Constants.OutcomeType.ALL_IN_ORDER, person.getPersonId(),
                                personType.getPersonTypeId())/* allInOrders */,
                        ta.getStaffId()/* staff id */);

                roadOpStats.getTAOfficerSummary().add(taStatsBO);
            } else if (personType.getPersonTypeId().equalsIgnoreCase(Constants.PersonType.ITA_EXAMINER)) {
                /* Get Statistics for ITA Examiner */
                Criteria criteriaITA = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                        .createCriteria(ITAExaminerDO.class);
                criteriaITA.add(Restrictions.eq("person.personId", person.getPersonId()));

                ITAExaminerDO ita = (ITAExaminerDO) criteriaITA.uniqueResult();

                ITAExaminerStatisticsBO itaStats = new ITAExaminerStatisticsBO(
                        NameUtil.getName(person.getFirstName(), person.getLastName()),
                        assignedPerson.getAttended(), ita.getExaminerId());

                roadOpStats.getITAExaminerSummary().add(itaStats);
            } else if (personType.getPersonTypeId().equalsIgnoreCase(Constants.PersonType.POLICE_OFFCER)) {
                /* Get Statistics for Police Officer */
                Criteria criteriaITA = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                        .createCriteria(PoliceOfficerDO.class);
                criteriaITA.add(Restrictions.eq("person.personId", person.getPersonId()));

                PoliceOfficerDO police = (PoliceOfficerDO) criteriaITA.uniqueResult();

                PoliceOfficerStatisticsBO policeStats = new PoliceOfficerStatisticsBO(
                        NameUtil.getName(person.getFirstName(), person.getLastName()),
                        assignedPerson.getAttended(), police.getPolOfficerCompNo());

                roadOpStats.getPoliceOfficerSummary().add(policeStats);
            }

        }
        /* ____________________________________ */

        currentRegionStats.getRoadOperationStatistics().add(roadOpStats);
    }
    /* ________________________________ */

    roadOpReportStatsOuput.setRegionStatistics(regionStats);
    return roadOpReportStatsOuput;
}

From source file:fsl.ta.toms.roms.dao.impl.ReportDAOImpl.java

/**
 * This is a helper function which checks the starting trial date of court
 * cases and returns all court case id as a list of integers based on the
 * start and end date ranges.//from w  w  w.  j a  v a 2s  .co m
 * 
 * @param startTrialDate
 * @param endTrialDate
 * @return
 */
@SuppressWarnings("unchecked")
private List<Integer> getCourtCasesIdsForTrialDateRange(Date startTrialDate, Date endTrialDate) {
    List<Integer> courtCaseIds = new ArrayList<Integer>();

    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(CourtAppearanceDO.class, "capp");

    criteria.setProjection(Projections.distinct(Projections.property("courtCase.courtCaseId")));

    criteria.add(Restrictions.between("CourtDTime",
            DateUtils.searchDateFormater(startTrialDate, DateUtils.SEARCHDATETYPE.START),
            DateUtils.searchDateFormater(endTrialDate, DateUtils.SEARCHDATETYPE.END)));

    courtCaseIds = criteria.list();

    return courtCaseIds;
}

From source file:gov.nih.nci.caintegrator.data.CaIntegrator2DaoImpl.java

License:BSD License

/**
 * {@inheritDoc}// w w  w .  j a  v a  2  s.  c o  m
 */
@Override
@SuppressWarnings(UNCHECKED) // Hibernate operations are untyped
public List<Gene> findGenesByLocation(String chromosome, Integer startPosition, Integer endPosition,
        GenomeBuildVersionEnum genomeBuildVersion) {
    String locStartPosition = "location.startPosition";
    String locEndPosition = "location.endPosition";
    Criteria geneLocationCriteria = getCurrentSession().createCriteria(GeneChromosomalLocation.class);
    // (gene.startPos <= startPosition && gene.endPos >= startPosition)
    //  || (gene.startPos >= lowerInput  && gene.startPos <= higherInput)
    Junction overallOrStatement = Restrictions.disjunction();
    overallOrStatement.add(Restrictions.conjunction().add(Restrictions.le(locStartPosition, startPosition))
            .add(Restrictions.ge(locEndPosition, startPosition)));
    overallOrStatement.add(Restrictions.conjunction().add(Restrictions.ge(locStartPosition, startPosition))
            .add(Restrictions.le(locStartPosition, endPosition)));
    geneLocationCriteria.add(overallOrStatement);
    geneLocationCriteria.add(getChromosomeRestriction(chromosome));
    geneLocationCriteria.createCriteria("geneLocationConfiguration")
            .add(Restrictions.eq("genomeBuildVersion", genomeBuildVersion));
    geneLocationCriteria.setProjection(Projections.property("geneSymbol"));
    List<String> geneSymbols = geneLocationCriteria.list();
    return geneSymbols.isEmpty() ? new ArrayList<Gene>()
            : getCurrentSession().createCriteria(Gene.class)
                    .setProjection(Projections.distinct(Projections.property(SYMBOL_ATTRIBUTE)))
                    .add(Restrictions.in(SYMBOL_ATTRIBUTE, geneSymbols)).addOrder(Order.asc(SYMBOL_ATTRIBUTE))
                    .list();
}

From source file:gov.nih.nci.caintegrator.data.CaIntegrator2DaoImpl.java

License:BSD License

/**
 * {@inheritDoc}/*from   w  ww  .  j  a  va  2s. c o  m*/
 */
@Override
@SuppressWarnings(UNCHECKED)
public <T> List<T> retrieveUniqueValuesForStudyAnnotation(Study study, AnnotationDefinition definition,
        EntityTypeEnum entityType, Class<T> objectClass) {
    AnnotationTypeEnum annotationType = definition.getDataType();
    if (annotationType == null) {
        throw new IllegalArgumentException("Data Type for the Annotation Definition is unknown.");
    }
    Criteria abstractAnnotationValueCriteria = getCurrentSession()
            .createCriteria(AbstractAnnotationValue.class);
    abstractAnnotationValueCriteria.add(Restrictions.eq(ANNOTATION_DEFINITION_ASSOCIATION, definition));
    addValuesToStudyCriteria(study, entityType, abstractAnnotationValueCriteria);

    String uniqueAttribute = "stringValue";
    switch (annotationType) {
    case STRING:
        uniqueAttribute = "stringValue";
        break;
    case NUMERIC:
        uniqueAttribute = "numericValue";
        break;
    case DATE:
        uniqueAttribute = "dateValue";
        break;
    default:
        throw new IllegalStateException("Unknown Annotation Type Type.");
    }
    abstractAnnotationValueCriteria.setProjection(Projections.distinct(Projections.property(uniqueAttribute)));
    return abstractAnnotationValueCriteria.list();

}

From source file:gov.nih.nci.caintegrator.data.CaIntegrator2DaoImpl.java

License:BSD License

/**
 * {@inheritDoc}/*from  www .j  a v a2  s .  c o m*/
 */
@Override
@SuppressWarnings(UNCHECKED)
public List<Platform> retrievePlatformsForGenomicSource(GenomicDataSourceConfiguration genomicSource) {
    Criteria arrayCriteria = getCurrentSession().createCriteria(Array.class);
    arrayCriteria.setProjection(Projections.distinct(Projections.property(PLATFORM_ASSOCIATION)))
            .add(Restrictions.isNotNull(PLATFORM_ASSOCIATION)).createCriteria("sampleCollection")
            .add(Restrictions.eq("genomicDataSource", genomicSource));

    return arrayCriteria.list();
}