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:es.tekniker.framework.ktek.questionnaire.mng.db.QuestionnaireManagerDB.java

License:Open Source License

public Ktek_questionnaire getQuestionnaire(PersistentSession session, int idquestionnaire) throws Exception {
    Ktek_questionnaire instance = null;/*w w  w. ja v  a2  s.com*/
    DAOFactory lDAOFactory = null;
    Ktek_questionnaireDAO instanceDAO = null;
    Ktek_questionnaireCriteria objKtek_questionnaireCriteria = null;
    long nowInMillis = 0;
    try {
        nowInMillis = Utils.getCalendarGMT().getTimeInMillis();

        lDAOFactory = es.tekniker.framework.ktek.questionnaire.DAOFactory.getDAOFactory();
        instanceDAO = lDAOFactory.getKtek_questionnaireDAO();

        objKtek_questionnaireCriteria = new Ktek_questionnaireCriteria();
        objKtek_questionnaireCriteria.ktek_pk_idquestionnaire.eq(idquestionnaire);
        objKtek_questionnaireCriteria.isdeleted.eq((short) 0);
        objKtek_questionnaireCriteria.datevalidfrom.lt(nowInMillis);

        objKtek_questionnaireCriteria.add(Restrictions.or(Restrictions.isNull("datevalidto"),
                Restrictions.gt("datevalidto", nowInMillis)));

        instance = instanceDAO.loadKtek_questionnaireByCriteria(objKtek_questionnaireCriteria);

        if (instance != null)
            log.debug("getQuestionnaire instance is not null");
        else
            log.info("getQuestionnaire instance is null for idquestionnaire " + idquestionnaire);

    } catch (Exception e) {
        log.error("getQuestionnaire Exception " + e.getMessage());
        e.printStackTrace();
        throw e;
    }

    return instance;
}

From source file:es.tid.fiware.rss.dao.impl.DbeTransactionDaoImpl.java

License:Open Source License

private Criteria getCriteriaTxBySvcRefcPrdtUserDate(String transactionId, Long nuServiceId, String refCode,
        Long nuProductId, Long nuMopId, String enduserid, Date fromDate, Date untilDate, String applicationId,
        String[] txTypes, String operationNature, String originalTxId, String gUserId, Long paymentMethodType) {
    Criteria criteria = this.getSession().createCriteria(DbeTransaction.class);

    if (null != transactionId) {
        criteria.add(Restrictions.eq("txTransactionId", transactionId));
    }/*from   w w w.  ja  v a2  s . c o m*/
    if (null != nuServiceId) {
        criteria.add(Restrictions.eq("bmService.nuServiceId", nuServiceId));
    }
    if (null != refCode) {
        criteria.add(Restrictions.eq("txReferenceCode", refCode));
    }
    if (null != nuProductId) {
        criteria.add(Restrictions.eq("bmProduct.nuProductId", nuProductId));
    }
    if (null != nuMopId) {
        criteria.add(Restrictions.eq("bmObMop.id.nuMopId", nuMopId));
    }
    if (null != enduserid) {
        criteria.add(Restrictions.eq("txEndUserId", enduserid));
    }
    if (null != applicationId) {
        criteria.add(Restrictions.eq("txApplicationId", applicationId));
    }
    if (null != fromDate) {
        criteria.add(Restrictions.ge("tsClientDate", fromDate));
    }
    if (null != untilDate) {
        criteria.add(Restrictions.le("tsClientDate", untilDate));
    }
    if ((null != txTypes) && (txTypes.length > 0)) {
        Criterion crTxTypes = Restrictions.eq("tcTransactionType", txTypes[0]);
        for (int i = 1; i < txTypes.length; i++) {
            crTxTypes = Restrictions.or(crTxTypes, Restrictions.eq("tcTransactionType", txTypes[i]));
        }
        criteria.add(crTxTypes);
    }
    if (null != operationNature) {
        criteria.add(Restrictions.eq("txOperationNature", operationNature));
    }
    if (null != originalTxId) {
        criteria.add(Restrictions.eq("txOrgTransactionId", originalTxId));
    }
    if (null != gUserId) {
        criteria.add(Restrictions.eq("txGlobalUserId", gUserId));
    }
    if (null != paymentMethodType) {
        criteria.add(Restrictions.eq("bmObMop.id.nuMopId", paymentMethodType));
    }

    return criteria;
}

