Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit using the given properties.

Usage

From source file:org.apache.roller.planet.business.jpa.JPAPersistenceStrategy.java

/**
 * Construct by finding JPA EntityManagerFactory.
 * @throws org.apache.roller.planet.PlanetException on any error
 */// w  ww .j av  a 2s . co m
protected JPAPersistenceStrategy() throws PlanetException {

    String jpaConfigurationType = PlanetConfig.getProperty("jpa.configurationType");
    if ("jndi".equals(jpaConfigurationType)) {
        // Lookup EMF via JNDI: added for Geronimo
        String emfJndiName = "java:comp/env/" + PlanetConfig.getProperty("jpa.emf.jndi.name");
        try {
            emf = (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
        } catch (NamingException e) {
            throw new PlanetException("Could not look up EntityManagerFactory in jndi at " + emfJndiName, e);
        }
    } else {
        DatabaseProvider dbProvider = PlanetStartup.getDatabaseProvider();

        // Add all JPA, OpenJPA, HibernateJPA, etc. properties found
        Properties emfProps = new Properties();
        Enumeration keys = PlanetConfig.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            if (key.startsWith("javax.persistence.") || key.startsWith("openjpa.")
                    || key.startsWith("hibernate.")) {
                String value = PlanetConfig.getProperty(key);
                logger.info(key + ": " + value);
                emfProps.setProperty(key, value);
            }
        }

        if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {
            emfProps.setProperty("javax.persistence.nonJtaDataSource", dbProvider.getJndiName());

        } else {
            emfProps.setProperty("javax.persistence.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("javax.persistence.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("javax.persistence.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("javax.persistence.jdbc.password", dbProvider.getJdbcPassword());
        }

        try {
            this.emf = Persistence.createEntityManagerFactory("PlanetPU", emfProps);
        } catch (PersistenceException pe) {
            logger.error("ERROR: creating entity manager", pe);
            throw new PlanetException(pe);
        }
    }
}

From source file:org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy.java

/**
 * Construct by finding JPA EntityManagerFactory.
 * @param dbProvider database configuration information for manual configuration.
 * @throws org.apache.roller.weblogger.WebloggerException on any error
 *//*from w w w . jav a 2s .c o m*/
@com.google.inject.Inject
protected JPAPersistenceStrategy(DatabaseProvider dbProvider) throws WebloggerException {
    String jpaConfigurationType = WebloggerConfig.getProperty("jpa.configurationType");
    if ("jndi".equals(jpaConfigurationType)) {
        // Lookup EMF via JNDI: added for Geronimo
        String emfJndiName = "java:comp/env/" + WebloggerConfig.getProperty("jpa.emf.jndi.name");
        try {
            emf = (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
        } catch (NamingException e) {
            throw new WebloggerException("Could not look up EntityManagerFactory in jndi at " + emfJndiName, e);
        }
    } else {

        // Add all JPA, OpenJPA, HibernateJPA, etc. properties found
        Properties emfProps = new Properties();
        Enumeration keys = WebloggerConfig.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            if (key.startsWith("javax.persistence.") || key.startsWith("openjpa.")
                    || key.startsWith("hibernate.")) {
                String value = WebloggerConfig.getProperty(key);
                logger.info(key + ": " + value);
                emfProps.setProperty(key, value);
            }
        }

        if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {
            emfProps.setProperty("javax.persistence.nonJtaDataSource", dbProvider.getJndiName());

        } else {
            emfProps.setProperty("javax.persistence.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("javax.persistence.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("javax.persistence.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("javax.persistence.jdbc.password", dbProvider.getJdbcPassword());
        }

        try {
            this.emf = Persistence.createEntityManagerFactory("RollerPU", emfProps);

        } catch (Throwable pe) {
            logger.error("ERROR: creating entity manager", pe);
            throw new WebloggerException(pe);
        }
    }
}

From source file:org.apache.hadoop.crypto.key.RangerKMSDB.java

private void initDBConnectivity() {
    try {/*from   w  ww . ja v  a 2s  .co  m*/

        DB_PROPERTIES = new HashMap<String, String>();
        DB_PROPERTIES.put(JPA_DB_DIALECT, conf.get(PROPERTY_PREFIX + DB_DIALECT));
        DB_PROPERTIES.put(JPA_DB_DRIVER, conf.get(PROPERTY_PREFIX + DB_DRIVER));
        DB_PROPERTIES.put(JPA_DB_URL, conf.get(PROPERTY_PREFIX + DB_URL));
        DB_PROPERTIES.put(JPA_DB_USER, conf.get(PROPERTY_PREFIX + DB_USER));
        DB_PROPERTIES.put(JPA_DB_PASSWORD, conf.get(PROPERTY_PREFIX + DB_PASSWORD));
        if (getDBFlavor(conf) == DB_FLAVOR_MYSQL) {
            updateDBSSLURL();
        }

        //DB_PROPERTIES.list(System.out);

        /*
        Set keys = DB_PROPERTIES.keySet();
                
           for (Iterator i = keys.iterator(); i.hasNext();) {
           String key = (String) i.next();
           String value = (String) DB_PROPERTIES.get(key);
           System.out.println(key + " = " + value);
           }
        */

        entityManagerFactory = Persistence.createEntityManagerFactory("persistence_ranger_server",
                DB_PROPERTIES);
        daoManager = new DaoManager();
        daoManager.setEntityManagerFactory(entityManagerFactory);
        daoManager.getEntityManager(); // this forces the connection to be made to DB
        logger.info("Connected to DB : " + isDbConnected());
    } catch (Exception excp) {
        excp.printStackTrace();
    }
}

From source file:org.sonar.jpa.session.AbstractDatabaseConnector.java

protected EntityManagerFactory createEntityManagerFactory() {
    // other settings are stored into /META-INF/persistence.xml
    Properties props = getHibernateProperties();
    logHibernateSettings(props);/*from  w w w.  j  a va 2  s  .co m*/
    return Persistence.createEntityManagerFactory("sonar", props);
}

From source file:desktop.olayinka.file.transfer.model.DerbyJDBCHelper.java

private DerbyJDBCHelper() {
    try {//  w  w w . jav  a2 s  .  co  m
        System.out.println(DB_URL);

        //ensure database is created
        String dbUrl = "jdbc:derby:" + DB_FILE.getAbsolutePath() + ";create=true;user=" + DB_USER + ";password="
                + DB_PWD;
        System.out.println(dbUrl);
        Connection mConnection;
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            mConnection = DriverManager.getConnection(dbUrl);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
            return;
        }
        onStart(mConnection);
        onUpgrade(mConnection);
        mConnection.commit();
        mConnection.close();

        //instantiate persistence unit
        EntityManagerFactory managerFactory = null;
        Map<String, String> persistenceMap = new HashMap<String, String>();

        persistenceMap.put("javax.persistence.jdbc.url", DB_URL);
        persistenceMap.put("javax.persistence.jdbc.user", DB_USER);
        persistenceMap.put("javax.persistence.jdbc.password", DB_PWD);

        URL resource = ClassLoader.getSystemResource("");
        File file = new File(String.valueOf(resource));

        managerFactory = Persistence.createEntityManagerFactory("A2PPU", persistenceMap);
        mManager = managerFactory.createEntityManager();

        deviceProvider = new JDBCDeviceProvider(mManager);

    } catch (Exception except) {
        except.printStackTrace();
        System.exit(1);
    }
}

From source file:org.apache.openjpa.conf.TestBadJdbcUrl.java

/**
  * Attempts to connect with given properties and analyze exception for the
 * existence of given target exception and error message strings.
 * /*from ww w  .ja v  a2  s . c om*/
 * @param props
 *            the properties to initialize the persistence unit
 * @param target
 *            the type expected exception to be raised.
 * @param nested
  *            the type expected nested exception. null implies not to look
 *            for any.
 * @param keys
 *            the strings that must occur in the exception message.
 */
private void verifyConnectException(Properties props, Class targetType, Class nestedType, String... keys) {
    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = Persistence.createEntityManagerFactory("test", props);
        em = emf.createEntityManager();
        OpenJPAPersistence.cast(em).getConnection();
        fail("Should have caught a " + targetType.getName());
    } catch (Throwable t) {
        assertException(t, targetType, nestedType);
        assertMessage(t, keys);
    } finally {
        if (em != null)
            em.close();
        if (emf != null)
            emf.close();
    }
}

From source file:org.apache.shindig.social.opensocial.jpa.eclipselink.Bootstrap.java

public void init(String unitName) {

    Map<String, String> properties = Maps.newHashMap();

    // Ensure RESOURCE_LOCAL transactions is used.
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

    // Configure the internal EclipseLink connection pool
    properties.put(JDBC_DRIVER, dbDriver);
    properties.put(JDBC_URL, dbUrl);
    properties.put(JDBC_USER, dbUser);/*  ww w.  j a v  a  2 s .  c om*/
    properties.put(JDBC_PASSWORD, dbPassword);
    properties.put(JDBC_READ_CONNECTIONS_MIN, minRead);
    properties.put(JDBC_WRITE_CONNECTIONS_MIN, minWrite);

    // Configure logging. FINE ensures all SQL is shown
    properties.put(LOGGING_LEVEL, "FINE");
    properties.put(LOGGING_TIMESTAMP, "true");
    properties.put(LOGGING_THREAD, "false");
    properties.put(LOGGING_SESSION, "false");

    // Ensure that no server-platform is configured
    properties.put(TARGET_SERVER, TargetServer.None);

    properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    properties.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql");
    properties.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql");
    properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE,
            PersistenceUnitProperties.DDL_BOTH_GENERATION);

    // properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
    // EnableIntegrityChecker.class.getName());

    LOG.info("Starting connection manager with properties " + properties);

    EntityManagerFactory emFactory = Persistence.createEntityManagerFactory(unitName, properties);
    entityManager = emFactory.createEntityManager();
}

From source file:com.xebialabs.deployit.maven.AbstractDeployitMojo.java

protected void startServer() {
    if (!SERVER_STARTED) {
        getLog().info("STARTING DEPLOYIT SERVER");
        DeployItConfiguration context = new DeployItConfiguration();

        context.setDatabaseType(SetupDatabaseType.HSQLDB);
        context.setDatabaseDriverClass(//from   w  w  w  .j  a  v  a  2 s  .  c o  m
                SetupDatabaseType.getDefaultDatabaseDriverClass(context.getDatabaseType()));
        context.setHibernateDialect(SetupDatabaseType.getHibernateDialect(context.getDatabaseType()));
        context.setDatabaseURL(
                "jdbc:hsqldb:file:" + new File(outputDirectory, "./deployit.hdb").getPath() + ";shutdown=true");
        context.setDatabaseUsername(SetupDatabaseType.getDefaultUsername(context.getDatabaseType()));
        context.setDatabasePassword("");
        File deployitRepoDir = new File(outputDirectory, "deployit.repo");
        deployitRepoDir.mkdir();
        context.setApplicationRepositoryPath(deployitRepoDir.getPath());
        context.setHttpPort(getPort());
        context.setApplicationToDeployPath("importablePackages");
        context.setMinThreads(10);
        context.setMaxThreads(50);
        context.setSecured(false);
        context.setHttpServerName("localhost");

        context.save();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ad-repository",
                context.getCreationalJPAProperties());
        emf.close();

        final Server s = new Server(context, ReleaseInfo.getReleaseInfo());
        s.start();
        getLog().info("STARTED DEPLOYIT SERVER");
        SERVER_STARTED = true;
    }
}

