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.Helpers.java

static Queue findQueue(String qName, EntityManager em) {
    try {/* w w  w .j  a  va  2s .  c  o  m*/
        return em.createQuery("SELECT q FROM Queue q WHERE q.name = :name", Queue.class)
                .setParameter("name", qName).getSingleResult();
    } catch (NoResultException ex) {
        return null;
    }
}

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

/**
 * Retrieve the value of a single-valued parameter.
 * /*  w ww  . java  2  s.  co m*/
 * @param key
 * @param defaultValue
 * @param em
 */
static String getParameter(String key, String defaultValue, EntityManager em) {
    try {
        GlobalParameter gp = em
                .createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class)
                .setParameter("key", key).getSingleResult();
        return gp.getValue();
    } catch (NoResultException e) {
        return defaultValue;
    }
}

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

static void checkConfiguration(String nodeName, EntityManager em) {
    // Node// w  ww.j  av  a  2s . c o  m
    long n = em.createQuery("SELECT COUNT(n) FROM Node n WHERE n.name = :l", Long.class)
            .setParameter("l", nodeName).getSingleResult();
    if (n == 0L) {
        throw new JqmInitError(
                "The node does not exist. It must be referenced (CLI option createnode) before it can be used");
    }
    Node nn = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    if (!StringUtils.hasText(nn.getDlRepo()) || !StringUtils.hasText(nn.getRepo())
            || !StringUtils.hasText(nn.getTmpDirectory())) {
        throw new JqmInitError(
                "The node does not have all its paths specified. Check node configuration (or recreate it with the CLI).");
    }

    // Default queue
    long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu where qu.defaultQueue = true")
            .getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "There is no default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }
    if (i > 1L) {
        throw new JqmInitError(
                "There is more than one default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }

    // Deployment parameters
    i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node.name = :localnode",
            Long.class).setParameter("localnode", nodeName).getSingleResult();
    if (i == 0L) {
        jqmlogger.warn(
                "This node is not bound to any queue. Either use the GUI to bind it or use CLI option -u to bind it to the default queue");
    }

    // Roles
    i = em.createQuery("SELECT count(rr) from RRole rr WHERE rr.name = :rr", Long.class)
            .setParameter("rr", "administrator").getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "The 'administrator' role does not exist. It is needed for the APIs. Run CLI option -u to create it.");
    }

    // Mail session
    i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn")
            .setParameter("nn", "mail/default").getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "Mail session named mail/default does not exist but is required for the engine to run"
                        + ". Use CLI option -u to create an empty one or use the admin web GUI to create it.");
    }
}

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

/**
 * Checks if a parameter exists. If it exists, it is updated. If it doesn't, it is created. Only works for parameters which key is
 * unique. Will create a transaction on the given entity manager.
 *///from w w w  .j av a 2s. c  om
static void setSingleParam(String key, String value, EntityManager em) {
    try {
        em.getTransaction().begin();
        GlobalParameter prm = em
                .createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class)
                .setParameter("key", key).getSingleResult();
        prm.setValue(value);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        GlobalParameter gp = new GlobalParameter();
        gp.setKey(key);
        gp.setValue(value);
        em.persist(gp);
        em.getTransaction().commit();
    }
}

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

/**
 * Creates or updates a node.<br>//from  w w  w.  j  av a2 s  . co m
 * This method makes the assumption metadata is valid. e.g. there MUST be a single default queue.<br>
 * Call {@link #updateConfiguration(EntityManager)} before to be sure if necessary.
 * 
 * @param nodeName
 *            name of the node that should be created or updated (if incompletely defined only)
 * @param em
 *            an EntityManager on which a transaction will be opened.
 */
static void updateNodeConfiguration(String nodeName, EntityManager em) {
    // Node
    Node n = null;
    try {
        n = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
                .getSingleResult();
    } catch (NoResultException e) {
        jqmlogger.info("Node " + nodeName
                + " does not exist in the configuration and will be created with default values");
        em.getTransaction().begin();

        n = new Node();
        n.setDlRepo(System.getProperty("user.dir") + "/outputfiles/");
        n.setName(nodeName);
        n.setPort(0);
        n.setRepo(System.getProperty("user.dir") + "/jobs/");
        n.setTmpDirectory(System.getProperty("user.dir") + "/tmp/");
        n.setRootLogLevel("INFO");
        em.persist(n);
        em.getTransaction().commit();
    }

    // Deployment parameters
    DeploymentParameter dp = null;
    long i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node = :localnode")
            .setParameter("localnode", n).getSingleResult();
    if (i == 0) {
        jqmlogger.info(
                "As this node is not bound to any queue, it will be set to poll from the default queue with default parameters");
        Queue q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                .getSingleResult();
        em.getTransaction().begin();
        dp = new DeploymentParameter();
        dp.setNbThread(5);
        dp.setNode(n);
        dp.setPollingInterval(1000);
        dp.setQueue(q);
        em.persist(dp);

        em.getTransaction().commit();
    }
}

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

