Example usage for org.hibernate.criterion Projections countDistinct

List of usage examples for org.hibernate.criterion Projections countDistinct

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections countDistinct.

Prototype

public static CountProjection countDistinct(String propertyName) 

Source Link

Document

A distinct property value count projection

Usage

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateApplicationDao.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
@Override//from w  w w .  j  av  a  2 s .  c o  m
public List<Integer> getTopXVulnerableAppsFromList(int numApps, List<Integer> teamIdList,
        List<Integer> applicationIdList, List<Integer> tagIdList, List<Integer> vulnTagIdList) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Application.class);
    criteria.createAlias("vulnerabilities", "vulnerability");
    criteria.add(Restrictions.eq("active", true));
    criteria.add(Restrictions.eq("vulnerability.active", true));
    criteria.add(Restrictions.eq("vulnerability.hidden", false));
    criteria.add(Restrictions.eq("vulnerability.isFalsePositive", false));

    if (vulnTagIdList.size() > 0) {
        criteria.createAlias("vulnerability.tags", "tags");
        criteria.add(Restrictions.in("tags.id", vulnTagIdList));
    }

    if (teamIdList.isEmpty() || applicationIdList.isEmpty()) {
        if (!applicationIdList.isEmpty()) {
            criteria.add(Restrictions.in("id", applicationIdList));
        }

        if (!teamIdList.isEmpty()) {
            criteria.add(Restrictions.in("organization.id", teamIdList));
        }
    } else {
        criteria.add(Restrictions.or(Restrictions.in("id", applicationIdList),
                Restrictions.in("organization.id", teamIdList)));
    }
    if (!tagIdList.isEmpty()) {
        criteria.createAlias("tags", "tag");
        criteria.add(Restrictions.in("tag.id", tagIdList));
    }

    criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("id"))
            .add(Projections.alias(Projections.countDistinct("vulnerability.id"), "vulnCount")));
    criteria.addOrder(Order.desc("vulnCount"));

    List<Integer> list = list();
    List results = criteria.list();
    int i = 0;
    for (Object result : results) {
        if (i++ >= numApps) {
            break;
        }
        Object[] resultArray = (Object[]) result;
        list.add((Integer) resultArray[0]);
    }

    if (list.isEmpty())
        list = Arrays.asList(-1);
    return list;
}

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateApplicationDao.java

License:Mozilla Public License

@Override
public List<Map<String, Object>> retrieveAppsInfoMap(List<Integer> applicationIdList,
        List<Integer> vulnTagIds) {

    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Application.class);

    criteria.createAlias("vulnerabilities", "vulnerability");
    criteria.createAlias("organization", "team");
    criteria.add(Restrictions.eq("active", true));
    criteria.add(Restrictions.eq("vulnerability.active", true));
    criteria.add(Restrictions.eq("vulnerability.isFalsePositive", false));
    criteria.createAlias("vulnerability.genericSeverity", "severity");

    if (applicationIdList.size() > 0) {
        criteria.add(Restrictions.in("id", applicationIdList));
    }/*from   w  w  w  .  j  a  va2 s  .  c  om*/

    if (vulnTagIds.size() > 0) {
        criteria.createAlias("vulnerability.tags", "tags");
        criteria.add(Restrictions.in("tags.id", vulnTagIds));
    }

    criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("id"), "appId")
            .add(Projections.groupProperty("name"), "appName")
            .add(Projections.groupProperty("team.id"), "teamId")
            .add(Projections.groupProperty("team.name"), "teamName")
            .add(Projections.groupProperty("severity.intValue"), "severityIntValue")
            .add(Projections.groupProperty("severity.name"), "severityNameValue")
            .add(Projections.alias(Projections.countDistinct("vulnerability.id"), "vulnCount")));
    criteria.addOrder(Order.desc("vulnCount"));
    criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

    List results = criteria.list();
    return results;
}

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateScanDao.java

License:Mozilla Public License

@Override
public long getTotalNumberFindingsMergedInScan(Integer scanId) {
    long numUniqueVulnerabilities = (Long) sessionFactory.getCurrentSession().createCriteria(Finding.class)
            .createAlias("vulnerability", "vuln").add(eq("scan.id", scanId))
            .setProjection(Projections.countDistinct("vuln.id")).uniqueResult();

    long numFindingsWithVulnerabilities = (Long) sessionFactory.getCurrentSession()
            .createCriteria(Finding.class).add(Restrictions.isNotNull("vulnerability"))
            .add(eq("scan.id", scanId)).setProjection(rowCount()).uniqueResult();

    return numFindingsWithVulnerabilities - numUniqueVulnerabilities;
}

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateVulnerabilitySearchDao.java

