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:eu.supersede.fe.multitenant.MultiJpaProvider.java

@PostConstruct
private void load() {
    Map<String, DataSource> datasources = dataSourceBasedMultiTenantConnectionProviderImpl.getDataSources();

    repositoriesFactory = new HashMap<>();

    for (String n : datasources.keySet()) {
        try {//from w  w  w .j a  va2s .  com
            log.info("Loading database: " + datasources.get(n).getConnection().getMetaData().getURL());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Map<String, Object> hibernateProps = new LinkedHashMap<>();
        hibernateProps.putAll(jpaProperties.getHibernateProperties(datasources.get(n)));

        hibernateProps.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");

        Set<String> packages = new HashSet<>();
        String[] tmp = MODELS_PACKAGES.split(",");

        for (String t : tmp) {
            packages.add(t.trim());
        }

        LocalContainerEntityManagerFactoryBean emfb = builder.dataSource(datasources.get(n))
                .packages(packages.toArray(new String[packages.size()])).properties(hibernateProps).jta(false)
                .build();

        emfb.afterPropertiesSet();
        EntityManagerFactory emf = emfb.getObject();
        EntityManager em = emf.createEntityManager();

        final JpaTransactionManager jpaTranMan = new JpaTransactionManager(emf);
        JpaRepositoryFactory jpaFactory = new JpaRepositoryFactory(em);
        jpaFactory.addRepositoryProxyPostProcessor(new MultiJpaRepositoryProxyPostProcessor(jpaTranMan));

        repositoriesFactory.put(n, new ContainerUtil(jpaFactory, emf, em));
    }
}

From source file:ict.DoLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  www.j a  v  a2  s .co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("WSPU");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        String _request = request.getParameter("AAA");
        String userID = new String(Base64.decodeBase64(_request));

        String _request_ = request.getParameter("BBB");
        String userPassword = new String(Base64.decodeBase64(_request_));

        //String userID = request.getParameter("userID");
        //String userPassword = request.getParameter("userPassword");
        User tmp = new User();
        tmp.setUserID(userID);
        tmp.setPassword(userPassword);
        System.out.println("*****" + tmp.getUserID());

        User user = entityManager.find(User.class, tmp.getUserID());
        if (user.getPassword().equals(tmp.getPassword())) {
            entityManager.getTransaction().commit();
            entityManager.close();
            entityManagerFactory.close();
            request.getSession(true).setAttribute("user", user.getUserName());
        }

    } catch (Exception e) {
        System.out.println("****ERROR:****" + e.getMessage());
    }
    response.sendRedirect("index.jsp");
}

From source file:com.dcsbootcamp.maven.integrationtest.GreeterConfig.java

/**
 * Provides a proxy instance of the current transaction's entity manager
 * which is ready to inject via constructor injection and guarantees
 * immutability.//from w  w w  .  ja  va2s.c om
 *
 * @param emf the entity manager factory
 * @return a proxy of entity manager
 */
@Bean
@Scope(SCOPE_PROTOTYPE)
EntityManager entityManagerProvider(EntityManagerFactory emf) {
    EntityManagerHolder holder = (EntityManagerHolder) getResource(emf);

    if (holder == null) {
        return emf.createEntityManager();
    }

    return holder.getEntityManager();
}

From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from  ww w  .jav  a  2s.  c  o  m

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

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);//from   ww  w  .  j  a va2s.com
    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:org.tinymediamanager.core.TmmModuleManager.java

/**
 * start up tmm - do initialization code here
 *///  ww w  .j  a v a  2 s  .c o m
public void startUp() {
    // enhance if needed
    if (System.getProperty("tmmenhancer") != null) {
        // changed enhancer to be in sync with the build.xml
        com.objectdb.Enhancer.enhance("-s org.tinymediamanager.core.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.movie.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.tvshow.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.scraper.MediaTrailer");
    }

    // get a connection to the database
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(TMM_DB);
    try {
        entityManager = entityManagerFactory.createEntityManager();
    } catch (PersistenceException e) {
        if (e.getCause().getMessage().contains("does not match db file")) {
            // happens when there's a recovery file which does not match (cannot be recovered) - just delete and try again
            FileUtils.deleteQuietly(new File(TMM_DB + "$"));
            entityManager = entityManagerFactory.createEntityManager();
        } else {
            // unknown
            throw (e);
        }
    }
}

From source file:test.unit.be.fedict.trust.service.PersistenceTest.java

@Before
public void setUp() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Ejb3Configuration configuration = new Ejb3Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
    configuration.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:beta");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.addAnnotatedClass(CertificateAuthorityEntity.class);
    configuration.addAnnotatedClass(RevokedCertificateEntity.class);
    configuration.addAnnotatedClass(TrustDomainEntity.class);
    configuration.addAnnotatedClass(CertificateConstraintEntity.class);
    configuration.addAnnotatedClass(PolicyConstraintEntity.class);
    configuration.addAnnotatedClass(DNConstraintEntity.class);
    configuration.addAnnotatedClass(EndEntityConstraintEntity.class);
    configuration.addAnnotatedClass(KeyUsageConstraintEntity.class);
    configuration.addAnnotatedClass(QCStatementsConstraintEntity.class);
    configuration.addAnnotatedClass(TrustPointEntity.class);
    configuration.addAnnotatedClass(AuditEntity.class);
    EntityManagerFactory entityManagerFactory = configuration.buildEntityManagerFactory();

    this.entityManager = entityManagerFactory.createEntityManager();
    this.entityManager.getTransaction().begin();
}

From source file:proyectodavid.Negocio.Estadistica.SAEstadisticaImp.java

public SAEstadisticaImp() {

    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ProyectoDavidPU");

    this.entityManager = entityManagerFactory.createEntityManager();

}

From source file:it.infn.ct.futuregateway.apiserver.v1.BaseService.java

/**
 * Return the EntityManager./*from w  ww  .  ja  va  2 s .co  m*/
 * Create a JPA EntityManger from the EntityMangerFactory registered
 * for this servlet context
 *
 * @return The EntityManager
 */
protected final EntityManager getEntityManager() {
    EntityManagerFactory emf = (EntityManagerFactory) getRequest().getServletContext()
            .getAttribute(Constants.SESSIONFACTORY);
    return emf.createEntityManager();
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a busca de todos os usurios existentes no banco de dados.
 * @author Richel Sensineli//ww w. ja v a2s .co m
 * @param nome String - Nome do usurio
 * @return Collection list
 */
@Override
public Collection buscaTodosUsuarios() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery("select u from UsuarioImpl u");
    Collection result = null;
    result = q.getResultList();
    em.clear();
    em.close();
    emf.close();
    return result;
}