Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.enioka.jqm.tools.JqmEngine.java

synchronized void checkEngineEnd() {
    jqmlogger.trace("Checking if engine should end with the latest poller");
    for (QueuePoller poller : pollers.values()) {
        if (poller.isRunning()) {
            jqmlogger.trace("At least the poller on queue " + poller.getQueue().getName()
                    + " is still running and prevents shutdown");
            return;
        }/*from   w w  w  . j a  v  a2  s . com*/
    }
    if (hasEnded) {
        return;
    }
    jqmlogger.trace("The engine should end with the latest poller");
    hasEnded = true;

    // If here, all pollers are down. Stop Jetty too
    this.server.stop();

    // Also stop the internal poller
    this.intPoller.stop();

    // Reset the stop counter - we may want to restart one day
    EntityManager em = null;
    try {
        em = Helpers.getNewEm();
        em.getTransaction().begin();
        this.node = em.find(Node.class, this.node.getId(), LockModeType.PESSIMISTIC_WRITE);
        this.node.setStop(false);
        this.node.setLastSeenAlive(null);
        em.getTransaction().commit();
    } catch (Exception e) {
        // Shutdown exception is ignored (happens during tests)
    } finally {
        Helpers.closeQuietly(em);
    }

    // JMX
    if (loadJmxBeans) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            mbs.unregisterMBean(name);
            jqmlogger.trace("unregistered bean " + name);
        } catch (Exception e) {
            jqmlogger.error("Could not unregister engine JMX bean", e);
        }
    }

    // Note: if present, the JMX listener is not stopped as it is JVM-global, like the JNDI context

    // Done
    this.ended.release();
    jqmlogger.info("JQM engine has stopped");
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public void edit(Persona persona) throws Exception {
    EntityManager em = null;
    try {//from   w w  w.  ja  v  a2s .c om
        em = getEntityManager();
        em.getTransaction().begin();

        Persona personaAntigua = em.find(Persona.class, persona.getId());
        Hibernate.initialize(personaAntigua.getPersonaFirmasCollection());

        //quitar los personaTitulo que no existan en la nueva persona editada
        for (PersonaTitulo perTituloAntiguo : personaAntigua.getPersonaTitulosCollection()) {
            if (!persona.getPersonaTitulosCollection().contains(perTituloAntiguo)) {
                em.remove(perTituloAntiguo);
            }
        }
        //poner en null los ids negativos para que se puedan crear
        for (PersonaTitulo perTitulo : persona.getPersonaTitulosCollection()) {
            if (perTitulo.getId() != null && perTitulo.getId() < 0) {
                perTitulo.setId(null);
            }
            if (perTitulo.getPersona() == null) {
                perTitulo.setPersona(persona);
            }
            Titulo titulo = perTitulo.getTitulo();
            if (titulo.getId() == null || titulo.getId() < 0) {
                titulo.setId(null);
                em.persist(titulo);
            }
            if (perTitulo.getUniversidad().getId() == null || perTitulo.getUniversidad().getId() < 0) {
                perTitulo.getUniversidad().setId(null);
                em.persist(perTitulo.getUniversidad());
            }
            em.merge(perTitulo);
        }

        for (PersonaFirma perFirmaAntiguo : personaAntigua.getPersonaFirmasCollection()) {
            //revisar las firmas que estn en el antigua persona pero ya no en el nuevo editado,
            // por lo tanto si ya no estn en el nuevo editado, hay que borrar las relaciones PersonaFirma
            // pero solo si no tiene PersonaArticulo relacionado (significara que esa firma est actualmente 
            // siendo usada en un artculo, por lo tanto no de debe borrar)
            boolean firmaEnEditado = false;

            //primero revisar si la firma que existia antes de la persona, existe en el nuevo editado
            for (PersonaFirma perFirma : persona.getPersonaFirmasCollection()) {
                if (StringUtils.equalsIgnoreCase(perFirmaAntiguo.getFirma().getNombre(),
                        perFirma.getFirma().getNombre())) {
                    firmaEnEditado = true;
                    break;
                }
            }
            if (!firmaEnEditado) {
                //si es que la firma de la persona sin editar ya no existe en la persona editada, quitar la relacin PersonaFirma

                //primero verificar que la firma no sea usada en ninguna PersonaArticulo
                if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                    Firma firmaBorrar = null;
                    if (perFirmaAntiguo.getFirma().getPersonasFirmaCollection().size() == 1) {
                        //si la firma a borrar esta asignada a solo una persona (que sera la persona actual, variable: persona),
                        // colocarla a la variable para borrarla
                        //Siempre las firmas van a estar asignadas al menos a una persona, caso contrario deben ser borradas
                        //Las firmas de personas desconocidas estn ligadas a una persona: la persona con id=0
                        firmaBorrar = perFirmaAntiguo.getFirma();
                    }
                    //borrar la relacin PersonaFirma
                    em.remove(perFirmaAntiguo);
                    if (firmaBorrar != null) {
                        //borrar la firma solo si estaba asignada a una sola persona
                        firmaBorrar.getPersonasFirmaCollection().clear();
                        em.remove(firmaBorrar);
                    }
                }
            }
            /*
            if (!persona.getPersonaFirmasCollection().contains(perFirmaAntiguo)) {
            if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                em.remove(em);
            }
            }*/
        }
        guardarPersonaFirma(em, persona);

        em.merge(persona);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.drools.container.spring.beans.persistence.VariablePersistenceStrategyTest.java

@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException,
        IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
    MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
    MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields(
            "This is a test Entity with annotations in fields and without accesors methods");
    MyVariableSerializable myVariableSerializable = new MyVariableSerializable(
            "This is a test SerializableObject");
    EntityManager em = ((EntityManagerFactory) ctx.getBean("myEmf")).createEntityManager();

    em.getTransaction().begin();
    em.persist(myEntity);//from w  ww  .  j  a va  2  s.  c  o m
    em.persist(myEntityMethods);
    em.persist(myEntityOnlyFields);
    em.getTransaction().commit();
    em.close();

    log.info("---> get bean jpaSingleSessionCommandService");
    StatefulKnowledgeSession service = (StatefulKnowledgeSession) ctx.getBean("jpaSingleSessionCommandService");

    int sessionId = service.getId();
    log.info("---> created SingleSessionCommandService id: " + sessionId);

    log.info("### Starting process ###");
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("x", "SomeString");
    parameters.put("y", myEntity);
    parameters.put("m", myEntityMethods);
    parameters.put("f", myEntityOnlyFields);
    parameters.put("z", myVariableSerializable);
    WorkflowProcessInstance processInstance = (WorkflowProcessInstance) service
            .startProcess("com.sample.ruleflow", parameters);
    log.info("Started process instance {}", processInstance.getId());

    TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    EntityManagerFactory emf = (EntityManagerFactory) ctx.getBean("myEmf");

    //        List< ? > result = emf.createEntityManager().createQuery( "select i from VariableInstanceInfo i" ).getResultList();
    //        assertEquals( 5,
    //                      result.size() );
    log.info("### Retrieving process instance ###");

    Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(EnvironmentName.TRANSACTION_MANAGER, ctx.getBean("txManager"));
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] {
            //  new JPAPlaceholderResolverStrategy(env),
            new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) });

    KnowledgeStoreService kstore = (KnowledgeStoreService) ctx.getBean("kstore1");
    KnowledgeBase kbase1 = (KnowledgeBase) ctx.getBean("kbase1");
    service = kstore.loadStatefulKnowledgeSession(sessionId, kbase1, null, env);

    processInstance = (WorkflowProcessInstance) service.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    assertNotNull(processInstance);
    assertEquals("SomeString", processInstance.getVariable("x"));
    assertEquals("This is a test Entity with annotation in fields",
            ((MyEntity) processInstance.getVariable("y")).getTest());
    assertEquals("This is a test Entity with annotations in methods",
            ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    assertEquals("This is a test Entity with annotations in fields and without accesors methods",
            ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    assertEquals("This is a test SerializableObject",
            ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    assertNull(processInstance.getVariable("a"));
    assertNull(processInstance.getVariable("b"));
    assertNull(processInstance.getVariable("c"));

    service.dispose();

    //        log.info("### Completing first work item ###");
    //        ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
    //
    //        workItem = handler.getWorkItem();
    //        assertNotNull( workItem );
    //        
    //        log.info("### Retrieving variable instance infos ###");
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        assertEquals(8, result.size());
    //        for (Object o: result) {
    //            assertTrue(VariableInstanceInfo.class.isAssignableFrom(o.getClass()));
    //            log.info(o);
    //        }
    //        
    //        log.info("### Retrieving process instance ###");
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNotNull(processInstance);
    //        assertEquals("SomeString", processInstance.getVariable("x"));
    //        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
    //        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    //        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    //        assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    //        assertEquals("Some new String", processInstance.getVariable("a"));
    //        assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
    //        assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
    //        log.info("### Completing second work item ###");
    //        ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    //
    //        workItem = handler.getWorkItem();
    //        assertNotNull(workItem);
    //        
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        assertEquals(8, result.size());
    //        
    //        log.info("### Retrieving process instance ###");
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNotNull(processInstance);
    //        assertEquals("SomeString", processInstance.getVariable("x"));
    //        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
    //        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    //        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    //        assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    //        assertEquals("Some changed String", processInstance.getVariable("a"));
    //        assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
    //        assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
    //        log.info("### Completing third work item ###");
    //        ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    //
    //        workItem = handler.getWorkItem();
    //        assertNull(workItem);
    //        
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        //This was 6.. but I change it to 0 because all the variables will go away with the process instance..
    //        //we need to change that to leave the variables there??? 
    //        assertEquals(0, result.size());
    //
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNull(processInstance);
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java

/** Processes the incoming request and calls the various methods to create the right output stream.
 *
 * @param request servlet request//w w w  . j av  a2 s  .co  m
 * @param response servlet response
 *
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long startTime = System.currentTimeMillis();

    StringBuffer baseUrl = createBaseUrl(request, true);
    if (CAPABILITIES_DTD == null) {
        CAPABILITIES_DTD = baseUrl.toString() + "/dtd/capabilities_1_1_1.dtd";
    }
    if (EXCEPTION_DTD == null) {
        EXCEPTION_DTD = baseUrl.toString() + "/dtd/exception_1_1_1.dtd";
    }
    if (DESCRIBELAYER_DTD == null) {
        DESCRIBELAYER_DTD = baseUrl.toString() + "/dtd/WMS_DescribeLayerResponse.dtd";
    }

    DataWrapper data = new DataWrapper(request, response);

    Object identity = null;
    EntityManager em;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
        em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        tx = em.getTransaction();
        tx.begin();

        DataMonitoring rr = new DataMonitoring();
        data.setRequestReporting(rr);

        String serviceName = OGCConstants.WMS_SERVICE_WMS;

        try {
            OGCRequest ogcrequest = calcOGCRequest(request);

            String personalCode = null;
            if (ogcrequest != null)
                personalCode = ogcrequest.getPersonalCode();

            data.setOgcrequest(ogcrequest);

            String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE);
            if (serviceParam != null || !"".equals(serviceParam)) {
                serviceName = serviceParam;
            }

            String iUrl = ogcrequest.getUrl();
            rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(),
                    request.getMethod());

            User user = checkLogin(request, personalCode, em);

            ogcrequest.checkRequestURL();

            Organization mainOrg = null;
            String userName = null;

            if (user != null) {
                mainOrg = user.getMainOrganization();
                userName = user.getUsername();
            }

            rr.setUserAndOrganization(user, mainOrg);
            data.setHeader("X-Kaartenbalie-User", userName);

            parseRequestAndData(data, user);

        } catch (AccessDeniedException adex) {
            rr.setClientRequestException(adex);
            response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie");
        } catch (ProviderException pex) {
            log.error("Error while communicating with provider: " + pex.getLocalizedMessage());
            rr.setClientRequestException(pex);
            handleRequestException(pex, data);
        } catch (Exception e) {
            log.error(String.format("Error while handling request for URI %s, query string %s: %s: %s",
                    request.getRequestURI(), request.getQueryString(), e.getClass().getName(), e.getMessage()),
                    e);
            rr.setClientRequestException(e);
            handleRequestException(e, data);
        } finally {
            rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(),
                    System.currentTimeMillis() - startTime);
        }
        if (!tx.getRollbackOnly()) {
            tx.commit();
        }
    } catch (Exception ex) {
        log.error("Error creating EntityManager", ex);
        handleRequestException(ex, data);
    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public FStoreUser updateFStoreUser(FStoreUser bu) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w  w w .j  ava  2 s .c om
    FStoreUser resis = entityManager.merge(bu);
    entityTransaction.commit();

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public Category updateCategory(Category c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/* w ww. j  av a  2 s .  c om*/
    Category resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public FStoreProperty updateProperty(FStoreProperty p) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from ww w . j a  va2  s .  com*/
    FStoreProperty bp = entityManager.merge(p);
    entityTransaction.commit();

    return bp;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveProduct(Product prod) {
    logger.info("Will save Product = " + prod.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*  www.j av  a2  s.c om*/
    entityManager.persist(prod);
    entityManager.flush();
    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveCategory(Category c) {
    logger.info("Will category = " + c.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//w  w w  .j  a  v  a2  s.c  o m

    entityManager.persist(c);
    entityManager.flush();
    entityTransaction.commit();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveProperty(FStoreProperty p) {
    logger.info("Will FStoreProperty = " + p.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();// w  w w .j a  v a 2  s  .  c o  m

    entityManager.persist(p);
    entityManager.flush();
    entityTransaction.commit();

}