License:Mozilla Public License

@Override
public List<VulnerabilityTreeElement> getTree(VulnerabilitySearchParameters parameters) {
    assert parameters != null;

    Criteria criteria = VulnerabilitySearchCriteriaConstructor
            .getCriteriaWithRestrictions(sessionFactory.getCurrentSession(), parameters);

    criteria.setProjection(Projections.projectionList().add(Projections.countDistinct("id"), "numResults")
            .add(Projections.groupProperty("severity.intValue"))
            .add(Projections.groupProperty("genericVulnAlias.id"), "genericVulnerabilityId")
            .add(Projections.groupProperty("genericVulnAlias.name"), "genericVulnerabilityName")
            .add(Projections.groupProperty("genericVulnAlias.cweId"), "genericVulnerabilityDisplayId")
            .add(Projections.groupProperty("severity.intValue"), "severityIntValue"))
            .addOrder(Order.desc("severityIntValue")).addOrder(Order.desc("numResults"));

    criteria.setResultTransformer(Transformers.aliasToBean(VulnerabilityTreeElement.class));

    return (List<VulnerabilityTreeElement>) criteria.list();
}

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateVulnerabilitySearchDao.java

License:Mozilla Public License

@Override
public List<Map> getScanComparison(VulnerabilitySearchParameters parameters, boolean isFalsePositive) {
    assert parameters != null;
    List<Integer> idList = getVulnIdList(parameters);

    if (idList.isEmpty())
        return list();

    Session session = sessionFactory.getCurrentSession();

    List<Map> fullList = list();

    // TODO refactor this to reduce duplication or remove the need for it
    int current = 0;
    while (current < idList.size()) {

        int start = current, end = current + 500;
        if (end > idList.size()) {
            end = idList.size();/*  www .  j a va2s . c om*/
        }

        List<Integer> thisPage = idList.subList(start, end);

        Criteria criteria = session.createCriteria(Vulnerability.class);

        criteria.createAlias("findings", "finding");
        criteria.createAlias("finding.scan", "scan");
        criteria.createAlias("scan.applicationChannel", "applicationChannel");
        criteria.createAlias("applicationChannel.channelType", "channelType");
        criteria.add(Restrictions.in("id", thisPage));

        ProjectionList projectionList = Projections.projectionList()
                .add(Projections.groupProperty("channelType.name"), "channelName")
                .add(Projections.alias(Projections.countDistinct("id"), "foundCount"));

        if (!isFalsePositive) {
            projectionList.add(Projections.groupProperty("foundHAMEndpoint"), "foundHAMEndpoint");
        }
        criteria.setProjection(projectionList);
        criteria.addOrder(Order.desc("foundCount"));
        criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        List results = (List<Map>) criteria.list();
        fullList.addAll(results);

        current += 500;
    }

    return fullList;

}

From source file:com.evolveum.midpoint.repo.sql.query.custom.ShadowQueryWithDisjunction.java

License:Apache License

@Override
public RQuery createQuery(ObjectQuery objectQuery, Class<? extends ObjectType> type,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean countingObjects, Session session) {

    DetachedCriteria c1 = DetachedCriteria.forClass(ClassMapper.getHQLTypeClass(ShadowType.class), "s");
    c1.createCriteria("strings", "s1", JoinType.LEFT_OUTER_JOIN);

    ParsedQuery parsedQuery = parse(objectQuery);
    Conjunction conjunction = Restrictions.conjunction();
    conjunction//ww w.ja v a 2 s .co  m
            .add(Restrictions.eq("resourceRef.targetOid", parsedQuery.refFilter.getValues().get(0).getOid()));
    Disjunction disjunction = Restrictions.disjunction();
    disjunction.add(createAttributeEq(parsedQuery.eqUidFilter,
            parsedQuery.eqUidFilter.getPath().lastNamed().getName()));
    disjunction.add(createAttributeEq(parsedQuery.eqNameFilter, SchemaConstantsGenerated.ICF_S_NAME));
    conjunction.add(disjunction);
    c1.add(conjunction);

    if (countingObjects) {
        c1.setProjection(Projections.countDistinct("s.oid"));
        return new RQueryCriteriaImpl(c1.getExecutableCriteria(session));
    }

    c1.setProjection(Projections.distinct(Projections.property("s.oid")));

    Criteria cMain = session.createCriteria(ClassMapper.getHQLTypeClass(ShadowType.class), "o");
    cMain.add(Subqueries.propertyIn("oid", c1));

    if (objectQuery != null && objectQuery.getPaging() != null) {
        cMain = updatePagingAndSorting(cMain, type, objectQuery.getPaging());
    }

    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("fullObject"));
    projections.add(Projections.property("stringsCount"));
    projections.add(Projections.property("longsCount"));
    projections.add(Projections.property("datesCount"));
    projections.add(Projections.property("referencesCount"));
    projections.add(Projections.property("polysCount"));
    projections.add(Projections.property("booleansCount"));

    cMain.setProjection(projections);

    cMain.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
    return new RQueryCriteriaImpl(cMain);
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Adds a new projection to the current projectionList stack.
 * Mandatory Attributes:<ul>//from w  w  w  .  jav  a  2s  .  c om
 * <li><b>name</b>: The field to create a projection on.</li>
 * <li><b>type</b>: The projection type.</li>
 * <li><b>alias</b>: The name applied to the projection returned field.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @throws SAXException
 * TODO: Implement checks for mandatory attributes.
 */
