Example usage for javax.persistence EntityManagerFactory createEntityManager

List of usage examples for javax.persistence EntityManagerFactory createEntityManager

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory createEntityManager.

Prototype

public EntityManager createEntityManager();

Source Link

Document

Create a new application-managed EntityManager.

Usage

From source file:org.rhq.server.metrics.migrator.DataSourceTest.java

public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();//from   ww  w .  j  a v a  2s.com
    Logger.getRootLogger().setLevel(Level.INFO);
    Logger.getLogger("org.rhq").setLevel(Level.DEBUG);
    EntityManagerFactory entityManagerFactory = null;
    EntityManager entityManager = null;
    ExistingDataBulkExportSource source = null;
    try {
        entityManagerFactory = createEntityManager();
        entityManager = entityManagerFactory.createEntityManager();
        source = new ExistingPostgresDataBulkExportSource(entityManager,
                "SELECT  schedule_id, time_stamp, value, minvalue, maxvalue FROM RHQ_MEASUREMENT_DATA_NUM_1D");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        source.initialize();
        int rowIndex = 0;
        int maxResults = 30000;
        for (;;) {
            List<Object[]> existingData = source.getData(rowIndex, maxResults);
            if (existingData.size() < maxResults) {
                break;
            } else {
                rowIndex += maxResults;
            }
        }
        stopWatch.stop();
        System.out.println("Execution: " + stopWatch);
    } finally {
        if (source != null) {
            source.close();
        }
        if (entityManager != null) {
            entityManager.close();
        }
        if (entityManagerFactory != null) {
            entityManagerFactory.close();
        }
    }
}

From source file:Department.java

