Example usage for org.hibernate.criterion Projections property

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

Introduction

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

Prototype

public static PropertyProjection property(String propertyName) 

Source Link

Document

A property value projection

Usage

From source file:eu.cloud4soa.relational.persistence.SLAViolationRepository.java

License:Apache License

/**
 * Returns all sla violations for a given PaaS provider following
 * the following query:// ww w.  j  a  v  a2  s .co m
 * 
 * SELECT slaviolation.id
 *    FROM slaviolation
 *    WHERE slaviolation.idenforcementjob IN (
 *       SELECT enforcementjob.id
 *        FROM enforcementjob
 *        JOIN slacontract ON enforcementjob.idslacontract=slacontract.id
 *        WHERE slacontract.idprovider=XXX
 *    )
 * 
 * @param providerId the id of the PaaS provider
 * @return a list of SLAViolation objects
 */
public List<SLAViolation> retrieveAllForProvider(String providerId) {
    DetachedCriteria slap_criteria = DetachedCriteria.forClass(SLATemplate.class)
            .add(Restrictions.eq("serviceProvider", providerId)).setProjection(Projections.property("id"));

    DetachedCriteria enf_criteria = DetachedCriteria.forClass(SLAEnforcementJob.class)
            .add(Property.forName("slaContractId").in(slap_criteria)).setProjection(Projections.property("id"));

    return (List<SLAViolation>) getSession().createCriteria(SLAViolation.class)
            .add(Subqueries.geAll("slaEnforcementJobId", enf_criteria)).list();
}

From source file:eu.cloud4soa.relational.persistence.SLAViolationRepository.java

License:Apache License

/**
 * Returns all sla violations for a given PaaS offering following
 * the following query:/* w w  w  .j a  va2s  .c o  m*/
 * 
 * SELECT slaviolation.id
 *    FROM slaviolation
 *    WHERE slaviolation.idappinstance IN (
 *       SELECT idappinstance.id
 *        FROM idappinstance
 *        JOIN paas ON idappinstance.idpaas=paas.id
 *        WHERE paas.id=XXX
 *    )
 * 
 * @param offeringId the id of the PaaS offering
 * @return a list of SLAViolation objects
 */
public List<SLAViolation> retrieveAllForOffering(String offeringId) {
    DetachedCriteria pass_criteria = DetachedCriteria.forClass(Paas.class)
            .add(Restrictions.eq("url", offeringId));

    DetachedCriteria acc_criteria = DetachedCriteria.forClass(Account.class)
            .add(Property.forName("paas").in(pass_criteria));

    DetachedCriteria app_criteria = DetachedCriteria.forClass(ApplicationInstance.class)
            .add(Property.forName("account").in(acc_criteria)).setProjection(Projections.property("id"));

    return (List<SLAViolation>) getSession().createCriteria(SLAViolation.class)
            .add(Subqueries.geAll("applicationInstanceUriId", app_criteria)).list();
}

From source file:eu.cloud4soa.relational.persistence.SLAViolationRepository.java

License:Apache License

/**
 * Returns all SLA violations for a given User between two moments in time.
 * /* ww  w .j a  v  a2s  .co m*/
 * @param userId the user id
 * @param start  the moment we start to get the SLA violations
 * @param end    the moment we finish to get the SLA violations
 * @return       a list of SLA violations
 */
public List<SLAViolation> retrieveAllForUserAndTime(String userId, Date start, Date end) {
    DetachedCriteria user_criteria = DetachedCriteria.forClass(User.class).add(Restrictions.eq("uriID", userId))
            .setProjection(Projections.property("id"));

    DetachedCriteria acc_criteria = DetachedCriteria.forClass(Account.class)
            .add(Property.forName("user.id").in(user_criteria)).setProjection(Projections.property("id"));

    DetachedCriteria app_criteria = DetachedCriteria.forClass(ApplicationInstance.class)
            .add(Property.forName("account.id").in(acc_criteria)).setProjection(Projections.property("uriID"));

    return (List<SLAViolation>) getSession().createCriteria(SLAViolation.class)
            .add(Property.forName("applicationInstanceUriId").in(app_criteria))
            .add(Restrictions.between("dateAndTime", start, end)).list();
}

