Example usage for org.hibernate.criterion Restrictions or

List of usage examples for org.hibernate.criterion Restrictions or

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions or.

Prototype

public static LogicalExpression or(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the disjuction of two expressions

Usage

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

@Override
public SummonsReportBO summonsReport(SummonsReportCriteriaBO reportCriteria, String userName, String userRegion,
        ReportDisplayInformationDAOImpl reportDisplayInformation) {
    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(SummonsDO.class, "s");
    criteria.createAlias("s.roadOperation", "ro", Criteria.LEFT_JOIN);
    criteria.createAlias("s.offender", "of", Criteria.LEFT_JOIN);
    criteria.createAlias("s.status", "st", Criteria.LEFT_JOIN);
    criteria.createAlias("ro.category", "c", Criteria.LEFT_JOIN);
    criteria.createAlias("s.taStaff", "ta", Criteria.LEFT_JOIN);
    criteria.createAlias("ta.person", "taPerson", Criteria.LEFT_JOIN);

    Criterion mainCriterion = Restrictions.sqlRestriction("1=1");

    if (reportCriteria.getOperationStartDate() != null && reportCriteria.getOperationEndDate() != null) {
        Date reportStartDate = DateUtils.searchDateFormater(reportCriteria.getOperationStartDate(),
                DateUtils.SEARCHDATETYPE.START);
        Date reportEndDate = DateUtils.searchDateFormater(reportCriteria.getOperationEndDate(),
                DateUtils.SEARCHDATETYPE.END);

        Criterion scheduledDate = Restrictions.or(
                Restrictions.between("ro.scheduledStartDtime", reportStartDate, reportEndDate),
                Restrictions.between("ro.scheduledEndDtime", reportStartDate, reportEndDate));

        Criterion actualDate = Restrictions.or(
                Restrictions.between("ro.actualStartDtime", reportStartDate, reportEndDate),
                Restrictions.between("ro.actualEndDtime", reportStartDate, reportEndDate));

        mainCriterion = Restrictions.and(mainCriterion, Restrictions.or(scheduledDate, actualDate));
    }/*  ww  w .  j  a v a  2 s  . c o m*/

    if (reportCriteria.getOffenceStartDate() != null && reportCriteria.getOffenceEndDate() != null) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.between("s.offenceDtime",
                        DateUtils.searchDateFormater(reportCriteria.getOffenceStartDate(),
                                DateUtils.SEARCHDATETYPE.START),
                        DateUtils.searchDateFormater(reportCriteria.getOffenceEndDate(),
                                DateUtils.SEARCHDATETYPE.END)));
    }

    if (reportCriteria.getIssuedStartDate() != null && reportCriteria.getIssuedEndDate() != null) {
        mainCriterion = Restrictions.and(mainCriterion, Restrictions.between("s.issueDate",
                DateUtils.searchDateFormater(reportCriteria.getIssuedStartDate(),
                        DateUtils.SEARCHDATETYPE.START),
                DateUtils.searchDateFormater(reportCriteria.getIssuedEndDate(), DateUtils.SEARCHDATETYPE.END)));
    }

    if (reportCriteria.getPrintStartDate() != null && reportCriteria.getPrintEndDate() != null) {
        mainCriterion = Restrictions.and(mainCriterion, Restrictions.between("s.printDtime",
                DateUtils.searchDateFormater(reportCriteria.getPrintStartDate(),
                        DateUtils.SEARCHDATETYPE.START),
                DateUtils.searchDateFormater(reportCriteria.getPrintEndDate(), DateUtils.SEARCHDATETYPE.END)));

    }

    if (reportCriteria.getOffenderId() != null && reportCriteria.getOffenderId() > 0) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("of.personId", reportCriteria.getOffenderId()));
    }

    if (StringUtil.isSet(reportCriteria.getOffenderTRN())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("of.trnNbr", reportCriteria.getOffenderTRN().trim()));
    }

    if (reportCriteria.getOperationCategory() != null && !reportCriteria.getOperationCategory().isEmpty()) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("c.categoryId", reportCriteria.getOperationCategory().trim()));

    }

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

    if (reportCriteria.getTAOfficeRegion() != null && !reportCriteria.getTAOfficeRegion().isEmpty()) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("ro.officeLocCode", reportCriteria.getTAOfficeRegion().trim()));
    }

    if (reportCriteria.getTAStaffId() != null && !reportCriteria.getTAStaffId().isEmpty()) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("ta.staffId", reportCriteria.getTAStaffId().trim()));
    }

    if (StringUtil.isSet(reportCriteria.getTAStaffTRN())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("taPerson.trnNbr", reportCriteria.getTAStaffTRN().trim()));
    }

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

    if (StringUtil.isSet(reportCriteria.getStatus())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("s.status.statusId", reportCriteria.getStatus().trim()));
    }

    if (StringUtil.isSet(reportCriteria.getOffenderFirstName())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions
                        .like("of.firstName", reportCriteria.getOffenderFirstName().trim(), MatchMode.ANYWHERE)
                        .ignoreCase());
    }

    if (StringUtil.isSet(reportCriteria.getOffenderLastName())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions
                        .like("of.lastName", reportCriteria.getOffenderLastName().trim(), MatchMode.ANYWHERE)
                        .ignoreCase());
    }

    criteria.add(mainCriterion);

    String stringStartDate = "";
    String stringEndDate = "";
    String dateTypeUsed = "";
    Date startDate = null;
    Date endDate = null;
    try {
        if (reportCriteria.getOperationStartDate() != null && reportCriteria.getOperationEndDate() != null) {
            startDate = reportCriteria.getOperationStartDate();
            endDate = reportCriteria.getOperationEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationEndDate());

            dateTypeUsed = "Operation";
        } else if (reportCriteria.getOffenceStartDate() != null && reportCriteria.getOffenceEndDate() != null) {
            startDate = reportCriteria.getOffenceStartDate();
            endDate = reportCriteria.getOffenceEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getOffenceStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getOffenceEndDate());

            dateTypeUsed = "Offence";
        } else if (reportCriteria.getPrintStartDate() != null && reportCriteria.getPrintEndDate() != null) {
            startDate = reportCriteria.getPrintStartDate();
            endDate = reportCriteria.getPrintEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getPrintStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getPrintEndDate());

            dateTypeUsed = "Print";
        } else if (reportCriteria.getIssuedStartDate() != reportCriteria.getIssuedEndDate()) {
            startDate = reportCriteria.getIssuedStartDate();
            endDate = reportCriteria.getIssuedEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getIssuedStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getIssuedEndDate());

            dateTypeUsed = "Issued";
        }
    } catch (Exception exe) {

    }

    /* Get report criteria names and descriptions */
    if (reportCriteria.getOffenderId() != null && reportCriteria.getOffenderId() > 0) {
        reportCriteria.setOffenderName(this.getPersonName(reportCriteria.getOffenderId()));
    } else if (StringUtil.isSet(reportCriteria.getOffenderTRN())) {
        reportCriteria.setOffenderName(this.getPersonName(reportCriteria.getOffenderTRN()));
    }

    reportCriteria
            .setOperationCategoryDesc(this.getOperationCategoryDesc(reportCriteria.getOperationCategory()));
    reportCriteria.setRoadOperationName(reportCriteria.getRoadOperationName());

    reportCriteria.setTAOfficeRegionDesc(this.getTAOfficeRegionDescription(reportCriteria.getTAOfficeRegion()));

    if (StringUtil.isSet(reportCriteria.getTAStaffId()))
        reportCriteria.setTAStaffName(this.getTAStaffName(reportCriteria.getTAStaffId()));
    else if (StringUtil.isSet(reportCriteria.getTAStaffTRN()))
        reportCriteria.setTAStaffName(this.getPersonName(reportCriteria.getTAStaffTRN()));
    /*
     * reportCriteria.setRoadOperationDesc(this.getRoadOperationName(
     * reportCriteria.getRoadOperationId()));
     */
    /* __________________________________________ */

    SummonsReportBO report = new SummonsReportBO(userName, userRegion, reportDisplayInformation.applicationName,
            reportDisplayInformation.summonsReportTitle + "(" + dateTypeUsed + ") " + stringStartDate + " TO "
                    + stringEndDate,
            startDate, endDate, reportCriteria.getSearchCriteriaString(),
            getTAOfficeRegionDescription(userRegion));

    List<SummonsReportResultsBO> summonsReportList = new ArrayList<SummonsReportResultsBO>();

    for (SummonsDO summons : (List<SummonsDO>) criteria.list()) {

        String offenderFullName = NameUtil.getName(
                (StringUtil.isSet(summons.getOffender().getFirstName())
                        ? summons.getOffender().getFirstName().trim()
                        : ""),
                (StringUtil.isSet(summons.getOffender().getLastName())
                        ? summons.getOffender().getLastName().trim()
                        : ""));

        String offenceDescription = summons.getRoadCheckOffenceOutcome().getRoadCheckOffence().getOffence()
                .getDescription();

        String tAStaffFullName = NameUtil.getName(
                (StringUtil.isSet(summons.getTaStaff().getPerson().getFirstName())
                        ? summons.getTaStaff().getPerson().getFirstName().trim()
                        : ""),
                (StringUtil.isSet(summons.getTaStaff().getPerson().getLastName())
                        ? summons.getTaStaff().getPerson().getLastName().trim()
                        : ""));

        VehicleDO vehicle = summons.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck()
                .getCompliance().getVehicle();
        String vehicleDetails = "";
        if (vehicle != null) {
            vehicleDetails = (StringUtil.isSet(vehicle.getModel()) ? vehicle.getModel().trim() : "") + "; "
                    + (StringUtil.isSet(vehicle.getMakeDescription()) ? vehicle.getMakeDescription().trim()
                            : "")
                    + "; Plate #: "
                    + (StringUtil.isSet(vehicle.getPlateRegNo()) ? vehicle.getPlateRegNo().trim() : "");
        }

        String locationOfOffence = summons.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck()
                .getCompliance().getCompliancyArtery().getDescription();

        String tAOfficeRegion = summons.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck()
                .getCompliance().getRoadOperation().getOfficeLocCode();

        String jPFullName = NameUtil.getName(
                (StringUtil.isSet(summons.getJusticeOfPeace().getPerson().getFirstName())
                        ? summons.getJusticeOfPeace().getPerson().getFirstName().trim()
                        : ""),
                (StringUtil.isSet(summons.getJusticeOfPeace().getPerson().getLastName())
                        ? summons.getJusticeOfPeace().getPerson().getLastName()
                        : ""));

        String roadOperationDetails = summons.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck()
                .getCompliance().getRoadOperation().getOperationName();

        /* Get latest trial for the summons */
        Criteria criteriaCourtAppearance = this.hibernateTemplate.getSessionFactory().getCurrentSession()
                .createCriteria(CourtAppearanceDO.class, "CApp");

        criteriaCourtAppearance.createAlias("CApp.courtCase", "CCase");
        criteriaCourtAppearance.createAlias("CCase.summons", "Summ");

        criteriaCourtAppearance.add(Restrictions.eq("Summ.summonsId", summons.getSummonsId()));

        criteriaCourtAppearance.addOrder(Order.asc("CApp.CourtDTime"));
        criteriaCourtAppearance.addOrder(Order.asc("CApp.courtAppearanceId"));

        Integer courtAppListSize = criteriaCourtAppearance.list().size();
        String courtDetails = "";

        if (courtAppListSize > 0) {
            CourtAppearanceDO courtApp = (CourtAppearanceDO) criteriaCourtAppearance.list()
                    .get(courtAppListSize - 1);

            String stringTrialDate = "";
            SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            try {
                stringTrialDate = dt.format(courtApp.getCourtDTime());

            } catch (Exception exe) {

            }

            courtDetails = String.format("Court Appearance Date is %s at %s.", stringTrialDate,
                    courtApp.getCourt().getDescription());
        }
        /* _______________________________ */

        SummonsReportResultsBO summonsRptResult = new SummonsReportResultsBO(offenderFullName,
                offenceDescription, tAStaffFullName, vehicleDetails, locationOfOffence, tAOfficeRegion,
                jPFullName, roadOperationDetails, courtDetails, getTAOfficeRegionDescription(tAOfficeRegion),
                summons.getOffenceDtime(), summons.getServedOnDate(), summons.getPrintDtime(),
                summons.getStatus().getStatusId(), summons.getStatus().getDescription(),
                summons.getManualSerialNumber(), summons.getComment(),
                summons.getReason() != null ? summons.getReason().getDescription() : null,
                summons.getReprintDtime());

        summonsReportList.add(summonsRptResult);
    }

    report.setResults(summonsReportList);
    return report;
}

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

