Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

In this page you can find the example usage for javax.persistence EntityManager createQuery.

Prototype

public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

Source Link

Document

Create an instance of TypedQuery for executing a Java Persistence query language statement.

Usage

From source file:com.enioka.jqm.tools.JqmEngine.java

private void purgeDeadJobInstances(EntityManager em, Node node) {
    em.getTransaction().begin();/* w  w w. j av  a2s .  co  m*/
    for (JobInstance ji : em
            .createQuery("SELECT ji FROM JobInstance ji WHERE ji.node = :node", JobInstance.class)
            .setParameter("node", node).getResultList()) {
        History h = em.find(History.class, ji.getId());
        if (h == null) {
            h = Helpers.createHistory(ji, em, State.CRASHED, Calendar.getInstance());
            Message m = new Message();
            m.setJi(ji.getId());
            m.setTextMessage(
                    "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash");
            em.persist(m);
        }

        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate();
    }
    em.getTransaction().commit();
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/*from   w  ww .  j av a 2 s  . c  o  m*/
 */
@Override
public List<LoginHistory> getRealLoginHistory(User user, Campaign campaign) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    Date startDate = new Date(Long.parseLong(campaign.getMeta(MetaKey.CAMPAIGN_START_TIME)));
    List<Round> rounds = campaign.getSortedRoundsAsList();
    Date endDate = rounds.get(rounds.size() - 1).getEndDate();
    TypedQuery<LoginHistory> q = em.createQuery(
            "select lh from LoginHistory lh where lh.user = :user and lh.loginDate between :start and :end",
            LoginHistory.class);
    q.setParameter("user", user);
    q.setParameter("start", startDate, TemporalType.TIMESTAMP);
    q.setParameter("end", endDate, TemporalType.TIMESTAMP);
    return q.getResultList();
}

From source file:io.coala.enterprise.Fact.java

/**
 * Semi-{@link Transactional} persistence short-hand utility method
 * /*w w w .j av a 2 s . c  o m*/
 * @param em the {@link EntityManager} to use for persistence calls
 * @param binder the {@link LocalBinder} to use for restoring results
 * @param query the JPQL query, e.g. {@code "SELECT f FROM "}
 * @return a {@link Stream} of all matching {@link Fact}s
 */
default Stream<Fact> find(final EntityManager em, final LocalBinder binder, final String query) {
    return em.createQuery(query, FactDao.class).getResultList().stream().map(dao -> dao.restore(binder));
}

From source file:com.enioka.jqm.tools.JqmEngine.java