From source file:es.ua.datos.cad.CAD.java

public List<DatasetTransp> getDatasetsTranspByDesc(String abbreviationLanguage, String desc) {

    List<DatasetTransp> datasetsTransp = new ArrayList<DatasetTransp>();

    Utilities utilities = new Utilities();

    desc.trim();//  w w  w . ja  v  a  2s .c o  m
    List<String> splitDescription = Arrays.asList(desc.split(" "));
    List<String> splitDescriptionWithoutStopWords = null;
    if (abbreviationLanguage.equals("es"))
        splitDescriptionWithoutStopWords = utilities.removeStopWordsTXT(splitDescription);
    else if (abbreviationLanguage.equals("va"))
        splitDescriptionWithoutStopWords = utilities.removeStopWordsTXTVa(splitDescription);
    else if (abbreviationLanguage.equals("en"))
        splitDescriptionWithoutStopWords = utilities.removeStopWordsTXTEn(splitDescription);

    Transaction tx = null;

    //Session session = null;

    /*if(this.session.isOpen())
       this.session = sessionFactory.getCurrentSession();
    else*/
    //this.session = sessionFactory.openSession();   
    this.session = sessionFactory.getCurrentSession();

    try {

        if (abbreviationLanguage.equals("es")) {

            tx = this.session.beginTransaction();

            Criteria criteria = this.session.createCriteria(DatasetTransp.class);

            for (String str : splitDescriptionWithoutStopWords) {
                System.out.println(str);
                Criterion name = Restrictions.ilike("nameDatasetTransp", "%" + str + "%");
                Criterion description = Restrictions.ilike("description", "%" + str + "%");
                Criterion publisher = Restrictions.ilike("publisher", "%" + str + "%");
                //LogicalExpression orRestriction = Restrictions.or(description, name,publisher);
                //criteria.add(orRestriction);
                criteria.add(Restrictions.or(Restrictions.or(name, description), publisher));
            }

            Criterion visibility = Restrictions.eq("visibility", "visible");

            criteria.add(visibility);
            //Sin duplicados
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

            datasetsTransp = criteria.list();

            for (DatasetTransp ds : datasetsTransp)
                System.out.println(ds.getIdDatasetTransp());

            tx.commit();

        } else {// Si no es en castellano traducimos      

            datasetsTransp = getTranslationDatasetTranspByDesc(abbreviationLanguage, desc);

        }

    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        //Si esta abierta la cerramos
        //if(this.session.isOpen())
        // this.session.close();System.out.println("SESSION CLOSE === getDatasetsTranspByDesc");

    }

    return datasetsTransp;
}

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./*from w w  w.  j  a v a 2s.c o  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:fr.gael.dhus.olingo.v1.SQLVisitor.java

License:Open Source License

private Criterion getCriterionLogical(BinaryOperator operator, Criterion left, Criterion right) {
    Criterion criterion;//from   www  .  j  av  a 2 s .c o m
    if (left == null && right == null) {
        criterion = null;
    } else if (left != null && right != null) {
        switch (operator) {
        case AND: {
            criterion = Restrictions.and(left, right);
            break;
        }
        case OR: {
            criterion = Restrictions.or(left, right);
            break;
        }
        default: {
            throw new UnsupportedOperationException("Unsupported operator: " + operator.toUriLiteral());
        }
        }
    } else if (left == null) {
        criterion = right;
    } else {
        criterion = left;
    }
    return criterion;
}

From source file:fr.mcc.ginco.dao.hibernate.AssociativeRelationshipDAO.java

License:CeCILL license

@Override
public List<String> getAssociatedConcepts(ThesaurusConcept concept) {

    DetachedCriteria d1 = DetachedCriteria.forClass(AssociativeRelationship.class, "ar1");
    d1.setProjection(Projections.projectionList().add(Projections.property("ar1.identifier.concept2")));
    d1.add(Restrictions.eq("identifier.concept1", concept.getIdentifier()));

    DetachedCriteria d2 = DetachedCriteria.forClass(AssociativeRelationship.class, "ar2");
    d2.setProjection(Projections.projectionList().add(Projections.property("ar2.identifier.concept1")));
    d2.add(Restrictions.eq("identifier.concept2", concept.getIdentifier()));

    Criteria criteria = getCurrentSession().createCriteria(ThesaurusConcept.class, "tc")
            .add(Restrictions.or(Subqueries.propertyIn("tc.identifier", d1),
                    Subqueries.propertyIn("tc.identifier", d2)))
            .setProjection(Projections.property("tc.identifier"));

    return criteria.list();
}

From source file:fr.mcc.ginco.dao.hibernate.AssociativeRelationshipDAO.java

License:CeCILL license

@Override
public AssociativeRelationship getAssociativeRelationship(String id1, String id2) {
    Criteria criteria = getCurrentSession().createCriteria(AssociativeRelationship.class, "ar")
            .add(Restrictions.or(
                    Restrictions.and(Restrictions.eq("conceptLeft.identifier", id1),
                            Restrictions.eq("conceptRight.identifier", id2)),
                    Restrictions.and(Restrictions.eq("conceptRight.identifier", id1),
                            Restrictions.eq("conceptLeft.identifier", id2))));

    return (AssociativeRelationship) criteria.uniqueResult();
}

From source file:fr.mcc.ginco.dao.hibernate.ThesaurusConceptDAO.java

License:CeCILL license

private void selectNoParents(Criteria criteria) {
    criteria.add(Restrictions.or(Restrictions.isNull("tc.parentConcepts"),
            Restrictions.isEmpty("tc.parentConcepts")));
}

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

@Override
public RoadOperationSummaryBO operationSummaryReport(OperationSummaryReportCriteriaBO reportCriteria,
        String userName, String userRegion, ReportDisplayInformationDAOImpl reportDisplayInformation) {
    Criteria criteriaRoadOp = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(RoadOperationDO.class, "ro");

    criteriaRoadOp.createAlias("ro.category", "cat");

    Criterion subCriteron = null;/*  www  .j  a v  a 2s . co  m*/

    Criterion mainCriteron = null;

    if (reportCriteria.getOperationStartDate() != null && reportCriteria.getOperationEndDate() != null) {
        mainCriteron = Restrictions.or(
                Restrictions.between("ro.scheduledStartDtime",
                        DateUtils.searchDateFormater(reportCriteria.getOperationStartDate(),
                                DateUtils.SEARCHDATETYPE.START),
                        DateUtils.searchDateFormater(reportCriteria.getOperationEndDate(),
                                DateUtils.SEARCHDATETYPE.END)),
                Restrictions.between("ro.scheduledEndDtime",
                        DateUtils.searchDateFormater(reportCriteria.getOperationStartDate(),
                                DateUtils.SEARCHDATETYPE.START),
                        DateUtils.searchDateFormater(reportCriteria.getOperationEndDate(),
                                DateUtils.SEARCHDATETYPE.END)));
    }

    if (reportCriteria.getTAOfficeRegions() != null && reportCriteria.getTAOfficeRegions().size() > 0) {

        subCriteron = Restrictions.in("ro.officeLocCode", reportCriteria.getTAOfficeRegions());

    }

    if (reportCriteria.getTeamLeadStaffIds() != null && reportCriteria.getTeamLeadStaffIds().size() > 0)

    {

        /* Get List of all road operations with staff as team lead. */
        Criteria teamLeadsByStaffIdCrit = this.getSession().createCriteria(TeamDO.class, "team");
        teamLeadsByStaffIdCrit
                .add(Restrictions.in("team.teamLead.staffId", reportCriteria.getTeamLeadStaffIds()));
        teamLeadsByStaffIdCrit.setProjection(Projections.property("team.roadOperation.roadOperationId"));

        List<Integer> teamLeadsByStaffId = teamLeadsByStaffIdCrit.list();

        if (teamLeadsByStaffId != null && teamLeadsByStaffId.size() > 0) {
            if (subCriteron == null) {
                subCriteron = Restrictions.in("ro.roadOperationId", teamLeadsByStaffId);
            } else {
                subCriteron = Restrictions.and(subCriteron,
                        Restrictions.in("ro.roadOperationId", teamLeadsByStaffId));
            }
        }
    }

    if (reportCriteria.getTeamLeadTRNs() != null && reportCriteria.getTeamLeadTRNs().size() > 0) {
        /* Get List of all road operations with staff as team lead. */
        Criteria teamLeadsByTRNCrit = this.getSession().createCriteria(TeamDO.class, "team");
        teamLeadsByTRNCrit.createAlias("team.teamLead", "teamLead");
        teamLeadsByTRNCrit.createAlias("teamLead.person", "person");
        teamLeadsByTRNCrit.add(Restrictions.in("person.trnNbr", reportCriteria.getTeamLeadTRNs()));
        teamLeadsByTRNCrit.setProjection(Projections.property("team.roadOperation.roadOperationId"));

        List<Integer> teamLeadsByTRN = teamLeadsByTRNCrit.list();

        if (teamLeadsByTRN != null && teamLeadsByTRN.size() > 0) {
            if (subCriteron == null) {
                subCriteron = Restrictions.in("ro.roadOperationId", teamLeadsByTRNCrit.list());
            } else {
                subCriteron = Restrictions.and(subCriteron,
                        Restrictions.in("ro.roadOperationId", teamLeadsByTRNCrit.list()));
            }
        }
    }

    if (reportCriteria.getOperationCategory() != null && !reportCriteria.getOperationCategory().isEmpty()) {
        if (subCriteron == null) {
            subCriteron = Restrictions
                    .eq("ro.category.categoryId", reportCriteria.getOperationCategory().trim()).ignoreCase();
        } else {
            subCriteron = Restrictions.and(subCriteron, Restrictions
                    .eq("ro.category.categoryId", reportCriteria.getOperationCategory().trim()).ignoreCase());
        }
    }

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

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

    if (reportCriteria.getRoadOperationIds() != null && !reportCriteria.getRoadOperationIds().isEmpty()) {
        if (subCriteron == null) {
            subCriteron = Restrictions.in("ro.roadOperationId", reportCriteria.getRoadOperationIds());
        } else {
            subCriteron = Restrictions.and(subCriteron,
                    Restrictions.in("ro.roadOperationId", reportCriteria.getRoadOperationIds()));
        }
    }

    if (subCriteron == null && mainCriteron != null)
        criteriaRoadOp.add(mainCriteron);
    else if (mainCriteron == null && subCriteron != null)
        criteriaRoadOp.add(subCriteron);
    else if (mainCriteron != null && subCriteron != null)
        criteriaRoadOp.add(Restrictions.and(mainCriteron, subCriteron));
    else
        return null;

    /* Get report criteria names and descriptions */
    reportCriteria.setTAOfficeDescription(this.getTAOfficeRegionDescription(userRegion));

    if (reportCriteria.getTeamLeadStaffIds() != null && reportCriteria.getTeamLeadStaffIds().size() > 0)
        reportCriteria.setTAStaffFullName(this.getTAStaffNames(reportCriteria.getTeamLeadStaffIds()));
    else if (reportCriteria.getTeamLeadTRNs() != null && reportCriteria.getTeamLeadTRNs().size() > 0)
        reportCriteria.setTAStaffFullName(this.getPersonNamesWithTRN(reportCriteria.getTeamLeadTRNs()));

    reportCriteria.setOperationCategoryDescription(
            this.getOperationCategoryDesc(reportCriteria.getOperationCategory()));

    criteriaRoadOp.addOrder(Order.asc("ro.officeLocCode"));
    criteriaRoadOp.addOrder(Order.asc("cat.description"));
    criteriaRoadOp.addOrder(Order.asc("ro.actualStartDtime"));
    criteriaRoadOp.addOrder(Order.asc("ro.actualEndDtime"));
    criteriaRoadOp.addOrder(Order.asc("ro.operationName"));

    List<RoadOperationSummaryResultsBO> results = new ArrayList<RoadOperationSummaryResultsBO>();

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

    }

    for (RoadOperationDO roadOp : (List<RoadOperationDO>) criteriaRoadOp.list()) {
        // Get counts that are needed to fill roadOpSummaryReportList
        Integer absentMembersCount = this.absentPersonCount(roadOp.getRoadOperationId());

        Integer teamMemberCount = this.teamMemberPersonCount(roadOp.getRoadOperationId());

        Integer summonsCount = this.summonsCount(roadOp.getRoadOperationId());

        Integer warningNoProsecutionCount = this.warningNoProsecutionCount(roadOp.getRoadOperationId());

        Integer warningNoticeCount = this.warningNoticeCount(roadOp.getRoadOperationId());

        Integer vehicleSeizedCount = this.roadCheckOutcomeCount(roadOp.getRoadOperationId(),
                Constants.OutcomeType.VEHICLE_SEIZURE);

        Integer complianceCount = this.complianceCount(roadOp.getRoadOperationId());

        Integer motorVehicleCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.MOTOR_VEHICLE);

        Integer dlCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.DRIVERS_LICENCE);

        Integer badgeCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.BADGE);

        Integer citationCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.CITATION);

        Integer roadLicenceCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.ROAD_LICENCE);

        Integer otherCheckCount = this.roadCheckTypeCount(roadOp.getRoadOperationId(),
                Constants.RoadCheckType.OTHER);

        Integer countJPs = this.getCountOfPersonType(roadOp.getRoadOperationId(), Constants.PersonType.JP);

        Integer countPoliceOfficers = this.getCountOfPersonType(roadOp.getRoadOperationId(),
                Constants.PersonType.POLICE_OFFCER);

        Integer countTAInspectors = this.getCountOfPersonType(roadOp.getRoadOperationId(),
                Constants.PersonType.TA_STAFF);

        Integer countITAExaminers = this.getCountOfPersonType(roadOp.getRoadOperationId(),
                Constants.PersonType.ITA_EXAMINER);

        /*****
         * UR-057 Got absent count for each person type
         */

        Integer absentITACount = absentPersonTypeCount(roadOp.getRoadOperationId(),
                Constants.PersonType.ITA_EXAMINER);
        Integer absentTACount = absentPersonTypeCount(roadOp.getRoadOperationId(),
                Constants.PersonType.TA_STAFF);
        Integer absentPoliceCount = absentPersonTypeCount(roadOp.getRoadOperationId(),
                Constants.PersonType.POLICE_OFFCER);
        Integer absentJPCount = absentPersonTypeCount(roadOp.getRoadOperationId(), Constants.PersonType.JP);

        /* __________________________________________________________________________ */

        /*
         * Get Duration of an road operation using actual start and end
         * time.
         */

        long operationDuration = 0;

        if (roadOp.getActualStartDtime() != null && roadOp.getActualEndDtime() != null)
            operationDuration = DateUtils.getDateDiff(roadOp.getActualStartDtime(), roadOp.getActualEndDtime(),
                    TimeUnit.MINUTES);

        /* ___________________________________________________________________ */

        RoadOperationSummaryResultsBO result = new RoadOperationSummaryResultsBO(
                roadOp.getAuditEntry().getCreateDTime()/* operationCreateDate */,
                roadOp.getScheduledEndDtime()/* scheduledEndDateTime */,
                roadOp.getScheduledStartDtime()/* scheduledStartDateTime */,
                roadOp.getActualStartDtime()/* actualStartDateTime */,
                roadOp.getActualEndDtime()/* actualEndDateTime */,
                roadOp.getStatus().getDescription()/* operationStatus */,
                roadOp.getCategory().getDescription()/* operationCategory */,
                roadOp.getOperationName()/* operationName */, summonsCount/* countSummonsIssued */,
                warningNoticeCount/* countWaningNoticesIssued */, vehicleSeizedCount/* countVehiclesSeized */,
                complianceCount/* countCompliancyActivitiesCommited */,
                motorVehicleCheckCount/* countMotorVehiclesChecked */,
                dlCheckCount/* countDrivesLicenceChecked */, badgeCheckCount/* countBadgesChecked */,
                citationCheckCount/* countCitationChecks */,
                roadLicenceCheckCount/* countRoadLicencesChecked */, otherCheckCount/* countOtherChecks */,
                (int) operationDuration/* durationOfOperationInMinutes */,
                absentMembersCount/* countAbsentMembers */, roadOp.getRoadOperationId()/* operationId */,
                this.roadCheckOutcomeCount(roadOp.getRoadOperationId(),
                        Constants.OutcomeType.REMOVE_PLATES)/* countPlatesRemoved */,
                this.roadCheckOutcomeCount(roadOp.getRoadOperationId(),
                        Constants.OutcomeType.WARNED_FOR_PROSECUTION)/* warningsForProcecution */,
                this.roadCheckOutcomeCount(roadOp.getRoadOperationId(), Constants.OutcomeType.ALL_IN_ORDER)/*
                                                                                                           * Integer
                                                                                                           * allInOrders
                                                                                                           */,
                teamMemberCount /* count team members */,
                this.getRoadOpTeamSummaryResults(roadOp.getRoadOperationId()) /* team Summaries */,
                roadOp.getOfficeLocCode()/*TAOfficeRegion*/,
                this.getTAOfficeRegionDescription(roadOp.getOfficeLocCode())/*TAOfficeRegion*/);

        result.setCountWarningNoProsecutions(warningNoProsecutionCount);
        result.setCountITAExaminers(countITAExaminers);
        result.setCountPoliceOfficers(countPoliceOfficers);
        result.setCountJPs(countJPs);
        result.setCountTAInspectors(countTAInspectors);

        /*****
         * UR-057 - Set absentee values for each assigned person group
         */
        result.setCountAbsentITAExaminers(absentITACount);
        result.setCountAbsentJPs(absentJPCount);
        result.setCountAbsentPoliceOfficers(absentPoliceCount);
        result.setCountAbsentTAInspectors(absentTACount);

        results.add(result);
    }

    return new RoadOperationSummaryBO(userName, userRegion, reportDisplayInformation.applicationName,
            reportDisplayInformation.roadOperationSummaryTitle + stringStartDate + " TO " + stringEndDate,
            reportCriteria.getOperationStartDate(), reportCriteria.getOperationEndDate(),
            reportCriteria.getSearchCriteriaString(), this.getTAOfficeRegionDescription(userRegion), results);
}

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