From source file:eu.jangos.manager.controller.AccountService.java

License:Apache License

/**
 * Provides access to the list of all accounts matching the parameters.
 *
 * The DateFilter works the same way: - NONE does not apply any filter. -
 * BEFORE & AFTER uses only the "From" date as filter. - BETWEEN uses both
 * "From" & "To" dates as filters.//  w  w  w.ja  v  a 2  s.co m
 *
 * @param name The name of the accounts to be found. Can contain %.
 * @param createdFilter The filter type for the creation date.
 * @param createdFrom The first creation date filter.
 * @param createdTo The second creation date filter.
 * @param loginFilter The filter type for the login date.
 * @param loginFrom The first login date filter.
 * @param loginTo The second login date filter.
 * @param locked The filter type for the lock value.
 * @param banned The filter type for the ban value.
 * @param online The filter type for the online value.
 * @param locale The locale on which this search must filter.
 * @param realm The locale on which this search must filter.
 * @return A List of Accounts matching the criterias.
 */
public List<Account> getAllAccounts(String name, DateType createdFilter, Date createdFrom, Date createdTo,
        DateType loginFilter, Date loginFrom, Date loginTo, BooleanType locked, BooleanType banned,
        BooleanType online, Locale locale, Realm realm) {

    boolean error = false;
    String message = "You must enter the following parameters:\n";

    // Checking name input.
    if (name == null || name.isEmpty()) {
        logger.error("The parameter name is null or empty");
        message += "- A name\n";
        error = true;
    }

    // Checking dates input.
    if ((createdFilter != DateType.NONE && createdFrom == null)
            || (createdFilter == DateType.BETWEEN && createdTo == null)
            || (loginFilter != DateType.NONE && loginFrom == null)
            || (loginFilter == DateType.BETWEEN && loginTo == null)) {
        logger.error("A date filter has been requested while the date values are incorrect");
        message += "- Valid dates when selecting a date filter\n";
        error = true;
    }

    if (error) {
        throw new IllegalArgumentException(message);
    }

    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Criteria query = session.createCriteria(Account.class, "acc");

        query.setFetchMode("locale", FetchMode.JOIN);
        query.setFetchMode("realm", FetchMode.JOIN);

        query.add(Restrictions.like("name", name));

        // This ban check is generating 2 SQL queries while, in SQL, you could do it in one.
        // Limitations of the criteria API.
        switch (banned) {
        case TRUE:
            // First, we get the list of IDs for the accounts that are banned.
            Criteria getBannedQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.eq("ban.active", true));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getBannedQuery.list()));
            break;
        case FALSE:
            // First, we get the list of ID for the accounts that are not banned.
            Criteria getNotBanQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.or(Restrictions.eq("ban.active", false),
                            Restrictions.isNull("ban.active")));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getNotBanQuery.list()));
            break;
        }

        // We add the realm restrictions, if it applies.
        if (!realm.getName().equals("ALL")) {
            query.add(Restrictions.eq("realm", realm));
        }

        // We add the locale restrictions, if it applies.
        if (!locale.getLocale().equals("ALL")) {
            query.add(Restrictions.eq("locale", locale));
        }

        query = Utils.applyDateFilter(query, "creation", createdFilter, createdFrom, createdTo);
        query = Utils.applyDateFilter(query, "lastlogin", loginFilter, loginFrom, loginTo);
        query = Utils.applyBooleanFilter(query, "locked", locked);
        query = Utils.applyBooleanFilter(query, "online", online);

        return query.list();
    } catch (HibernateException he) {
        logger.error("There was an error connecting to the database.");
        return null;
    }
}

From source file:eu.jangos.realm.controller.characters.ItemInstanceService.java

License:Apache License

/**
 * Return only the necessary fields of the equipment of the character in parameter for the CharEnum packet.
 *
 * @param character//from w w w . ja  v a2s.  c  o  m
 * @return A List of arrays of Object with the following structure: [slot,entry] where slot is the slot 
 * into which this item is located and entry is the ID of the item_template.
 */