public static void main(String[] a) throws Exception {
        JPAUtil util = new JPAUtil();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
        EntityManager em = emf.createEntityManager();
        ProfessorService service = new ProfessorService(em);

        em.getTransaction().begin();/*w  w  w. ja  v  a  2 s  . c o  m*/

        service.findWithAlias();

        util.checkData("select * from EMP");

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

From source file:Department.java

public static void main(String[] a) throws Exception {
        JPAUtil util = new JPAUtil();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
        EntityManager em = emf.createEntityManager();
        ProfessorService service = new ProfessorService(em);

        em.getTransaction().begin();//from www. j ava  2  s  .co  m

        service.init(3);
        service.next();
        service.previous();

        for (Object o : service.getCurrentResults()) {
            System.out.print(o);
        }

        System.out.println("Page " + (service.getCurrentPage() + 1) + " of " + service.getMaxPages());

        if (service.getCurrentPage() == 0) {
            System.out.print("Previous disabled ");
        }

        if (service.getCurrentPage() + 1 == service.getMaxPages()) {
            System.out.print("Next disabled ");
        }

        util.checkData("select * from Professor");
        util.checkData("select * from Department");

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

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;/*from   www .  ja  v  a  2s  .  com*/
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}

From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public static void main(String[] argv) throws Exception {
    if (argv.length != 2) {
        System.err.println("Usage: Bootstrap <jpa.properties> <output file>");
        System.exit(1);//from w  w  w.ja  va  2  s  .  c  o  m
    }
    Properties properties = new Properties();
    try (InputStream is = new FileInputStream(new File(argv[0]))) {
        properties.load(is);
    }

    EntityManagerFactory emf = Persistence.createEntityManagerFactory(WellKnownObject.CORE, properties);
    EntityManager em = emf.createEntityManager();
    Bootstrap bootstrap = new Bootstrap(em);
    bootstrap.clear();
    em.getTransaction().begin();
    bootstrap.bootstrap();
    em.getTransaction().commit();
    em.clear();
    bootstrap.serialize(argv[1]);
}

From source file:com.medicaid.mmis.util.DataLoader.java

/**
 * The main function, imports the files given as arguments.
 * //  w  w w  . j  av  a 2  s. com
 * @param args the file names
 * @throws IOException for read/write errors
 * @throws PortalServiceException for any other errors
 */
public static void main(String[] args) throws IOException, PortalServiceException {
    if (args.length != 2) {
        System.out.println("2 file path arguments are required.");
        return;
    }

    PropertyConfigurator.configure("log4j.properties");
    logger = Logger.getLogger(DataLoader.class);

    LookupServiceBean lookupBean = new LookupServiceBean();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load");
    EntityManager em = emf.createEntityManager();
    lookupBean.setEm(em);
    DataLoader loader = new DataLoader();
    loader.setLookup(lookupBean);

    SequenceGeneratorBean sequence = new SequenceGeneratorBean();
    sequence.setEm(em);

    ProviderEnrollmentServiceBean enrollmentBean = new ProviderEnrollmentServiceBean();
    enrollmentBean.setEm(em);
    enrollmentBean.setSequence(sequence);
    enrollmentBean.setLookupService(lookupBean);

    loader.setEnrollmentService(enrollmentBean);

    long processId = sequence.getNextValue("PROCESS_ID");
    System.out.println("Started process id " + processId);

    BufferedReader br = null;
    PrintWriter accepted = null;
    PrintWriter rejected = null;
    try {
        System.out.println("Processing file 1...");
        File success = new File("accepted_1_" + processId + ".txt");
        File failure = new File("rejected_1_" + processId + ".txt");
        success.createNewFile();
        failure.createNewFile();
        accepted = new PrintWriter(success);
        rejected = new PrintWriter(failure);
        br = new BufferedReader(new FileReader(args[0]));
        String line = null;
        int total = 0;
        int errors = 0;
        while ((line = br.readLine()) != null) {
            total++;
            try {
                em.getTransaction().begin();
                loader.readProviderFile(new ByteArrayInputStream(line.getBytes()));
                em.getTransaction().commit();
                accepted.println(line);
                logger.info("Commit row " + total);
            } catch (PortalServiceException e) {
                rejected.println(line);
                em.getTransaction().rollback();
                errors++;
                logger.error("Rollback row " + total + " :" + e.getMessage());
            }
        }

        accepted.flush();
        accepted.close();
        rejected.flush();
        rejected.close();
        br.close();
        System.out.println("Total records read: " + total);
        System.out.println("Total rejected: " + errors);

        System.out.println("Processing file 2...");
        success = new File("accepted_2_" + processId + ".txt");
        failure = new File("rejected_2_" + processId + ".txt");
        success.createNewFile();
        failure.createNewFile();
        accepted = new PrintWriter(success);
        rejected = new PrintWriter(failure);
        br = new BufferedReader(new FileReader(args[1]));
        line = null;
        total = 0;
        errors = 0;
        while ((line = br.readLine()) != null) {
            total++;
            try {
                em.getTransaction().begin();
                Map<String, OwnershipInformation> owners = loader
                        .readWS000EXT2OWNBEN(new ByteArrayInputStream(line.getBytes()));
                for (Map.Entry<String, OwnershipInformation> entry : owners.entrySet()) {
                    enrollmentBean.addBeneficialOwners(entry.getKey(), entry.getValue());
                }
                em.getTransaction().commit();
                accepted.println(line);
                logger.info("Commit row " + total);
            } catch (PortalServiceException e) {
                rejected.println(line);
                em.getTransaction().rollback();
                errors++;
                logger.error("Rollback row " + total + " :" + e.getMessage());
            }
        }
        accepted.flush();
        rejected.flush();
        System.out.println("Total records read: " + total);
        System.out.println("Total rejected: " + errors);

    } finally {
        if (br != null) {
            br.close();
        }
        if (accepted != null) {
            accepted.close();
        }
        if (rejected != null) {
            rejected.close();
        }
    }
}

From source file:ro.allevo.fintpws.security.RolesUtils.java

public static boolean hasReadAuthorityOnQueue(QueueEntity queueEntity) {
    EntityManagerFactory configEntityManagerFactory = Persistence.createEntityManagerFactory("fintpCFG");
    EntityManager entityManagerConfig = configEntityManagerFactory.createEntityManager();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserEntity loggedUser = (UserEntity) authentication.getPrincipal();
    Query query = entityManagerConfig
            .createQuery("SELECT ur.roleid FROM UserRoleEntity ur, QueuesRoleMapEntity qr "
                    + "WHERE ur.roleid = qr.roleid " + "AND ur.userid=:userid " + "AND qr.queueid=:queueid");
    query.setParameter("userid", loggedUser.getUserid());
    query.setParameter("queueid", queueEntity.getGuid());
    List roles = query.getResultList();
    if (roles.isEmpty()) {
        return false;
    }//from   w  w w  .j  a  v  a2 s .  c  o  m
    return true;
}

From source file:ro.allevo.fintpws.security.RolesUtils.java

public static boolean hasWriteAuthorityOnQueue(QueueEntity queueEntity) {
    EntityManagerFactory configEntityManagerFactory = Persistence.createEntityManagerFactory("fintpCFG");
    EntityManager entityManagerConfig = configEntityManagerFactory.createEntityManager();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserEntity loggedUser = (UserEntity) authentication.getPrincipal();
    Query query = entityManagerConfig.createQuery(
            "SELECT ur.roleid FROM UserRoleEntity ur, QueuesRoleMapEntity qr " + "WHERE ur.roleid = qr.roleid "
                    + "AND ur.userid=:userid " + "AND qr.queueid=:queueid " + "AND qr.actiontype = 'RW'");
    query.setParameter("userid", loggedUser.getUserid());
    query.setParameter("queueid", queueEntity.getGuid());
    List roles = query.getResultList();
    if (roles.isEmpty()) {
        return false;
    }//  www.  j  ava  2s .  c o  m
    return true;
}

From source file:GestoreAccountLocale.GestoreAccountLocale.java

private static void memorizzaAccount(Account account) {
    EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("ClientMDBPU");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();/*from w ww.j a  v a  2s .c  o  m*/
    try {
        em.persist(account);
        em.getTransaction().commit();
    } catch (Exception e) {
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}

From source file:org.easy.test.criteria.DbHelper.java

public static int initDb(String connectionUrl, String... dataFiles) {

    Preconditions.checkNotNull(connectionUrl);
    Preconditions.checkNotNull(dataFiles);

    Preconditions.checkArgument(dataFiles.length > 0);

    Connection conn = null;//from  www.  j a  v  a2s  .c  o  m
    int errorCount = 0;
    try {
        Class.forName(JDBC_DRIVER_CLASS);
        conn = DriverManager.getConnection(connectionUrl);
        Preconditions.checkNotNull(conn, "DB Connection is null");

        EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        em = factory.createEntityManager();

        for (String fileName : dataFiles) {
            if (!myDataFiles.contains(fileName)) {
                InputStream fileInputStream = DbHelper.class.getClassLoader().getResourceAsStream(fileName);

                Preconditions.checkNotNull(fileInputStream, "Unable to find " + fileName);
                errorCount += org.apache.derby.tools.ij.runScript(conn, fileInputStream, "UTF-8", System.out,
                        "UTF-8");
                myDataFiles.add(fileName);
                log.debug("Processed " + dataFiles);
            } else {
                log.debug("Skiped " + dataFiles);
            }
        }

        populated = true;

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        errorCount++;
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
        errorCount++;
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
        errorCount++;
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            log.warn(e);
            errorCount++;
        }
    }

    return errorCount;
}