@SuppressWarnings("unchecked")
@Override/*from  w ww.j a  v a2 s . co 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

@Override
public WarningNoProsecutionReportBO warningNoProsecutionReport(WarningNoProReportCriteriaBO reportCriteria,
        String userName, String userRegion, ReportDisplayInformationDAOImpl reportDisplayInformation) {
    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(WarningNoProsecutionDO.class, "wnp");

    /* Create aliases */
    criteria.createAlias("wnp.roadOperation", "roadOp");
    criteria.createAlias("wnp.offender", "off");
    criteria.createAlias("wnp.taStaff", "staff");
    criteria.createAlias("wnp.status", "status");
    criteria.createAlias("roadOp.category", "cat");
    criteria.createAlias("staff.person", "taPerson");
    /* _____________ */

    Criterion mainCriterion = Restrictions.sqlRestriction("1=1");

    if (reportCriteria.getOperationStartDate() != null && reportCriteria.getOperationEndDate() != null) {
        Date reportStartDate = DateUtils.searchDateFormater(reportCriteria.getOperationStartDate(),
                DateUtils.SEARCHDATETYPE.START);
        Date reportEndDate = DateUtils.searchDateFormater(reportCriteria.getOperationEndDate(),
                DateUtils.SEARCHDATETYPE.END);

        Criterion scheduledDate = Restrictions.or(
                Restrictions.between("roadOp.scheduledStartDtime", reportStartDate, reportEndDate),
                Restrictions.between("roadOp.scheduledEndDtime", reportStartDate, reportEndDate));

        Criterion actualDate = Restrictions.or(
                Restrictions.between("roadOp.actualStartDtime", reportStartDate, reportEndDate),
                Restrictions.between("roadOp.actualEndDtime", reportStartDate, reportEndDate));

        mainCriterion = Restrictions.and(mainCriterion, Restrictions.or(scheduledDate, actualDate));
    }//w w  w  .  ja  va  2s .c o  m

    if (reportCriteria.getIssuedStartDate() != null && reportCriteria.getIssuedEndDate() != null) {
        Date reportStartDate = DateUtils.searchDateFormater(reportCriteria.getIssuedStartDate(),
                DateUtils.SEARCHDATETYPE.START);
        Date reportEndDate = DateUtils.searchDateFormater(reportCriteria.getIssuedEndDate(),
                DateUtils.SEARCHDATETYPE.END);

        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.between("wnp.issueDate", reportStartDate, reportEndDate));
    }

    if (reportCriteria.getPrintStartDate() != null && reportCriteria.getPrintEndDate() != null) {
        Date reportStartDate = DateUtils.searchDateFormater(reportCriteria.getPrintStartDate(),
                DateUtils.SEARCHDATETYPE.START);
        Date reportEndDate = DateUtils.searchDateFormater(reportCriteria.getPrintEndDate(),
                DateUtils.SEARCHDATETYPE.END);

        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.between("wnp.printDtime", reportStartDate, reportEndDate));
    }

    if (StringUtil.isSet(reportCriteria.getOffenderFirstName())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions
                        .like("off.firstName", reportCriteria.getOffenderFirstName().trim(), MatchMode.ANYWHERE)
                        .ignoreCase());
    }

    if (reportCriteria.getOffenderId() != null && reportCriteria.getOffenderId() > 0) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("off.personId", reportCriteria.getOffenderId()));
    }

    if (StringUtil.isSet(reportCriteria.getOffenderLastName())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions
                        .like("off.lastName", reportCriteria.getOffenderLastName().trim(), MatchMode.ANYWHERE)
                        .ignoreCase());
    }

    if (StringUtil.isSet(reportCriteria.getOffenderTRN())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("off.trnNbr", reportCriteria.getOffenderTRN().trim()));
    }

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

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

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

    if (StringUtil.isSet(reportCriteria.getStatus())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("status.statusId", reportCriteria.getStatus().trim()));
    }

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

    if (StringUtil.isSet(reportCriteria.getTAStaffId())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("staff.staffId", reportCriteria.getTAStaffId().trim()));
    }

    if (StringUtil.isSet(reportCriteria.getTAStaffTRN())) {
        mainCriterion = Restrictions.and(mainCriterion,
                Restrictions.eq("taPerson.trnNbr", reportCriteria.getTAStaffTRN().trim()));
    }

    criteria.add(mainCriterion);

    String stringStartDate = "";
    String stringEndDate = "";
    String dateTypeUsed = "";
    Date startDate = null;
    Date endDate = null;
    try {
        if (reportCriteria.getOperationStartDate() != null && reportCriteria.getOperationEndDate() != null) {
            startDate = reportCriteria.getOperationStartDate();
            endDate = reportCriteria.getOperationEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationEndDate());

            dateTypeUsed = "Operation";
        } else if (reportCriteria.getPrintStartDate() != null && reportCriteria.getPrintEndDate() != null) {
            startDate = reportCriteria.getPrintStartDate();
            endDate = reportCriteria.getPrintEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getPrintStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getPrintEndDate());

            dateTypeUsed = "Print";
        } else if (reportCriteria.getIssuedStartDate() != reportCriteria.getIssuedEndDate()) {
            startDate = reportCriteria.getIssuedStartDate();
            endDate = reportCriteria.getIssuedEndDate();
            stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getIssuedStartDate());
            stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getIssuedEndDate());

            dateTypeUsed = "Issued";
        }
    } catch (Exception exe) {

    }
    /* Get report criteria names and descriptions */
    if (reportCriteria.getOffenderId() != null && reportCriteria.getOffenderId() > 0) {
        reportCriteria.setOffenderName(this.getPersonName(reportCriteria.getOffenderId()));
    } else if (StringUtil.isSet(reportCriteria.getOffenderTRN())) {
        reportCriteria.setOffenderName(this.getPersonName(reportCriteria.getOffenderTRN()));
    }

    reportCriteria
            .setOperationCategoryDesc(this.getOperationCategoryDesc(reportCriteria.getOperationCategory()));
    reportCriteria.setRoadOperationName(reportCriteria.getRoadOperationName());

    reportCriteria.setTAOfficeRegionDesc(this.getTAOfficeRegionDescription(reportCriteria.getTAOfficeRegion()));

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

    criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

    Iterator iterator = criteria.list().iterator();

    List<WarningNoProsecutionDetailsBO> warningNoProDetailsList = new ArrayList<WarningNoProsecutionDetailsBO>();

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

        RoadOperationDO roadOp = (RoadOperationDO) result.get("roadOp");
        PersonDO offender = (PersonDO) result.get("off");
        TAStaffDO taStaff = (TAStaffDO) result.get("staff");
        StatusDO status = (StatusDO) result.get("status");
        CDCategoryDO category = (CDCategoryDO) result.get("cat");
        WarningNoProsecutionDO warningNoPro = (WarningNoProsecutionDO) result.get("wnp");

        Integer roadCheckId = warningNoPro.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck()
                .getRoadCheckId();

        WarningNoProsecutionDetailsBO warningNoProItem = new WarningNoProsecutionDetailsBO(
                this.getPersonName(taStaff.getPerson().getPersonId())/* tAStaffFullName */,
                taStaff.getStaffId()/* tAStaffID */,
                this.getTeamLeadName(roadOp.getRoadOperationId(),
                        taStaff.getPerson().getPersonId())/* tATeamLeadFullName */,
                this.getPersonName(offender.getPersonId())/* offenderFullName */,
                this.getDLNumFromDLCheck(roadCheckId)/* offendersDriverLicence */,
                this.getVehicleDetailsFromMVCheck(roadCheckId)/* offenderVehicleDetials */,
                this.getVehicleOwenersFullNames(roadCheckId)/* vehicleOwnerFullNames */,
                roadOp.getOperationName()/* roadOperationName */,
                warningNoPro.getRoadCheckOffenceOutcome().getRoadCheckOffence().getRoadCheck().getCompliance()
                        .getCompliancyArtery().getShortDescription()/* locationOfOffence */,
                warningNoPro.getOffenceDtime()/* dateOfOffence */,
                warningNoPro.getManualSerialNumber()/* manualSerialNumber */,
                status.getDescription()/* status */,
                warningNoPro.getRoadCheckOffenceOutcome().getRoadCheckOffence().getOffence()
                        .getDescription()/* offenceDescription */,
                warningNoPro.getAllegation()/* allegation */, warningNoPro.getRoadCheckOffenceOutcome()
                        .getRoadCheckOffence().getOffence().getShortDescription()/* offenceShortDescription */);

        warningNoProDetailsList.add(warningNoProItem);
    }

    return new WarningNoProsecutionReportBO(userName, userRegion, reportDisplayInformation.applicationName,
            reportDisplayInformation.warningNoticeNoProsecutionReportTitle + " (" + dateTypeUsed + ") "
                    + stringStartDate + " TO " + stringEndDate,
            startDate, endDate, reportCriteria.getSearchCriteriaString(), userRegion, warningNoProDetailsList);
}

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

