Example usage for org.hibernate.criterion Restrictions gt

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

Introduction

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

Prototype

public static SimpleExpression gt(String propertyName, Object value) 

Source Link

Document

Apply a "greater than" constraint to the named property

Usage

From source file:org.smallmind.persistence.orm.hibernate.HibernateDao.java

License:Open Source License

public Iterable<D> scrollById(final I greaterThan, final int fetchSize) {

    return scrollByCriteria(new CriteriaDetails() {

        @Override/*from  ww  w.  j  av  a 2s  .c o  m*/
        public Criteria completeCriteria(Criteria criteria) {

            return criteria.add(Restrictions.gt("id", greaterThan)).addOrder(Order.asc("id"))
                    .setFetchSize(fetchSize);
        }
    });
}

From source file:org.socraticgrid.alertmanager.dao.AlertTicketDao.java

License:Apache License

/**
 * Perform a query for tickets//  ww  w .ja va2  s . c  o  m
 *
 * @param params Query parameters
 * @return Query results
 */
@SuppressWarnings("unchecked")
public List<AlertTicket> findTickets(TicketQueryParams params) {
    log.debug("Beginning ticket query");

    String ticketUniqueId = null;
    Integer escalationPeriodGT = null;
    String action = null;
    String actionUserId = null;
    String patientId = null;
    String type = null;
    Boolean archive = null;
    Boolean deleteFlag = null;

    if (params != null) {
        ticketUniqueId = params.getTicketUniqueId();
        escalationPeriodGT = params.getEscalationPeriodGT();
        patientId = params.getPatientId();
        type = params.getType();

        archive = params.isArchive();
        deleteFlag = params.getDeleteFlag();
        actionUserId = params.getActionUserId();
    }

    List<AlertTicket> tickets = null;
    Session sess = null;
    try {
        SessionFactory fact = HibernateUtil.getSessionFactory();
        if (fact != null) {
            sess = fact.openSession();
            if (sess != null) {
                Criteria criteria = sess.createCriteria(AlertTicket.class);

                if (ticketUniqueId != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Ticket query - ticket unique id: " + ticketUniqueId);
                    }
                    criteria.add(Restrictions.eq("ticketUniqueId", ticketUniqueId));
                }

                if (escalationPeriodGT != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Ticket query - escalationPeriod greater than: " + escalationPeriodGT);
                    }
                    criteria.add(Restrictions.gt("escalationPeriod", escalationPeriodGT));
                }

                if (patientId != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Ticket query - patientId: " + patientId);
                    }

                    criteria.add(Restrictions.eq("patientUnitNumber", patientId));
                }

                if (type != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Ticket query - type: " + type);
                    }

                    criteria.add(Restrictions.eq("type", type));
                }

                //FILTER for AlertContact
                if (actionUserId != null) {

                    if (log.isDebugEnabled()) {
                        log.debug("Ticket query - Recipient id: " + actionUserId);
                    }

                    criteria.createCriteria("providers").add(Restrictions.eq("userId", actionUserId));
                }

                //FILTER for AlertStatus
                if ((archive != null) && (deleteFlag != null)) {

                    if (actionUserId != null) {
                        criteria.createCriteria("status")
                                .add(Restrictions.and(
                                        Restrictions.and(Restrictions.eq("archive", archive.booleanValue()),
                                                Restrictions.eq("deleted", deleteFlag.booleanValue())),
                                        Restrictions.eq("userId", actionUserId)));
                    } else {
                        criteria.createCriteria("status")
                                .add(Restrictions.and(Restrictions.eq("archive", archive.booleanValue()),
                                        Restrictions.eq("deleted", deleteFlag.booleanValue())));
                    }
                } else if ((archive != null) && (deleteFlag == null)) {

                    if (actionUserId != null) {
                        criteria.createCriteria("status")
                                .add(Restrictions.and(Restrictions.eq("archive", archive.booleanValue()),
                                        Restrictions.eq("userId", actionUserId)));
                    } else {

                        criteria.createCriteria("status")
                                .add(Restrictions.eq("archive", archive.booleanValue()));
                    }
                } else if ((archive == null) && (deleteFlag != null)) {

                    if (actionUserId != null) {
                        criteria.createCriteria("status")
                                .add(Restrictions.and(Restrictions.eq("deleted", deleteFlag.booleanValue()),
                                        Restrictions.eq("userId", actionUserId)));
                    } else {

                        criteria.createCriteria("status")
                                .add(Restrictions.eq("deleted", deleteFlag.booleanValue()));
                    }
                }
                //TMNTIME
                long startTime = System.currentTimeMillis();
                criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
                tickets = criteria.list();

                long duration = System.currentTimeMillis() - startTime;
                System.out.println("TIME(ms): " + duration);

            } else {
                log.error("Failed to obtain a session from the sessionFactory");
            }
        } else {
            log.error("Session factory was null");
        }
        if (log.isDebugEnabled()) {
            log.debug("Completed retrieve of tickets query. "
                    + ((tickets == null) ? "0" : Integer.toString(tickets.size())) + " results returned.");
        }
    } finally {
        if (sess != null) {
            try {
                sess.close();
            } catch (Throwable t) {
                log.error("Failed to close session: " + t.getMessage(), t);
            }
        }
    }
    return tickets;
}

