Example usage for org.hibernate.criterion Restrictions disjunction

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

Introduction

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

Prototype

public static Disjunction disjunction() 

Source Link

Document

Group expressions together in a single disjunction (A or B or C...).

Usage

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

License:Open Source License

/**
 * ?//w  ww.j a v  a2 s. 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:ar.com.zauber.commons.repository.query.visitor.CriteriaFilterVisitor.java

License:Apache License

/**
 * Operacion logica de union de criterions de un composite.
 *
 * @param operation operacion de union logica entre componentes
 * @return un Criterion Junction/*from   w w w  . ja  v a  2 s  . co m*/
 */
private Junction setJunctionCriterion(final Connector operation) {
    if (operation instanceof AndConnector) {
        return Restrictions.conjunction();
    } else {
        return Restrictions.disjunction();
    }
}

From source file:au.com.optus.mcas.sdp.bizservice.ott.ordertracking.batchjob.dao.impl.OttOrderActivityDaoImpl.java

License:Open Source License

/**
 * This method is used to retrieve OrderTrackingActivityDetails using the last success run
 * and return the list of OttOrderActivity objects.
 * @param lastSuccessRun/*from  ww  w .j  av  a 2 s. c o m*/
 *        Date
 * @return List
 */
public List<OttOrderActivity> retrieveOrderTrackingActivityDetails(Date lastSuccessRun) {
    LOG.info("retrieveOrderTrackingActivityDetails Method ----------- STARTS");
    List<OttOrderActivity> ottOrderActivityList = new ArrayList<OttOrderActivity>();
    if (lastSuccessRun != null) {
        DetachedCriteria criteria = super.createDetachedCriteria();
        Calendar c = Calendar.getInstance();
        c.setTime(lastSuccessRun);
        Date time = c.getTime();
        criteria.add(Restrictions.disjunction().add(Restrictions.eq("transitionTaskModifiedTime", time))
                .add(Restrictions.gt("transitionTaskModifiedTime", time)));

        ottOrderActivityList = findByCriteria(criteria);
        if (!ottOrderActivityList.isEmpty()) {
            LOG.debug("OttOrderActivityDaoImpl : retrieveOrderTrackingActivityDetails : "
                    + "Record found for lastSuccessRun " + lastSuccessRun
                    + " in OTT_ORDER_ACTIVITY_VIEW table");

        }

    }
    LOG.debug("OttOrderActivityDaoImpl : retrieveOrderTrackingActivityDetails : "
            + "Record not found for lastSuccessRun " + lastSuccessRun + " in OTT_ORDER_ACTIVITY_VIEW table");
    LOG.info("retrieveOrderTrackingActivityDetails Method ----------- ENDS");
    return ottOrderActivityList;

}

From source file:au.com.optus.mcas.sdp.bizservice.ott.ordertracking.batchjob.dao.impl.OttOrderSummaryDaoImpl.java

License:Open Source License

/**
 * This method is used the retrieve OrderTrackingSummaryDetails using last success run
 * and returns the list of OttOrderSummary object.
 * @param lastSuccessRun//from  w w  w.  java  2s .  c om
 *         Date
 * @return List
 *
 */
public List<OttOrderSummary> retrieveOrderTrackingSummaryDetails(Date lastSuccessRun) {
    LOG.info("retrieveOrderTrackingSummaryDetails Method ----------- STARTS");
    List<OttOrderSummary> ottOrderSummaryList = new ArrayList<OttOrderSummary>();
    if (lastSuccessRun != null) {
        DetachedCriteria criteria = super.createDetachedCriteria();
        Calendar c = Calendar.getInstance();
        c.setTime(lastSuccessRun);
        criteria.add(Restrictions.disjunction().add(Restrictions.eq("orderModifiedDate", c.getTime()))
                .add(Restrictions.gt("orderModifiedDate", c.getTime()))
                .add(Restrictions.eq("orderCustomerModifiedDate", c.getTime()))
                .add(Restrictions.gt("orderCustomerModifiedDate", c.getTime())));

        ottOrderSummaryList = findByCriteria(criteria);
        if (!ottOrderSummaryList.isEmpty()) {
            LOG.debug("OttOrderSummaryDaoImpl : retrieveOrderTrackingSummaryDetails : "
                    + "Record found for lastSuccessRun " + lastSuccessRun + " in OTT_ORDER_SUMMARY_VIEW table");
            return ottOrderSummaryList;

        }
    }
    LOG.debug(
            "OttOrderSummaryDaoImpl : retrieveOrderTrackingSummaryDetails : Record not found for lastSuccessRun "
                    + lastSuccessRun + " in OTT_ORDER_SUMMARY_VIEW table");
    LOG.info("retrieveOrderTrackingSummaryDetails Method ----------- ENDS");
    return ottOrderSummaryList;

}

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.//from w  ww .  ja v  a 2  s.  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);//ww w  . j  av  a 2  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 w  w . ja  va  2 s  .c om*/
    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;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.KeysPage.java

