Ejemplo n.º 1
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @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 {

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      emf = Persistence.createEntityManagerFactory("image-sharing-servicePU");
      em = emf.createEntityManager();

      JsonArrayBuilder builder = Json.createArrayBuilder();

      for (Images i : (List<Images>) em.createNamedQuery("Images.findAll").getResultList()) {
        String imagePath = i.getPath();

        builder.add(
            Json.createObjectBuilder()
                .add("path", imagePath)
                .add("id", i.getId())
                .add("rating", "1"));
      }

      JsonArray arr = builder.build();

      out.println(arr);

    } catch (Exception e) {
      out.println(e);
    } finally {
      em.close();
      emf.close();
      out.close();
    }
  }
  @Test
  public void testWrappedFromEntityManagerAPI() throws Exception {
    buildArchive();

    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone");
    assertThat(HibernateEntityManagerFactory.class.isAssignableFrom(emf.getClass())).isTrue();
    SessionFactory factory = ((HibernateEntityManagerFactory) emf).getSessionFactory();
    assertThat(factory.getClass()).isEqualTo(OgmSessionFactory.class);

    Session s = factory.openSession();
    assertThat(s.getClass()).isEqualTo(OgmSession.class);
    assertThat(s.getSessionFactory().getClass()).isEqualTo(OgmSessionFactory.class);

    Cavalier cavalier = new Cavalier();
    cavalier.setName("Caroline");

    EntityManager em = emf.createEntityManager();
    assertThat(em.unwrap(Session.class).getClass()).isEqualTo(OgmSession.class);
    assertThat(em.getDelegate().getClass()).isEqualTo(OgmSession.class);

    s.save(cavalier);

    Cavalier c = (Cavalier) s.get(Cavalier.class, cavalier.getId());
    assertTrue(c.getId().equals(cavalier.getId()));
    assertTrue(c.getName().equals(cavalier.getName()));

    em.close();

    emf.close();
  }
Ejemplo n.º 3
0
 protected void onTearDown() throws Exception {
   taskSession.dispose();
   emfTaskJPA.close();
   if (useJTA) {
     ds.close();
   }
 }
Ejemplo n.º 4
0
  public static void main(String[] args) {
    Group g1 = new Group("Foo");
    Group g2 = new Group("Bar");
    Group g3 = new Group("Baz");

    Person p1 = new Person("Jack");
    Person p2 = new Person("Jane");
    Person p3 = new Person("John");

    g1.addPerson(p1);
    g1.addPerson(p2);
    g2.addPerson(p2);
    g3.addPerson(p3);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Groups");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(p1);
    em.persist(p2);
    em.persist(p3);
    em.persist(g1);
    em.persist(g2);
    em.persist(g3);
    em.getTransaction().commit();

    em.close();
    emf.close();
  }
  @Test
  public void testJTAStandalone() throws Exception {

    final EntityManagerFactory emf =
        Persistence.createEntityManagerFactory(
            "jpajtastandalone", TestHelper.getEnvironmentProperties());

    TransactionManager transactionManager = extractJBossTransactionManager(emf);

    transactionManager.begin();
    final EntityManager em = emf.createEntityManager();
    Poem poem = new Poem();
    poem.setName("L'albatros");
    em.persist(poem);
    transactionManager.commit();

    em.clear();

    transactionManager.begin();
    poem = em.find(Poem.class, poem.getId());
    assertThat(poem).isNotNull();
    assertThat(poem.getName()).isEqualTo("L'albatros");
    em.remove(poem);
    transactionManager.commit();

    em.close();

    dropSchemaAndDatabase(emf);
    emf.close();
  }
Ejemplo n.º 6
0
 public synchronized void closeEntityManagerFactory() {
   if (emf != null) {
     emf.close();
     emf = null;
     log.info("Persistence Manager has been closed");
   }
 }
  @Test
  public void testCreateThenDrop() throws Exception {
    URL persistenceXmlUrl =
        Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML_RESOURCE_NAME);
    if (persistenceXmlUrl == null) {
      persistenceXmlUrl =
          Thread.currentThread()
              .getContextClassLoader()
              .getResource('/' + PERSISTENCE_XML_RESOURCE_NAME);
    }

    assertNotNull(persistenceXmlUrl);

    ParsedPersistenceXmlDescriptor persistenceUnit =
        PersistenceXmlParser.locateIndividualPersistenceUnit(persistenceXmlUrl);
    // creating the EMF causes SchemaCreator to be run...
    EntityManagerFactory emf =
        Bootstrap.getEntityManagerFactoryBuilder(persistenceUnit, Collections.emptyMap()).build();

    // closing the EMF causes the delayed SchemaDropper to be run...
    //		wrap in a transaction just to see if we can get this to fail in the way the WF report says;
    //		in my experience however this succeeds with or without the transaction
    final TransactionManager tm =
        emf.unwrap(SessionFactoryImplementor.class)
            .getServiceRegistry()
            .getService(JtaPlatform.class)
            .retrieveTransactionManager();

    tm.begin();
    Transaction txn = tm.getTransaction();
    emf.close();
    txn.commit();
  }