public void addProjection(Attributes attrs) throws SAXException {
    ProjectionList projectionList = projectionStack.peek();
    if (projectionList == null) {
        throw new SAXException(
                "Attempted to add Projection and no ProjectionList Exists On The Stack. (Projection must be embedded inside a Projections)");
    }
    String type = attrs.getValue("type");
    String name = attrs.getValue("name");
    String alias = attrs.getValue("alias");
    if ("avg".equalsIgnoreCase(type)) {
        projectionList.add(Projections.avg(name), alias);
    } else if ("count".equalsIgnoreCase(type)) {
        projectionList.add(Projections.count(name), alias);
    } else if ("countDistinct".equalsIgnoreCase(type)) {
        projectionList.add(Projections.countDistinct(name), alias);
    } else if ("groupProperty".equalsIgnoreCase(type)) {
        projectionList.add(Projections.groupProperty(name), alias);
    } else if ("max".equalsIgnoreCase(type)) {
        projectionList.add(Projections.max(name), alias);
    } else if ("min".equalsIgnoreCase(type)) {
        projectionList.add(Projections.min(name), alias);
    } else if ("sum".equalsIgnoreCase(type)) {
        projectionList.add(Projections.sum(name), alias);
    } else if ("rowCount".equalsIgnoreCase(type)) {
        projectionList.add(Projections.rowCount(), alias);
    }

}

From source file:com.hypersocket.resource.AbstractAssignableResourceRepositoryImpl.java

License:Open Source License

@Override
public Long getAssignedResourceCount(List<Principal> principals, final String searchPattern,
        CriteriaConfiguration... configs) {

    Criteria criteria = createCriteria(getResourceClass());
    criteria.setProjection(Projections.property("id"));
    criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }/*from www. j  ava  2  s .co m*/

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));
    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", true));

    List<?> ids = criteria.list();

    criteria = createCriteria(getResourceClass());
    criteria.setProjection(Projections.countDistinct("name"));
    criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));
    if (ids.size() > 0) {
        criteria.add(Restrictions.not(Restrictions.in("id", ids)));
    }

    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", false));
    criteria = criteria.createCriteria("principals");
    List<Long> pids = new ArrayList<Long>();
    for (Principal p : principals) {
        pids.add(p.getId());
    }
    criteria.add(Restrictions.in("id", pids));

    Long count = (Long) criteria.uniqueResult();
    return count + ids.size();

}

From source file:com.hypersocket.session.SessionRepositoryImpl.java

License:Open Source License

@Override
public Long getActiveSessionCount(boolean distinctUsers) {
    Criteria criteria = createCriteria(Session.class);

    criteria.add(Restrictions.isNull("signedOut"));
    criteria.add(Restrictions.eq("system", false));

    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    if (distinctUsers) {
        criteria.setProjection(Projections.countDistinct("principal"));
    } else {//w w  w . j  av  a2s.  c  om
        criteria.setProjection(Projections.rowCount());
    }
    return (long) criteria.uniqueResult();
}

From source file:com.hypersocket.session.SessionRepositoryImpl.java

License:Open Source License

@Override
public Long getSessionCount(final Date startDate, final Date endDate, final boolean distinctUsers) {

    Criteria criteria = createCriteria(Session.class);

    criteria.add(Restrictions.or(/*from ww  w . j  a  v  a 2s. c o  m*/
            Restrictions.and(Restrictions.ge("created", startDate), Restrictions.lt("created", endDate)),
            Restrictions.and(Restrictions.lt("created", startDate), Restrictions
                    .or(Restrictions.ge("signedOut", startDate), Restrictions.isNull("signedOut")))));

    criteria.add(Restrictions.eq("system", false));

    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    if (distinctUsers) {
        criteria.setProjection(Projections.countDistinct("principal"));
    } else {
        criteria.setProjection(Projections.rowCount());
    }
    return (long) criteria.uniqueResult();
}