From source file:org.squashtest.tm.internal.domain.report.common.hibernate.AboveDateCriterion.java

License:Open Source License

@Override
public Criterion makeCriterion() {
    try {//w w  w .  ja v  a 2  s.co  m
        Criterion result = null;

        Date arg = makeDate();

        result = Restrictions.gt(getAttributePath(), arg);

        return result;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.unitime.timetable.action.SolverParamDefAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SolverParamDefForm myForm = (SolverParamDefForm) form;

    // Check Access
    sessionContext.checkPermission(Right.SolverParameters);

    // Read operation to be performed
    String op = (myForm.getOp() != null ? myForm.getOp() : request.getParameter("op"));

    if (request.getParameter("op2") != null && request.getParameter("op2").length() > 0)
        op = request.getParameter("op2");

    if (op == null) {
        myForm.reset(mapping, request);/*  w  ww. j  ava  2s.co m*/
        myForm.setVisible(Boolean.TRUE);
    }

    // Reset Form
    if ("Back".equals(op)) {
        if (myForm.getUniqueId() != null)
            request.setAttribute("hash", myForm.getUniqueId());
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
    }

    if ("Add Solver Parameter".equals(op)) {
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
        myForm.setOp("Save");
        myForm.setGroup(request.getParameter("group"));
    }

    // Add / Update
    if ("Update".equals(op) || "Save".equals(op)) {
        // Validate input
        ActionMessages errors = myForm.validate(mapping, request);
        if (errors.size() > 0) {
            saveErrors(request, errors);
        } else {
            Transaction tx = null;
            try {
                SolverParameterDefDAO dao = new SolverParameterDefDAO();
                org.hibernate.Session hibSession = dao.getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                SolverParameterDef def = null;
                if (op.equals("Save"))
                    def = new SolverParameterDef();
                else
                    def = dao.get(myForm.getUniqueId(), hibSession);

                def.setName(myForm.getName());
                def.setDescription(myForm.getDescription());
                def.setDefault(myForm.getDefault());
                def.setType(myForm.getType());
                def.setVisible(myForm.getVisible());
                SolverParameterGroup group = null;
                List groups = hibSession.createCriteria(SolverParameterGroup.class)
                        .add(Restrictions.eq("name", myForm.getGroup())).list();
                if (!groups.isEmpty())
                    group = (SolverParameterGroup) groups.get(0);
                if (def.getGroup() != null && !def.getGroup().equals(group)) {
                    List list = hibSession.createCriteria(SolverParameterDef.class)
                            .add(Restrictions.eq("group", def.getGroup()))
                            .add(Restrictions.gt("order", def.getOrder())).list();
                    for (Iterator i = list.iterator(); i.hasNext();) {
                        SolverParameterDef d = (SolverParameterDef) i.next();
                        d.setOrder(new Integer(d.getOrder().intValue() - 1));
                        dao.save(d, hibSession);
                    }
                    myForm.setOrder(-1);
                }
                if (myForm.getOrder() < 0) {
                    def.setOrder(new Integer(group == null ? 0 : group.getParameters().size()));
                }
                def.setGroup(group);
                dao.saveOrUpdate(def, hibSession);

                if (tx != null)
                    tx.commit();

                hibSession.refresh(def);
                request.setAttribute("hash", def.getUniqueId().toString());
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                Debug.error(e);
            }
            myForm.reset(mapping, request);
            myForm.setVisible(Boolean.TRUE);
        }
    }

    // Edit
    if (op.equals("Edit")) {
        String id = request.getParameter("id");
        ActionMessages errors = new ActionMessages();
        if (id == null || id.trim().length() == 0) {
            errors.add("key", new ActionMessage("errors.invalid", "Unique Id : " + id));
            saveErrors(request, errors);
        } else {
            SolverParameterDefDAO dao = new SolverParameterDefDAO();
            SolverParameterDef def = dao.get(new Long(id));
            if (def == null) {
                errors.add("name", new ActionMessage("errors.invalid", "Unique Id : " + id));
                saveErrors(request, errors);
            } else {
                myForm.setUniqueId(def.getUniqueId());
                myForm.setName(def.getName());
                myForm.setOrder(def.getOrder().intValue());
                myForm.setDescription(def.getDescription());
                myForm.setGroup(def.getGroup().getName());
                myForm.setType(def.getType());
                myForm.setDefault(def.getDefault());
                myForm.setVisible(def.isVisible());
                myForm.setOp("Update");
            }
        }
    }

    // Delete 
    if ("Delete".equals(op)) {
        Transaction tx = null;

        try {
            SolverParameterDefDAO dao = new SolverParameterDefDAO();
            org.hibernate.Session hibSession = dao.getSession();
            if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                tx = hibSession.beginTransaction();

            SolverParameterDef def = dao.get(myForm.getUniqueId(), hibSession);

            List list = hibSession.createCriteria(SolverParameterDef.class)
                    .add(Restrictions.eq("group", def.getGroup())).add(Restrictions.gt("order", def.getOrder()))
                    .list();

            for (Iterator i = list.iterator(); i.hasNext();) {
                SolverParameterDef d = (SolverParameterDef) i.next();
                d.setOrder(new Integer(d.getOrder().intValue() - 1));
                dao.save(d, hibSession);
            }

            dao.delete(def, hibSession);

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
        if (myForm.getGroup() != null)
            request.setAttribute("hash", myForm.getGroup());
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
    }

    // Move Up or Down
    if ("Move Up".equals(op) || "Move Down".equals(op)) {
        Transaction tx = null;

        try {
            SolverParameterDefDAO dao = new SolverParameterDefDAO();
            org.hibernate.Session hibSession = dao.getSession();
            if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                tx = hibSession.beginTransaction();

            SolverParameterDef def = dao.get(myForm.getUniqueId(), hibSession);
            if ("Move Up".equals(op)) {
                List list = hibSession.createCriteria(SolverParameterDef.class)
                        .add(Restrictions.eq("group", def.getGroup()))
                        .add(Restrictions.eq("order", new Integer(def.getOrder().intValue() - 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterDef prior = (SolverParameterDef) list.get(0);
                    prior.setOrder(new Integer(prior.getOrder().intValue() + 1));
                    dao.save(prior, hibSession);
                    def.setOrder(new Integer(def.getOrder().intValue() - 1));
                    dao.save(def, hibSession);
                }
            } else {
                List list = hibSession.createCriteria(SolverParameterDef.class)
                        .add(Restrictions.eq("group", def.getGroup()))
                        .add(Restrictions.eq("order", new Integer(def.getOrder().intValue() + 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterDef next = (SolverParameterDef) list.get(0);
                    next.setOrder(new Integer(next.getOrder().intValue() - 1));
                    dao.save(next, hibSession);
                    def.setOrder(new Integer(def.getOrder().intValue() + 1));
                    dao.save(def, hibSession);
                }
            }
            myForm.setOrder(def.getOrder().intValue());

            if (myForm.getUniqueId() != null)
                request.setAttribute("hash", myForm.getUniqueId());

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
    }
    if ("List".equals(myForm.getOp())) {
        // Read all existing settings and store in request
        getSolverParameterDefs(request, myForm.getUniqueId());
        return mapping.findForward("list");
    }

    return mapping.findForward("Save".equals(myForm.getOp()) ? "add" : "edit");
}

From source file:org.unitime.timetable.action.SolverParamGroupsAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SolverParamGroupsForm myForm = (SolverParamGroupsForm) form;

    // Check Access
    sessionContext.checkPermission(Right.SolverParameterGroups);

    // Read operation to be performed
    String op = (myForm.getOp() != null ? myForm.getOp() : request.getParameter("op"));

    if (request.getParameter("op2") != null && request.getParameter("op2").length() > 0)
        op = request.getParameter("op2");

    if (op == null) {
        myForm.setOp("List");
    }//from w  w w . ja  va2s  .co m

    // Reset Form
    if ("Back".equals(op)) {
        myForm.reset(mapping, request);
    }

    if ("Add Solver Parameter Group".equals(op)) {
        myForm.reset(mapping, request);
        myForm.setOp("Save");
    }

    // Add / Update
    if ("Update".equals(op) || "Save".equals(op)) {
        // Validate input
        ActionMessages errors = myForm.validate(mapping, request);
        if (errors.size() > 0) {
            saveErrors(request, errors);
        } else {
            SolverParameterGroupDAO dao = new SolverParameterGroupDAO();
            SolverParameterGroup group = null;

            if (op.equals("Save"))
                group = new SolverParameterGroup();
            else
                group = dao.get(myForm.getUniqueId());

            group.setName(myForm.getName());
            group.setDescription(myForm.getDescription());
            group.setType(myForm.getType());
            if (myForm.getOrder() < 0) {
                group.setOrder(new Integer(dao.findAll().size()));
            }
            dao.saveOrUpdate(group);

            myForm.reset(mapping, request);
        }
    }

    // Edit
    if ("Edit".equals(op)) {
        String id = request.getParameter("id");
        ActionMessages errors = new ActionMessages();
        if (id == null || id.trim().length() == 0) {
            errors.add("key", new ActionMessage("errors.invalid", "Unique Id : " + id));
            saveErrors(request, errors);
        } else {
            SolverParameterGroupDAO dao = new SolverParameterGroupDAO();
            SolverParameterGroup group = dao.get(new Long(id));
            if (group == null) {
                errors.add("name", new ActionMessage("errors.invalid", "Unique Id : " + id));
                saveErrors(request, errors);
            } else {
                myForm.setUniqueId(group.getUniqueId());
                myForm.setName(group.getName());
                myForm.setOrder(group.getOrder().intValue());
                myForm.setType(group.getType());
                myForm.setDescription(group.getDescription());
                myForm.setOp("Update");
            }
        }
    }

    // Delete 
    if ("Delete".equals(op)) {
        Transaction tx = null;

        try {
            SolverParameterGroupDAO dao = new SolverParameterGroupDAO();
            org.hibernate.Session hibSession = dao.getSession();
            if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                tx = hibSession.beginTransaction();

            SolverParameterGroup group = dao.get(myForm.getUniqueId(), hibSession);

            List list = hibSession.createCriteria(SolverParameterGroup.class)
                    .add(Restrictions.gt("order", group.getOrder())).list();

            for (Iterator i = list.iterator(); i.hasNext();) {
                SolverParameterGroup g = (SolverParameterGroup) i.next();
                g.setOrder(new Integer(g.getOrder().intValue() - 1));
                dao.save(g, hibSession);
            }

            dao.delete(group, hibSession);

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
        myForm.reset(mapping, request);
    }

    // Move Up or Down
    if ("Move Up".equals(op) || "Move Down".equals(op)) {
        Transaction tx = null;

        try {
            SolverParameterGroupDAO dao = new SolverParameterGroupDAO();
            org.hibernate.Session hibSession = dao.getSession();
            if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                tx = hibSession.beginTransaction();

            SolverParameterGroup group = dao.get(myForm.getUniqueId(), hibSession);
            if ("Move Up".equals(op)) {
                List list = hibSession.createCriteria(SolverParameterGroup.class)
                        .add(Restrictions.eq("order", new Integer(group.getOrder().intValue() - 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterGroup prior = (SolverParameterGroup) list.get(0);
                    prior.setOrder(new Integer(prior.getOrder().intValue() + 1));
                    dao.save(prior, hibSession);
                    group.setOrder(new Integer(group.getOrder().intValue() - 1));
                    dao.save(group, hibSession);
                }
            } else {
                List list = hibSession.createCriteria(SolverParameterGroup.class)
                        .add(Restrictions.eq("order", new Integer(group.getOrder().intValue() + 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterGroup next = (SolverParameterGroup) list.get(0);
                    next.setOrder(new Integer(next.getOrder().intValue() - 1));
                    dao.save(next, hibSession);
                    group.setOrder(new Integer(group.getOrder().intValue() + 1));
                    dao.save(group, hibSession);
                }
            }
            myForm.setOrder(group.getOrder().intValue());

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
        myForm.reset(mapping, request);
    }

    if ("List".equals(myForm.getOp())) {
        //Read all existing settings and store in request
        getSolverParameterGroups(request);
        return mapping.findForward("list");
    }

    return mapping.findForward("Save".equals(myForm.getOp()) ? "add" : "edit");
}

From source file:org.webical.dao.hibernateImpl.EventDaoWebDavHibernateBufferedImpl.java

License:Open Source License

@Transaction(readOnly = false)
@SuppressWarnings("unchecked")
public List<Event> getEventsForPeriod(Calendar calendar, Date dtStart, Date dtEnd) throws DaoException {
    if (calendar == null || dtStart == null || dtEnd == null)
        return null;

    List<Event> eventList = new ArrayList<Event>();

    refreshCalendarEventsAfterRefreshTime(calendar);
    try {/*ww  w. j ava 2  s.c o m*/
        Criteria criteria = getSession().createCriteria(Event.class);
        criteria.add(Restrictions.eq(Calendar.CALENDAR_PROPERTY_NAME, calendar));
        criteria.add(Restrictions.lt("dtStart", new Date(dtEnd.getTime() + CalendarUtils.secondInMs)));
        criteria.add(Restrictions.gt("dtEnd", new Date(dtStart.getTime() - CalendarUtils.secondInMs)));
        if (log.isDebugEnabled())
            log.debug(criteria.toString() + " " + calendar.getName());

        List<Event> events = criteria.list();
        eventList.addAll(this.getRecurringEvents(calendar, events, dtStart, dtEnd));

        if (log.isDebugEnabled()) {
            log.debug("Events: " + eventList.size() + " for period: " + dtStart + " to " + dtEnd);
        }
        return eventList;
    } catch (Exception e) {
        log.error(e, e);
        throw new DaoException("Could not get Events", e);
    }
}

From source file:org.xerela.provider.devices.internal.OsVersionResolutionScheme.java

License:Mozilla Public License

private PageData search(String osType, String operator, String version, PageData pageData, String sortColumn,
        boolean descending) {

    AdapterMetadata adapterMetadata = DeviceProviderActivator.getAdapterService().getAdapterMetadata(osType);
    if (adapterMetadata != null) {
        Session session = DeviceProviderActivator.getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(ZDeviceLite.class).setFirstResult(pageData.getOffset())
                .setMaxResults(pageData.getPageSize());

        criteria.add(Restrictions.eq(ATTR_ADAPTER_ID, osType));
        if (version != null && version.trim().length() > 0) {
            String canonicalVersion = ServerDeviceElf.computeCononicalVersion(version,
                    adapterMetadata.getSoftwareVersionRegEx());
            if (">".equals(operator)) //$NON-NLS-1$
            {/*  w  w  w. j  a  va2 s.c om*/
                criteria.add(Restrictions.gt(ATTR_CANONICAL_OS_VERSION, canonicalVersion));
            } else if ("<".equals(operator)) //$NON-NLS-1$
            {
                criteria.add(Restrictions.lt(ATTR_CANONICAL_OS_VERSION, canonicalVersion));
            } else if ("=".equals(operator)) //$NON-NLS-1$
            {
                criteria.add(Restrictions.eq(ATTR_CANONICAL_OS_VERSION, canonicalVersion));
            } else if ("<=".equals(operator)) //$NON-NLS-1$
            {
                criteria.add(Restrictions.le(ATTR_CANONICAL_OS_VERSION, canonicalVersion));
            } else if (">=".equals(operator)) //$NON-NLS-1$
            {
                criteria.add(Restrictions.ge(ATTR_CANONICAL_OS_VERSION, canonicalVersion));
            } else {
                throw new RuntimeException(
                        String.format("Invalid operator '%s'supplied to search method.", operator)); //$NON-NLS-1$
            }
        }

        return populatePageData(pageData, criteria, sortColumn, descending);
    }

    return new PageData();
}

From source file:org.yes.cart.service.domain.impl.CustomerOrderServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}/* w  ww .j  a va 2 s.c  om*/
 */
public List<CustomerOrder> findCustomerOrders(final Customer customer, final Date since) {
    if (since == null) {
        return getGenericDao().findByCriteria(Restrictions.eq("customer", customer));
    }
    return getGenericDao().findByCriteria(Restrictions.eq("customer", customer),
            Restrictions.gt("orderTimestamp", since));
}

From source file:org.yes.cart.service.dto.impl.DtoPromotionServiceImpl.java

License:Apache License

@Override
public List<PromotionDTO> findBy(final String shopCode, final String currency, final String filter,
        final int page, final int pageSize) throws UnmappedInterfaceException, UnableToCreateInstanceException {

    final List<PromotionDTO> dtos = new ArrayList<>();

    if (StringUtils.hasLength(shopCode) && StringUtils.hasLength(currency)) {
        // only allow lists for shop+currency selection

        final List<Criterion> criteria = new ArrayList<Criterion>();
        criteria.add(Restrictions.eq("shopCode", shopCode));
        criteria.add(Restrictions.eq("currency", currency));
        if (StringUtils.hasLength(filter)) {

            final Pair<Date, Date> dateSearch = ComplexSearchUtils.checkDateRangeSearch(filter);

            if (dateSearch != null) {

                if (dateSearch.getFirst() != null) {

                    criteria.add(Restrictions.le("enabledFrom", dateSearch.getFirst()));

                }/*from   w ww  .  j  a  v a2 s. com*/

                if (dateSearch.getSecond() != null) {

                    criteria.add(Restrictions.ge("enabledTo", dateSearch.getSecond()));

                }

            } else {

                final Pair<String, String> enabled = ComplexSearchUtils.checkSpecialSearch(filter, ENABLED);

                boolean enabledOnly = enabled != null && "+".equals(enabled.getFirst());
                boolean disabledOnly = enabled != null && "-".equals(enabled.getFirst());

                if (enabledOnly) {
                    final Date now = new Date();
                    criteria.add(Restrictions.eq("enabled", Boolean.TRUE));
                    criteria.add(Restrictions.or(Restrictions.isNull("enabledFrom"),
                            Restrictions.le("enabledFrom", now)));
                    criteria.add(Restrictions.or(Restrictions.isNull("enabledTo"),
                            Restrictions.gt("enabledTo", now)));
                }
                if (disabledOnly) {
                    final Date now = new Date();
                    criteria.add(Restrictions.or(Restrictions.eq("enabled", Boolean.FALSE),
                            Restrictions.gt("enabledFrom", now), Restrictions.lt("enabledTo", now)));
                }

                if (enabled == null || !enabled.getFirst().equals(enabled.getSecond())) {

                    final Pair<String, String> tagOrCodeOrConditionOrAction = ComplexSearchUtils
                            .checkSpecialSearch(enabled != null ? enabled.getSecond() : filter,
                                    TAG_OR_CODE_OR_CONDITION_OR_ACTION);

                    if (tagOrCodeOrConditionOrAction != null) {

                        if ("#".equals(tagOrCodeOrConditionOrAction.getFirst())) {

                            criteria.add(Restrictions.or(
                                    Restrictions.ilike("code", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.ANYWHERE),
                                    Restrictions.ilike("tag", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.ANYWHERE)));

                        } else if ("!".equals(tagOrCodeOrConditionOrAction.getFirst())) {

                            criteria.add(Restrictions.or(
                                    Restrictions.ilike("promoType", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.EXACT),
                                    Restrictions.ilike("promoAction", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.EXACT)));

                        } else if ("?".equals(tagOrCodeOrConditionOrAction.getFirst())) {

                            criteria.add(Restrictions.or(
                                    Restrictions.ilike("eligibilityCondition",
                                            tagOrCodeOrConditionOrAction.getSecond(), MatchMode.ANYWHERE),
                                    Restrictions.ilike("promoActionContext",
                                            tagOrCodeOrConditionOrAction.getSecond(), MatchMode.ANYWHERE)));

                        }

                    } else {

                        criteria.add(Restrictions.or(Restrictions.ilike("code", filter, MatchMode.ANYWHERE),
                                Restrictions.ilike("name", filter, MatchMode.ANYWHERE),
                                Restrictions.ilike("description", filter, MatchMode.ANYWHERE)));

                    }
                }
            }

        }

        final List<Promotion> entities = getService().getGenericDao().findByCriteria(page * pageSize, pageSize,
                criteria.toArray(new Criterion[criteria.size()]), PROMO_ORDER);

        fillDTOs(entities, dtos);
    }

    return dtos;
}

From source file:org.yes.cart.service.dto.impl.DtoPromotionServiceImpl.java

License:Apache License

@Override
public List<PromotionDTO> findBy(final String shopCode, final String currency, final String filter,
        final List<String> types, final List<String> actions, final int page, final int pageSize)
        throws UnmappedInterfaceException, UnableToCreateInstanceException {

    final List<PromotionDTO> dtos = new ArrayList<>();

    if (StringUtils.hasLength(shopCode) && StringUtils.hasLength(currency)) {
        // only allow lists for shop+currency selection

        final List<Criterion> criteria = new ArrayList<Criterion>();
        criteria.add(Restrictions.eq("shopCode", shopCode));
        criteria.add(Restrictions.eq("currency", currency));
        if (StringUtils.hasLength(filter)) {

            final Pair<Date, Date> dateSearch = ComplexSearchUtils.checkDateRangeSearch(filter);

            if (dateSearch != null) {

                if (dateSearch.getFirst() != null) {

                    criteria.add(Restrictions.le("enabledFrom", dateSearch.getFirst()));

                }/*from  www. j  a v a  2 s.com*/

                if (dateSearch.getSecond() != null) {

                    criteria.add(Restrictions.ge("enabledTo", dateSearch.getSecond()));

                }

            } else {

                final Pair<String, String> enabled = ComplexSearchUtils.checkSpecialSearch(filter, ENABLED);

                boolean enabledOnly = enabled != null && "+".equals(enabled.getFirst());
                boolean disabledOnly = enabled != null && "-".equals(enabled.getFirst());

                if (enabledOnly) {
                    final Date now = new Date();
                    criteria.add(Restrictions.eq("enabled", Boolean.TRUE));
                    criteria.add(Restrictions.or(Restrictions.isNull("enabledFrom"),
                            Restrictions.le("enabledFrom", now)));
                    criteria.add(Restrictions.or(Restrictions.isNull("enabledTo"),
                            Restrictions.gt("enabledTo", now)));
                }
                if (disabledOnly) {
                    final Date now = new Date();
                    criteria.add(Restrictions.or(Restrictions.eq("enabled", Boolean.FALSE),
                            Restrictions.gt("enabledFrom", now), Restrictions.lt("enabledTo", now)));
                }

                if (enabled == null || !enabled.getFirst().equals(enabled.getSecond())) {

                    final Pair<String, String> tagOrCodeOrConditionOrAction = ComplexSearchUtils
                            .checkSpecialSearch(enabled != null ? enabled.getSecond() : filter,
                                    TAG_OR_CODE_OR_CONDITION_OR_ACTION);

                    if (tagOrCodeOrConditionOrAction != null) {

                        if ("#".equals(tagOrCodeOrConditionOrAction.getFirst())) {

                            criteria.add(Restrictions.or(
                                    Restrictions.ilike("code", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.ANYWHERE),
                                    Restrictions.ilike("tag", tagOrCodeOrConditionOrAction.getSecond(),
                                            MatchMode.ANYWHERE)));

                        } else if ("?".equals(tagOrCodeOrConditionOrAction.getFirst())) {

                            criteria.add(Restrictions.or(
                                    Restrictions.ilike("eligibilityCondition",
                                            tagOrCodeOrConditionOrAction.getSecond(), MatchMode.ANYWHERE),
                                    Restrictions.ilike("promoActionContext",
                                            tagOrCodeOrConditionOrAction.getSecond(), MatchMode.ANYWHERE)));

                        }

                    } else {

                        criteria.add(Restrictions.or(Restrictions.ilike("code", filter, MatchMode.ANYWHERE),
                                Restrictions.ilike("name", filter, MatchMode.ANYWHERE),
                                Restrictions.ilike("description", filter, MatchMode.ANYWHERE)));

                    }
                }
            }

        }

        if (CollectionUtils.isNotEmpty(types)) {
            criteria.add(Restrictions.in("promoType", types));
        }
        if (CollectionUtils.isNotEmpty(actions)) {
            criteria.add(Restrictions.in("promoAction", actions));
        }

        final List<Promotion> entities = getService().getGenericDao().findByCriteria(page * pageSize, pageSize,
                criteria.toArray(new Criterion[criteria.size()]), PROMO_ORDER);

        fillDTOs(entities, dtos);
    }

    return dtos;
}