Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

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

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:nl.b3p.kaartenbalie.service.servlet.GeneralServlet.java

public static User checkLogin(HttpServletRequest request, String pcode) throws Exception {
    User user = null;/*from w  ww.  j  a va2  s  .  com*/
    Object identity = null;
    EntityTransaction tx = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.INIT_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.INIT_EM);
        tx = em.getTransaction();
        tx.begin();

        user = checkLogin(request, pcode, em);

        tx.commit();
    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.INIT_EM);
    }

    return user;
}

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.
 *//*  ww  w  .  j  a v a 2 s  .c  o m*/
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:entity.files.SYSFilesTools.java

public static List<SYSFiles> putFiles(File[] files, Object attachable) {
    ArrayList<SYSFiles> successful = new ArrayList<SYSFiles>(files.length);
    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {/*from   www.  j a va 2 s  .com*/
            em.getTransaction().begin();

            for (File file : files) {
                if (file.isFile()) { // prevents exceptions if somebody has the bright idea to include directories.
                    SYSFiles sysfile = putFile(em, ftp, file);
                    if (attachable != null) {
                        if (attachable instanceof NReport) {
                            SYSNR2FILE link = em.merge(new SYSNR2FILE(sysfile, (NReport) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNrAssignCollection().add(link);
                            ((NReport) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Prescription) {
                            SYSPRE2FILE link = em.merge(new SYSPRE2FILE(sysfile, (Prescription) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getPreAssignCollection().add(link);
                            ((Prescription) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResInfo) {
                            SYSINF2FILE link = em.merge(new SYSINF2FILE(sysfile, (ResInfo) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getBwiAssignCollection().add(link);
                            ((ResInfo) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResValue) {
                            SYSVAL2FILE link = em.merge(new SYSVAL2FILE(sysfile, (ResValue) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getValAssignCollection().add(link);
                            ((ResValue) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof NursingProcess) {
                            SYSNP2FILE link = em.merge(new SYSNP2FILE(sysfile, (NursingProcess) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNpAssignCollection().add(link);
                            ((NursingProcess) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Users) {
                            User2File link = em.merge(new User2File(sysfile, (Users) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getUsersAssignCollection().add(link);
                            ((Users) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Resident) {
                            Resident2File link = em.merge(new Resident2File(sysfile, (Resident) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getResidentAssignCollection().add(link);
                            ((Resident) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qmsplan) {
                            Qmsplan2File link = em.merge(new Qmsplan2File(sysfile, (Qmsplan) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsplanAssignCollection().add(link);
                            ((Qmsplan) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qms) {
                            Qms2File link = em.merge(new Qms2File(sysfile, (Qms) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsAssignCollection().add(link);
                            ((Qms) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrainingAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training2Users) {
                            em.merge(((SYSFilesContainer) attachable).attachFile(sysfile));
                        }
                    }
                    successful.add(sysfile);
                }
                if (successful.size() != files.length) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.nodirectories")));
                }
            }
            em.getTransaction().commit();
        } catch (OptimisticLockException ole) {
            OPDE.warn(ole);
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                OPDE.getMainframe().emptyFrame();
                OPDE.getMainframe().afterLogin();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception ex) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.fatal(ex);
        } finally {
            em.close();
            try {
                ftp.disconnect();
            } catch (Exception e) {
                OPDE.error(e);
            }
        }
    }
    return successful;
}

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

static void closeQuietly(EntityManager em) {
    try {/*from ww w . j  a v  a 2s.c o m*/
        if (em != null) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            em.close();
        }
    } catch (Exception e) {
        // fail silently
    }
}

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

/**
 * Creates or updates metadata common to all nodes: default queue, global parameters, roles...<br>
 * It is idempotent. It also has the effect of making broken metadata viable again.
 *//*from  w  w w . ja va  2 s.  c  om*/
static void updateConfiguration(EntityManager em) {
    em.getTransaction().begin();

    // Default queue
    Queue q = null;
    long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu").getSingleResult();
    if (i == 0L) {
        q = new Queue();
        q.setDefaultQueue(true);
        q.setDescription("default queue");
        q.setTimeToLive(1024);
        q.setName("DEFAULT");
        em.persist(q);

        jqmlogger.info("A default queue was created in the configuration");
    } else {
        try {
            q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                    .getSingleResult();
            jqmlogger.info("Default queue is named " + q.getName());
        } catch (NonUniqueResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.info("Queue " + q.getName()
                    + " was modified to become the default queue as there were mutliple default queue");
        } catch (NoResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.warn("Queue  " + q.getName()
                    + " was modified to become the default queue as there was no default queue");
        }
    }

    // Global parameters
    initSingleParam("mavenRepo", "http://repo1.maven.org/maven2/", em);
    initSingleParam(Constants.GP_DEFAULT_CONNECTION_KEY, Constants.GP_JQM_CONNECTION_ALIAS, em);
    initSingleParam("logFilePerLaunch", "true", em);
    initSingleParam("internalPollingPeriodMs", "60000", em);
    initSingleParam("disableWsApi", "false", em);
    initSingleParam("enableWsApiSsl", "false", em);
    initSingleParam("enableWsApiAuth", "true", em);
    initSingleParam("enableInternalPki", "true", em);

    // Roles
    RRole adminr = createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*");
    createRoleIfMissing(em, "config admin",
            "can read and write all configuration, except security configuration", "node:*", "queue:*",
            "qmapping:*", "jndi:*", "prm:*", "jd:*");
    createRoleIfMissing(em, "config viewer", "can read all configuration except for security configuration",
            "node:read", "queue:read", "qmapping:read", "jndi:read", "prm:read", "jd:read");
    createRoleIfMissing(em, "client",
            "can use the full client API except reading logs, files and altering position", "node:read",
            "queue:read", "job_instance:*", "jd:read");
    createRoleIfMissing(em, "client power user", "can use the full client API", "node:read", "queue:read",
            "job_instance:*", "jd:read", "logs:read", "queue_position:create", "files:read");
    createRoleIfMissing(em, "client read only", "can query job instances and get their files", "queue:read",
            "job_instance:read", "logs:read", "files:read");

    // Users
    createUserIfMissing(em, "root", "all powerful user", adminr);

    // Mail session
    i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn")
            .setParameter("nn", "mail/default").getSingleResult();
    if (i == 0) {
        HashMap<String, String> prms = new HashMap<String, String>();
        prms.put("smtpServerHost", "smtp.gmail.com");

        JndiObjectResource res = new JndiObjectResource();
        res.setAuth(null);
        res.setDescription("default parameters used to send e-mails");
        res.setFactory("com.enioka.jqm.providers.MailSessionFactory");
        res.setName("mail/default");
        res.setType("javax.mail.Session");
        res.setSingleton(true);
        em.persist(res);

        JndiObjectResourceParameter prm = new JndiObjectResourceParameter();
        prm.setKey("smtpServerHost");
        prm.setValue("smtp.gmail.com");
        res.getParameters().add(prm);
        prm.setResource(res);
    }

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

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users./*  w  w  w  .j  a v  a 2  s  .co  m*/
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}

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

private static void ws(String option) {
    if ("enable".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("disableWsApi", "false", em);
        Helpers.setSingleParam("enableWsApiSsl", "false", em);
        Helpers.setSingleParam("enableWsApiAuth", "true", em);
        Helpers.setSingleParam("disableWsApiSimple", "false", em);
        Helpers.setSingleParam("disableWsApiClient", "false", em);
        Helpers.setSingleParam("disableWsApiAdmin", "false", em);
        Helpers.setSingleParam("enableInternalPki", "true", em);

        em.getTransaction().begin();
        em.createQuery(//from  w w  w .  j a  v  a 2 s .c om
                "UPDATE Node n set n.loapApiSimple = true, n.loadApiClient = true, n.loadApiAdmin = true, n.dns=:n")
                .setParameter("n", "0.0.0.0").executeUpdate();
        em.getTransaction().commit();
        em.close();
    } else if ("disable".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        em.getTransaction().begin();
        em.createQuery("UPDATE Node n set n.loadApiClient = false, n.loadApiAdmin = false").executeUpdate();
        em.getTransaction().commit();
        em.close();
    }
    if ("ssl".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableWsApiSsl", "true", em);
        Helpers.setSingleParam("enableWsApiAuth", "true", em);
        em.close();
    }
    if ("nossl".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableWsApiSsl", "false", em);
        em.close();
    }
    if ("internalpki".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableInternalPki", "true", em);
        em.close();
    }
    if ("externalpki".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableInternalPki", "false", em);
        em.close();
    }
}

From source file:com.openmeap.model.ModelTestUtils.java

static public void createModel(EntityManager em) {
    if (em == null) {
        em = createEntityManager();/*from  w ww .j  av  a2  s. co  m*/
    }
    try {
        Map<String, Map<String, ? extends ModelEntity>> modelBeans = (Map<String, Map<String, ? extends ModelEntity>>) ModelTestUtils
                .newModelBeans().getBean("mockModel");

        // we need to set all (except the Device.uuid) pk's to null,
        // so the entity manager doesn't flip out, thinking we've passed it
        // a detached entity for persistence.
        for (Map.Entry<String, Map<String, ? extends ModelEntity>> classes : modelBeans.entrySet())
            for (ModelEntity member : classes.getValue().values())
                if (!(member instanceof ApplicationInstallation))
                    member.setPk(null);

        em.getTransaction().begin();

        for (String className : new String[] { "GlobalSettings", "Application", "ApplicationArchive",
                "ApplicationVersion", "Deployment", "ApplicationInstallation" }) {
            Map<String, ? extends ModelEntity> members = modelBeans.get(className);
            for (ModelEntity member : members.values()) {
                if (className.equals("Application")) {
                    ((Application) member).setDeployments(null);
                }
                em.persist(member);
                em.flush();
            }
        }

        em.getTransaction().commit();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

private static void user(String[] options) {
    if (options.length < 3) {
        throw new IllegalArgumentException(
                "-U option requires one login, one password and at least one role (in this order)");
    }// w ww .jav  a  2s  . c  o  m

    EntityManager em = null;
    try {
        em = Helpers.getNewEm();

        RRole[] roles = new RRole[options.length - 2];
        for (int i = 2; i < options.length; i++) {
            try {
                roles[i - 2] = em.createQuery("SELECT r FROM RRole r WHERE r.name=:l", RRole.class)
                        .setParameter("l", options[i]).getSingleResult();
            } catch (NoResultException ex) {
                throw new IllegalArgumentException("Role " + options[i] + " does not exist");
            }
        }

        em.getTransaction().begin();
        RUser u = Helpers.createUserIfMissing(em, options[0], "created through CLI", roles);
        u.setPassword(options[1]);
        Helpers.encodePassword(u);
        em.getTransaction().commit();
    } finally {
        Helpers.closeQuietly(em);
    }
}

From source file:dao.UsuarioDao.java

public List<Usuario> consultarTodosUsuarios() {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("LoginUsersPU");
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();
    Query q = em.createNamedQuery("Usuario.findAll");
    List<Usuario> todosUsuarios = q.getResultList();
    return todosUsuarios;
}