public List getEquipmentCharEnum(Characters character) {
    logger.debug("getEquipment " + character.getName());

    try (Session session = HibernateUtil.getCharSession().openSession()) {
        ProjectionList proList = Projections.projectionList();
        proList.add(Projections.property("slot"), "slot");
        proList.add(Projections.property("fkObjectEntry"), "entry");

        return session.createCriteria(ItemInstance.class).setProjection(proList)
                .add(Restrictions.and(Restrictions.eq("characters.guid", character.getGuid()),
                        Restrictions.eq("itemStorageType.id", ItemStorageEnum.EQUIPPED.getValue())))
                .addOrder(Order.asc("slot")).list();
    } catch (HibernateException he) {
        logger.debug("There was an error querying the database.");
        return null;
    }
}

From source file:eu.jangos.realm.controller.world.ItemService.java

License:Apache License

/**
 * Return the item which has the given ID.
 * @param id The id of the item to be found.
 * @return The corresponding item or null if the item is not found.
 *//*from  w ww .j a  va  2  s .c o m*/
public Object[] getItemByIDCharEnum(int id) {
    logger.debug("Loading information for the item with the id " + id);

    try (Session session = HibernateUtil.getWorldSession().openSession()) {
        ProjectionList proList = Projections.projectionList();
        proList.add(Projections.property("displayid"), "displayid");
        proList.add(Projections.property("ivt.id"), "id");

        return (Object[]) session.createCriteria(Item.class).createAlias("inventorytype", "ivt")
                .setProjection(proList).add(Restrictions.eq("entry", id)).uniqueResult();

    } catch (HibernateException he) {
        logger.debug("There was an error connecting to the database.");
        return null;
    }
}

From source file:eu.optimis.common.trec.db.ip.TrecIP2SPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<SpInfo> getDistinctSpIDs() throws Exception {
    Session session = null;/*from   ww w . j a  va2 s  .  c  om*/
    List<SpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(IpToSp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("spInfo"))));
        //         criteria.setMaxResults(MAX_RESULTS);
        results = (List<SpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:eu.optimis.common.trec.db.ip.TrecSP2IPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IpInfo> getDistinctIpIDs() throws Exception {
    Session session = null;/* w w  w.j  av  a  2 s  .c  o  m*/
    List<IpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(SpToIp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("ipInfo"))));
        results = (List<IpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:eu.optimis.common.trec.db.sp.TrecSP2IPDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IpInfo> getDistinctIpIDs() throws Exception {
    Session session = null;//from  ww w . j  ava2s . com
    List<IpInfo> results = null;
    SessionFactory sf = HibernateUtil.getSessionFactory();
    try {
        session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        // Search by IP Name
        Criteria criteria = session.createCriteria(SpToIp.class);
        criteria.setProjection(
                Projections.distinct(Projections.projectionList().add(Projections.property("ipInfo"))));
        //         criteria.setMaxResults(MAX_RESULTS);
        results = (List<IpInfo>) criteria.list();
        tx.commit();
        return results;
    } catch (Exception e) {
        logger.error("ERROR " + e.getMessage());
        throw new Exception(e.toString());
    }
}

From source file:fr.insalyon.creatis.vip.application.server.dao.hibernate.SimulationStatsData.java

License:Open Source License

@Override
public List<String> getWorkflowsPerUser(List<String> workflowsId) throws WorkflowsDBDAOException {
    List<String> result = new ArrayList<String>();
    try {/*from   w  ww  .  j  ava 2s.co m*/
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Workflow.class);
        criteria.add(Restrictions.in("id", workflowsId));

        ProjectionList p = Projections.projectionList();
        p.add(Projections.groupProperty("username"));
        p.add(Projections.property("username"));
        p.add(Projections.alias(Projections.count("status"), "nbWfls"));

        //p.add(Projections.count("status"));
        criteria.setProjection(p);
        criteria.addOrder(Order.desc("nbWfls"));
        List l = criteria.list();
        session.getTransaction().commit();
        session.close();

        Iterator it = l.iterator();
        while (it.hasNext()) {
            Object ob[] = (Object[]) it.next();
            if (ob[0] != null && ob[1] != null) {
                result.add(String.valueOf(ob[0]) + "##" + String.valueOf(ob[2]));
            }
        }

        return result;
    } catch (HibernateException ex) {
        throw new WorkflowsDBDAOException(ex);
    }
}