From source file:sf.net.experimaestro.scheduler.Scheduler.java

/**
 * Initialise the task manager/*from  ww w.ja  v a 2 s  . co  m*/
 *
 * @param baseDirectory The directory where the XPM database will be stored
 */
public Scheduler(File baseDirectory) throws IOException {
    if (INSTANCE != null) {
        throw new XPMRuntimeException("Only one scheduler instance should be created");
    }

    INSTANCE = this;

    // Initialise the database
    LOGGER.info("Initialising database in directory %s", baseDirectory);
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.connection.url",
            format("jdbc:hsqldb:file:%s/xpm;shutdown=true;hsqldb.tx=mvcc", baseDirectory));
    properties.put("hibernate.connection.username", "");
    properties.put("hibernate.connection.password", "");

    /* From HSQLDB http://hsqldb.org/doc/guide/sessions-chapt.html#snc_tx_mvcc
            
    In MVCC mode
    - locks are at the row level
    - no shared (i.e. read) locks
    - in TRANSACTION_READ_COMMITTED mode: if a session wants to read/write a row that was written by another one => wait
    - in TRANSACTION_REPEATABLE_READ: if a session wants to write the same row than another one => exception
    */
    properties.put("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

    ArrayList<Class<?>> loadedClasses = new ArrayList<>();
    ServiceLoader<PersistentClassesAdder> services = ServiceLoader.load(PersistentClassesAdder.class);
    for (PersistentClassesAdder service : services) {
        service.add(loadedClasses);
    }

    properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES, loadedClasses);

    entityManagerFactory = Persistence.createEntityManagerFactory("net.bpiwowar.experimaestro", properties);

    // Add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(Scheduler.this::close));

    // Create reused criteria queries
    CriteriaBuilder builder = entityManagerFactory.getCriteriaBuilder();
    readyJobsQuery = builder.createQuery(Long.TYPE);
    Root<Job> root = readyJobsQuery.from(Job.class);
    readyJobsQuery.orderBy(builder.desc(root.get("priority")));
    readyJobsQuery.where(root.get("state").in(ResourceState.READY));
    readyJobsQuery.select(root.get(Resource_.resourceID));

    // Initialise the running resources so that they can retrieve their state
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    TypedQuery<Resource> query = entityManager.createQuery("from resources r where r.state = :state",
            Resource.class);
    query.setParameter("state", ResourceState.RUNNING);
    for (Resource resource : query.getResultList()) {
        LOGGER.info("Job %s is running: starting a watcher", resource);
        Job job = (Job) resource;
        if (job.process != null) {
            job.process.init(job);
        } else {
            Transaction.run(em -> {
                // Set the job state to ERROR (and update the state in case it was finished)
                // The job should take care of setting a new process if the job is still running
                Job _job = em.find(Job.class, job.getId());
                _job.setState(ResourceState.ERROR);
                _job.updateStatus();
                LOGGER.error("No process attached to a running job. New status is: %s", _job.getState());
            });
        }
        resource.updateStatus();
    }

    // Start the thread that notify dependencies
    LOGGER.info("Starting the notifier thread");
    notifier = new Notifier();
    notifier.start();
    runningThreadsCounter.add();

    // Start the thread that notify dependencies
    LOGGER.info("Starting the messager thread");
    messengerThread = new MessengerThread();
    messengerThread.start();
    runningThreadsCounter.add();

    // Start the thread that start the jobs
    LOGGER.info("Starting the job runner thread");
    readyJobSemaphore.setValue(true);
    runner = new JobRunner("JobRunner");
    runner.start();
    runningThreadsCounter.add();

    executorService = Executors.newFixedThreadPool(1);

    LOGGER.info("Done - ready status work now");
}

