Example usage for org.hibernate.criterion Restrictions in

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

Introduction

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

Prototype

public static Criterion in(String propertyName, Collection values) 

Source Link

Document

Apply an "in" constraint to the named property.

Usage

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  w  ww . j ava 2 s.  c o  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.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  w  w w . j a  v a  2  s  .c om
public QuerySessionAccessResponse querySessionAccess(final QuerySessionAccess querySessionAccess) {
    /* Request parameters. */
    final QuerySessionAccessType request = querySessionAccess.getQuerySessionAccess();
    final QueryFilterType filter = request.getQuerySelect();

    String debug = "Received " + this.getClass().getSimpleName()
            + "#querySessionAccess with params: select operator=" + filter.getOperator() + ", type="
            + filter.getTypeForQuery().toString() + ", like=" + filter.getQueryLike();
    if (request.getStartTime() != null)
        debug += ", start=" + request.getStartTime().getTime();
    if (request.getEndTime() != null)
        debug += ", end=" + request.getEndTime().getTime();
    this.logger.debug(debug);

    /* Response parameters. */
    final QuerySessionAccessResponse response = new QuerySessionAccessResponse();
    final QuerySessionAccessResponseType respType = new QuerySessionAccessResponseType();
    final PaginationType page = new PaginationType();
    page.setNumberOfPages(1);
    page.setPageLength(0);
    page.setPageNumber(1);
    respType.setPagination(page);
    response.setQuerySessionAccessResponse(respType);

    final org.hibernate.Session db = DataAccessActivator.getNewSession();
    try {
        RequestorType uid = request.getRequestor();
        final User requestor = this.getUserFromUserID(uid, db);
        if (requestor == null) {
            this.logger.info("Unable to generate report because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return response;
        }

        /* We are only interested in sessions that are complete. */
        Criteria query = db.createCriteria(Session.class).add(Restrictions.eq("active", Boolean.FALSE))
                .add(Restrictions.isNotNull("removalTime")).addOrder(Order.asc("requestTime"));

        /* If the user has requested a time period, only add that to query. */
        if (request.getStartTime() != null)
            query.add(Restrictions.ge("requestTime", request.getStartTime().getTime()));
        if (request.getEndTime() != null)
            query.add(Restrictions.le("requestTime", request.getEndTime().getTime()));

        if (request.getPagination() != null) {
            /* Add the requested pagination. */
            final PaginationType pages = request.getPagination();
            final int noPages = pages.getNumberOfPages();
            final int pageNumber = pages.getPageNumber();
            final int pageLength = pages.getPageLength();

            if (noPages > 1)
                query.setMaxResults(pageLength);
            if (pageNumber > 1)
                query.setFirstResult((pageNumber - 1) * pageLength);
        }

        if (filter.getTypeForQuery() == TypeForQuery.RIG) {
            /* Only administrators can do rig queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow rig reporting.");
                return response;
            }

            query.add(Restrictions.eq("assignedRigName", filter.getQueryLike()));
        } else if (filter.getTypeForQuery() == TypeForQuery.RIG_TYPE) {
            /* Only administrators can do rig type queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow rig type reporting.");
                return response;
            }

            final RigType rigType = new RigTypeDao(db).findByName(filter.getQueryLike());
            if (rigType == null) {
                this.logger.warn("Cannot provide session report because rig type '" + filter.getQueryLike()
                        + "' not found.");
                return response;
            }

            query.createCriteria("rig").add(Restrictions.eq("rigType", rigType));
        } else if (filter.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) {
            /* Only administrators can do request capabilities queries. */
            if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona()
                        + "' does not allow request capabilities reporting.");
                return response;
            }

            final RequestCapabilities reqCaps = new RequestCapabilitiesDao(db)
                    .findCapabilites(filter.getQueryLike());
            if (reqCaps == null) {
                this.logger.warn("Cannot provide session report because request capabilities '"
                        + filter.getQueryLike() + "' not found.");
                return response;
            }

            List<Rig> capRigs = new ArrayList<Rig>();
            for (MatchingCapabilities match : reqCaps.getMatchingCapabilitieses()) {
                capRigs.addAll(match.getRigCapabilities().getRigs());
            }

            if (capRigs.size() == 0) {
                this.logger.warn(
                        "Cannot provide session report because there are no rigs with request capabilities '"
                                + reqCaps.getCapabilities() + "'.");
                return response;
            }

            query.add(Restrictions.in("rig", capRigs));
        } else if (filter.getTypeForQuery() == TypeForQuery.USER_CLASS) {
            final UserClass userClass = new UserClassDao(db).findByName(filter.getQueryLike());
            if (userClass == null) {
                this.logger.warn("Cannot provide session report because user class '" + filter.getQueryLike()
                        + "' was not found.");
                return response;
            }

            if (User.ACADEMIC.equals(requestor.getPersona())) {
                /* An academic may only generate reports for the classes 
                 * they have have reporting permission in. */
                boolean hasPerm = false;

                final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator();
                while (it.hasNext()) {
                    final AcademicPermission ap = it.next();
                    if (ap.getUserClass().getId().equals(userClass.getId()) && ap.isCanGenerateReports()) {
                        hasPerm = true;
                        break;
                    }
                }

                if (!hasPerm) {
                    this.logger.info("Unable to generate report for user class " + userClass.getName()
                            + " because the user " + requestor.qName()
                            + " does not own or have permission to report it.");
                    return response;
                }

                this.logger.debug("Academic " + requestor.qName()
                        + " has permission to generate report from user class " + userClass.getName() + '.');
            } else if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide a user session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona() + "' does not allow reporting.");
                return response;
            }

            query.createCriteria("resourcePermission").add(Restrictions.eq("userClass", userClass));
        } else if (filter.getTypeForQuery() == TypeForQuery.USER) {
            final User user = new UserDao(db).findByQName(filter.getQueryLike());
            if (user == null) {
                this.logger.warn("Cannot provide session report because user  '" + filter.getQueryLike()
                        + "' was not found.");
                return response;
            }

            if (User.ACADEMIC.equals(requestor.getPersona())) {
                /* The report can only contain sessions originating from the user
                 * classes the academic has reporting permission in. */
                List<ResourcePermission> perms = new ArrayList<ResourcePermission>();

                final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator();
                while (it.hasNext()) {
                    final AcademicPermission ap = it.next();
                    if (!ap.isCanGenerateReports())
                        continue;

                    perms.addAll(ap.getUserClass().getResourcePermissions());
                }

                if (perms.size() == 0) {
                    this.logger.info("Unable to generate report for user " + user.qName() + " because the user "
                            + requestor.qName() + " does not own or have permission to report "
                            + "on any of the users permissions.");
                    return response;
                }

                query.add(Restrictions.in("resourcePermission", perms));
            } else if (!User.ADMIN.equals(requestor.getPersona())) {
                this.logger.warn("Cannot provide a user session report for user '" + requestor.qName()
                        + "' because their persona '" + requestor.getPersona() + "' does not allow reporting.");
                return response;
            }

            query.add(Restrictions.eq("user", user));
        } else {
            this.logger.error("Cannot provide a session report because the query type '"
                    + filter.getTypeForQuery().toString() + "' was not understood.");
            return response;
        }

        for (final Session s : (List<Session>) query.list()) {
            final AccessReportType report = new AccessReportType();

            /* Set user who was in session. */
            final RequestorType sUser = new RequestorType();
            final UserNSNameSequence nsSequence = new UserNSNameSequence();
            nsSequence.setUserName(s.getUserName());
            nsSequence.setUserNamespace(s.getUserNamespace());
            sUser.setRequestorNSName(nsSequence);
            sUser.setUserQName(s.getUserNamespace() + ':' + s.getUserName());
            report.setUser(sUser);

            /* User class. */
            if (s.getResourcePermission() != null)
                report.setUserClass(s.getResourcePermission().getUserClass().getName());

            /* Rig details. */
            report.setRigName(s.getAssignedRigName());
            if (s.getRig() != null)
                report.setRigType(s.getRig().getRigType().getName());

            /* Session start. */
            Calendar cal = Calendar.getInstance();
            cal.setTime(s.getRequestTime());
            report.setQueueStartTime(cal);

            /* Session timings. */
            if (s.getAssignmentTime() != null) {
                final int queueD = (int) ((s.getAssignmentTime().getTime() - s.getRequestTime().getTime())
                        / 1000);
                report.setQueueDuration(queueD);
                cal = Calendar.getInstance();
                cal.setTime(s.getAssignmentTime());
                report.setSessionStartTime(cal);
                final int sessionD = (int) ((s.getRemovalTime().getTime() - s.getAssignmentTime().getTime())
                        / 1000);
                report.setSessionDuration(sessionD);
            } else {
                final int queueD = (int) ((s.getRemovalTime().getTime() - s.getRequestTime().getTime()) / 1000);
                report.setQueueDuration(queueD);

                cal = Calendar.getInstance();
                cal.setTime(s.getRemovalTime());
                report.setSessionStartTime(cal);
                report.setSessionDuration(0);
            }

            /* Session end. */
            cal = Calendar.getInstance();
            cal.setTime(s.getRemovalTime());
            report.setSessionEndTime(cal);
            report.setReasonForTermination(s.getRemovalReason());

            respType.addAccessReportData(report);
        }

    } finally {
        db.close();
    }

    return response;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private Criteria buildGeneralSubjectCriteria(SubjectVO subjectVO) {
    Criteria criteria = getSession().createCriteria(LinkSubjectStudy.class);
    criteria.createAlias("person", "p");
    if (subjectVO.getLinkSubjectStudy().getStudy() != null) {
        criteria.add(Restrictions.eq("study.id", subjectVO.getLinkSubjectStudy().getStudy().getId()));
    } else {/* w w  w .  j a  va  2 s.c om*/
        criteria.add(Restrictions.in("study", subjectVO.getStudyList()));
        criteria.createAlias("study", "st");
        criteria.addOrder(Order.asc("st.name"));
    }
    if (subjectVO.getLinkSubjectStudy().getPerson() != null) {

        if (subjectVO.getLinkSubjectStudy().getPerson().getId() != null) {
            criteria.add(Restrictions.eq("p.id", subjectVO.getLinkSubjectStudy().getPerson().getId()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getFirstName() != null) {
            criteria.add(Restrictions.ilike("p.firstName",
                    subjectVO.getLinkSubjectStudy().getPerson().getFirstName(), MatchMode.ANYWHERE));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getMiddleName() != null) {
            criteria.add(Restrictions.ilike("p.middleName",
                    subjectVO.getLinkSubjectStudy().getPerson().getMiddleName(), MatchMode.ANYWHERE));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getLastName() != null) {
            /* old code pre George adding personlastname lookup criteria.add(Restrictions.ilike("p.lastName", subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE));*/
            //log.info("Lastname: " + subjectVO.getLinkSubjectStudy().getPerson().getLastName());
            DetachedCriteria previousLastNames = DetachedCriteria.forClass(PersonLastnameHistory.class, "l")
                    .setProjection(Projections.property("l.lastName"))
                    .add(Restrictions.ilike("l.lastName",
                            subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE))
                    .add(Restrictions.eqProperty("p.id", "l.person.id"));
            criteria.add(Restrictions.or(Restrictions.ilike("p.lastName",
                    subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE),
                    Subqueries.exists(previousLastNames)));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getDateOfBirth() != null) {
            criteria.add(Restrictions.eq("p.dateOfBirth",
                    subjectVO.getLinkSubjectStudy().getPerson().getDateOfBirth()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getGenderType() != null) {
            criteria.add(Restrictions.eq("p.genderType.id",
                    subjectVO.getLinkSubjectStudy().getPerson().getGenderType().getId()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getVitalStatus() != null) {
            criteria.add(Restrictions.eq("p.vitalStatus.id",
                    subjectVO.getLinkSubjectStudy().getPerson().getVitalStatus().getId()));
        }

        if (!subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().isEmpty()) {
            OtherID o = (OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0];
            if (o != null && o.getOtherID() != null && !o.getOtherID().isEmpty()) {
                log.info("OtherID search");
                //               DetachedCriteria otherID = DetachedCriteria.forClass(OtherID.class, "O")
                //                     .setProjection(Projections.projectionList().add(Projections.property("O.otherID")))
                //                     .add(Restrictions.ilike("O.otherID", ((OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0]).getOtherID(), MatchMode.EXACT))
                //                     .add(Restrictions.eqProperty("p.id", "O.person.id"));
                //               criteria.add(Subqueries.exists(otherID));
                criteria.createAlias("p.otherIDs", "o");
                criteria.add(Restrictions.ilike("o.otherID",
                        ((OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0])
                                .getOtherID(),
                        MatchMode.ANYWHERE));
                criteria.setProjection(Projections.distinct(
                        Projections.projectionList().add(Projections.property("o.personid"), "lss.person.id")));
            }
        }
    }

    if (subjectVO.getLinkSubjectStudy().getSubjectUID() != null
            && subjectVO.getLinkSubjectStudy().getSubjectUID().length() > 0) {
        criteria.add(Restrictions.ilike("subjectUID", subjectVO.getLinkSubjectStudy().getSubjectUID(),
                MatchMode.ANYWHERE));
    }

    if (subjectVO.getLinkSubjectStudy().getSubjectStatus() != null) {
        criteria.add(Restrictions.eq("subjectStatus", subjectVO.getLinkSubjectStudy().getSubjectStatus()));
        SubjectStatus subjectStatus = getSubjectStatus("Archive");
        if (subjectStatus != null) {
            criteria.add(Restrictions.ne("subjectStatus", subjectStatus));
        }
    } else {
        SubjectStatus subjectStatus = getSubjectStatus("Archive");
        if (subjectStatus != null) {
            criteria.add(Restrictions.ne("subjectStatus", subjectStatus));
        }
    }
    if (subjectVO.getRelativeUIDs().size() > 0) {
        criteria.add(Restrictions.not(Restrictions.in("subjectUID", subjectVO.getRelativeUIDs().toArray())));
    }

    criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.id())));

    criteria.addOrder(Order.asc("subjectUID"));
    return criteria;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

public List<Upload> searchUploadsForBio(Upload uploadCriteria) {
    Criteria criteria = getSession().createCriteria(Upload.class);
    // - due to nature of table design...we need to specify it like this
    // ideally we might want to just have arkmodule in the upload table?
    // criteria.add(Restrictions.eq("arkFunction",
    // uploadCriteria.getArkFunction()));

    ArkFunction biospecArkFunction = getArkFunctionByName(Constants.FUNCTION_KEY_VALUE_BIOSPECIMEN);
    //ArkFunction biocollArkFunction = getArkFunctionByName(Constants.FUNCTION_KEY_VALUE_LIMS_COLLECTION);
    ArkFunction biocollArkFunction = getArkFunctionByName(Constants.FUNCTION_KEY_VALUE_LIMS_CUSTOM_FIELD);

    List<ArkFunction> arkFunctionsForBio = new ArrayList<ArkFunction>();
    arkFunctionsForBio.add(biospecArkFunction);
    arkFunctionsForBio.add(biocollArkFunction);

    criteria.add(Restrictions.in("arkFunction", arkFunctionsForBio));

    if (uploadCriteria.getId() != null) {
        criteria.add(Restrictions.eq("id", uploadCriteria.getId()));
    }//from  w  w  w  .ja  v a 2  s.c om

    if (uploadCriteria.getStudy() != null) {
        criteria.add(Restrictions.eq("study", uploadCriteria.getStudy()));
    }

    if (uploadCriteria.getFileFormat() != null) {
        criteria.add(Restrictions.ilike("fileFormat", uploadCriteria.getFileFormat()));
    }

    if (uploadCriteria.getDelimiterType() != null) {
        criteria.add(Restrictions.ilike("delimiterType", uploadCriteria.getDelimiterType()));
    }

    if (uploadCriteria.getFilename() != null) {
        criteria.add(Restrictions.ilike("filename", uploadCriteria.getFilename()));
    }

    criteria.addOrder(Order.desc("id"));
    List<Upload> resultsList = criteria.list();

    return resultsList;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

public List<Upload> searchUploadsForBiospecimen(Upload uploadCriteria, List studyListForUser) {
    Criteria criteria = getSession().createCriteria(Upload.class);
    // - due to nature of table design...we need to specify it like this
    // ideally we might want to just have arkmodule in the upload table?
    // criteria.add(Restrictions.eq("arkFunction",
    // uploadCriteria.getArkFunction()));

    ArkFunction biospecArkFunction = getArkFunctionByName(Constants.FUNCTION_KEY_VALUE_BIOSPECIMEN);

    List<ArkFunction> arkFunctionsForBio = new ArrayList<ArkFunction>();
    arkFunctionsForBio.add(biospecArkFunction);

    criteria.add(Restrictions.eq("arkFunction", uploadCriteria.getArkFunction()));

    if (uploadCriteria.getId() != null) {
        criteria.add(Restrictions.eq("id", uploadCriteria.getId()));
    }/*from  ww w  .ja  va2 s. c o  m*/

    if (!studyListForUser.isEmpty()) {
        criteria.add(Restrictions.in("study", studyListForUser));
    }

    if (uploadCriteria.getFileFormat() != null) {
        criteria.add(Restrictions.ilike("fileFormat", uploadCriteria.getFileFormat()));
    }

    if (uploadCriteria.getDelimiterType() != null) {
        criteria.add(Restrictions.ilike("delimiterType", uploadCriteria.getDelimiterType()));
    }

    if (uploadCriteria.getFilename() != null) {
        criteria.add(Restrictions.ilike("filename", uploadCriteria.getFilename()));
    }

    criteria.addOrder(Order.desc("id"));
    List<Upload> resultsList = criteria.list();

    return resultsList;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

public List<SubjectVO> matchSubjectsFromInputFile(FileUpload subjectFileUpload, Study study) {
    List<SubjectVO> subjectVOList = new ArrayList<SubjectVO>();
    List<String> subjectUidList = new ArrayList<String>(0);

    if (subjectFileUpload != null) {
        try {//from   w  w w  . j  av  a 2 s . c o  m
            subjectUidList = CsvListReader.readColumnIntoList(subjectFileUpload.getInputStream());
        } catch (IOException e) {
            log.error("Error in Subject list file");
            return subjectVOList;
        }

        Criteria criteria = getSession().createCriteria(LinkSubjectStudy.class);
        criteria.add(Restrictions.eq("study", study));
        criteria.add(Restrictions.in("subjectUID", subjectUidList));
        List<LinkSubjectStudy> subjectList = criteria.list();

        for (Iterator<LinkSubjectStudy> iterator = subjectList.iterator(); iterator.hasNext();) {
            LinkSubjectStudy linkSubjectStudy = (LinkSubjectStudy) iterator.next();
            // Place the LinkSubjectStudy instance into a SubjectVO and add the SubjectVO into a List
            SubjectVO subject = new SubjectVO();
            subject.setSubjectUID(linkSubjectStudy.getSubjectUID());
            subject.setLinkSubjectStudy(linkSubjectStudy);
            //Person person = subject.getLinkSubjectStudy().getPerson();
            //subject.setSubjectPreviousLastname(getPreviousLastname(person));
            subjectVOList.add(subject);
        }
    }
    return subjectVOList;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> applyConsentStatusFilters(DataExtractionVO allTheData, Search search,
        List<Long> idsToInclude) {

    //for(Long l : idsToInclude) {
    //   log.info("including: " + l);
    //}/*  ww w.j  ava 2s .co  m*/
    boolean hasConsentFilters = false;
    if (search.getQueryFilters().isEmpty()) {
        return idsToInclude;
    } else {
        for (QueryFilter filter : search.getQueryFilters()) {
            if (filter.getConsentStatusField() != null) {
                hasConsentFilters = true;
            }
        }
    }
    Criteria filter = getSession().createCriteria(Consent.class, "c");
    filter.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
    filter.createAlias("c.linkSubjectStudy", "lss");
    if (!idsToInclude.isEmpty()) {
        filter.add(Restrictions.in("lss.id", idsToInclude));
    }
    filter.createAlias("c.studyComponentStatus", "cscs");
    filter.createAlias("c.studyComp", "csc");

    if (!hasConsentFilters) {

        for (QueryFilter qf : search.getQueryFilters()) {
            if (qf.getConsentStatusField() != null) {
                switch (qf.getOperator()) {
                case EQUAL:
                    filter.add(Restrictions.eq(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case BETWEEN:
                    filter.add(Restrictions.between(getConsentFilterFieldName(qf), qf.getValue(),
                            qf.getSecondValue()));
                    break;
                case GREATER_THAN:
                    filter.add(Restrictions.gt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case GREATER_THAN_OR_EQUAL:
                    filter.add(Restrictions.ge(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case IS_EMPTY:
                    filter.add(Restrictions.isEmpty(getConsentFilterFieldName(qf)));
                    break;
                case IS_NOT_EMPTY:
                    filter.add(Restrictions.isNotEmpty(getConsentFilterFieldName(qf)));
                    break;
                case LESS_THAN:
                    filter.add(Restrictions.lt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LESS_THAN_OR_EQUAL:
                    filter.add(Restrictions.le(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LIKE:
                    filter.add(Restrictions.like(getConsentFilterFieldName(qf), qf.getValue(),
                            MatchMode.ANYWHERE));
                    break;
                case NOT_EQUAL:
                    filter.add(Restrictions.ne(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                default:
                    break;
                }
            }
        }
    }
    filter.setProjection(
            Projections.distinct(Projections.projectionList().add(Projections.property("lss.id"))));

    List<Long> consentStatusIDs = filter.list();

    Collection<Consent> csData = Collections.EMPTY_LIST;

    if (!consentStatusIDs.isEmpty()) {
        Criteria consentData = getSession().createCriteria(Consent.class, "c");
        consentData.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
        consentData.createAlias("c.linkSubjectStudy", "lss");
        consentData.add(Restrictions.in("lss.id", consentStatusIDs));
        csData = consentData.list();
    }

    HashMap<String, ExtractionVO> hashOfConsentStatusData = allTheData.getConsentStatusData();

    ExtractionVO valuesForThisLss = new ExtractionVO();
    HashMap<String, String> map = null;
    LinkSubjectStudy previousLss = null;
    int count = 0;
    //will try to order our results and can therefore just compare to last LSS and either add to or create new Extraction VO
    for (Consent data : csData) {
        if (previousLss == null) {
            map = new HashMap<String, String>();
            previousLss = data.getLinkSubjectStudy();
            count = 0;
        } else if (data.getLinkSubjectStudy().getId().equals(previousLss.getId())) {
            //then just put the data in
            count++;
        } else { //if its a new LSS finalize previous map, etc
            valuesForThisLss.setKeyValues(map);
            valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
            hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
            previousLss = data.getLinkSubjectStudy();
            map = new HashMap<String, String>();//reset
            valuesForThisLss = new ExtractionVO();
            count = 0;
        }
        if (data.getStudyComp().getName() != null) {
            map.put(count + "_Study Component Name", data.getStudyComp().getName());
        }
        if (data.getStudyComponentStatus() != null) {
            map.put(count + "_Study Component Status", data.getStudyComponentStatus().getName());
        }
        if (data.getConsentDate() != null) {
            map.put(count + "_Consent Date", data.getConsentDate().toString());
        }
        if (data.getConsentedBy() != null) {
            map.put(count + "_Consented By", data.getConsentedBy());
        }
    }

    //finalize the last entered key value sets/extraction VOs
    if (map != null && previousLss != null) {
        valuesForThisLss.setKeyValues(map);
        valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
        hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
    }

    //can probably now go ahead and add these to the dataVO...even though inevitable further filters may further axe this list or parts of it.
    allTheData.setConsentStatusData(hashOfConsentStatusData);
    if (hasConsentFilters) {
        return consentStatusIDs;
    } else {
        return idsToInclude;
    }
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> addDataFromMegaBiocollectionQuery(DataExtractionVO allTheData,
        Collection<BiocollectionField> biocollectionFields, Collection<CustomFieldDisplay> collectionCFDs,
        Search search, List<Long> idsToInclude, List<Long> biocollectionIdsAfterFiltering) {
    String bioCollectionFilters = getBiocollectionFilters(search);

    Collection<BioCollection> bioCollectionList = Collections.EMPTY_LIST;

    if (biocollectionFields.isEmpty() && bioCollectionFilters.isEmpty()) {
        if (idsToInclude.isEmpty()) {
            // no need - skip querying
        } else {//  www  . j ava 2 s .  co  m
            biocollectionIdsAfterFiltering = getBioCollectionIdForSubjectIds(idsToInclude);
            if (!biocollectionIdsAfterFiltering.isEmpty()) {
                bioCollectionList = getSession().createCriteria(BioCollection.class)
                        .add(Restrictions.in("id", biocollectionIdsAfterFiltering)).list();
            }
        }
    }

    if (!idsToInclude.isEmpty() && biocollectionIdsAfterFiltering.isEmpty()
            && (!bioCollectionFilters.isEmpty() || !biocollectionFields.isEmpty())) {

        StringBuffer queryBuffer = new StringBuffer("select distinct biocollection ");
        queryBuffer.append("from BioCollection biocollection "); //   TODO:  improve preformance by prefetch
        queryBuffer.append(" where biocollection.study.id = " + search.getStudy().getId());

        if (!bioCollectionFilters.isEmpty()) {
            queryBuffer.append(bioCollectionFilters);
        }
        queryBuffer.append("  and biocollection.linkSubjectStudy.id in (:idsToInclude) ");

        Query query = getSession().createQuery(queryBuffer.toString());
        query.setParameterList("idsToInclude", idsToInclude);
        bioCollectionList = query.list();
    }
    HashSet uniqueSubjectIDs = new HashSet<Long>();
    HashMap<String, ExtractionVO> hashOfBioCollectionData = allTheData.getBiocollectionData();

    for (BioCollection bioCollection : bioCollectionList) {
        ExtractionVO sev = new ExtractionVO();
        sev.setKeyValues(constructKeyValueHashmap(bioCollection, biocollectionFields));
        hashOfBioCollectionData.put(bioCollection.getBiocollectionUid(), sev);
        uniqueSubjectIDs.add(bioCollection.getLinkSubjectStudy().getId());
        sev.setSubjectUid(bioCollection.getLinkSubjectStudy().getSubjectUID()); //TODO: mow that we haevb this probably need to fetch join to save us a bunch of hits to the db
        biocollectionIdsAfterFiltering.add(bioCollection.getId());
    }

    //maintaining list of subject IDs for filtering past results
    if (!bioCollectionFilters.isEmpty()) {
        idsToInclude = new ArrayList(uniqueSubjectIDs);
    }
    return biocollectionIdsAfterFiltering;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> addDataFromMegaBiospecimenQuery(DataExtractionVO allTheData,
        Collection<BiospecimenField> biospecimenFields, //Collection<CustomFieldDisplay> specimenCFDs, 
        Search search, List<Long> idsToInclude, List<Long> biospecimenIdsAfterFiltering,
        List<Long> bioCollectionIdsAfterFiltering) {

    String biospecimenFilters = getBiospecimenFilters(search);

    HashMap<String, ExtractionVO> hashOfBiospecimenData = allTheData.getBiospecimenData();

    Collection<Biospecimen> biospecimenList = null;

    if ((biospecimenFields.isEmpty() && biospecimenFilters.isEmpty())) {
        if (idsToInclude.isEmpty()) {
            // no need
        } else {/*w w  w .  j  a  v  a2  s. c  o m*/
            biospecimenIdsAfterFiltering = getBiospecimenIdForSubjectIds(idsToInclude);
            if (biospecimenIdsAfterFiltering.isEmpty()) {
                return Collections.EMPTY_LIST;
            } else {
                biospecimenList = getSession().createCriteria(Biospecimen.class)
                        .add(Restrictions.in("id", biospecimenIdsAfterFiltering)).list();
            }
        }
    } else if ((!biospecimenFields.isEmpty() || !biospecimenFilters.isEmpty()) && !idsToInclude.isEmpty()) {

        StringBuffer queryBuffer = new StringBuffer("select distinct biospecimen ");
        queryBuffer.append("from Biospecimen biospecimen ");
        queryBuffer.append("    left join fetch biospecimen.sampleType sampleType ");
        queryBuffer.append("   left join fetch biospecimen.invCell invCell "); //Not lookup compatible
        queryBuffer.append("   left join fetch biospecimen.storedIn storedIn ");
        queryBuffer.append("   left join fetch biospecimen.grade grade ");
        queryBuffer.append("   left join fetch biospecimen.species species ");
        queryBuffer.append("   left join fetch biospecimen.unit unit ");
        queryBuffer.append("   left join fetch biospecimen.treatmentType treatmentType ");
        queryBuffer.append("   left join fetch biospecimen.quality quality ");
        queryBuffer.append("   left join fetch biospecimen.anticoag anticoag ");
        queryBuffer.append("   left join fetch biospecimen.status status ");
        queryBuffer.append("   left join fetch biospecimen.biospecimenProtocol biospecimenProtocol ");
        queryBuffer.append("   left join fetch biospecimen.bioCollection biocollection ");
        queryBuffer.append(" where biospecimen.study.id = " + search.getStudy().getId());
        if (!biospecimenFilters.isEmpty()) {
            queryBuffer.append(biospecimenFilters);
        }

        queryBuffer.append("  and biospecimen.linkSubjectStudy.id in (:idsToInclude) ");

        if (!bioCollectionIdsAfterFiltering.isEmpty()) {
            queryBuffer.append("  and biospecimen.bioCollection.id in (:biocollectionsToFilter) ");
        } else {
            biospecimenIdsAfterFiltering = new ArrayList<Long>();
            return new ArrayList<Long>();
        }

        Query query = getSession().createQuery(queryBuffer.toString());
        query.setParameterList("idsToInclude", idsToInclude);
        if (!bioCollectionIdsAfterFiltering.isEmpty()) {
            query.setParameterList("biocollectionsToFilter", bioCollectionIdsAfterFiltering);
        }

        biospecimenList = query.list();
    }
    HashSet uniqueSubjectIDs = new HashSet<Long>();
    for (Biospecimen biospecimen : biospecimenList) {
        ExtractionVO sev = new ExtractionVO();
        sev.setKeyValues(constructKeyValueHashmap(biospecimen, biospecimenFields));
        sev.setSubjectUid(biospecimen.getLinkSubjectStudy().getSubjectUID());
        hashOfBiospecimenData.put(biospecimen.getBiospecimenUid(), sev);
        uniqueSubjectIDs.add(biospecimen.getLinkSubjectStudy().getId());
        biospecimenIdsAfterFiltering.add(biospecimen.getId());
    }

    //maintaining list of subject IDs for filtering past results
    if (!biospecimenFilters.isEmpty()) {

        idsToInclude.clear();
        for (Object id : uniqueSubjectIDs) {
            idsToInclude.add((Long) id);
        }
        log.info("LATEST LIST OF IDS SIZE=" + idsToInclude.size());
    }
    allTheData.setBiospecimenData(hashOfBiospecimenData);//wouldnt think I need to set ht
    //log.info("addDataFromMegaBiospecimenQuery.biospecimenIdsAfterFiltering: " + biospecimenIdsAfterFiltering.size());
    return biospecimenIdsAfterFiltering;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

@Override
public List<StudyComp> getStudyComponentsNeverUsedInThisSubject(Study study,
        LinkSubjectStudy linkSubjectStudy) {
    List<StudyComp> consentStudyCompLst = getDifferentStudyComponentsInConsentForSubject(study,
            linkSubjectStudy);//from   w  w w. j  a v  a  2  s . com
    List<Long> consentStudyCompIdLst = new ArrayList<Long>();
    for (StudyComp studyComp : consentStudyCompLst) {
        consentStudyCompIdLst.add(studyComp.getId());
    }
    Criteria criteria = getSession().createCriteria(StudyComp.class);
    criteria.add(Restrictions.eq("study", study));
    if (!consentStudyCompIdLst.isEmpty()) {
        criteria.add(Restrictions.not(Restrictions.in("id", consentStudyCompIdLst)));
    }
    return criteria.list();
}