public void init(PortletConfig config) throws PortletException { super.init(config); // create application properties with default Properties defaultProps = PropertiesUtils.loadDefault(getPortletContext().getRealPath(default_properties)); applicationProps = new Properties(defaultProps); // now load properties from last invocation applicationProps = PropertiesUtils.loadLastState( applicationProps, getPortletContext().getRealPath(saved_properties)); // sets values if (applicationProps.getProperty("defaultURL") != null) defaultURL = applicationProps.getProperty("defaultURL"); if (applicationProps.getProperty("defaultHeight") != null) defaultHeight = applicationProps.getProperty("defaultHeight"); if (applicationProps.getProperty("defaultWidth") != null) defaultWidth = applicationProps.getProperty("defaultWidth"); if (applicationProps.getProperty("defaultMessage") != null) defaultMessage = applicationProps.getProperty("defaultMessage"); if (applicationProps.getProperty("hide_url") != null) if (applicationProps.getProperty("hide_url").equalsIgnoreCase("true")) hide_url = true; if (applicationProps.getProperty("hide_new_windows") != null) if (applicationProps.getProperty("hide_new_windows").equalsIgnoreCase("true")) hide_new_windows = true; // CREATOR_CONSULTATION = new CreateConsultation(); // CREATOR_URI = new CreateUri(); emf_consultation = Persistence.createEntityManagerFactory("consultation"); emf_resource = Persistence.createEntityManagerFactory("resource"); daoConsultation = new DAOConsultation(emf_consultation); daoResource = new DAOResource(emf_resource); }
/** * This method does all of the setup for the test and returns a HashMap containing the persistence * objects that the test might need. * * @param persistenceUnitName The name of the persistence unit used by the test. * @return HashMap<String Object> with persistence objects, such as the EntityManagerFactory and * DataSource */ public static HashMap<String, Object> setupWithPoolingDataSource( final String persistenceUnitName, String dataSourceName, final boolean testMarshalling) { HashMap<String, Object> context = new HashMap<String, Object>(); // set the right jdbc url Properties dsProps = getDatasourceProperties(); String jdbcUrl = dsProps.getProperty("url"); String driverClass = dsProps.getProperty("driverClassName"); determineTestMarshalling(dsProps, testMarshalling); if (TEST_MARSHALLING) { Class<?> testClass = null; StackTraceElement[] ste = Thread.currentThread().getStackTrace(); int i = 1; do { try { testClass = Class.forName(ste[i++].getClassName()); } catch (ClassNotFoundException e) { // do nothing.. } } while (PersistenceUtil.class.equals(testClass) && i < ste.length); assertNotNull("Unable to resolve test class!", testClass); jdbcUrl = initializeTestDb(dsProps, testClass); } boolean startH2TcpServer = false; if (jdbcUrl.matches("jdbc:h2:tcp:.*")) { startH2TcpServer = true; } // Setup the datasource PoolingDataSource ds1 = setupPoolingDataSource(dsProps, dataSourceName, startH2TcpServer); if (driverClass.startsWith("org.h2")) { ds1.getDriverProperties().setProperty("url", jdbcUrl); } ds1.init(); context.put(DATASOURCE, ds1); // Setup persistence EntityManagerFactory emf; if (TEST_MARSHALLING) { Properties overrideProperties = new Properties(); overrideProperties.setProperty("hibernate.connection.url", jdbcUrl); EntityManagerFactory realEmf = Persistence.createEntityManagerFactory(persistenceUnitName, overrideProperties); emf = (EntityManagerFactory) EntityManagerFactoryProxy.newInstance(realEmf); UserTransaction ut = (UserTransaction) UserTransactionProxy.newInstance(realEmf); context.put(TRANSACTION, ut); } else { emf = Persistence.createEntityManagerFactory(persistenceUnitName); } context.put(ENTITY_MANAGER_FACTORY, emf); return context; }
@Test public void testPersistenceHook() { assertEquals( Persistence.createEntityManagerFactory("test-data-source").getClass(), EntityManagerFactoryImpl.class); assertEquals( Persistence.createEntityManagerFactory("test-data-source", new HashMap()).getClass(), EntityManagerFactoryImpl.class); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { request.getPart("file").write(request.getPart("file").getSubmittedFileName()); // out.println("File uploaded successfully! " + // request.getPart("file").getSubmittedFileName()); } catch (Exception e) { out.println("Exception -->" + e.getMessage()); } finally { } // create a new transaction to add data about the image upload to DB. emf = Persistence.createEntityManagerFactory("ImageRektPU"); em = emf.createEntityManager(); // out.println("Still works<br>"); // out.println("Transaction created<br>"); try { em.getTransaction().begin(); // out.println("Transaction created<br>"); // int fileuploader = Integer.parseInt(request.getParameter("fileuploader")); // out.println("User " + request.getParameter("user")); User u = (User) em.createNamedQuery("User.findByUid") .setParameter("uid", Integer.parseInt(request.getParameter("user"))) .getSingleResult(); // out.println(u.getUname() + "<br>"); // image title, description, Date generated in java the name of the file // Image img = new Image(request.getParameter("titleinput"), // request.getParameter("descriptioninput"), new Date(), // request.getPart("file").getSubmittedFileName(), u); Image img = new Image( request.getParameter("titleinput"), request.getParameter("descriptioninput"), new Date(), request.getPart("file").getSubmittedFileName(), u); // out.println(img.getTitle() + "<br>"); em.persist(img); em.getTransaction().commit(); // out.println("File in DB successfully!"); emf = Persistence.createEntityManagerFactory("ImageRektPU"); em = emf.createEntityManager(); em.getTransaction().begin(); this.imageList = em.createNamedQuery("Image.findAll").getResultList(); image = this.imageList.get(this.imageList.size() - 1); out.println(image.getIid()); em.getTransaction().commit(); } catch (Exception e) { out.println("BOOM! " + e); } emf.close(); }
@Override protected void createStaticEntityMangers() throws Exception { super.createStaticEntityMangers(); TestContext ctx = TestContext.get(); emfac2 = Persistence.createEntityManagerFactory(ctx.getPersistenceUnitName() + "2"); emfac3 = Persistence.createEntityManagerFactory(ctx.getPersistenceUnitName() + "3"); em2 = emfac2.createEntityManager(); em3 = emfac3.createEntityManager(); }
public static synchronized EntityManager getEntityManager() { if (em == null) { em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager(); } if (!em.isOpen()) { em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager(); } if (!em.getTransaction().isActive()) { em.getTransaction().begin(); } // log.debug("created EntityManager"); return em; }
@Test public void noFetchJoinTest() { List<User> users = joiner.find(Q.from(QUser.user1)); Assert.assertFalse(Persistence.getPersistenceUtil().isLoaded(users.get(0), "groups")); JoinDescription e = J.left(QGroup.group).fetch(false); users = joiner.find(Q.from(QUser.user1).joins(Collections.singletonList(e))); Assert.assertFalse(Persistence.getPersistenceUtil().isLoaded(users.get(0), "groups")); e.fetch(true); entityManager.clear(); users = joiner.find(Q.from(QUser.user1).joins(Collections.singletonList(e))); Assert.assertTrue(Persistence.getPersistenceUtil().isLoaded(users.get(0), "groups")); }
@Test public void testExcludeHbmPar() throws Exception { File testPackage = buildExcludeHbmPar(); addPackageToClasspath(testPackage); EntityManagerFactory emf = null; try { emf = Persistence.createEntityManagerFactory("excludehbmpar", new HashMap()); } catch (PersistenceException e) { Throwable nested = e.getCause(); if (nested == null) { throw e; } nested = nested.getCause(); if (nested == null) { throw e; } if (!(nested instanceof ClassNotFoundException)) { throw e; } fail("Try to process hbm file: " + e.getMessage()); } EntityManager em = emf.createEntityManager(); Caipirinha s = new Caipirinha("Strong"); em.getTransaction().begin(); em.persist(s); em.getTransaction().commit(); em.getTransaction().begin(); s = em.find(Caipirinha.class, s.getId()); em.remove(s); em.getTransaction().commit(); em.close(); emf.close(); }
@Deprecated public static StatefulKnowledgeSession loadStatefulKnowledgeSession( KnowledgeBase kbase, int sessionId) { Properties properties = getProperties(); String persistenceEnabled = properties.getProperty("persistence.enabled", "false"); RuntimeEnvironmentBuilder builder = null; if ("true".equals(persistenceEnabled)) { String dialect = properties.getProperty( "persistence.persistenceunit.dialect", "org.hibernate.dialect.H2Dialect"); Map<String, String> map = new HashMap<String, String>(); map.put("hibernate.dialect", dialect); EntityManagerFactory emf = Persistence.createEntityManagerFactory( properties.getProperty( "persistence.persistenceunit.name", "org.jbpm.persistence.jpa"), map); builder = RuntimeEnvironmentBuilder.Factory.get() .newDefaultBuilder() .entityManagerFactory(emf) .addEnvironmentEntry( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); } else { builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder(); } builder.knowledgeBase(kbase); RuntimeManager manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get()); return (StatefulKnowledgeSession) manager.getRuntimeEngine(EmptyContext.get()).getKieSession(); }
private EntityManagerFactory makeEntityManagerFactory(String s) throws SQLException { Properties props = new Properties(); String url = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1", s); props.put("javax.persistence.jdbc.url", url); props.put("javax.persistence.jdbc.driver", "org.h2.Driver"); props.put("javax.persistence.transactionType", "RESOURCE_LOCAL"); // OpenJPA support props.put("openjpa.Connection2URL", url); props.put("openjpa.Connection2DriverName", "org.h2.Driver"); props.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(SchemaAction='add')"); props.put("openjpa.ConnectionRetainMode", "always"); props.put("openjpa.ConnectionFactoryMode", "local"); // eclipse-link support props.put("eclipselink.ddl-generation", "create-tables"); props.put("eclipselink.ddl-generation.output-mode", "database"); // Hibernate support props.put("hibernate.hbm2ddl.auto", "create-drop"); props.put("hibernate.connection.driver_class", "org.h2.Driver"); props.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); props.put("hibernate.connection.url", url); props.put("hibernate.show_sql", "true"); JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(url); String dataSourceUrl = "java:/dummyDataSource_" + s; try { new InitialContext().bind(dataSourceUrl, dataSource); } catch (NamingException e) { throw new AssertionError(e); } props.put("hibernate.connection.datasource", dataSourceUrl); return Persistence.createEntityManagerFactory(s, props); }
/** Initialise JPA entity manager factories. */ public JPAApi start() { for (JPAConfig.PersistenceUnit persistenceUnit : jpaConfig.persistenceUnits()) { emfs.put( persistenceUnit.name, Persistence.createEntityManagerFactory(persistenceUnit.unitName)); } return this; }
public static synchronized EntityManager getEntityManager() { if (em == null) { if (emf == null) emf = Persistence.createEntityManagerFactory("AgendaContatos"); em = emf.createEntityManager(); } return em; }
public class AccountServlet extends HttpServlet { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistenceunit"); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); Principal p = req.getUserPrincipal(); String username = p.getName(); req.setAttribute("username", username); if (req.isUserInRole("user")) { session.setAttribute("user", true); } else if (req.isUserInRole("owner")) { session.setAttribute("owner", true); OwnerAccountPage ownerAccountPage = new OwnerAccountPage(entityManagerFactory); CharityOwner ownersCharity = ownerAccountPage.getCharity(username); req.setAttribute("charity", ownersCharity); } RequestDispatcher requestDispatcher = req.getRequestDispatcher("../WEB-INF/account.jsp"); requestDispatcher.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
public Collection<Genre> lister() { EntityManager em = Persistence.createEntityManagerFactory("DTAStreamingWebPU").createEntityManager(); return em.createQuery("SELECT g FROM Genres g ORDER BY g.id").getResultList(); }
@ManagedBean(eager = true) @RequestScoped public class History implements Serializable { /** */ private static final long serialVersionUID = -7136876637706661208L; EntityManagerFactory emf = Persistence.createEntityManagerFactory("jobqueue-api-pu"); EntityManager em = emf.createEntityManager(); private ArrayList<com.enioka.jqm.jpamodel.History> hs = null; public History() {} public ArrayList<com.enioka.jqm.jpamodel.History> getHs() { em.clear(); @SuppressWarnings("unchecked") List<com.enioka.jqm.jpamodel.History> tmp = em.createQuery("SELECT h FROM History h").getResultList(); hs = new ArrayList<com.enioka.jqm.jpamodel.History>(); for (com.enioka.jqm.jpamodel.History j : tmp) { hs.add(j); } return hs; } public void setHs(ArrayList<com.enioka.jqm.jpamodel.History> hs) { this.hs = hs; } }
/** Created by Rekish on 11/13/2015. Retrieve data from the Assignee table in the database */ public class AssigneeDAOImpl implements AssigneeDAO { private static final Logger LOGGER = LoggerFactory.getLogger(AssigneeDAOImpl.class); private EntityManagerFactory factory = Persistence.createEntityManagerFactory("issueUnit"); private EntityManager manager = factory.createEntityManager(); private static final String EXCEPTION_STRING = "Exception Occurred"; /** @return all the possible options from the assignee table as a List<> */ @Override public List<Assignee> getAssigneeList() { LOGGER.info("Getting all assignee's."); List<Assignee> assigneeList = null; try { manager.getTransaction().begin(); Query query = manager.createQuery("SELECT a FROM Assignee a"); manager.getTransaction().commit(); assigneeList = query.getResultList(); } catch (IllegalStateException exception) { LOGGER.error(EXCEPTION_STRING, exception); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); manager.close(); factory.close(); } } return assigneeList; } }
@Override protected void setUp() throws Exception { super.setUp(); env = EnvironmentFactory.newEnvironment(); Environment domainEnv = EnvironmentFactory.newEnvironment(); domainEmf = Persistence.createEntityManagerFactory("org.jbpm.persistence.example"); domainEnv.set(EnvironmentName.ENTITY_MANAGER_FACTORY, domainEmf); env.set( EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] { new JPAPlaceholderResolverStrategy(domainEnv), new SerializablePlaceholderResolverStrategy( ClassObjectMarshallingStrategyAcceptor.DEFAULT) }); ksession.setEnvironment(env); server = new MinaTaskServer(taskService); System.out.println("Waiting for the MinaTask Server to come up"); try { startTaskServerThread(server, false); } catch (Exception e) { startTaskServerThread(server, true); } AsyncMinaHTWorkItemHandler asyncWSHumanTaskHandler = new AsyncMinaHTWorkItemHandler("my-mina-connector", client, ksession, null); setClient(asyncWSHumanTaskHandler.getClient()); setHandler(asyncWSHumanTaskHandler); }
@Override protected void setUp() throws Exception { ds1 = setupPoolingDataSource(); ds1.init(); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); }
public static EntityManagerFactory getEMF() { if (emf == null) { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); System.out.println(emf.isOpen()); } return emf; }
/** * Returns a list of dates from trade open until expiration. * * @param expiration * @return */ public static List<Date> getTradeDatesStarting(Date expiration, Date startDate) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAOptionsTrader"); EntityManager em = emf.createEntityManager(); // Note: table name refers to the Entity Class and is case sensitive // field names are property names in the Entity Class Query query = em.createQuery( "select distinct(opt.trade_date) from " + TradeProperties.SYMBOL_FOR_QUERY + " opt " + "where " + "opt.trade_date >= :tradeDate " + "opt.expiration=:expiration " // + "and opt.call_put = :call_put " // + "and opt.delta > 0.04 " // + "and opt.delta < 0.96 " + "order by opt.trade_date"); query.setParameter("tradeDate", startDate); query.setParameter("expiration", expiration); // query.setParameter("call_put", callPut); List<Date> dates = query.getResultList(); em.close(); return dates; }
public void remover(Integer id) throws Exception { EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAW-Trabalho-ModelPU"); EntityManager em = emf.createEntityManager(); try { if (em.getTransaction().isActive() == false) { em.getTransaction().begin(); } Venda objeto = em.find(Venda.class, id); em.remove(objeto); em.getTransaction().commit(); } catch (Exception e) { if (em.getTransaction().isActive() == false) { em.getTransaction().begin(); } em.getTransaction().rollback(); throw new Exception("Erro ao executar a operação de persistência:" + e.getMessage()); } finally { em.close(); emf.close(); } }
@Test public void testCfgXmlPar() throws Exception { File testPackage = buildCfgXmlPar(); addPackageToClasspath(testPackage); EntityManagerFactory emf = Persistence.createEntityManagerFactory("cfgxmlpar", new HashMap()); EntityManager em = emf.createEntityManager(); Item i = new Item(); i.setDescr("Blah"); i.setName("factory"); Morito m = new Morito(); m.setPower("SuperStrong"); em.getTransaction().begin(); em.persist(i); em.persist(m); em.getTransaction().commit(); em.getTransaction().begin(); i = em.find(Item.class, i.getName()); em.remove(i); em.remove(em.find(Morito.class, m.getId())); em.getTransaction().commit(); em.close(); emf.close(); }
@Test public void testDefaultPar() throws Exception { File testPackage = buildDefaultPar(); addPackageToClasspath(testPackage); // run the test EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultpar", new HashMap()); EntityManager em = emf.createEntityManager(); ApplicationServer as = new ApplicationServer(); as.setName("JBoss AS"); Version v = new Version(); v.setMajor(4); v.setMinor(0); v.setMicro(3); as.setVersion(v); Mouse mouse = new Mouse(); mouse.setName("mickey"); em.getTransaction().begin(); em.persist(as); em.persist(mouse); assertEquals(1, em.createNamedQuery("allMouse").getResultList().size()); Lighter lighter = new Lighter(); lighter.name = "main"; lighter.power = " 250 W"; em.persist(lighter); em.flush(); em.remove(lighter); em.remove(mouse); assertNotNull(as.getId()); em.remove(as); em.getTransaction().commit(); em.close(); emf.close(); }
public static EntityManager getEntityManager() { if (em == null) { emf = Persistence.createEntityManagerFactory("Twitt"); em = emf.createEntityManager(); } return em; }
public Genre rechercher(String id) { EntityManager em = Persistence.createEntityManagerFactory("DTAStreamingWebPU").createEntityManager(); return em.find(Genre.class, id); }
public static void main(String[] args) throws Exception { System.out.println("hello from Customer.java"); EntityManagerFactory factory = Persistence.createEntityManagerFactory("customerPU"); EntityManager manager = factory.createEntityManager(); Query q1 = manager.createQuery("SELECT COUNT(c) FROM Customer c"); Long count = (Long) q1.getSingleResult(); if (count == 0) { // record is empty, read from data.txst System.out.println("record empty, read from data.txt..."); // try { FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { // System.out.println(s); // split the string s Object[] items = s.split("\\|"); // store in string list // List<String> itemList= new ArrayList<String>(Arrays.asList(items)); // string list converted to array // Object[] itemArray = itemList.toArray(); // insert data into database table manager.getTransaction().begin(); Customer c = new Customer(); // add email c.setEmail((String) items[0]); // add pass c.setPass((String) items[1]); // add name c.setName((String) items[2]); // add address c.setAddress((String) items[3]); // add yob c.setYob((String) items[4]); // change to managed state manager.persist(c); manager.getTransaction().commit(); } fr.close(); } // display the records Query q2 = manager.createNamedQuery("Customer.findAll"); List<Customer> customers = q2.getResultList(); for (Customer c : customers) { System.out.println(c.getName() + ", " + c.getEmail()); } manager.close(); factory.close(); }
@BeforeClass public static void initializeEntityManagerFactory() { entityManagerFactory = Persistence.createEntityManagerFactory("MyTestPersistenceUnit", properties()); System.out.println("InitializeEntityFactory!!"); }
public static void main(String[] args) { try { EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU"); EntityManager manager = f.createEntityManager(); Scanner in = new Scanner(System.in); System.out.print("Enter id to modify"); int id = in.nextInt(); in.nextLine(); Emp e = manager.find(Emp.class, id); System.out.println("current details are"); System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary()); System.out.println("Enter name to update"); String n = in.nextLine(); System.out.println("Enter job to update"); String j = in.nextLine(); System.out.println("Enter salary to update"); int s = in.nextInt(); EntityTransaction t = manager.getTransaction(); t.begin(); e.setEname(n); e.setJob(j); e.setSalary(s); t.commit(); manager.close(); System.out.println("updated"); } catch (Exception e) { System.out.println(e); } }
/** Constructs the EntityManagerFactory. */ @BeforeClass public static void setUpJPA() { dataSource = DatabaseTools.setupJDBCandJNDI(jndi, databaseName); // Create the JPA EMF emf = Persistence.createEntityManagerFactory(persistentUnit); }
/** * Cria o Entity Manager caso não esteja criado. * * @return EntityManagerFactory - Fabrica do Entity Manager */ public static EntityManagerFactory getEntityManagerFactory() { if (fabrica == null) { fabrica = Persistence.createEntityManagerFactory("netquiz"); } return fabrica; }