Ejemplo n.º 8
0
  @After
  public void tearDown() throws Exception {
    int removeAllTasks = taskService.removeAllTasks();

    emf.close();
    ds.close();
  }
Ejemplo n.º 9
0
 @AfterClass
 public static void destroyEntityManagerFactory() {
   // logger.info("Closing EntityManagerFactory");
   if (entityManagerFactory != null) {
     entityManagerFactory.close();
   }
 }
Ejemplo n.º 10
0
  // EXCLUI UM CAIXA
  @Override
  public void excluir(Caixa caixa) throws PersistenceException {
    EntityManagerFactory conexao = Persistence.createEntityManagerFactory("MDJPapeisPU");
    try {
      EntityManager entityManager = conexao.createEntityManager();
      entityManager.getTransaction().begin();

      // Tornando o caixa gerenciável pelo entityManager, necessário para usar o método remove a
      // seguir
      caixa = entityManager.find(Caixa.class, caixa.getCodigo());

      entityManager.remove(caixa);
      entityManager.getTransaction().commit();
      entityManager.close();
    } catch (IllegalArgumentException ex) {
      System.out.println("CaixaDAO - CATCH IllegalArgumentException");
      ex.printStackTrace();
      throw new PersistenceException(ex);
    } catch (PersistenceException ex) {
      System.out.println("CaixaDAO - CATCH PersistenceException");
      ex.printStackTrace();
      throw new PersistenceException(ex);
    } finally {
      conexao.close();
    }
  }
Ejemplo n.º 11
0
  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();
  }
Ejemplo n.º 12
0
  @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();
  }
Ejemplo n.º 13
0
 public static void reset() {
   if (emf != null && emf.isOpen()) {
     emf.close();
   }
   emf = Persistence.createEntityManagerFactory("org.drools.grid");
   whitePages = new JpaWhitePages(emf);
 }
 private void purge() {
   FullTextEntityManager ftEm = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
   ftEm.purgeAll(Book.class);
   ftEm.flushToIndexes();
   ftEm.close();
   emf.close();
 }
Ejemplo n.º 15
0
  @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();
  }
