Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:org.apache.airavata.registry.core.experiment.catalog.ExpCatResourceUtils.java

public static ExperimentCatResource getUser(String userName, String gatewayId) throws RegistryException {
    EntityManager em = null;
    try {/*from  w  w  w.j ava2s.com*/
        if (isUserExist(userName, gatewayId)) {
            em = getEntityManager();
            UserPK userPK = new UserPK();
            userPK.setUserName(userName);
            userPK.setGatewayId(gatewayId);
            Users user = em.find(Users.class, userPK);
            UserResource userResource = (UserResource) Utils.getResource(ResourceType.USER, user);
            em.close();
            return userResource;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RegistryException(e);
    } finally {
        if (em != null && em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            em.close();
        }
    }
    return null;

}

From source file:org.apache.airavata.registry.core.experiment.catalog.ExpCatResourceUtils.java

/**
 * @param gatewayResource/*from www.j  a  va 2  s  . co m*/
 * @param userResource
 */
public static WorkerResource addGatewayWorker(GatewayResource gatewayResource, UserResource userResource)
        throws RegistryException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        if (!isGatewayExist(gatewayResource.getGatewayName())) {
            gatewayResource.save();
        }
        if (!isUserExist(userResource.getUserName(), gatewayResource.getGatewayId())) {
            userResource.save();
        }
        Gateway gateway = em.find(Gateway.class, gatewayResource.getGatewayId());
        GatewayWorker gatewayWorker = new GatewayWorker();
        gatewayWorker.setGateway(gateway);
        gatewayWorker.setUserName(userResource.getUserName());
        em.persist(gatewayWorker);
        em.getTransaction().commit();
        em.close();
        return (WorkerResource) Utils.getResource(ResourceType.GATEWAY_WORKER, gatewayWorker);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RegistryException(e);
    } finally {
        if (em != null && em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            em.close();
        }
    }
}

From source file:org.ejbca.core.ejb.ra.UserData.java

/** @return the found entity instance or null if the entity does not exist */
public static UserData findByUsername(EntityManager entityManager, String username) {
    if (username == null) {
        return null;
    }/*  www  . j a va  2s .  c  o  m*/
    return entityManager.find(UserData.class, username);
}

From source file:org.apache.juddi.config.Install.java

/**
 * Checks if there is a database with a root publisher. If it is not found
 * an/*from  w  w  w.  j av  a 2 s. c  o m*/
 * 
 * @param config
 * @return true if it finds a database with the root publisher in it.
 * @throws ConfigurationException
 */
protected static boolean alreadyInstalled(Configuration config) throws ConfigurationException {

    String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
    org.apache.juddi.model.Publisher publisher = null;
    int numberOfTries = 0;
    while (numberOfTries++ < 100) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            publisher = em.find(org.apache.juddi.model.Publisher.class, rootPublisherStr);
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
        if (publisher != null)
            return true;

        if (config.getBoolean(Property.JUDDI_LOAD_INSTALL_DATA, Property.DEFAULT_LOAD_INSTALL_DATA)) {
            log.debug("Install data not yet installed.");
            return false;
        } else {
            try {
                log.info("Install data not yet installed.");
                log.info("Going to sleep and retry...");
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    throw new ConfigurationException("Could not load the Root node data. Please check for errors.");
}

From source file:org.apache.airavata.persistance.registry.jpa.ResourceUtils.java

/**
 * @param gatewayResource//from w  ww .j  a v a2 s.  co m
 * @param userResource
 */
public static WorkerResource addGatewayWorker(GatewayResource gatewayResource, UserResource userResource)
        throws RegistryException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        if (!isGatewayExist(gatewayResource.getGatewayName())) {
            gatewayResource.save();
        }
        if (!isUserExist(userResource.getUserName())) {
            userResource.save();
        }
        Gateway gateway = em.find(Gateway.class, gatewayResource.getGatewayName());
        Users user = em.find(Users.class, userResource.getUserName());
        Gateway_Worker gatewayWorker = new Gateway_Worker();
        gatewayWorker.setGateway(gateway);
        gatewayWorker.setUser(user);
        em.persist(gatewayWorker);
        em.getTransaction().commit();
        em.close();
        return (WorkerResource) Utils.getResource(ResourceType.GATEWAY_WORKER, gatewayWorker);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RegistryException(e);
    } finally {
        if (em != null && em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            em.close();
        }
    }
}

From source file:nl.b3p.viewer.stripes.ApplicationActionBean.java

public static Resolution checkRestriction(ActionBeanContext context, Application application,
        EntityManager em) {

    String username = context.getRequest().getRemoteUser();
    User u = null;//from  ww w  .ja  v  a2 s .c o  m
    if (username != null) {
        Principal p = context.getRequest().getUserPrincipal();
        if (p instanceof User) {
            u = (User) p;
        } else {
            u = em.find(User.class, p.getName());
        }
    }
    if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em)
            && (username == null || u != null && u.isAuthenticatedByIp())) {
        RedirectResolution login = new RedirectResolution(LoginActionBean.class)
                .addParameter("name", application.getName()) // binded parameters not included ?
                .addParameter("version", application.getVersion()).includeRequestParameters(true);
        context.getRequest().getSession().invalidate();
        return login;
    } else if (!Authorizations.isApplicationReadAuthorized(application, context.getRequest(), em)
            && username != null) {
        ResourceBundle bundle = ResourceBundleProvider
                .getResourceBundle(determineLocaleForBundle(context, application));
        String msg = bundle.getString("viewer.applicationactionbean.norights");
        context.getValidationErrors().addGlobalError(new SimpleError(msg));
        context.getRequest().getSession().invalidate();
        return new ForwardResolution("/WEB-INF/jsp/error_retry.jsp");
    }
    return null;
}

From source file:org.opencastproject.messages.MailService.java

/**
 * Find the entity from the given type with the given id
 *
 * @param id//from   w w w . j ava  2 s  .  co  m
 *          the identifier of the entity to find
 * @param em
 *          The entity manager
 * @param entityClass
 *          The class of the type to find
 * @return an {@link org.opencastproject.util.data.Option option} object
 */
public static <A> Option<A> find(Option<Long> id, EntityManager em, Class<A> entityClass) {
    for (Long a : id) {
        return option(em.find(entityClass, a));
    }
    return none();
}

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Initialize a entity. //w  ww  . java2s  . c o m
 * @param em entity manager to use
 * @param entity entity to initialize
 * @param depth max depth on recursion
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void initialize(EntityManager em, Object entity, int depth) {
    // return on nulls, depth = 0 or already initialized objects
    if (entity == null || depth == 0) {
        return;
    }

    PersistenceUnitUtil unitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();
    EntityType entityType = em.getMetamodel().entity(entity.getClass());
    Set<Attribute> attributes = entityType.getDeclaredAttributes();

    Object id = unitUtil.getIdentifier(entity);

    if (id != null) {
        Object attached = em.find(entity.getClass(), unitUtil.getIdentifier(entity));

        for (Attribute a : attributes) {
            if (!unitUtil.isLoaded(entity, a.getName())) {
                if (a.isCollection()) {
                    intializeCollection(em, entity, attached, a, depth);
                } else if (a.isAssociation()) {
                    intialize(em, entity, attached, a, depth);
                }
            }
        }
    }
}

From source file:uk.co.threeonefour.ifictionary.web.user.dao.JpaUserDao.java

@Transactional
public User get(String id) {

    EntityManager em = entityManager;
    return em.find(User.class, id);
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static Run load(String resourceUri, EntityManager em) {
    Run run = em.find(Run.class, resourceUri);
    return run;//from  w w w. ja va 2 s .co m
}