static RRole createRoleIfMissing(EntityManager em, String roleName, String description, String... permissions) {
    try {// w ww.j  a  va  2s  . c  o m
        return em.createQuery("SELECT rr from RRole rr WHERE rr.name = :r", RRole.class)
                .setParameter("r", roleName).getSingleResult();
    } catch (NoResultException e) {
        RRole r = new RRole();
        r.setName(roleName);
        r.setDescription(description);
        em.persist(r);

        for (String s : permissions) {
            RPermission p = new RPermission();
            p.setName(s);
            p.setRole(r);
            em.persist(p);
            r.getPermissions().add(p);
        }
        return r;
    }
}

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

static RUser createUserIfMissing(EntityManager em, String login, String description, RRole... roles) {
    RUser res = null;/*from ww w  .ja  va  2  s.  c o  m*/
    try {
        res = em.createQuery("SELECT r from RUser r WHERE r.login = :l", RUser.class).setParameter("l", login)
                .getSingleResult();
    } catch (NoResultException e) {
        res = new RUser();
        res.setFreeText(description);
        res.setLogin(login);
        res.setPassword(String.valueOf((new SecureRandom()).nextInt()));
        encodePassword(res);
        em.persist(res);
    }
    res.setLocked(false);
    for (RRole r : res.getRoles()) {
        r.getUsers().remove(res);
    }
    res.getRoles().clear();
    for (RRole r : roles) {
        res.getRoles().add(r);
        r.getUsers().add(res);
    }

    return res;
}

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

static void dumpParameters(EntityManager em, Node n) {
    String terse = getParameter("disableVerboseStartup", "false", em);
    if ("false".equals(terse)) {
        jqmlogger.info("Global cluster parameters are as follow:");
        List<GlobalParameter> prms = em.createQuery("SELECT gp FROM GlobalParameter gp", GlobalParameter.class)
                .getResultList();//  w ww .  j a v a  2s. c o  m
        for (GlobalParameter prm : prms) {
            jqmlogger.info(String.format("\t%1$s = %2$s", prm.getKey(), prm.getValue()));
        }

        jqmlogger.info("Node parameters are as follow:");
        jqmlogger.info("\tfile produced storage directory: " + n.getDlRepo());
        jqmlogger.info("\tHTTP listening interface: " + n.getDns());
        jqmlogger.info("\tlooks for payloads inside: " + n.getRepo());
        jqmlogger.info("\tlog level: " + n.getRootLogLevel());
        jqmlogger.info("\ttemp files will be created inside: " + n.getTmpDirectory());
        jqmlogger.info("\tJMX registry port: " + n.getJmxRegistryPort());
        jqmlogger.info("\tJMX server port: " + n.getJmxServerPort());
        jqmlogger.info("\tHTTP listening port: " + n.getPort());
        jqmlogger.info("\tAPI admin enabled: " + n.getLoadApiAdmin());
        jqmlogger.info("\tAPI client enabled: " + n.getLoadApiClient());
        jqmlogger.info("\tAPI simple enabled: " + n.getLoapApiSimple());

        jqmlogger.info("Node polling parameters are as follow:");
        List<DeploymentParameter> dps = em
                .createQuery("SELECT dp FROM DeploymentParameter dp WHERE dp.node.id = :n",
                        DeploymentParameter.class)
                .setParameter("n", n.getId()).getResultList();

        // Pollers
        for (DeploymentParameter dp : dps) {
            jqmlogger.info("\t" + dp.getQueue().getName() + " - every " + dp.getPollingInterval()
                    + "ms - maximum " + dp.getNbThread() + " concurrent threads");
        }
    }
}

From source file:net.maritimecloud.identityregistry.controllers.LogoControllerTest.java

private void assertNumberOfLogos(int expectedLogoCount) {
    EntityManager em = emf.createEntityManager();
    try {/*from w ww. j av  a2s  . c  om*/
        List<Logo> logos = em.createQuery("select l from Logo l", Logo.class).getResultList();
        assertEquals("Number of logos", expectedLogoCount, logos.size());
    } catch (Exception e) {
        em.close();
    }
}

From source file:io.coala.bind.LocalId.java

public Stream<LocalId> find(final EntityManager em, final LocalBinder binder, final String query) {
    return em.createQuery(query, LocalIdDao.class).getResultList().stream().map(dao -> {
        return dao.restore(binder);
    });/*w ww. j  a v  a  2 s  .  c  o m*/
}