@Override
public Integer getTotalROMSOffences(String trn, String dln, String... plateNumber) {

    if (trn == null && dln == null && plateNumber == null) {
        return null;
    }/*from  w  w  w.  j a  v  a 2  s.c  o m*/
    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(ROMS_CitationOffenceView.class, "roms_cit_view");

    if (trn != null && dln != null) {
        criteria.add(Restrictions.or(Restrictions.eq("trnNbr", trn).ignoreCase(),
                Restrictions.eq("dlNo", dln).ignoreCase()));
    } else if (trn != null) {
        criteria.add(Restrictions.eq("trnNbr", trn).ignoreCase());
    } else if (dln != null) {
        criteria.add(Restrictions.eq("dlNo", dln).ignoreCase());
    } else if (plateNumber != null && plateNumber[0] != null) {
        criteria.add(Restrictions.eq("plateNumber", plateNumber[0]).ignoreCase());
    }

    //Case restriction based on discrepancy 212 - This allows correct total count to be returned by not counting documents other than summons
    criteria.add(Restrictions.isNotNull("caseStatus"));
    criteria.setProjection(Projections.rowCount());

    return (Integer) criteria.uniqueResult();

}

From source file:gov.nih.nci.caarray.dao.VocabularyDaoImpl.java

License:BSD License