License:Open Source License

/**
 * Returns the list of keys for a user class. If the parameter 'historical'
 * is part of the request parameters and has a value of 'true', non-usable
 * keys are returned otherwise usable keys are returned. Usable keys are 
 * those that are 'active', have remaining uses and have not elapsed
 * their expiry time. //from w  ww.  j  av  a2  s .c  o  m
 * 
 * @param request request
 * @return list of permission keys
 * @throws JSONException 
 */
@SuppressWarnings("unchecked")
public JSONArray getList(HttpServletRequest request) throws JSONException {
    JSONArray arr = new JSONArray();

    String className = request.getParameter("name");
    if (className == null) {
        this.logger.warn("Unable to provide access key list because the user class name was not provided.");
        return arr;
    }

    Criteria qu = this.db.createCriteria(UserClassKey.class).add(Restrictions.eq("userTargeted", Boolean.FALSE))
            .addOrder(Order.asc("id"));

    if ("true".equals(request.getAttribute("historical"))) {
        qu.add(Restrictions.disjunction().add(Restrictions.eq("active", Boolean.FALSE))
                .add(Restrictions.eq("remaining", 0)))
                .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.lt("expiry", new Date())));
    } else {
        qu.add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.gt("remaining", 0))
                .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.gt("expiry", new Date())));
    }

    qu = qu.createCriteria("userClass").add(Restrictions.eq("name", className));

    for (UserClassKey key : (List<UserClassKey>) qu.list()) {
        JSONObject keyObj = new JSONObject();
        keyObj.put("key", key.getRedeemKey());
        keyObj.put("active", key.isActive());
        keyObj.put("remaining", key.getRemaining());
        arr.put(keyObj);
    }

    return arr;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.UsersPage.java

License:Open Source License