Ejemplo n.º 16
0
  private void shutdown() {
    if (entityManager != null) {
      try {
        if (entityManager.getTransaction().isActive()) {
          entityManager.getTransaction().rollback();
        }
      } finally {
        entityManager.close();
        entityManager = null;
      }
    }

    if (entityManagerFactory != null) {
      entityManagerFactory.getCache().evictAll();
      entityManagerFactory.close();
      entityManagerFactory = null;
    }

    // clean shutdown of derby
    if (isDerby) {
      try {
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
      } catch (SQLException e) {
        if (!e.getMessage().equals("Derby system shutdown.")) {
          throw new RuntimeException(e);
        }
      }
    }
  }
  public void testIllegalStateExceptionOnClosedEntityManagerFactory() {
    EntityManagerFactory emf = null;
    Metamodel metamodel = null;
    boolean exceptionThrown = false;
    try {
      emf = initialize();

      // Verify an ISE if the emf is closed
      emf.close();
      closeEntityManagerFactory(PERSISTENCE_UNIT_NAME);
      try {
        metamodel = emf.getMetamodel();
      } catch (IllegalStateException e) {
        exceptionThrown = true;
        assertNull(metamodel);
        assertTrue(e instanceof IllegalStateException);
        // System.out.println("_Disclaimer: The above IllegalStateException is expected as part of
        // testing.");
        // e.printStackTrace();
      }
      assertTrue(exceptionThrown);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 18
0
  /**
   * This method should be called in the @After method of a test to clean up the persistence unit
   * and datasource.
   *
   * @param context A HashMap generated by {@link org.drools.persistence.util.PersistenceUtil
   *     setupWithPoolingDataSource(String)}
   */
  public static void cleanUp(HashMap<String, Object> context) {
    if (context != null) {

      BitronixTransactionManager txm = TransactionManagerServices.getTransactionManager();
      if (txm != null) {
        txm.shutdown();
      }

      Object emfObject = context.remove(ENTITY_MANAGER_FACTORY);
      if (emfObject != null) {
        try {
          EntityManagerFactory emf = (EntityManagerFactory) emfObject;
          emf.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      Object ds1Object = context.remove(DATASOURCE);
      if (ds1Object != null) {
        try {
          PoolingDataSource ds1 = (PoolingDataSource) ds1Object;
          ds1.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
  }
 @Override
 public void destroy() {
   entityManagerFactory.close();
   entityManagerFactory = null;
   threadLocal = null;
   Logger.debug("%s destroyed.", PersistenceManagerImpl.class.getName());
 }
  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();
    }
  }
Ejemplo n.º 21
0
  public static void main(String[] args) {

    EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("JPA");
    EntityManager entitymanager = emfactory.createEntityManager();
    entitymanager.getTransaction().begin();

    // Teaching staff entity
    TeachingStaff ts1 = new TeachingStaff(1, "Gopal", "MSc MEd", "Maths");
    TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English");

    // Non-Teaching Staff entity
    NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts");
    NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin");

    // storing all entities
    entitymanager.persist(ts1);
    entitymanager.persist(ts2);
    entitymanager.persist(nts1);
    entitymanager.persist(nts2);

    entitymanager.getTransaction().commit();

    entitymanager.close();
    emfactory.close();
  }
Ejemplo n.º 22
0
  @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 void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("TA-FINAL-PU");
    EntityManager em = emf.createEntityManager();

    Filme f = new Filme();
    Filme ff = em.find(Filme.class, 42);

    Cinema c = new Cinema();
    Cinema cc = em.find(Cinema.class, 2);

    Sessao obj = new Sessao();
    obj.setData(Calendar.getInstance());
    obj.setHora("16h as 18h");
    obj.setValorInteiro(28.00);
    obj.setValorMeia(14.00);
    obj.setNumSala("25b");

    obj.setCinema(cc);
    obj.setFilme(ff);

    em.getTransaction().begin();
    em.persist(obj);
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
Ejemplo n.º 24
0
 @AfterClass
 public static void tearDownClass() throws Exception {
   if (emf != null) {
     emf.close();
     emf = null;
   }
 }
 @AfterClass
 public static void classCleanUp() throws Exception {
   if (emf != null) {
     emf.close();
     emf = null;
   }
 }
Ejemplo n.º 26
0
  private static void insereIteracao(Pendencia pendencia) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("hemoproject");
    EntityManager manager = factory.createEntityManager();

    manager.getTransaction().begin();

    UserDAO usuariodao = new UserDAO();

    // obtem o usuário
    usuariodao.beginTransaction();
    User usuario = usuariodao.findUserByMasp("@Importacao");
    usuariodao.closeTransaction();

    Iteracao iteracao = new Iteracao();
    // iteracao.setCategoria(Categoria.CONFIGURACAO);
    iteracao.setDescricao("Pendente de validação do usuário. Conforme e-mail enviado.");
    iteracao.setStatus(Status.PENDENTE_USUARIO);
    iteracao.setUsuario(usuario);
    iteracao.setPendencia(pendencia);
    iteracao.setDataDaPendencia(new GregorianCalendar().getInstance());

    manager.persist(iteracao);
    manager.getTransaction().commit();

    manager.close();
    factory.close();

    System.out.println("gravou");
  }
 @Test
 public void testClose() {
   cache.put("pu1", emFactory);
   emFactory.close();
   replay(emFactory);
   producer.close();
   verify(emFactory);
 }
Ejemplo n.º 28
0
 public void teardown() {
   if (entityManager != null) {
     entityManager.close();
   }
   if (entityManagerFactory != null) {
     entityManagerFactory.close();
   }
 }
 @After
 public void teardown() {
   globalScheduler.shutdown();
   if (manager != null) {
     manager.close();
   }
   emf.close();
 }
 @Override
 public void stop(StopContext context) {
   JPA_LOGGER.stoppingService("Persistence Unit", pu.getScopedPersistenceUnitName());
   if (entityManagerFactory != null) {
     entityManagerFactory.close();
     entityManagerFactory = null;
   }
 }