Example usage for org.hibernate.criterion Projections projectionList

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

Introduction

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

Prototype

public static ProjectionList projectionList() 

Source Link

Document

Create a new projection list.

Usage

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

License:Mozilla Public License

@Override
public List<Integer> mapIDsThatNeedCountersInApps(List<Integer> appIds,
        Collection<Integer> findingIdRestrictions) {

    // get list of finding IDs to ScanRepeatFindingMapIDs
    ProjectionList list = Projections.projectionList().add(Projections.id()) // 0
            .add(Projections.property("findingAlias.id")); // 1
    List<Object[]> idArrayList = getBasicMapCriteria().createAlias("finding", "findingAlias")
            .setProjection(list).list();

    // move results into Java Map
    // needs to be int -> list<int> because you can have multiple maps to a single finding ID
    // and they all need counters
    Map<Integer, List<Integer>> findingIdToMapIdMap = map();
    for (Object[] integers : idArrayList) {
        if (integers[0] instanceof Integer && integers[1] instanceof Integer) {
            Integer findingId = (Integer) integers[1], mapId = (Integer) integers[0];
            if (!findingIdToMapIdMap.containsKey(findingId)) {
                findingIdToMapIdMap.put(findingId, listOf(Integer.class));
            }/*from   w ww .  j  a  v  a 2  s.co  m*/

            findingIdToMapIdMap.get(findingId).add(mapId);
        }
    }

    // keep only valid finding IDs
    Set<Integer> keys = findingIdToMapIdMap.keySet();
    keys.retainAll(findingIdRestrictions);

    // map to the ScanRepeatFindingMap IDs
    List<Integer> mapIds = list();
    for (Integer key : keys) {
        mapIds.addAll(findingIdToMapIdMap.get(key));
    }
    return mapIds;
}

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();/*w w w .  j  av a  2s.  c  o m*/
        }

        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.denimgroup.threadfix.data.dao.hibernate.HibernateVulnerabilitySearchDao.java

License:Mozilla Public License

private List<Integer> getVulnIdList(VulnerabilitySearchParameters parameters) {
    Criteria criteria = VulnerabilitySearchCriteriaConstructor
            .getCriteriaWithRestrictions(sessionFactory.getCurrentSession(), parameters);

    criteria.setProjection(Projections.projectionList().add(Projections.property("id")));

    List<Integer> idList = (List<Integer>) criteria.list();
    return idList;
}

From source file:com.eharmony.matching.seeking.translator.hibernate.HibernateQueryTranslator.java

License:Apache License

@Override
public <T, R> Projection translateProjection(Query<T, R> query) {
    if (query.getReturnFields().size() > 0) {
        ProjectionList projectionList = Projections.projectionList();
        for (String returnField : query.getReturnFields()) {
            projectionList.add(Projections.property(returnField));
        }//from   w ww . j a  va2 s  .  c o m
        return projectionList;
    } else {
        return null;
    }
}

From source file:com.ephesoft.dcma.da.dao.hibernate.PageTypeDaoImpl.java

License:Open Source License

/**
 * An API to fetch all batch class id, document type names and Page type names corresponding to each other.
 * /*  www .j ava 2 s  .c om*/
 * @param batchClassIdentifierList List<String>
 * @return List<Object[]>
 */
