Example usage for javax.persistence EntityManager flush

List of usage examples for javax.persistence EntityManager flush

Introduction

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

Prototype

public void flush();

Source Link

Document

Synchronize the persistence context to the underlying database.

Usage

From source file:portal.api.impl.PortalJpaController.java

public void deleteAllInstalledVxFs() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w ww  . j a va 2 s  .c o m

    Query q = entityManager.createQuery("DELETE FROM InstalledVxF ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();
}

From source file:portal.api.impl.PortalJpaController.java

public void deleteAllMANOplatforms() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w ww. j a va2s  .  co  m

    Query q = entityManager.createQuery("DELETE FROM MANOplatform");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:portal.api.impl.PortalJpaController.java

public void deleteAllMANOproviders() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from  w  w w.ja  va  2s. co  m*/

    Query q = entityManager.createQuery("DELETE FROM MANOprovider");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java

@Test
@PerfTest(invocations = 10)/*from   w w w.j a  v a  2  s.c  o m*/
public void testCRUDWithBatch() {
    Map<String, String> batchProperty = new HashMap<String, String>(1);
    batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, "5");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    Assert.assertEquals(5, ((Batcher) client).getBatchSize());

    final String originalName = "vivek";

    for (int i = 0; i < 9; i++) {
        PersonCouchDB object = new PersonCouchDB();
        object.setAge(32);
        object.setPersonId(ROW_KEY + i);
        object.setPersonName(originalName);
        em.persist(object);

        if (i >= 5) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNull(result);
        } else if (i > 0 && i % 4 == 0) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNotNull(result);
            Assert.assertEquals(result.getPersonId(), object.getPersonId());
            Assert.assertEquals(result.getAge(), object.getAge());
            Assert.assertEquals(result.getPersonName(), object.getPersonName());
        }
    }
    em.flush();
    em.clear();
    em.close();
    em = null;
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem/*from ww  w.  jav a 2  s. c  om*/
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

/** Checks wether an user, given his username and password, is allowed to use the system.
 *
 * @param username String representing the username.
 * @param password String representing the password.
 *
 * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null).
 */// www.j a v a  2s  .  c om
@Override
public Principal authenticate(String username, String password) {

    String encpw = null;
    try {
        encpw = KBCrypter.encryptText(password);
    } catch (Exception ex) {
        log.error("error encrypting password: ", ex);
    }
    Object identity = null;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em
                    .createQuery("from User u where " + "u.timeout > :nu "
                            + "and lower(u.username) = lower(:username) " + "and u.password = :password")
                    .setParameter("nu", new Date()).setParameter("username", username)
                    .setParameter("password", encpw).getSingleResult();
            // if we get a result, this means successful login
            // set lastloginstatus to null to indicate success
            user.setLastLoginStatus(null);

            return user;
        } catch (NoResultException nre) {
            log.debug("No results using encrypted password");
        }
        // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW
        User wrong_password_user = (User) em
                .createQuery(
                        "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ")
                .setParameter("nu", new Date()).setParameter("username", username).getSingleResult();
        wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED);
        em.flush();
        log.warn("Login failure for username " + username);
    } catch (Exception e) {
        log.error("Exception checking user credentails", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }

    return null;
}

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

/**
 * Checks the login session or credentials
 *
 * @param request The incoming request//from  ww w  .  j  a va2s. c  o  m
 * @param em The entityManager
 * @param pcode
 * @return The user Principal
 * @throws AccessDeniedException if the user can not be authenticated
 */
protected User checkLogin(HttpServletRequest request, EntityManager em, String pcode)
        throws AccessDeniedException {
    User user = (User) request.getUserPrincipal();

    if (user != null) {
        log.info("Cookie accepted for login, username: " + user.getName());

        return user;
    }

    // Try preemptive basic login
    // attempt to dig out authentication info only if the user has not yet been authenticated
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null) {
        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        String encpw = null;
        try {
            encpw = KBCrypter.encryptText(password);
        } catch (Exception ex) {
            log.error("error encrypting password: ", ex);
        }
        try {
            user = (User) em
                    .createQuery("from User " + "where lower(username) = lower(:username) "
                            + "and password = :password ")
                    .setParameter("username", username).setParameter("password", encpw).getSingleResult();
            em.flush();
        } catch (NonUniqueResultException nue) {
            log.error(
                    "More than one person found for these credentials (to be fixed in database), trying next method.");
            user = null;
        } catch (NoResultException nre) {
            user = null;
            log.debug("No results using encrypted password, trying next method");
        }

        // extra check voor oude non-encrypted passwords
        if (user == null) {
            try {
                user = (User) em
                        .createQuery("from User " + "where lower(username) = lower(:username) "
                                + "and password = :password ")
                        .setParameter("username", username).setParameter("password", encpw).getSingleResult();

                // Volgende keer dus wel encrypted
                user.setPassword(encpw);
                em.merge(user);
                em.flush();

                if (!user.checkRole("beheerder")) {
                    throw new NoResultException("Not a admin");
                }
                log.debug("Cleartext password now encrypted!");
            } catch (NonUniqueResultException nue) {
                log.error(
                        "More than one person found for these (cleartext) credentials (to be fixed in database), trying next method.");
                user = null;
            } catch (NoResultException nre) {
                log.debug("No results using cleartext password, trying next method.");
            }
        }
    }
    if (user != null && user.checkRole("beheerder")) {
        log.info("Basic authentication accepted for login, username: " + user.getName());
        return user;
    } else {
        throw new AccessDeniedException(
                "Authorisation required for this service! No credentials found in Personal url, Authentication header or Cookie, Giving up! ");
    }
}

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

