Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

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

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@PUT
@Path("{username}.json")
@RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = {
        @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") })
public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) {
    JSONArray rolesArray = (JSONArray) JSONValue.parse(roles);
    EntityManager em = null;
    EntityTransaction tx = null;//w w  w.  java 2s .com
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing user
        Query q = em.createNamedQuery("user");
        q.setParameter("u", username);
        q.setParameter("o", securityService.getOrganization().getId());
        JpaUser jpaUser = null;
        try {
            jpaUser = (JpaUser) q.getSingleResult();
            jpaUser.roles.clear();
            for (Object role : rolesArray) {
                jpaUser.roles.add((String) role);
            }
            em.merge(jpaUser);
        } catch (NoResultException e) {
            return null; // this will be translated into a 404
        }
        tx.commit();
        return Response.noContent().build();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.rhq.enterprise.server.core.CoreServerServiceImpl.java

/**
 * @see CoreServerService#getLatestPlugins()
 */// w ww .j  ava 2s . co  m
@SuppressWarnings("unchecked")
@Override
public List<Plugin> getLatestPlugins() {
    EntityManager em = null;
    List<Plugin> plugins = new ArrayList<Plugin>();

    try {
        em = LookupUtil.getEntityManager();
        Query q = em.createNamedQuery(Plugin.QUERY_FIND_ALL_INSTALLED);
        List<Plugin> resultList = q.getResultList();
        for (Plugin potentialPlugin : resultList) {
            if (potentialPlugin.isEnabled()) {
                plugins.add(potentialPlugin);
            }
        }
    } catch (Exception e) {
        log.warn("Failed to get the list of latest plugins", e);
        throw new WrappedRemotingException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }

    return plugins;
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Get all user settings based upon its key.
 * @param key The key to search for.//from   w  w w  . j  a v  a 2  s  .  c  om
 * @return A {@link UserSettingDto} that matches the key.
 * @throws UserSettingsServiceException
 */
private List<UserSettingDto> getUserSettingsByKey(String key) throws UserSettingsServiceException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        logger.debug("Getting user settings for '%s' in org '%s'", username, orgId);
        Query q = em.createNamedQuery("UserSettings.findByKey").setParameter("key", key)
                .setParameter("username", username).setParameter("org", orgId);
        List<UserSettingDto> result = q.getResultList();
        if (result.size() == 0) {
            logger.debug("Found no user settings.");
            return null;
        }

        return result;
    } catch (Exception e) {
        logger.error("Could not get user setting: {}", ExceptionUtils.getStackTrace(e));
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

/**
 * Loads all <tt>ConfigletStates</tt> managed by a specific <tt>EntityManager</tt> into an array.
 *
 * <p>Performs the query "listAllConfiglets" on the database and returns an array containing the result.
 *
 * @param emParam an EntityManager managing ConfigletStates
 * @return an array containing all ConfigletStates of the database
 *//*from w w  w . j a  v  a2 s. c o m*/
@SuppressWarnings({ "unchecked", "JpaQueryApiInspection", "MethodMayBeStatic" })
private synchronized ConfigletState[] loadConfigletStates(final EntityManager emParam) {
    final ConfigletState[] states;
    emParam.getTransaction().begin();
    try {
        Query query = emParam.createNamedQuery("listAllConfiglets");
        final List<ConfigletState> list = (List<ConfigletState>) query.getResultList();
        Object[] states_ = list.toArray();
        states = new ConfigletState[states_.length];
        for (int i = 0; i < states_.length; i++)
            states[i] = (ConfigletState) states_[i];
        return states;
    } finally {
        if (emParam.getTransaction().isActive())
            emParam.getTransaction().commit();
    }
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * @param offset//ww  w .  j ava2s . co  m
 *          The number of limits to page to.
 * @param limit
 *          The maximum number of settings to return.
 * @return Find all of the user settings for the current user.
 * @throws UserSettingsServiceException
 *           Thrown if there is a problem getting the user settings.
 */
private UserSettings getUserSettings(int limit, int offset) throws UserSettingsServiceException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        logger.debug("Getting user settings for '%s' in org '%s'", username, orgId);
        Query q = em.createNamedQuery("UserSettings.findByUserName").setParameter("username", username)
                .setParameter("org", orgId).setMaxResults(limit).setFirstResult(offset);
        List<UserSettingDto> result = q.getResultList();
        if (result.size() == 0) {
            logger.debug("Found no user settings.");
        }
        UserSettings userSettings = new UserSettings();
        for (UserSettingDto userSettingsDto : result) {
            UserSetting userSetting = userSettingsDto.toUserSetting();
            logger.debug("Found user setting id: %d key: %s value: %s", userSetting.getId(),
                    userSetting.getKey().toString(), userSetting.getValue().toString());
            userSettings.addUserSetting(userSetting);
        }
        return userSettings;
    } catch (Exception e) {
        logger.error("Could not get user settings: %s", ExceptionUtils.getStackTrace(e));
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * Gets an agent by name and organization, using an open entitymanager.
 * // w ww. j  a  va2 s .c  o  m
 * @param name
 *          the unique agent name
 * @param org
 *          the organization
 * @param em
 *          the entity manager
 * @return the agent or <code>null</code> if no agent has been found
 */
protected AgentImpl getAgentEntity(String name, String organization, EntityManager em) {
    try {
        Query q = em.createNamedQuery("Agent.get");
        q.setParameter("id", name);
        q.setParameter("org", organization);
        return (AgentImpl) q.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:in.bookmylab.jpa.JpaDAO.java

public void saveSpmBooking(SpmLabBooking spm) throws AppException {
    EntityManager em = emf.createEntityManager();
    try {// ww w  .j a  v a2s  . co  m
        em.getTransaction().begin();
        if (spm.spmId == null) {
            em.persist(spm);
            fixAnalysisModesAndResourceType(spm.booking, em, false);
        } else {
            // Validate status change, if any
            Query q = em.createNamedQuery("ResourceBooking.findById");
            ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", spm.booking.bookingId)
                    .getSingleResult();
            if (!statusChangeValid(rb.status, spm.booking.status)) {
                throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status,
                        spm.booking.status));
            }

            fixAnalysisModesAndResourceType(spm.booking, em, true);
            em.merge(spm);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:in.bookmylab.jpa.JpaDAO.java

public void saveXrdBooking(XrdLabBooking xrd) throws AppException {
    EntityManager em = emf.createEntityManager();
    try {//from   w w w  .  j  a  v  a2  s .  co m
        em.getTransaction().begin();
        if (xrd.xrdId == null) {
            em.persist(xrd);
            fixAnalysisModesAndResourceType(xrd.booking, em, false);
        } else {
            // Validate status change, if any
            Query q = em.createNamedQuery("ResourceBooking.findById");
            ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", xrd.booking.bookingId)
                    .getSingleResult();
            if (!statusChangeValid(rb.status, xrd.booking.status)) {
                throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status,
                        xrd.booking.status));
            }

            fixAnalysisModesAndResourceType(xrd.booking, em, true);
            em.merge(xrd);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

private int getTotal() {
    EntityManager em = null;
    try {//from w  w  w .  j a va 2  s  .  c om
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("findTotal");
        return ((Long) q.getSingleResult()).intValue();
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public int getViews(String mediapackageId) {
    EntityManager em = null;
    try {/*  www  . j  ava 2s . c  o  m*/
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("countSessionsOfMediapackage");
        q.setParameter("mediapackageId", mediapackageId);
        return ((Long) q.getSingleResult()).intValue();
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}