/**
 * Gets a list of users with a specific search term. The users may be 
 * excluded from a specific class. /*from  ww  w . j a  va 2 s.co  m*/
 * 
 * @param request
 * @return response
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public JSONArray list(HttpServletRequest request) throws JSONException {
    JSONArray arr = new JSONArray();

    Criteria qu = this.db.createCriteria(User.class);

    String search = request.getParameter("search");
    if (search != null) {
        /* Search filter. */
        qu.add(Restrictions.disjunction().add(Restrictions.like("name", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("firstName", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("lastName", search, MatchMode.ANYWHERE)));
    }

    if (request.getParameter("max") != null) {
        /* Max results. */
        qu.setMaxResults(Integer.parseInt(request.getParameter("max")));
    }

    if (request.getParameter("in") != null) {
        /* Users in class. */
        UserClass inClass = new UserClassDao(this.db).findByName(request.getParameter("in"));
        if (inClass == null) {
            this.logger.warn("Not going to add in class as a user list restriction because the class '"
                    + request.getParameter("in") + "' was not found.");
        } else {
            qu.createCriteria("userAssociations").add(Restrictions.eq("userClass", inClass));
        }
    }

    if (request.getParameter("notIn") != null) {
        /* Users not in class. */
        UserClass notInClass = new UserClassDao(this.db).findByName(request.getParameter("notIn"));
        if (notInClass == null) {
            this.logger.warn("Not going to add not in class as a user list restriction because the class '"
                    + request.getParameter("notIn") + "' was not found.");
        } else {
            DetachedCriteria subQu = DetachedCriteria.forClass(User.class)
                    .setProjection(Property.forName("name")).createCriteria("userAssociations")
                    .add(Restrictions.eq("userClass", notInClass));

            List<String> names = subQu.getExecutableCriteria(this.db).list();
            if (names.size() > 0) {
                qu.add(Restrictions.not(Restrictions.in("name", names)));
            }
        }
    }

    qu.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    qu.addOrder(Order.asc("lastName"));
    qu.addOrder(Order.asc("name"));

    for (User user : (List<User>) qu.list()) {
        JSONObject uo = new JSONObject();
        uo.put("name", user.getNamespace() + "-_-" + user.getName());

        if (user.getFirstName() == null || user.getLastName() == null) {
            uo.put("display", user.getName());
        } else {
            uo.put("display", user.getLastName() + ", " + user.getFirstName());
        }

        arr.put(uo);
    }

    return arr;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.rigmanagement.intf.RigManagement.java

License:Open Source License

@Override
public PutRigOfflineResponse putRigOffline(PutRigOffline putRigOffline) {
    PutRigOfflineType param = putRigOffline.getPutRigOffline();
    this.logger.debug("Received RigManagement#putRigOffline with params: requestor ID=" + param.getRequestorID()
            + "requestor namespace=" + param.getRequestorNameSpace() + ", requestor name"
            + param.getRequestorName() + ", rig name=" + param.getRig().getName() + ", offline start="
            + param.getStart().getTime() + ", offline end=" + param.getEnd().getTime() + ", reason="
            + param.getReason() + '.');

    PutRigOfflineResponse response = new PutRigOfflineResponse();
    OperationResponseType result = new OperationResponseType();
    response.setPutRigOfflineResponse(result);

    RigDao dao = new RigDao();
    try {//from  ww  w.ja va 2s .  com
        if (!this.isAuthorised(param, dao.getSession())) {
            this.logger.warn("Unable to put a rig offline because the user is not authorised to perform this "
                    + "operation (not a ADMIN).");
            result.setFailureCode(1);
            result.setFailureReason("Not authorised.");
            return response;
        }

        Rig rig = dao.findByName(param.getRig().getName());
        if (rig == null) {
            this.logger.warn("Unable to put a rig offline because the rig with name " + param.getRig().getName()
                    + " was not found.");
            result.setFailureCode(2);
            result.setFailureReason("Rig not found.");
            return response;
        }

        if (param.getStart().after(param.getEnd())) {
            this.logger
                    .warn("Unable to put a rig offline because the offline start " + param.getStart().getTime()
                            + " is after the offline end " + param.getEnd().getTime() + ".");
            result.setFailureCode(3);
            result.setFailureReason("Start after end.");
            return response;
        }

        Date startDate = param.getStart().getTime();
        Date endDate = param.getEnd().getTime();

        if ((Integer) dao.getSession().createCriteria(RigOfflineSchedule.class)
                .add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.eq("rig", rig))
                .add(Restrictions.disjunction()
                        .add(Restrictions.and(Restrictions.gt("startTime", startDate),
                                Restrictions.lt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate)))
                        .add(Restrictions.and(Restrictions.lt("startTime", startDate),
                                Restrictions.gt("endTime", endDate))))
                .setProjection(Projections.rowCount()).uniqueResult() > 0) {
            this.logger.warn("Unable to put a rig offline because there is a concurrent rig offline period.");
            result.setFailureCode(4);
            result.setFailureReason("Concurrent offline period.");
            return response;
        }

        result.setSuccessful(true);

        RigOfflineSchedule offline = new RigOfflineSchedule();
        offline.setActive(true);
        offline.setRig(rig);
        offline.setStartTime(startDate);
        offline.setEndTime(endDate);
        offline.setReason(param.getReason());
        new RigOfflineScheduleDao(dao.getSession()).persist(offline);

        /* Notify the booking engine. */
        BookingEngineService service = RigManagementActivator.getBookingService();
        if (service != null)
            service.putRigOffline(offline, dao.getSession());

        /* If the period is currently active, clear the rig maintenance state. */
        Date now = new Date();
        if (rig.isActive() && rig.isOnline() && offline.getStartTime().before(now)
                && offline.getEndTime().after(now)) {
            this.logger.info("Setting maintenance state on rig " + rig.getName() + '.');
            if (this.notTest)
                new RigMaintenance().putMaintenance(rig, true, dao.getSession());

            rig.setOnline(false);
            rig.setOfflineReason("In maintenance.");
            new RigLogDao(dao.getSession()).addOfflineLog(rig, "In maintenance.");
            dao.flush();
        }
    } finally {
        dao.closeSession();
    }

    return response;
}