From source file:com.srotya.tau.api.ApplicationManager.java

/**
 * @param appConfiguration//from w  ww  .  j a  va2 s.c  om
 */
public void init(AppConfig appConfiguration) {
    config = new Properties(System.getProperties());
    if (appConfiguration.getTauConfig() != null) {
        try {
            config.load(new FileInputStream(appConfiguration.getTauConfig()));
        } catch (IOException e) {
            throw new RuntimeException("Configuration file not loaded", e);
        }
    } else {
        try {
            config.load(
                    ApplicationManager.class.getClassLoader().getResourceAsStream("default-config.properties"));
        } catch (IOException e) {
            throw new RuntimeException("Default configuration file not loaded", e);
        }
    }
    try {
        Utils.createDatabase(config.getProperty(JAVAX_PERSISTENCE_JDBC_URL),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_DB, "tau"),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_USER),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_PASSWORD),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_DRIVER));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    config.setProperty(JAVAX_PERSISTENCE_JDBC_URL, config.getProperty(JAVAX_PERSISTENCE_JDBC_URL)
            + config.getProperty(JAVAX_PERSISTENCE_JDBC_DB, "tau") + "?useSSL=false");
    factory = Persistence.createEntityManagerFactory("tau", config);
    EntityManager em = factory.createEntityManager();
    em.close();
    initializeEventSourcer();
    checkAndCreateGlobalRuleGroup();
}