synchronized void syncPollers(EntityManager em, Node node) {
    if (node.getEnabled()) {
        List<DeploymentParameter> dps = em
                .createQuery("SELECT dp FROM DeploymentParameter dp WHERE dp.node.id = :n",
                        DeploymentParameter.class)
                .setParameter("n", node.getId()).getResultList();

        QueuePoller p = null;/*from   w  w  w .ja va  2s.c  o m*/
        for (DeploymentParameter i : dps) {
            if (pollers.containsKey(i.getId())) {
                p = pollers.get(i.getId());
                p.setPollingInterval(i.getPollingInterval());

                if (i.getEnabled()) {
                    p.setMaxThreads(i.getNbThread());
                } else {
                    p.setMaxThreads(0);
                }
            } else {
                p = new QueuePoller(this, i.getQueue(), (i.getEnabled() ? i.getNbThread() : 0),
                        i.getPollingInterval());
                pollers.put(i.getId(), p);
                Thread t = new Thread(p);
                t.start();
            }
        }

        // Remove deleted pollers
        for (int dp : this.pollers.keySet().toArray(new Integer[0])) {
            boolean found = false;
            for (DeploymentParameter ndp : dps) {
                if (ndp.getId().equals(dp)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                QueuePoller qp = this.pollers.get(dp);
                qp.stop();
                this.pollers.remove(dp);
            }
        }
    } else {
        // Pause all pollers
        for (QueuePoller qp : this.pollers.values()) {
            qp.setMaxThreads(0);
        }
    }
}

From source file:org.noorganization.instalist.server.api.UnitResource.java

/**
 * Get a list of units./*from ww w  .  j  a  v a2s . co m*/
 * @param _groupId The id of the group containing the requested units.
 * @param _changedSince Requests only the elements that changed since the given date. ISO
 *                     8601 time e.g. 2016-01-19T11:54:07+01:00
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getUnits(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    List<Unit> resultUnits;
    List<DeletedObject> resultDeletedUnits;

    if (changedSince == null) {
        resultUnits = new ArrayList<Unit>(group.getUnits());
        TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery(
                "select do from " + "DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedUnitsQuery.setParameter("group", group);
        deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT);
        resultDeletedUnits = deletedUnitsQuery.getResultList();
    } else {
        TypedQuery<Unit> unitsQuery = manager.createQuery(
                "select u from Unit u where " + "u.group = :group and u.updated > :updated", Unit.class);
        unitsQuery.setParameter("group", group);
        unitsQuery.setParameter("updated", changedSince);
        resultUnits = unitsQuery.getResultList();

        TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery("select do from "
                + "DeletedObject do where do.group = :group and do.type = :type and " + "do.updated > :updated",
                DeletedObject.class);
        deletedUnitsQuery.setParameter("group", group);
        deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT);
        deletedUnitsQuery.setParameter("updated", changedSince);
        resultDeletedUnits = deletedUnitsQuery.getResultList();
    }
    manager.close();

    List<UnitInfo> rtn = new ArrayList<UnitInfo>(resultUnits.size() + resultDeletedUnits.size());
    for (Unit current : resultUnits) {
        UnitInfo info = new UnitInfo().withDeleted(false);
        info.setName(current.getName());
        info.setUUID(current.getUUID());
        info.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(info);
    }
    for (DeletedObject current : resultDeletedUnits) {
        UnitInfo info = new UnitInfo().withDeleted(true);
        info.setUUID(current.getUUID());
        info.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(info);
    }

    return ResponseFactory.generateOK(rtn);
}

From source file:com.enioka.jqm.tools.Loader.java

/**
 * Part of the endOfRun process that needs the database. May be deferred if the database is not available.
 *//*from www.  ja  va2 s  .c  o m*/
void endOfRunDb() {
    EntityManager em = Helpers.getNewEm();

    try {
        // Retrieve the object to update
        job = em.find(JobInstance.class, this.job.getId());

        // Which end time should we use? Default is always use DB time to avoid time lips between servers.
        Date dbTimeTmp = em.createQuery("SELECT current_timestamp() AS A from GlobalParameter", Date.class)
                .getSingleResult();
        Calendar dbTime = Calendar.getInstance();
        dbTime.setTime(dbTimeTmp);
        if (!this.isDelayed) {
            // In case of delayed finalization, use the stored time instead of db time.
            this.endDate = dbTime;
        }

        // Done: put inside history & remove instance from queue.
        em.getTransaction().begin();
        History h = Helpers.createHistory(job, em, this.resultStatus, endDate);
        jqmlogger.trace("An History was just created for job instance " + h.getId());
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (RuntimeException e) {
        endBlockDbFailureAnalysis(e);
    } finally {
        Helpers.closeQuietly(em);
    }
}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine// www . jav a2 s  .  com
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//from   w  ww.  jav  a  2  s .c  o m
 */
@Override
public <T extends BaseEntity> List<T> findByJpaQuery(CrudDTO<T> crudDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        TypedQuery<T> query = em.createQuery(crudDTO.getJpaQuery(), crudDTO.getEntity());
        JpaUtil.bindQueryParams(query, crudDTO.getPosParams());
        return query.getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//from   w w w.  j a  va  2s.  com
 */
@Override
public <T> List<T> findByQueryAndMapConstructor(Class<T> resultClass, String jpaQuery, List<Object> posParams) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        TypedQuery<T> query = em.createQuery(jpaQuery, resultClass);
        JpaUtil.bindQueryParams(query, posParams);
        return query.getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from  ww  w.  jav a  2s  . c om*/
 */
@Override
public <T extends BaseEntity> List<T> findPaginatedRecordsByJpaQuery(CrudDTO<T> crudDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        TypedQuery<T> typedQuery = em.createQuery(crudDTO.getJpaQuery(), crudDTO.getEntity());
        JpaUtil.bindQueryParams(typedQuery, crudDTO.getPosParams());
        return typedQuery.setFirstResult(crudDTO.getStartPos()).setMaxResults(crudDTO.getMaxResult())
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}