@Override
public SummonsOutstandingReportBO summonsOutstandingReport(SummonsOutstandingReportCriteriaBO 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");

    Date reportStartDate = DateUtils.searchDateFormater(reportCriteria.getOperationStartDate(),
            DateUtils.SEARCHDATETYPE.START);
    Date reportEndDate = DateUtils.searchDateFormater(reportCriteria.getOperationEndDate(),
            DateUtils.SEARCHDATETYPE.END);

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

    /* Only summons which are not yet issued should be returned */
    List<String> summonsOutstandingStatusList = new ArrayList<String>();
    summonsOutstandingStatusList.add(fsl.ta.toms.roms.constants.Constants.DocumentStatus.CANCELLED);
    summonsOutstandingStatusList.add(fsl.ta.toms.roms.constants.Constants.DocumentStatus.WITHDRAWN);
    summonsOutstandingStatusList.add(fsl.ta.toms.roms.constants.Constants.DocumentStatus.SERVED);
    Criterion subCriterion = Restrictions.not(Restrictions.in("st.statusId", summonsOutstandingStatusList));
    /* _________________________________________________________ */

    if (reportCriteria.getOffenderId() != null && reportCriteria.getOffenderId() > 0) {
        subCriterion = Restrictions.and(subCriterion,
                Restrictions.eq("of.personId", reportCriteria.getOffenderId()));
    }/*w w w .ja v a2s .c  o  m*/

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

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

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

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

    }

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

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

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

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

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

    criteria.add(Restrictions.and(mainCriterion, subCriterion));

    NameUtil nameUtil = new NameUtil();
    String stringStartDate = "";
    String stringEndDate = "";
    try {
        stringStartDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationStartDate());
        stringEndDate = DateUtils.getFormattedUtilDate(reportCriteria.getOperationEndDate());
    } 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()));
     */
    /* __________________________________________ */

    SummonsOutstandingReportBO report = new SummonsOutstandingReportBO(userName, userRegion,
            reportDisplayInformation.applicationName,
            reportDisplayInformation.summonsOutstandingReportTitle + stringStartDate + " TO " + stringEndDate,
            reportCriteria.getOperationStartDate(), reportCriteria.getOperationEndDate(),
            reportCriteria.getSearchCriteriaString(), getTAOfficeRegionDescription(userRegion));

    List<SummonsOutstandingReportResultsBO> summonsOutStReportList = new ArrayList<SummonsOutstandingReportResultsBO>();

    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());
        }
        /* _______________________________ */

        SummonsOutstandingReportResultsBO summonsOutstanding = new SummonsOutstandingReportResultsBO(
                offenderFullName, offenceDescription, tAStaffFullName, vehicleDetails, locationOfOffence,
                tAOfficeRegion, jPFullName, roadOperationDetails, courtDetails,
                getTAOfficeRegionDescription(tAOfficeRegion), summons.getServedOnDate());

        summonsOutStReportList.add(summonsOutstanding);
    }

    report.setResults(summonsOutStReportList);
    return report;
}