Example usage for org.hibernate.criterion Restrictions and

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

Introduction

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

Prototype

public static LogicalExpression and(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the conjuction of two expressions

Usage

From source file:loginServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();// w ww .j  a va 2  s.c  o  m
    //userpass query
    Criteria crit = session.createCriteria(SystemUser.class);
    Criterion cond1 = Restrictions.eq("username", username);
    Criterion cond2 = Restrictions.eq("password", password);
    crit.add(Restrictions.and(cond1, cond2));
    if ((SystemUser) crit.uniqueResult() != null) {
        //redirect positive
        RequestDispatcher rdp = request.getRequestDispatcher("/success.jsp");
        rdp.forward(request, response);
    } else {
        //redirect negative 
        RequestDispatcher rdp = request.getRequestDispatcher("/fail.jsp");
        rdp.forward(request, response);
    }
    ;

}

From source file:alpha.portal.service.impl.AlphaCardManagerImpl.java

License:Apache License

/**
 * Returns a {@link Criterion} to get all Adornments with the given userId
 * as contributor.//from  ww w  . j  a  v  a2s.  c om
 * 
 * @param userId
 *            the users id
 * @return a {@link Criterion}
 */
public static Criterion getContributorCriterionOwn(final String userId) {
    return Restrictions.and(AlphaCardManagerImpl._CONTRIBUTOR, Restrictions.eq("ad.value", userId));
}

From source file:alpha.portal.service.impl.AlphaCardManagerImpl.java

License:Apache License

/**
 * Returns a {@link Criterion} to get all Adornments where the given userId
 * is not the contributor./*from ww  w  .j  ava2s.c o m*/
 * 
 * @param userId
 *            the users id
 * @return a {@link Criterion}
 */
public static Criterion getContributorCriterionOthers(final String userId) {
    return Restrictions.and(AlphaCardManagerImpl._CONTRIBUTOR, Restrictions.ne("ad.value", userId));
}

From source file:alpha.portal.service.impl.AlphaCardManagerImpl.java

License:Apache License

/**
 * Returns a {@link Criterion} to get all Adornments where the
 * contributorrole is one of roles./*from  www  .  jav a 2s.  c om*/
 * 
 * @param roles
 *            the roles
 * @return a {@link Criterion}
 */
public static Criterion getContributorRoleCriterionOwn(final String... roles) {
    return Restrictions.and(AlphaCardManagerImpl._CONTRIBUTORROLE, Restrictions.in("ad.value", roles));
}

From source file:alpha.portal.service.impl.AlphaCardManagerImpl.java

License:Apache License

/**
 * Returns a {@link Criterion} to get all Adornments where the
 * contributorrole is not in roles./*from w w w  .j a  va 2  s  .c om*/
 * 
 * @param roles
 *            the roles
 * @return a {@link Criterion}
 */
public static Criterion getContributorRoleCriterionOthers(final String... roles) {
    return Restrictions.and(AlphaCardManagerImpl._CONTRIBUTORROLE,
            Restrictions.not(Restrictions.in("ad.value", roles)));
}

From source file:alpha.portal.service.impl.AlphaCardManagerImplTest.java

License:Apache License

/**
 * Test criterion./* w ww . jav  a  2 s.c o m*/
 */
@Test
public void testCriterion() {
    Assert.assertEquals(
            Restrictions.and(AlphaCardManagerImpl._CONTRIBUTOR, Restrictions.ne("ad.value", "123")).toString(),
            AlphaCardManagerImpl.getContributorCriterionOthers("123").toString());
    Assert.assertEquals(
            Restrictions.and(AlphaCardManagerImpl._CONTRIBUTOR, Restrictions.eq("ad.value", "123")).toString(),
            AlphaCardManagerImpl.getContributorCriterionOwn("123").toString());
    Assert.assertEquals(
            Restrictions.and(AlphaCardManagerImpl._CONTRIBUTORROLE,
                    Restrictions.not(Restrictions.in("ad.value", new String[] { "role1" }))).toString(),
            AlphaCardManagerImpl.getContributorRoleCriterionOthers("role1").toString());
    Assert.assertEquals(
            Restrictions.and(AlphaCardManagerImpl._CONTRIBUTORROLE,
                    Restrictions.in("ad.value", new String[] { "role1" })).toString(),
            AlphaCardManagerImpl.getContributorRoleCriterionOwn("role1").toString());
}

