Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction begin.

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

From source file:com.appdynamicspilot.persistence.BasePersistenceImpl.java

@Transactional
public void save(final Serializable object) {
    EntityManager entityManager = getEntityManager();
    EntityTransaction txn = entityManager.getTransaction();
    txn.begin();
    try {//from ww  w .ja v a 2  s  . c o m
        entityManager.persist(object);
    } catch (Exception ex) {
        logger.error(ex);
        txn.rollback();
    } finally {
        if (!txn.getRollbackOnly()) {
            txn.commit();
        }
    }

}

From source file:org.spc.ofp.tubs.domain.common.CommonRepository.java

public boolean saveImportStatus(final ImportStatus status) {
    boolean success = false;
    final EntityManager mgr = emf.createEntityManager();
    final EntityTransaction xa = mgr.getTransaction();
    xa.begin();
    try {/*from   w  w  w  .java2  s.c o  m*/
        if (status.getId() > 0L) {
            mgr.merge(status);
        } else {
            mgr.persist(status);
        }
        xa.commit();
        success = true;
    } catch (Exception ignoreMe) {
        rollbackQuietly(xa);
    } finally {
        mgr.close();
    }
    return success;
}

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();

    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();/*from w  w w. ja  v a2 s. c o m*/

    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:it.infn.ct.futuregateway.apiserver.resources.observers.TaskObserver.java

@Override
public final void update(final Observable obs, final Object arg) {
    if (!(obs instanceof Task)) {
        log.error("Wrong abject associated with the oserver");
    }/*from   w ww  .  j  a  v a  2  s . c  o m*/
    Task t = (Task) obs;
    if (t.getId() == null || t.getStatus() == null) {
        return;
    }
    log.debug("Task " + t.getId() + " updated");
    if (t.getStatus().equals(Task.STATUS.WAITING) && t.getApplicationDetail() != null) {
        if (t.getInputFiles() != null) {
            for (TaskFile tf : t.getInputFiles()) {
                if (tf.getStatus().equals(TaskFile.FILESTATUS.NEEDED)) {
                    return;
                }
            }
        }
        t.setStatus(Task.STATUS.READY);
        submit(t);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction et = em.getTransaction();
    try {
        et.begin();
        em.merge(t);
        et.commit();
    } catch (RuntimeException re) {
        log.error("Impossible to update the task!");
        log.error(re);
        if (et != null && et.isActive()) {
            et.rollback();
        }
    } finally {
        em.close();
    }
}

From source file:br.com.blackhouse.internet.bindings.intercept.TransactionalInterceptor.java

@AroundInvoke
public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction transaction = entityManager.getTransaction();

    try {//from  ww  w. ja va 2  s. c  o  m
        if (!transaction.isActive()) {
            transaction.begin();
        }

        return context.proceed();

    } catch (Exception e) {
        logger.error("Exception in transactional method call", e);

        if (transaction != null) {
            transaction.rollback();
        }

        throw e;

    } finally {
        if (transaction != null && transaction.isActive()) {
            transaction.commit();
        }
    }

}

From source file:org.apache.juddi.v3.auth.JUDDIAuthenticator.java

/**
* @return the userId that came in on the request providing the user has
 * a publishing account in jUDDI.// w  ww  .jav a2s.  c  o m
* @param authorizedName
* @param credential
* @return authorizedName
* @throws AuthenticationException 
*/
public String authenticate(String authorizedName, String credential) throws AuthenticationException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!");
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! " + authorizedName, ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null) {
            log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(authorizedName);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }
        return authorizedName;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public Object create(ODataUri uri, Object entity, EntityDataModel entityDataModel) throws ODataException {
    Object jpaEntity = entityMapper.convertODataEntityToDS(entity, entityDataModel);
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {//from   ww  w . j av a2  s. co m
        transaction.begin();

        LOG.info("Persisting entity: {}", jpaEntity);
        entityManager.persist(jpaEntity);

        return entityMapper.convertDSEntityToOData(jpaEntity, entity.getClass(), entityDataModel);
    } finally {
        if (transaction.isActive()) {
            transaction.commit();
        } else {
            transaction.rollback();
        }
    }
}

From source file:org.apache.juddi.v3.auth.XMLDocAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   w  w  w  . ja  va 2 s.  c om
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));

        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:org.apache.juddi.api.impl.UDDISubscriptionListenerImpl.java

@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage {
    try {//w w  w. j av a  2  s  .  c o m
        JAXBContext context = JAXBContext.newInstance(body.getClass());
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(body, sw);

        logger.info("Notification received by UDDISubscriptionListenerService : " + sw.toString());

        @SuppressWarnings("rawtypes")
        NotificationList nl = NotificationList.getInstance();
        nl.getNotifications().add(sw.toString());

        org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null;

        //find the clerks to go with this subscription
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();

            this.getEntityPublisher(em, body.getAuthInfo());
            String subscriptionKey = body.getSubscriptionResultsList().getSubscription().getSubscriptionKey();
            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }
            apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }

        XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(), apiClientSubscriptionInfo.getToClerk(),
                body.getSubscriptionResultsList());

    } catch (JAXBException jaxbe) {
        logger.error("", jaxbe);
        throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client"));
    }

    new ValidateSubscriptionListener().validateNotification(body);

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);
    return dr;
}

From source file:org.apache.openjpa.persistence.event.TestBeforeCommit.java

@Override
public void setUp() throws Exception {
    if (emf == null) {
        emf = createEMF(AnEntity.class);
    }//www.java2 s  .c  o  m
    dict = ((JDBCConfiguration) emf.getConfiguration()).getDBDictionaryInstance();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tran = em.getTransaction();

    tran.begin();
    em.createQuery("Delete from AnEntity").executeUpdate();
    tran.commit();

    tran.begin();
    ae = new AnEntity();
    ae.setId(PKID);
    ae.setName("");
    em.persist(ae);
    tran.commit();
    em.close();
}