/**
 * {@inheritDoc}//from  w  ww.  j  ava 2  s  . c o  m
 */
@SuppressWarnings(UNCHECKED)
public Term findTermInAllTermSourceVersions(TermSource termSource, String value) {
    Criteria criteria = getCurrentSession().createCriteria(Term.class);
    criteria.add(Restrictions.eq("value", value).ignoreCase());
    criteria.createAlias("source", "ts");
    if (termSource.getUrl() == null) {
        criteria.add(Restrictions.eq("ts.name", termSource.getName()));
    } else {
        criteria.add(Restrictions.or(Restrictions.eq("ts.name", termSource.getName()),
                Restrictions.eq("ts.url", termSource.getUrl())));
    }
    criteria.addOrder(Order.desc("ts.version"));
    List<Term> terms = criteria.list();
    return terms.isEmpty() ? null : terms.get(0);
}

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

private List<Function> findFunctionsBy(String sampleId, AdvancedSampleSearchBean searchBean) throws Exception {
    List<Function> functions = new ArrayList<Function>();
    if (!searchBean.getHasFunction()) {
        return functions;
    }/*  w ww.  ja  va 2 s .c o m*/
    Long id = new Long(sampleId);
    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    DetachedCriteria crit = DetachedCriteria.forClass(Function.class);
    Junction junction = getFunctionJunction(searchBean, crit);
    if (junction != null) {
        crit.createAlias("composingElement", "ce", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("ce.nanomaterialEntity", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("nanoEntity.sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("comp.sample", "sample", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("functionalizingEntity", "funcEntity", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("funcEntity.sampleComposition", "comp2", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("comp2.sample", "sample2", CriteriaSpecification.LEFT_JOIN);
        crit.add(Restrictions.or(Restrictions.eq("sample.id", id), Restrictions.eq("sample2.id", id)));
        crit.add(junction);
        crit.setFetchMode("targetCollection", FetchMode.JOIN);

        List results = appService.query(crit);
        for (int i = 0; i < results.size(); i++) {
            Function function = (Function) results.get(i);
            functions.add(function);
        }
    } else if (searchBean.getFuncCount() > 1) {
        // Hibernate Criteria API doesn't support union, union in java
        for (CompositionQueryBean query : searchBean.getCompositionQueries()) {
            if (query.getCompositionType().equals("function")) {
                crit = DetachedCriteria.forClass(Function.class);
                crit.createAlias("composingElement", "ce", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("ce.nanomaterialEntity", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("nanoEntity.sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("comp.sample", "sample", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("functionalizingEntity", "funcEntity", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("funcEntity.sampleComposition", "comp2", CriteriaSpecification.LEFT_JOIN);
                crit.createAlias("comp2.sample", "sample2", CriteriaSpecification.LEFT_JOIN);
                crit.add(Restrictions.or(Restrictions.eq("sample.id", id), Restrictions.eq("sample2.id", id)));
                DetachedCriteria subCrit = getFunctionSubquery(query, "", "", "id");
                crit.add(Subqueries.exists(subCrit));
                crit.setFetchMode("targetCollection", FetchMode.JOIN);
                crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
                List results = appService.query(crit);
                for (int i = 0; i < results.size(); i++) {
                    Function function = (Function) results.get(i);
                    if (!functions.contains(function)) {
                        functions.add(function);
                    }
                }
            }
        }
    }
    return functions;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

private DetachedCriteria getFunctionSubquery(CompositionQueryBean query, String funcAlias1, String funcAlias2,
        String projectionProperty) throws Exception {
    DetachedCriteria subCrit = DetachedCriteria.forClass(Function.class, "subCrit");
    subCrit.setProjection(Projections.distinct(Property.forName(projectionProperty)));
    Criterion funcCrit = getFunctionCriterion(query, "", "");
    subCrit.add(funcCrit);/*from  w  w  w  . j av a  2 s .c o  m*/
    if (funcAlias1.equals(funcAlias2)) {
        subCrit.add(Restrictions.eqProperty("subCrit." + projectionProperty, funcAlias1 + "id"));
    } else {
        subCrit.add(Restrictions.or(Restrictions.eqProperty("subCrit." + projectionProperty, funcAlias1 + "id"),
                Restrictions.eqProperty("subCrit." + projectionProperty, funcAlias2 + "id")));
    }
    return subCrit;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

private Criterion getFunctionCriterion(CompositionQueryBean compQuery, String functionAlias1,
        String functionAlias2) throws Exception {
    String funcClassName = ClassUtils.getShortClassNameFromDisplayName(compQuery.getEntityType());
    Class clazz = ClassUtils.getFullClass("function." + funcClassName);
    Criterion funcCrit, funcCrit1, funcCrit2 = null;
    // other function type
    if (clazz == null) {
        if (!functionAlias1.equals(functionAlias2)) {
            // inherent function
            Criterion otherFuncCrit1 = Restrictions.eq(functionAlias1 + "class", "OtherFunction");
            Criterion otherFuncCrit2 = Restrictions.eq(functionAlias1 + "type", compQuery.getEntityType());
            funcCrit1 = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
            // function
            Criterion otherFuncCrit3 = Restrictions.eq(functionAlias2 + "class", "OtherFunction");
            Criterion otherFuncCrit4 = Restrictions.eq(functionAlias2 + "type", compQuery.getEntityType());
            funcCrit2 = Restrictions.and(otherFuncCrit3, otherFuncCrit4);
            funcCrit = Restrictions.or(funcCrit1, funcCrit2);
        } else {//from  ww w.  j a  v a2 s  .  c om
            Criterion otherFuncCrit1 = Restrictions.eq(functionAlias1 + "class", "OtherFunction");
            Criterion otherFuncCrit2 = Restrictions.eq(functionAlias1 + "type", compQuery.getEntityType());
            funcCrit = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
        }
    } else {
        if (!functionAlias1.equals(functionAlias2)) {
            funcCrit1 = Restrictions.eq(functionAlias1 + "class", funcClassName);
            funcCrit2 = Restrictions.eq(functionAlias2 + "class", funcClassName);
            funcCrit = Restrictions.and(funcCrit1, funcCrit2);
        } else {
            funcCrit = Restrictions.eq(functionAlias1 + "class", funcClassName);
        }
    }
    return funcCrit;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

private DetachedCriteria getPointOfContactSubquery(SampleQueryBean query, String pocAlias1, String pocAlias2,
        String projectionProperty) {
    DetachedCriteria subCrit = DetachedCriteria.forClass(PointOfContact.class, "subCrit");
    subCrit.createAlias("subCrit.organization", "organization", CriteriaSpecification.LEFT_JOIN);
    subCrit.setProjection(Projections.distinct(Property.forName("id")));
    Disjunction pocDisjunction = getPointOfContactDisjunctionPerQuery(query, "", "");
    subCrit.add(pocDisjunction);//from   w ww .  j a  v a 2s .co m
    if (pocAlias1.equals(pocAlias2)) {
        subCrit.add(Restrictions.eqProperty("subCrit." + projectionProperty, pocAlias1 + "id"));
    } else {
        subCrit.add(Restrictions.or(Restrictions.eqProperty("subCrit." + projectionProperty, pocAlias1 + "id"),
                Restrictions.eqProperty("subCrit." + projectionProperty, pocAlias2 + "id")));
    }
    return subCrit;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public List<String> findSampleIdsBy(String sampleName, String samplePointOfContact,
        String[] nanomaterialEntityClassNames, String[] otherNanomaterialEntityTypes,
        String[] functionalizingEntityClassNames, String[] otherFunctionalizingEntityTypes,
        String[] functionClassNames, String[] otherFunctionTypes, String[] characterizationClassNames,
        String[] otherCharacterizationTypes, String[] wordList) throws Exception {
    List<String> sampleIds = new ArrayList<String>();

    //logger.error("Processing: " + sampleName);

    // can't query for the entire Sample object due to
    // limitations in pagination in SDK

    // added createdDate and sample name in the results so data can be
    // sorted by date and name
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
            .setProjection(Projections.projectionList().add(Projections.property("id"))
                    .add(Projections.property("name")).add(Projections.property("createdDate")));
    if (!StringUtils.isEmpty(sampleName)) {
        TextMatchMode nameMatchMode = new TextMatchMode(sampleName);
        crit.add(Restrictions.ilike("name", nameMatchMode.getUpdatedText(), nameMatchMode.getMatchMode()));
    }//from  ww  w .  j  av  a 2  s .  c  om
    if (!StringUtils.isEmpty(samplePointOfContact)) {
        TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("primaryPointOfContact", "pointOfContact");
        crit.createAlias("pointOfContact.organization", "organization");
        crit.createAlias("otherPointOfContactCollection", "otherPoc", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("otherPoc.organization", "otherOrg", CriteriaSpecification.LEFT_JOIN);
        String[] critStrs = { "pointOfContact.lastName", "pointOfContact.firstName", "pointOfContact.role",
                "organization.name", "otherPoc.lastName", "otherPoc.firstName", "otherOrg.name" };
        for (String critStr : critStrs) {
            Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode.getUpdatedText(),
                    pocMatchMode.getMatchMode());
            disjunction.add(pocCrit);
        }
        crit.add(disjunction);
    }

    // join composition
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0
            || functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
        crit.createAlias("sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
    }
    // join nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // join functionalizing entity
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0) {
            Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class", nanomaterialEntityClassNames);
            disjunction.add(nanoEntityCrit);
        }
        if (otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0) {
            Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class", "OtherNanomaterialEntity");
            Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type", otherNanomaterialEntityTypes);
            Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1, otherNanoCrit2);
            disjunction.add(otherNanoCrit);
        }
        crit.add(disjunction);
    }

    // functionalizing entity
    // need to turn class names into integers in order for the .class
    // clause to work
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0) {
            Integer[] functionalizingEntityClassNameIntegers = this
                    .convertToFunctionalizingEntityClassOrderNumber(functionalizingEntityClassNames);
            Criterion funcEntityCrit = Restrictions.in("funcEntity.class",
                    functionalizingEntityClassNameIntegers);
            disjunction.add(funcEntityCrit);
        }
        if (otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
            Integer classOrderNumber = Constants.FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP
                    .get("OtherFunctionalizingEntity");
            Criterion otherFuncCrit1 = Restrictions.eq("funcEntity.class", classOrderNumber);
            Criterion otherFuncCrit2 = Restrictions.in("funcEntity.type", otherFunctionalizingEntityTypes);
            Criterion otherFuncCrit = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
            disjunction.add(otherFuncCrit);
        }
        crit.add(disjunction);
    }

    // function
    if (functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("nanoEntity.composingElementCollection", "compElement",
                CriteriaSpecification.LEFT_JOIN).createAlias("compElement.inherentFunctionCollection", "inFunc",
                        CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("funcEntity.functionCollection", "func", CriteriaSpecification.LEFT_JOIN);
        if (functionClassNames != null && functionClassNames.length > 0) {
            Criterion funcCrit1 = Restrictions.in("inFunc.class", functionClassNames);
            Criterion funcCrit2 = Restrictions.in("func.class", functionClassNames);
            disjunction.add(funcCrit1).add(funcCrit2);
        }
        if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
            Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq("inFunc.class", "OtherFunction"),
                    Restrictions.in("inFunc.type", otherFunctionTypes));
            Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq("func.class", "OtherFunction"),
                    Restrictions.in("func.type", otherFunctionTypes));
            disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
        }
        crit.add(disjunction);
    }

    // join characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0
            || wordList != null && wordList.length > 0) {
        crit.createAlias("characterizationCollection", "chara", CriteriaSpecification.LEFT_JOIN);
    }
    // characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (characterizationClassNames != null && characterizationClassNames.length > 0) {
            Criterion charCrit = Restrictions.in("chara.class", characterizationClassNames);
            disjunction.add(charCrit);
        }
        if (otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
            Criterion otherCharCrit1 = Restrictions.eq("chara.class", "OtherCharacterization");
            Criterion otherCharCrit2 = Restrictions.in("chara.name", otherCharacterizationTypes);
            Criterion otherCharCrit = Restrictions.and(otherCharCrit1, otherCharCrit2);
            disjunction.add(otherCharCrit);
        }
        crit.add(disjunction);
    }
    // join keyword, finding, publication
    if (wordList != null && wordList.length > 0) {
        crit.createAlias("keywordCollection", "keyword1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("chara.findingCollection", "finding", CriteriaSpecification.LEFT_JOIN)
                .createAlias("finding.fileCollection", "charFile", CriteriaSpecification.LEFT_JOIN)
                .createAlias("charFile.keywordCollection", "keyword2", CriteriaSpecification.LEFT_JOIN);
        // publication keywords
        crit.createAlias("publicationCollection", "pub1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("pub1.keywordCollection", "keyword3", CriteriaSpecification.LEFT_JOIN);
    }

    // keyword
    if (wordList != null && wordList.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        for (String keyword : wordList) {
            // strip wildcards from either ends of keyword
            keyword = StringUtils.stripWildcards(keyword);
            Criterion keywordCrit1 = Restrictions.ilike("keyword1.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit2 = Restrictions.ilike("keyword2.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit3 = Restrictions.ilike("keyword3.name", keyword, MatchMode.ANYWHERE);
            disjunction.add(keywordCrit1);
            disjunction.add(keywordCrit2);
            disjunction.add(keywordCrit3);
        }
        for (String word : wordList) {
            Criterion summaryCrit1 = Restrictions.ilike("chara.designMethodsDescription", word,
                    MatchMode.ANYWHERE);
            Criterion summaryCrit2 = Restrictions.ilike("charFile.description", word, MatchMode.ANYWHERE);
            Criterion summaryCrit = Restrictions.or(summaryCrit1, summaryCrit2);
            disjunction.add(summaryCrit);
        }
        crit.add(disjunction);
    }

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();

    List results = appService.query(crit);

    int resSize = results.size();
    /*
     * We will look only though the maximum amount of allowed records to avoid Exceptions
     */
    int maxCount = appService.getMaxRecordsCount();
    Set<Sample> samples = new HashSet<Sample>();
    for (int i = 0; (i < resSize) && (i < maxCount); i++) {
        try {
            /*
             * There is a bug when searching with keyword "tes", where the following line
             * whould trigger a ClassCastException. Reason unknow but suspected to be reaching
             * the last row of a dataset. 
             */
            //            Object[] row = (Object[]) obj;
            Object[] row = (Object[]) results.get(i);

            Long sampleId = (Long) row[0];
            if (springSecurityAclService.currentUserHasReadPermission(sampleId,
                    SecureClassesEnum.SAMPLE.getClazz())
                    || springSecurityAclService.currentUserHasWritePermission(sampleId,
                            SecureClassesEnum.SAMPLE.getClazz())) {
                Sample sample = new Sample();
                sample.setId(sampleId);
                sample.setName((String) row[1]);
                sample.setCreatedDate((Date) row[2]);
                samples.add(sample);
            } else {
                logger.debug("User doesn't have access to sample of ID: " + sampleId);
            }

        } catch (ClassCastException e) {
            logger.error("Got ClassCastException: " + e.getMessage());
            break;
        }
    }

    List<Sample> orderedSamples = new ArrayList<Sample>(samples);
    // Collections.sort(orderedSamples,
    // Collections.reverseOrder(new Comparators.SampleDateComparator()));

    Collections.sort(orderedSamples, new Comparators.SampleDateComparator());

    for (Sample sample : orderedSamples) {
        sampleIds.add(sample.getId().toString());
    }

    return sampleIds;
}