@Override
public List<Object[]> getDocTypeNameAndPgTypeName(List<String> batchClassIdentifierList) {
    DetachedCriteria criteria = criteria();
    criteria.createAlias(DOC_TYPE, DOC_TYPE, JoinFragment.RIGHT_OUTER_JOIN);
    criteria.createAlias(DOC_TYPE_BATCH_CLASS, BATCH_CLASS, JoinFragment.INNER_JOIN);
    criteria.add(Restrictions.in(BATCH_CLASS_IDENTIFIER, batchClassIdentifierList));
    criteria.addOrder(Order.asc(BATCH_CLASS_IDENTIFIER));
    criteria.addOrder(Order.asc(DOC_TYPE_NAME));
    criteria.setProjection(Projections.projectionList().add(Projections.property(BATCH_CLASS_IDENTIFIER))
            .add(Projections.property(DOC_TYPE_NAME)).add(Projections.property(NAME)));
    return find(criteria);
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static List<Collection<MetricStatistics>> getManyMetricStatistics(
        List<GetMetricStatisticsParams> getMetricStatisticsParamses) {
    if (getMetricStatisticsParamses == null)
        throw new IllegalArgumentException("getMetricStatisticsParamses can not be null");
    Date now = new Date();
    Map<GetMetricStatisticsParams, Collection<MetricStatistics>> resultMap = Maps.newHashMap();
    Multimap<Class, GetMetricStatisticsParams> hashGroupMap = LinkedListMultimap.create();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (getMetricStatisticsParams == null)
            throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
        getMetricStatisticsParams.validate(now);
        Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
                getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
        hashGroupMap.put(metricEntityClass, getMetricStatisticsParams);
    }/* w  w w .ja v a  2 s .  co m*/
    for (Class metricEntityClass : hashGroupMap.keySet()) {
        try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
            // set some global criteria to start (for narrowing?)
            Date minDate = null;
            Date maxDate = null;
            Junction disjunction = Restrictions.disjunction();
            Map<GetMetricStatisticsParams, TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>> multiAggregationMap = Maps
                    .newHashMap();
            for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap.get(metricEntityClass)) {
                multiAggregationMap.put(getMetricStatisticsParams,
                        new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
                                GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE));
                Junction conjunction = Restrictions.conjunction();
                conjunction = conjunction
                        .add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
                conjunction = conjunction
                        .add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
                conjunction = conjunction
                        .add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
                conjunction = conjunction
                        .add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
                conjunction = conjunction
                        .add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
                conjunction = conjunction.add(
                        Restrictions.eq("dimensionHash", hash(getMetricStatisticsParams.getDimensionMap())));
                if (getMetricStatisticsParams.getUnits() != null) {
                    conjunction = conjunction
                            .add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
                }
                disjunction = disjunction.add(conjunction);
                if (minDate == null || getMetricStatisticsParams.getStartTime().before(minDate)) {
                    minDate = getMetricStatisticsParams.getStartTime();
                }
                if (maxDate == null || getMetricStatisticsParams.getEndTime().after(maxDate)) {
                    maxDate = getMetricStatisticsParams.getEndTime();
                }
            }
            Criteria criteria = Entities.createCriteria(metricEntityClass);
            criteria = criteria.add(Restrictions.lt("timestamp", maxDate));
            criteria = criteria.add(Restrictions.ge("timestamp", minDate));
            criteria = criteria.add(disjunction);

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.max("sampleMax"));
            projectionList.add(Projections.min("sampleMin"));
            projectionList.add(Projections.sum("sampleSize"));
            projectionList.add(Projections.sum("sampleSum"));
            projectionList.add(Projections.groupProperty("units"));
            projectionList.add(Projections.groupProperty("timestamp"));
            projectionList.add(Projections.groupProperty("accountId"));
            projectionList.add(Projections.groupProperty("metricName"));
            projectionList.add(Projections.groupProperty("metricType"));
            projectionList.add(Projections.groupProperty("namespace"));
            projectionList.add(Projections.groupProperty("dimensionHash"));
            criteria.setProjection(projectionList);
            criteria.addOrder(Order.asc("timestamp"));

            ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
            while (results.next()) {
                MetricEntity me = getMetricEntity(results);
                for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap
                        .get(metricEntityClass)) {
                    if (metricDataMatches(getMetricStatisticsParams, me)) {
                        Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = multiAggregationMap
                                .get(getMetricStatisticsParams);
                        GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensionHash());
                        MetricStatistics item = new MetricStatistics(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensions());
                        if (!aggregationMap.containsKey(key)) {
                            aggregationMap.put(key, item);
                        } else {
                            MetricStatistics totalSoFar = aggregationMap.get(key);
                            totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                            totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                            totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                            totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
                        }
                    }
                }
            }
            for (GetMetricStatisticsParams getMetricStatisticsParams : multiAggregationMap.keySet()) {
                resultMap.put(getMetricStatisticsParams,
                        multiAggregationMap.get(getMetricStatisticsParams).values());
            }
        }
    }
    List<Collection<MetricStatistics>> resultList = Lists.newArrayList();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (resultMap.get(getMetricStatisticsParams) == null) {
            resultList.add(new ArrayList<MetricStatistics>());
        } else {
            resultList.add(resultMap.get(getMetricStatisticsParams));
        }
    }
    return resultList;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static Collection<MetricStatistics> getMetricStatistics(
        GetMetricStatisticsParams getMetricStatisticsParams) {
    if (getMetricStatisticsParams == null)
        throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
    Date now = new Date();
    getMetricStatisticsParams.validate(now);
    Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
            getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
    Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
            GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE);
    try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
        Criteria criteria = Entities.createCriteria(metricEntityClass);
        criteria = criteria.add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
        criteria = criteria.add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
        criteria = criteria.add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
        criteria = criteria.add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
        criteria = criteria.add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
        criteria = criteria.add(Restrictions.eq("dimensionHash", getMetricStatisticsParams.getDimensionHash()));
        if (getMetricStatisticsParams.getUnits() != null) {
            criteria = criteria.add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
        }/*w  w  w  . j a  v  a 2 s.  c  o m*/

        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.max("sampleMax"));
        projectionList.add(Projections.min("sampleMin"));
        projectionList.add(Projections.sum("sampleSize"));
        projectionList.add(Projections.sum("sampleSum"));
        projectionList.add(Projections.groupProperty("units"));
        projectionList.add(Projections.groupProperty("timestamp"));
        criteria.setProjection(projectionList);
        criteria.addOrder(Order.asc("timestamp"));
        ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
        while (results.next()) {
            MetricEntity me = getMetricEntity(getMetricStatisticsParams.getAccountId(),
                    getMetricStatisticsParams.getMetricName(), getMetricStatisticsParams.getNamespace(),
                    getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash(),
                    results);
            GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                    getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                    getMetricStatisticsParams.getDimensionHash());
            MetricStatistics item = new MetricStatistics(me, getMetricStatisticsParams.getStartTime(),
                    getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensions());
            if (!aggregationMap.containsKey(key)) {
                aggregationMap.put(key, item);
            } else {
                MetricStatistics totalSoFar = aggregationMap.get(key);
                totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
            }
        }
    }
    return Lists.newArrayList(aggregationMap.values());
}

From source file:com.eucalyptus.entities.EntityCache.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<Pair<String, Integer>> loadVersionMap() {
    try (final TransactionResource db = Entities.transactionFor(example)) {
        List<Object[]> idVersionList = (List<Object[]>) Entities.createCriteria(example.getClass())
                .add(Example.create(example)).setReadOnly(true).setCacheable(false).setFetchSize(1000)
                .setProjection(/*  w ww  .  j  ava  2s .c  o  m*/
                        Projections.projectionList().add(Projections.id()).add(Projections.property("version")))
                .list();
        return Lists.newArrayList(Iterables.transform(idVersionList, ObjectArrayToStringIntPair.INSTANCE));
    }
}

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 .j  a  v a 2s.c om*/
            .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);
}