Example usage for org.hibernate.criterion Projections max

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

Introduction

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

Prototype

public static AggregateProjection max(String propertyName) 

Source Link

Document

A property maximum value projection

Usage

From source file:es.itecban.deployment.environmentmanager.manager.AgentConnector.java

License:Apache License

/**
 * Connects to a TM with a specific ip address. The port by default is 1155
 * @param environmentname//from w  ww .java2 s . c  om
 * @return the TargetManager MXBean
 * @throws Exception 
 */

protected static TargetManagerMXBean connect2TM(String environmentname, String dirIp, String port,
        SessionFactory sessionFactory) throws Exception {

    if (dirIp == null) {
        final Session session = sessionFactory.openSession();
        session.beginTransaction();
        try {
            // Get the latest date for the "photos" stored in the database
            Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);
            timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
            timestampCriteria.add(Restrictions.eq("name", environmentname));
            Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();
            if (lastEvironmentTimestampCriteria == null)
                throw new Exception("There is no environment with that name in the database");
            //TODO: cambiar cuando el TM este actualizado en indra
            String qSelect = "select dtt.uUID from DeploymentTargetType as dtt"
                    + " where dtt.timestamp=:timestamp and" + " dtt.name=:environmentName";
            Query query = session.createQuery(qSelect);
            query.setParameter("timestamp", lastEvironmentTimestampCriteria);
            query.setString("environmentName", environmentname);
            dirIp = (String) query.uniqueResult();
        } catch (Exception e) {
            System.err.println("Error while retrieving the ip to connect via JMX");
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    if (port == null)
        port = "1155";
    String serviceurl = "service:jmx:rmi:///jndi/rmi://" + dirIp + ":" + port + "/TargetManager";
    logger.info("JMX direction: " + serviceurl);

    TargetManagerMXBean targetmanagermxbean = null;
    try {
        //checks if the connection is already established (in the connectionTable)
        MBeanServerConnection mBeanServerConnection = null;
        if (!connectionTable.containsKey(serviceurl)) {
            //the connection does not exist. Creating the new connection
            JMXConnector jmxconnector = JMXConnectorFactory.connect(new JMXServiceURL(serviceurl));
            mBeanServerConnection = jmxconnector.getMBeanServerConnection();
            targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                    new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
            logger.info("New connection created to TargetManager with name: " + targetmanagermxbean.getName());
            connectionTable.put(serviceurl, mBeanServerConnection);
        } else {
            mBeanServerConnection = (MBeanServerConnection) connectionTable.get(serviceurl);
            try {
                targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                        new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
                if (targetmanagermxbean == null || !targetmanagermxbean.isactive())
                    throw new Exception();
                logger.info("Connection obtained to TargetManager with name: " + targetmanagermxbean.getName());

            } catch (Exception e) {
                logger.info("Recreating the connection to TargetManager");
                //maybe the connection to the target manager has been closed so it must be created again
                try {
                    JMXConnector jmxconnector = JMXConnectorFactory.connect(new JMXServiceURL(serviceurl));
                    mBeanServerConnection = jmxconnector.getMBeanServerConnection();
                    targetmanagermxbean = JMX.newMXBeanProxy(mBeanServerConnection,
                            new ObjectName(Constants.TM_OBJECT_NAME), TargetManagerMXBean.class);
                    if (targetmanagermxbean == null || !targetmanagermxbean.isactive())
                        throw new Exception();
                    connectionTable.put(serviceurl, mBeanServerConnection);
                    logger.info("Connection recreated to TargetManager with name: "
                            + targetmanagermxbean.getName());
                } catch (Exception e1) {
                    logger.severe("Impossible to recreate the connection to the TargetManager with name: "
                            + targetmanagermxbean.getName());
                    e1.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        logger.severe("Problem while connecting to the targetmanager via JMX " + e);
        throw new Exception("running.error.tm.connection");
    }
    return targetmanagermxbean;
}

From source file:es.itecban.deployment.environmentmanager.manager.DBCleanerImpl.java

License:Apache License

/**
 * Cleans all the photos of a date interval
 *///  w w w  .  ja v a2 s.  co  m

// @Override
// public int clean(XMLGregorianCalendar minDate, XMLGregorianCalendar
// maxDate) throws Exception {
//
// logger.info("Beginning the cleannin of data.");
// final Session session = this.sessionFactory.openSession();
// int i = 0;
// List<DeploymentTargetType> environmentList = null;
// try {
// Criteria dttCriteria = session
// .createCriteria(DeploymentTargetType.class);
// // cuando no hay fecha es null o es ""??
// if (minDate != null)
// dttCriteria.add(Restrictions.ge("timestamp", minDate));
// if (maxDate != null)
// dttCriteria.add(Restrictions.le("timestamp", maxDate));
// dttCriteria.setMaxResults(3);
// boolean more = true;
//         
// while (more){
// session.beginTransaction();
// environmentList = dttCriteria.setMaxResults(3).list();
// if (environmentList.size() < 3)
// more = false;
// for (DeploymentTargetType environment : environmentList) {
// session.delete(environment);
// i++;
// }
// // Check if there is more to delete
// session.getTransaction().commit();
//            
// }
// } catch (Exception e) {
// logger.severe("Error while deleting the environment from the database"
// + e);
// throw new Exception(
// "Error while deleting the environment from the database" + e);
// } finally {
// session.close();
// }
// logger.info("Finished the cleannin of data.");
// return i;
// }
private Object getLastEnvironmentDayDate(String environmentName, XMLGregorianCalendar minDate,
        XMLGregorianCalendar maxDate) {

    final Session session = this.sessionFactory.openSession();
    session.beginTransaction();

    // Get the latest date for the "photos" stored in the database
    Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);

    if (minDate != null)
        timestampCriteria.add(Restrictions.ge("timestamp", minDate));
    if (maxDate != null)
        timestampCriteria.add(Restrictions.lt("timestamp", maxDate));

    timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
    timestampCriteria.add(Restrictions.eq("name", environmentName));
    Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();

    session.close();
    return lastEvironmentTimestampCriteria;
}

From source file:es.itecban.deployment.environmentmanager.manager.EnvironmentManagerImpl.java

License:Apache License

private Object getLastEnvironmentDate(String environmentName) {

    final Session session = this.sessionFactory.openSession();
    session.beginTransaction();/*from ww  w  . jav  a 2s  .co  m*/

    // Get the latest date for the "photos" stored in the database
    Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);
    timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
    timestampCriteria.add(Restrictions.eq("name", environmentName));
    Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();

    session.close();
    return lastEvironmentTimestampCriteria;
}

From source file:es.sm2.openppm.core.dao.HistorickpiDAO.java

License:Open Source License

/**
 * Max value//w  w  w  .j a  va  2s .c o  m
 * 
 * @param kpi
 * @return 
 */
public Double maxValue(Projectkpi kpi) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    crit.add(Restrictions.eq(Historickpi.PROJECTKPI, kpi)).setProjection(Projections.max(Historickpi.VALUEKPI));

    return (Double) crit.uniqueResult();
}

From source file:es.sm2.openppm.core.dao.ProcurementpaymentsDAO.java

License:Open Source License

/**
 * Find min and max actual dates of projects
 * /*from  w w w  . j av  a  2 s .co  m*/
 * @param projects
 * @return
 */
public RangeDateWrap findMinAndMaxActualDatesByProjects(List<Project> projects) {

    RangeDateWrap range = null;

    if (ValidateUtil.isNotNull(projects)) {

        Criteria crit = getSession().createCriteria(getPersistentClass())
                .add(Restrictions.in(Procurementpayments.PROJECT, projects))
                .setProjection(Projections.projectionList()
                        .add(Projections.min(Procurementpayments.ACTUALDATE),
                                RangeDateWrap.Fields.MINDATE.toString())
                        .add(Projections.max(Procurementpayments.ACTUALDATE),
                                RangeDateWrap.Fields.MAXDATE.toString()))
                .setResultTransformer(Transformers.aliasToBean(RangeDateWrap.class));

        range = (RangeDateWrap) crit.uniqueResult();
    }

    return range;
}

From source file:es.sm2.openppm.core.dao.ProjectActivityDAO.java

License:Open Source License

/**
 * Update Planned Dates of root activity
 * //  ww  w . j  a  va2 s . c  om
 * @param project
 * @param rootActivity
 */
public void updatePlannedDates(Project project, Projectactivity rootActivity) {

    // Num of activities of project
    int numActivities = rowCountEq(Projectactivity.PROJECT, project);

    // Get max and min project activity dates
    Criteria crit = getSession().createCriteria(getPersistentClass())
            .setProjection(Projections.projectionList().add(Projections.min(Projectactivity.PLANINITDATE))
                    .add(Projections.max(Projectactivity.PLANENDDATE)))
            .add(Restrictions.eq(Projectactivity.PROJECT, project));

    // Exclude root activities
    if (numActivities > 1) {
        crit.add(Restrictions.ne(Projectactivity.IDACTIVITY, rootActivity.getIdActivity()));
    }

    Object[] row = (Object[]) crit.uniqueResult();

    // Init calculated plan dates
    Date calculatedPlanStartDate = null;
    Date calculatedPlanFinishDate = null;

    // If there is result set root activity
    if (row != null && row.length > 0) {

        Date planInitDate = (Date) row[0];
        Date planEndDate = (Date) row[1];

        rootActivity.setPlanInitDate(planInitDate);
        rootActivity.setPlanEndDate(planEndDate);
        rootActivity = makePersistent(rootActivity);

        // Set calculated plan dates 
        calculatedPlanStartDate = planInitDate == null ? project.getPlannedInitDate() : planInitDate;
        calculatedPlanFinishDate = planEndDate == null ? project.getPlannedFinishDate() : planEndDate;
    } else {

        // Set calculated plan dates 
        calculatedPlanStartDate = project.getPlannedInitDate();
        calculatedPlanFinishDate = project.getPlannedFinishDate();
    }

    // Update calculated planning dates
    Query query = getSession().createQuery("update Project p "
            + " set p.calculatedPlanStartDate = :calculatedPlanStartDate,"
            + " p.calculatedPlanFinishDate = :calculatedPlanFinishDate" + " where p.idProject = :idProject");
    query.setInteger("idProject", project.getIdProject());
    query.setDate("calculatedPlanStartDate", calculatedPlanStartDate);
    query.setDate("calculatedPlanFinishDate", calculatedPlanFinishDate);
    query.executeUpdate();
}

From source file:gov.nih.nci.firebird.test.data.TestDataLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
protected <T extends PersistentObject> T getLastCreatedObject(Class<T> objectClass) {
    DetachedCriteria maxId = DetachedCriteria.forClass(objectClass).setProjection(Projections.max("id"));
    return (T) Iterables
            .getFirst(session.createCriteria(objectClass).add(Property.forName("id").eq(maxId)).list(), null);
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

/**
 * Adds a projection that allows the criteria to retrieve a  maximum property value
 *
 * @param propertyName The name of the property
 * @param alias The alias to use// ww w  .ja v a 2 s.  c o  m
 */
public org.grails.datastore.mapping.query.api.Projections max(String propertyName, String alias) {
    final AggregateProjection proj = Projections.max(calculatePropertyName(propertyName));
    addProjectionToList(proj, alias);
    return this;
}

From source file:interfaces.Alta.java

private int maxIdCliente() {
    Session session;//ww w.j  a va 2  s .  co m
    session = ConexionUtil.getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(Cliente.class);
    criteria.add(Restrictions.isNotNull("idCliente"));
    criteria.setProjection(Projections.projectionList().add(Projections.max("idCliente")));

    if (criteria.list().get(0) != null) {
        return (int) criteria.list().get(0) + 1;
    } else
        return 1;
}

From source file:it.unitn.elisco.dao.CourseDAO.java

private ContextBasics getCurrentContextBasics(Session s, Course course) {

    DetachedCriteria maxId = DetachedCriteria.forClass(Context.class).add(Restrictions.eq("course", course))
            .setProjection(Projections.max("id"));

    Criteria criteria = s.createCriteria(Context.class);
    criteria.add(Property.forName("id").eq(maxId));

    criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id")
            .add(Projections.property("title"), "title").add(Projections.property("subtitle"), "subtitle"))
            .setResultTransformer(Transformers.aliasToBean(ContextBasics.class));

    return (ContextBasics) criteria.uniqueResult();
}