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:org.apache.juddi.v3.auth.LdapSimpleAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/*from ww  w . j  av  a 2  s .  c o  m*/

    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;
        logger.error("config exception! " + authorizedName, ex);
    }
    boolean isLdapUser = false;
    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));
        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        env.put(Context.SECURITY_PRINCIPAL, authorizedName);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher 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();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

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

public void getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID,
        Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  ww  w .  j a va  2  s  .  c  o  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag);

        int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS;
        try {
            transferExpirationDays = AppConfig.getConfiguration()
                    .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS);
            // For output
            nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
        } catch (ConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
        }

        String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID();
        org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken();
        transferToken.setTransferToken(transferKey);
        // For output
        opaqueToken.value = transferKey.getBytes();

        GregorianCalendar gc = new GregorianCalendar();
        gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays);

        transferToken.setExpirationDate(gc.getTime());

        try {
            DatatypeFactory df = DatatypeFactory.newInstance();
            // For output
            expirationTime.value = df.newXMLGregorianCalendar(gc);
        } catch (DatatypeConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
        }

        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key);
            transferToken.getTransferKeys().add(tokenKey);
        }

        em.persist(transferToken);

        tx.commit();

        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

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

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default persist/*from  w ww.ja va2 s.  co m*/
 * 
 * @param obj
 *            object to persist
 * @throws PersistException
 *             on errors (transaction is being rolled back)
 */
public void persist(T obj) throws PersistException {
    if (obj == null) {
        return;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        em.persist(obj);
        t.commit();
    } catch (Exception e) {
        t.rollback();
        throw new PersistException(e.getMessage(), e);
    }
}

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

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }//from  ww  w  .  j a  v  a  2s.  co m

    boolean isLdapUser = false;

    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;
        logger.error("config exception! " + authorizedName, ex);
    }

    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));

        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        String format = String.format(
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR),
                authorizedName);

        env.put(Context.SECURITY_PRINCIPAL, format);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher 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();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default merge//from  www  . ja v a  2s.c o  m
 * 
 * @param obj
 *            object to merge
 * @throws MergeException
 *             on errors (transaction is being rolled back)
 * @return managed object
 */
public T merge(T obj) throws MergeException {
    if (obj == null) {
        return null;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        obj = em.merge(obj);
        t.commit();
        return obj;
    } catch (Exception e) {
        t.rollback();
        throw new MergeException("Cannot merge changes to " + String.valueOf(obj) + " into the database", e);
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default persist//  w  w  w.j  a v a 2 s .c  o m
 * 
 * @param objs
 *            objects to persist
 * @throws PersistException
 *             on errors (transaction is being rolled back)
 */
public void persist(Collection<T> objs) throws PersistException {
    if (objs == null || objs.isEmpty()) {
        return;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            em.persist(obj);
        }
        t.commit();
    } catch (Exception e) {
        t.rollback();
        throw new PersistException(e.getMessage(), e);
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * //from   ww w. j  av  a  2 s .co  m
 * @param obj
 *            object to remove
 * @return remove object
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public T remove(T obj) throws Exception {
    if (obj == null) {
        return null;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        T tmp = em.contains(obj) ? obj : em.merge(obj);
        em.remove(tmp);
        t.commit();
        return tmp;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}//from  w  ww  .j  av a  2 s.  co m
 */
@Override
public void saveUser(User user) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    em.persist(user);
    tx.commit();
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}// w  w  w .  j ava2s  .c  o  m
 */
@Override
public LoginHistory addLoginHistory(User user, Date loginDate, Date logoutDate) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    LoginHistory history = user.addLoginHistory(loginDate, logoutDate);
    tx.commit();
    return history;
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default merge//from w w w  . jav a2s  . c om
 * 
 * @param objs
 *            objects to merge
 * @return list of merged/managed objects
 * @throws MergeException
 *             on errors (transaction is being rolled back)
 */
public Collection<T> merge(Collection<T> objs) throws MergeException {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    final Collection<T> tmp = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            tmp.add(em.merge(obj));
        }
        t.commit();
        return tmp;
    } catch (Exception e) {
        t.rollback();
        throw new MergeException("Cannot merge changes to " + String.valueOf(objs) + " into the database", e);
    }
}