protected static User checkLoginPreemptiveAuthentication(HttpServletRequest request, EntityManager em) {

    /* Zoek gebruiker via Preemptive authentication */
    User user = null;/*from www .  java 2s . c  o  m*/
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null) {
        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        String encpw = null;
        try {
            encpw = KBCrypter.encryptText(password);
        } catch (Exception ex) {
            log.error("Fout tijdens encrypten wachtwoord: ", ex);
        }
        try {
            user = (User) em
                    .createQuery("from User u where " + "lower(u.username) = lower(:username) "
                            + "and u.password = :password")
                    .setParameter("username", username).setParameter("password", encpw).getSingleResult();
        } catch (NonUniqueResultException nue) {
            log.error("Meerdere gebruikers gevonden via encrypted wachtwoord.");
            user = null;
        } catch (NoResultException nre) {
            log.debug("Geen gebruiker gevonden via encrypted wachtwoord.");
            user = null;
        }

        /* Controleer ingevuld wachtwoord met db gebruiker wachtwoord */
        if (user == null) {
            try {
                user = (User) em.createQuery("from User u where " + "lower(u.username) = lower(:username) ")
                        .setParameter("username", username).getSingleResult();
            } catch (NoResultException nre) {
                log.debug("Gebruiker " + username + " niet gevonden in db.");
                user = null;
            }

            if (user != null && !user.getPassword().equals(encpw)) {
                user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW);

                em.merge(user);
                em.flush();

                log.debug("Wachtwoord voor gebruiker " + username + " verkeerd...");
                user = null;
            }
        }
    }

    if (user != null) {
        log.debug("Basic authentication gelukt voor gebruiker: " + user.getName());
        user.setLastLoginStatus(null);
    }
    return user;
}

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

protected static User checkLoginLDAP(HttpServletRequest request, EntityManager em) {
    /* Probeer LDAP bind, ldapUseLdap is param in web.xml */
    User user = null;//from  w ww. jav a 2s .  c om
    String authorizationHeader = request.getHeader("Authorization");
    if (MyEMFDatabase.getLdapUseLdap() != null && MyEMFDatabase.getLdapUseLdap()
            && authorizationHeader != null) {

        LDAPUtil ldapUtil = new LDAPUtil();

        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        // check if user is in ldap
        boolean inLdap = ldapUtil.userInLdap(MyEMFDatabase.getLdapHost(), MyEMFDatabase.getLdapPort(), username,
                password, MyEMFDatabase.getLdapUserSuffix());

        // check if username already in kaartenbalie database
        user = ldapUtil.getUserByName(em, username);

        /* case 1: wel in ldap, niet in db, return nieuw gebruiker */
        if (inLdap && user == null) {
            user = new User();
            user.setUsername(username);
            user.setPassword(User.createCode());

            List<Roles> gebruikerRol = ldapUtil.getGebruikerRol(em);
            user.getRoles().retainAll(gebruikerRol);
            user.getRoles().addAll(gebruikerRol);

            Set ips = new HashSet(1);
            ips.add("0.0.0.0");
            user.setIps(ips);

            String personalUrl = User.createCode();
            user.setPersonalURL(personalUrl);

            if (MyEMFDatabase.getLdapDefaultGroup() != null && !MyEMFDatabase.getLdapDefaultGroup().isEmpty()) {
                Organization org = ldapUtil.getLDAPOrg(em, MyEMFDatabase.getLdapDefaultGroup());
                user.setMainOrganization(org);
            }

            Date userTimeOut = ldapUtil.getDefaultTimeOut(36);
            user.setTimeout(userTimeOut);

            user.setLastLoginStatus(null);

            em.persist(user);
            em.flush();

            log.debug("Gebruiker " + username + " in Ldap maar nog niet in db.");

            return user;
        }

        /* case 2: wel in ldap, wel in db, return user */
        if (inLdap && user != null) {
            user.setLastLoginStatus(null);
            em.flush();

            log.debug("Gebruiker " + username + " in Ldap en al in db.");

            return user;
        }

        /* case 3: niet in ldap, wel in db, uitroepteken zetten */
        if (!inLdap && user != null) {
            user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW);
            em.flush();

            log.debug("Gebruiker " + username + " niet in Ldap maar wel in db.");

            return null;
        }

        /* case 4: niet in ldap, niet in db, niets doen */
        log.debug("Gebruiker " + username + " niet in Ldap en niet in db.");
    }
    return user;
}

From source file:org.rhq.enterprise.server.alert.AlertDefinitionWithComplexNotificationsTest.java

private void removeNoExceptions(final Object o) {
    try {/*from www .  j a va  2  s.c  o  m*/
        executeInTransaction(false, new TransactionCallback() {
            public void execute() {
                EntityManager em = getEntityManager();
                Object o2 = em.merge(o);

                if (o2 instanceof Resource) {
                    ResourceTreeHelper.deleteResource(em, (Resource) o2);
                } else {
                    em.remove(o2);
                }

                em.flush();
            }
        });
    } catch (Exception e) {
        LOG.error("Failed to DELETE an object from database: " + o, e);
    }
}