From source file:apm.common.service.DataService.java

License:Open Source License

/**
 * ?/*from w w  w .  ja  v  a 2s.  c  o  m*/
 * @param dc Hibernate
 * @param user ?UserUtils.getUser()??
 * @param officeAlias ??dc.createAlias("office", "office");
 * @param userAlias ???
 * @return ?
 */
protected static Junction dataScopeFilter(User user, String officeAlias, String userAlias) {

    // ????
    List<String> dataScope = Lists.newArrayList();
    Junction junction = Restrictions.disjunction();

    // ???
    if (!user.isAdmin()) {
        for (Role r : user.getRoleList()) {
            String DATA_SCOPE = r.getDataScope();
            if (!dataScope.contains(DATA_SCOPE) && StringUtils.isNotBlank(officeAlias)) {
                boolean isDataScopeAll = false;
                if (Role.DATA_SCOPE_ALL.equals(DATA_SCOPE)) {
                    isDataScopeAll = true;
                } else if (Role.DATA_SCOPE_COMPANY_AND_CHILD.equals(DATA_SCOPE)) { //(?)??
                    junction.add(Restrictions.eq(officeAlias + ".id", user.getCompany().getId()));
                    junction.add(Restrictions.like(officeAlias + ".parentIds",
                            user.getCompany().getParentIds() + user.getCompany().getId() + ",%"));
                } else if (Role.DATA_SCOPE_COMPANY.equals(DATA_SCOPE)) {
                    junction.add(Restrictions.eq(officeAlias + ".id", user.getCompany().getId()));
                    junction.add(Restrictions.and(
                            Restrictions.eq(officeAlias + ".parent.id", user.getCompany().getId()),
                            Restrictions.eq(officeAlias + ".type", "2"))); // ?
                } else if (Role.DATA_SCOPE_OFFICE_AND_CHILD.equals(DATA_SCOPE)) {
                    junction.add(Restrictions.eq(officeAlias + ".id", user.getOffice().getId()));
                    junction.add(Restrictions.like(officeAlias + ".parentIds",
                            user.getOffice().getParentIds() + user.getOffice().getId() + ",%"));
                } else if (Role.DATA_SCOPE_OFFICE.equals(DATA_SCOPE)) {
                    junction.add(Restrictions.eq(officeAlias + ".id", user.getOffice().getId()));
                } else if (Role.DATA_SCOPE_CUSTOM.equals(DATA_SCOPE)) {
                    junction.add(Restrictions.in(officeAlias + ".id", r.getOfficeIdList()));
                }
                //else if (Role.DATA_SCOPE_SELF.equals(DATA_SCOPE)){
                if (!isDataScopeAll) {
                    if (StringUtils.isNotBlank(userAlias)) {
                        junction.add(Restrictions.eq(userAlias + ".id", user.getId()));
                    } else {
                        junction.add(Restrictions.isNull(officeAlias + ".id"));
                    }
                } else {
                    // ?????
                    junction = Restrictions.disjunction();
                    break;
                }
                dataScope.add(DATA_SCOPE);
            }
        }
    }
    return junction;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Adds a day range constraint to a bookings query so that bookings within
 * this day are returned.// w  w  w .j  a  v a2s  . c  o m
 * 
 * @return restriction
 */
private Criterion addDayRange() {
    return Restrictions.disjunction().add(Restrictions.and( // Booking within day
            Restrictions.ge("startTime", this.dayBegin), Restrictions.le("endTime", this.dayEnd)))
            .add(Restrictions.and( // Booking starts before day and ends on this day
                    Restrictions.lt("startTime", this.dayBegin), Restrictions.gt("endTime", this.dayBegin)))
            .add(Restrictions.and( // Booking starts on day and ends after day
                    Restrictions.lt("startTime", this.dayEnd), Restrictions.gt("endTime", this.dayEnd)))
            .add(Restrictions.and(Restrictions.le("startTime", this.dayBegin),
                    Restrictions.gt("endTime", this.dayEnd)));
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsService.java

License:Open Source License

@Override
public CreateBookingResponse createBooking(CreateBooking createBooking) {
    /* --------------------------------------------------------------------
     * -- Read request parameters.                                       --
     * -------------------------------------------------------------------- */
    CreateBookingType request = createBooking.getCreateBooking();
    String debug = "Received " + this.getClass().getSimpleName() + "#createBooking with params: ";

    UserIDType uid = request.getUserID();
    debug += " user ID=" + uid.getUserID() + ", user namespace=" + uid.getUserNamespace() + ", user name="
            + uid.getUserName() + " user QName=" + uid.getUserQName();

    BookingType booking = request.getBooking();
    int pid = booking.getPermissionID().getPermissionID();
    debug += ", permission=" + pid;

    Calendar start = booking.getStartTime();
    Calendar end = booking.getEndTime();
    this.dstHack(start);
    this.dstHack(end);

    debug += ", start=" + start.getTime() + ", end=" + end.getTime();

    debug += ", send notification=" + request.getSendNotification() + ", notification time zone="
            + request.getNotificationTimezone() + '.';
    this.logger.debug(debug);

    /* --------------------------------------------------------------------
     * -- Generate default response parameters.                          --
     * -------------------------------------------------------------------- */
    CreateBookingResponse response = new CreateBookingResponse();
    BookingResponseType status = new BookingResponseType();
    status.setSuccess(false);//w w  w .  ja  va2 s .  c om
    response.setCreateBookingResponse(status);

    Session ses = DataAccessActivator.getNewSession();
    try {
        /* ----------------------------------------------------------------
         * -- Load the user.                                             --
         * ---------------------------------------------------------------- */
        User user = this.getUserFromUserID(uid, ses);
        if (user == null) {
            this.logger.info("Unable to create a booking because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            status.setFailureReason("User not found.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Load the permission.                                       --
         * ---------------------------------------------------------------- */
        ResourcePermission perm = new ResourcePermissionDao(ses).get(Long.valueOf(pid));
        if (perm == null) {
            this.logger.info("Unable to create a booking because the permission has not been found. Supplied "
                    + "permission ID=" + pid + '.');
            status.setFailureReason("Permission not found.");
            return response;
        }

        if (!this.checkPermission(user, perm)) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " does not have permission " + pid + '.');
            status.setFailureReason("Does not have permission.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Check permission constraints.                              --
         * ---------------------------------------------------------------- */
        Date startDate = start.getTime();
        Date endDate = end.getTime();

        if (!perm.getUserClass().isBookable()) {
            this.logger.info("Unable to create a booking because the permission " + pid + " is not bookable.");
            status.setFailureReason("Permission not bookable.");
            return response;
        }

        if (startDate.before(perm.getStartTime()) || endDate.after(perm.getExpiryTime())) {
            this.logger
                    .info("Unable to create a booking because the booking time is outside the permission time. "
                            + "Permission start: " + perm.getStartTime() + ", expiry: " + perm.getExpiryTime()
                            + ", booking start: " + startDate + ", booking end: " + endDate + '.');
            status.setFailureReason("Booking time out of permission range.");
            return response;
        }

        /* Time horizon is a moving offset when bookings can be made. */
        Calendar horizon = Calendar.getInstance();
        horizon.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon());
        if (horizon.after(start)) {
            this.logger.info("Unable to create a booking because the booking start time (" + startDate
                    + ") is before the time horizon (" + horizon.getTime() + ").");
            status.setFailureReason("Before time horizon.");
            return response;
        }

        /* Maximum concurrent bookings. */
        int numBookings = (Integer) ses.createCriteria(Bookings.class)
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                .add(Restrictions.eq("resourcePermission", perm)).setProjection(Projections.rowCount())
                .uniqueResult();
        if (numBookings >= perm.getMaximumBookings()) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " already has the maxiumum numnber of bookings (" + numBookings + ").");
            status.setFailureReason("User has maximum number of bookings.");
            return response;
        }

        /* User bookings at the same time. */
        numBookings = (Integer) ses.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                .add(Restrictions.disjunction()
                        .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                                Restrictions.lt("startTime", endDate)))
                        .add(Restrictions.and(Restrictions.gt("endTime", startDate),
                                Restrictions.le("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.le("startTime", startDate),
                                Restrictions.gt("endTime", endDate))))
                .uniqueResult();
        if (numBookings > 0) {
            this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                    + user.getName() + " has concurrent bookings.");
            status.setFailureReason("User has concurrent bookings.");
            return response;
        }

        /* ----------------------------------------------------------------
         * -- Create booking.                                            --
         * ---------------------------------------------------------------- */
        BookingCreation bc = this.engine.createBooking(user, perm, new TimePeriod(start, end), ses);
        if (bc.wasCreated()) {
            status.setSuccess(true);
            BookingIDType bid = new BookingIDType();
            bid.setBookingID(bc.getBooking().getId().intValue());
            status.setBookingID(bid);

            new BookingNotification(bc.getBooking()).notifyCreation();
        } else {
            status.setSuccess(false);
            status.setFailureReason("Resource not free.");

            BookingListType bestFits = new BookingListType();
            status.setBestFits(bestFits);
            for (TimePeriod tp : bc.getBestFits()) {
                numBookings = (Integer) ses.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                        .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                        .add(Restrictions.disjunction()
                                .add(Restrictions.and(Restrictions.gt("startTime", tp.getStartTime().getTime()),
                                        Restrictions.lt("startTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.gt("endTime", tp.getStartTime().getTime()),
                                        Restrictions.le("endTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.le("startTime", tp.getStartTime().getTime()),
                                        Restrictions.gt("endTime", tp.getEndTime().getTime()))))
                        .uniqueResult();
                if (numBookings > 0) {
                    this.logger.debug("Excluding best fit option for user " + user.qName() + " because it is "
                            + "concurrent with an existing.");
                    continue;
                }
                BookingType fit = new BookingType();
                fit.setPermissionID(booking.getPermissionID());
                fit.setStartTime(tp.getStartTime());
                fit.setEndTime(tp.getEndTime());
                bestFits.addBookings(fit);
            }
        }
    } finally {
        ses.close();
    }

    return response;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.pojo.impl.BookingsServiceImpl.java

License:Open Source License

@Override
public BookingOperation createBooking(Calendar start, Calendar end, User user, ResourcePermission perm,
        Session db) {//from   w  ww  . j  a  va  2  s. c o m
    BookingOperation response = new BookingOperation();
    response.setSuccess(false);

    /* ----------------------------------------------------------------
     * -- Check permission constraints.                              --
     * ---------------------------------------------------------------- */
    Date startDate = start.getTime();
    Date endDate = end.getTime();

    if (!perm.getUserClass().isBookable()) {
        this.logger.info(
                "Unable to create a booking because the permission " + perm.getId() + " is not bookable.");
        response.setFailureReason("Permission not bookable.");
        return response;
    }

    if (startDate.before(perm.getStartTime()) || endDate.after(perm.getExpiryTime())) {
        this.logger.info("Unable to create a booking because the booking time is outside the permission time. "
                + "Permission start: " + perm.getStartTime() + ", expiry: " + perm.getExpiryTime()
                + ", booking start: " + startDate + ", booking end: " + endDate + '.');
        response.setFailureReason("Booking time out of permission range.");
        return response;
    }

    /* Time horizon is a moving offset when bookings can be made. */
    Calendar horizon = Calendar.getInstance();
    horizon.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon());
    if (horizon.after(start)) {
        this.logger.info("Unable to create a booking because the booking start time (" + startDate
                + ") is before the time horizon (" + horizon.getTime() + ").");
        response.setFailureReason("Before time horizon.");
        return response;
    }

    /* Maximum concurrent bookings. */
    int numBookings = (Integer) db.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE))
            .add(Restrictions.eq("user", user)).add(Restrictions.eq("resourcePermission", perm))
            .setProjection(Projections.rowCount()).uniqueResult();
    if (numBookings >= perm.getMaximumBookings()) {
        this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                + user.getName() + " already has the maxiumum numnber of bookings (" + numBookings + ").");
        response.setFailureReason("User has maximum number of bookings.");
        return response;
    }

    /* User bookings at the same time. */
    numBookings = (Integer) db.createCriteria(Bookings.class).setProjection(Projections.rowCount())
            .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
            .add(Restrictions.disjunction()
                    .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                            Restrictions.lt("startTime", endDate)))
                    .add(Restrictions.and(Restrictions.gt("endTime", startDate),
                            Restrictions.le("endTime", endDate)))
                    .add(Restrictions.and(Restrictions.le("startTime", startDate),
                            Restrictions.gt("endTime", endDate))))
            .uniqueResult();

    if (numBookings > 0) {
        this.logger.info("Unable to create a booking because the user " + user.getNamespace() + ':'
                + user.getName() + " has concurrent bookings.");
        response.setFailureReason("User has concurrent bookings.");
        return response;
    }

    /* ----------------------------------------------------------------
     * -- Create booking.                                            --
     * ---------------------------------------------------------------- */
    if (ResourcePermission.CONSUMER_PERMISSION.equals(perm.getType())) {
        CreateBookingRequest request = new CreateBookingRequest();
        if (request.createBooking(user, perm.getRemotePermission(), start, end, db)) {
            response.setSuccess(request.wasSuccessful());
            response.setFailureReason(request.getReason());
            if (request.wasSuccessful()) {
                /* Provider created booking so we now need to create it 
                 * locally. */
                this.logger.debug("Successfullly created booking at provider with identifier "
                        + request.getBookingID() + '.');
                Bookings bk = new Bookings();
                bk.setActive(true);
                bk.setStartTime(startDate);
                bk.setEndTime(endDate);
                bk.setDuration((int) (end.getTimeInMillis() - start.getTimeInMillis()) / 1000);
                bk.setResourcePermission(perm);
                bk.setResourceType(ResourcePermission.CONSUMER_PERMISSION);
                bk.setProviderId(request.getBookingID());
                bk.setUser(user);
                bk.setUserNamespace(user.getNamespace());
                bk.setUserName(user.getName());
                response.setBooking(new BookingsDao(db).persist(bk));

                /* Notification emails are only sent to home users. */
                new BookingNotification(bk).notifyCreation();
            } else {
                this.logger.info("Provider failed to create booking with reason " + request.getReason());

                /* Provider returned that it couldn't create booking. */
                for (BookingTime bt : request.getBestFits()) {
                    response.addBestFit(bt.getStart(), bt.getEnd());
                }
            }
        } else {
            /* Provider call failed. */
            this.logger
                    .info("Provider call to create booking failed with reason " + request.getFailureReason());
            response.setSuccess(false);
            response.setFailureReason("Provider request failed (" + request.getFailureReason() + ")");
        }
    } else {
        BookingCreation bc = this.engine.createBooking(user, perm, new TimePeriod(start, end), db);
        if (bc.wasCreated()) {
            response.setSuccess(true);
            response.setBooking(bc.getBooking());

            /* Notification emails are only sent to home users. */
            if (perm.getRemotePermission() == null)
                new BookingNotification(bc.getBooking()).notifyCreation();
        } else {
            response.setSuccess(false);
            response.setFailureReason("Resource not free.");

            for (TimePeriod tp : bc.getBestFits()) {
                numBookings = (Integer) db.createCriteria(Bookings.class).setProjection(Projections.rowCount())
                        .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("user", user))
                        .add(Restrictions.disjunction()
                                .add(Restrictions.and(Restrictions.gt("startTime", tp.getStartTime().getTime()),
                                        Restrictions.lt("startTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.gt("endTime", tp.getStartTime().getTime()),
                                        Restrictions.le("endTime", tp.getEndTime().getTime())))
                                .add(Restrictions.and(Restrictions.le("startTime", tp.getStartTime().getTime()),
                                        Restrictions.gt("endTime", tp.getEndTime().getTime()))))
                        .uniqueResult();
                if (numBookings > 0) {
                    this.logger.debug("Excluding best fit option for user " + user.qName() + " because it is "
                            + "concurrent with an existing.");
                    continue;
                }

                response.addBestFit(tp.getStartTime(), tp.getEndTime());
            }
        }
    }

    return response;
}