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.noorganization.instalist.server.api.ProductResource.java

/**
 * Get a list of products./*ww w.j  a v a 2 s  . c o  m*/
 * @param _groupId The id of the group containing the products.
 * @param _changedSince Optional. Limits the request to the elements that changed since the
 *                      given date. ISO 8601 time e.g. "2016-01-19T11:54:07+0100".
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getProducts(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    List<Product> foundProducts;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (_changedSince != null) {
        Instant changedSince;
        try {
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
        } catch (ParseException _e) {
            manager.close();
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
        }

        TypedQuery<Product> foundProductsQuery = manager.createQuery(
                "select p from " + "Product p where p.group = :group and p.updated > :updated", Product.class);
        foundProductsQuery.setParameter("group", group);
        foundProductsQuery.setParameter("updated", changedSince);
        foundProducts = foundProductsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedListsQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and"
                        + " do.type = :type",
                DeletedObject.class);
        foundDeletedListsQuery.setParameter("group", group);
        foundDeletedListsQuery.setParameter("updated", changedSince);
        foundDeletedListsQuery.setParameter("type", DeletedObject.Type.PRODUCT);
        foundDeleted = foundDeletedListsQuery.getResultList();
    } else {
        TypedQuery<Product> foundProductsQuery = manager
                .createQuery("select p from " + "Product p where p.group = :group", Product.class);
        foundProductsQuery.setParameter("group", group);
        foundProducts = foundProductsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedProductsQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        foundDeletedProductsQuery.setParameter("group", group);
        foundDeletedProductsQuery.setParameter("type", DeletedObject.Type.PRODUCT);
        foundDeleted = foundDeletedProductsQuery.getResultList();
    }
    manager.close();

    ArrayList<ProductInfo> rtn = new ArrayList<ProductInfo>(foundProducts.size() + foundDeleted.size());
    for (Product current : foundProducts) {
        ProductInfo toAdd = new ProductInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setDefaultAmount(current.getDefaultAmount());
        toAdd.setStepAmount(current.getStepAmount());
        if (current.getUnit() != null)
            toAdd.setUnitUUID(current.getUnit().getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(false);
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        ProductInfo toAdd = new ProductInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

private JobInstance getRunningJI(int jobId) {
    EntityManager em = Helpers.getNewEm();
    JobInstance jj = null;/*from ww w  .  j a v a  2  s .  c om*/
    try {
        jj = em.find(JobInstance.class, jobId);
    } catch (Exception e) {
        throw new JqmRuntimeException("Could not query job instance", e);
    } finally {
        em.close();
    }
    return jj;
}

From source file:de.zib.gndms.infra.model.GridEntityModelHandler.java

/**
 * @param emParam the EntityManager to be used or null for an EM from this handler's system
 * @param id a resource id/*from   ww  w  .  j ava2  s  .co m*/
 * @return model with id id if included in database, null otherwise
 */
public final @Nullable M tryLoadModelById(final EntityManager emParam, final @NotNull String id) {
    final @NotNull Class<M> curModelClass = getModelClass();
    return txRun(emParam, new Function<EntityManager, M>() {
        public M apply(@com.google.common.base.Nullable @NotNull EntityManager entityManager) {
            return entityManager.find(curModelClass, id);
        }
    });
}

From source file:fr.amapj.service.services.meslivraisons.MesLivraisonsService.java

/**
 * Retourne la liste des livraisons pour le producteur spcifi 
 *//*from   w  w w . j  a  va 2 s. c o m*/
@DbRead
public MesLivraisonsDTO getLivraisonProducteur(Date d, Long idProducteur) {
    EntityManager em = TransactionHelper.getEm();

    MesLivraisonsDTO res = new MesLivraisonsDTO();

    Producteur producteur = em.find(Producteur.class, idProducteur);

    res.dateDebut = fr.amapj.common.DateUtils.firstMonday(d);
    res.dateFin = DateUtils.addDays(res.dateDebut, 6);

    // On rcupre ensuite la liste de tous les cellules de contrats de cet utilisateur dans cet intervalle
    List<ContratCell> cells = getAllQte(em, res.dateDebut, res.dateFin, producteur);

    //
    for (ContratCell cell : cells) {
        addCell(cell, res);
    }

    return res;

}

From source file:nl.b3p.kaartenbalie.struts.AccountingAction.java

private Organization getOrganization(DynaValidatorForm dynaForm, HttpServletRequest request) throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    Organization organization = null;//w  ww.j av  a  2 s .co  m
    Integer id = getID(dynaForm);

    if (id == null) {
        User principalUser = (User) request.getUserPrincipal();
        if (principalUser == null) {
            return null;
        }
        User user = (User) em.find(User.class, principalUser.getId());
        if (user == null) {
            return null;
        }
        organization = user.getMainOrganization();
    } else {
        organization = (Organization) em.find(Organization.class, id);
    }

    return organization;
}

From source file:org.noorganization.instalist.server.api.CategoriesResource.java

/**
 * Get a list of categories./*from w  w w  .j  a v  a2 s. co m*/
 *
 * @param _groupId The id of the group.
 * @param _changedSince Optional. Requests only the elements that changed since the given date.
 *                      ISO 8601 time e.g. 2016-01-19T11:54:07+01:00
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getCategories(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    try {

        Instant changedSince = null;
        if (_changedSince != null) {
            try {
                changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
            } catch (ParseException _e) {
                return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);
            }
        }

        List<Category> categories;
        List<DeletedObject> deletedCategories;
        EntityManager manager = DatabaseHelper.getInstance().getManager();
        DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

        if (changedSince != null) {
            TypedQuery<Category> categoriesQuery = manager.createQuery(
                    "select c from Category c " + "where c.group = :groupid and c.updated > :updated",
                    Category.class);
            categoriesQuery.setParameter("groupid", group);
            categoriesQuery.setParameter("updated", changedSince);
            categories = categoriesQuery.getResultList();

            TypedQuery<DeletedObject> deletedCategoriesQuery = manager
                    .createQuery("select do " + "from DeletedObject do where do.group = :groupid and "
                            + "do.type = :type and do.updated > :updated", DeletedObject.class);
            deletedCategoriesQuery.setParameter("groupid", group);
            deletedCategoriesQuery.setParameter("updated", changedSince);
            deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
            deletedCategories = deletedCategoriesQuery.getResultList();
        } else {
            TypedQuery<Category> categoriesQuery = manager
                    .createQuery("select c from Category c " + "where c.group = :groupid", Category.class);
            categoriesQuery.setParameter("groupid", group);
            categories = categoriesQuery.getResultList();

            TypedQuery<DeletedObject> deletedCategoriesQuery = manager.createQuery(
                    "select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type",
                    DeletedObject.class);
            deletedCategoriesQuery.setParameter("groupid", group);
            deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
            deletedCategories = deletedCategoriesQuery.getResultList();
        }
        manager.close();

        List<CategoryInfo> rtnPayload = new ArrayList<CategoryInfo>(
                categories.size() + deletedCategories.size());
        for (Category currentCat : categories) {
            CategoryInfo info = new CategoryInfo();
            info.setUUID(currentCat.getUUID());
            info.setName(currentCat.getName());
            info.setLastChanged(Date.from(currentCat.getUpdated()));
            info.setDeleted(false);
            rtnPayload.add(info);
        }
        for (DeletedObject currentCat : deletedCategories) {
            CategoryInfo info = new CategoryInfo();
            info.setUUID(currentCat.getUUID());
            info.setLastChanged(Date.from(currentCat.getUpdated()));
            info.setDeleted(true);
            rtnPayload.add(info);
        }

        return ResponseFactory.generateOK(rtnPayload);
    } catch (Exception _e) {
        _e.printStackTrace();
        throw _e;
    }
}

From source file:org.noorganization.instalist.server.api.TagResource.java

/**
 * Get a single tag./* w w w  .java2  s  .  c  o m*/
 * @param _groupId The id of the group containing the tag.
 * @param _tagUUID The uuid of the requested tag.
 */
@GET
@TokenSecured
@Path("{taguuid}")
@Produces({ "application/json" })
public Response getTag(@PathParam("groupid") int _groupId, @PathParam("taguuid") String _tagUUID)
        throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_tagUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITagController tagController = ControllerFactory.getTagController(manager);
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    Tag current = tagController.findByGroupAndUUID(group, toFind);
    if (current == null) {
        if (tagController.findDeletedByGroupAndUUID(group, toFind) == null) {
            manager.close();
            return ResponseFactory.generateNotFound(new Error().withMessage("Tag was not " + "found."));
        }
        manager.close();
        return ResponseFactory.generateGone(new Error().withMessage("Tag was deleted " + "before."));
    }
    manager.close();

    TagInfo rtn = new TagInfo().withDeleted(false);
    rtn.setUUID(current.getUUID());
    rtn.setName(current.getName());
    rtn.setLastChanged(Date.from(current.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

From source file:fr.amapj.service.services.meslivraisons.MesLivraisonsService.java

/**
 * Permet de charger la liste de tous les livraisons
 * dans une transaction en lecture/* w  w  w.  j  a  va2 s.  c  om*/
 */
@DbRead
public MesLivraisonsDTO getMesLivraisons(Date d, List<RoleList> roles, Long idUtilisateur) {
    EntityManager em = TransactionHelper.getEm();

    MesLivraisonsDTO res = new MesLivraisonsDTO();

    Utilisateur user = em.find(Utilisateur.class, idUtilisateur);

    res.dateDebut = fr.amapj.common.DateUtils.firstMonday(d);
    res.dateFin = DateUtils.addDays(res.dateDebut, 6);

    // On rcupre ensuite la liste de tous les cellules de contrats de cet utilisateur dans cet intervalle
    List<ContratCell> cells = getAllQte(em, res.dateDebut, res.dateFin, user);

    //
    for (ContratCell cell : cells) {
        addCell(cell, res);
    }

    // On rcupre ensuite la liste de toutes les permanences de cet utilisateur dans cet intervalle
    List<DatePermanence> dds = getAllDistributionsForUtilisateur(em, res.dateDebut, res.dateFin, user);
    for (DatePermanence dd : dds) {
        addDistribution(em, dd, res);
    }

    // On rcupre ensuite le planning mensuel si il y en a un
    res.planningMensuel = computePlanningMensuel(em, res.dateDebut, res.dateFin, roles);

    return res;

}

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   w ww .  j a  v a  2  s .co  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.noorganization.instalist.server.api.TagResource.java

/**
 * Get a list of tags./*from   www  . j a  v  a2s  .  co  m*/
 * @param _groupId The id of the group containing the tags.
 * @param _changedSince Limits the request to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100. Optional.
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getTags(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    List<Tag> tags;
    List<DeletedObject> deletedTags;
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (changedSince != null) {
        TypedQuery<Tag> tagQuery = manager.createQuery(
                "select t from Tag t where " + "t.group = :group and t.updated > :updated", Tag.class);
        tagQuery.setParameter("group", group);
        tagQuery.setParameter("updated", changedSince);
        tags = tagQuery.getResultList();

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("updated", changedSince);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    } else {
        tags = new ArrayList<Tag>(group.getTags());

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    }
    manager.close();

    ArrayList<TagInfo> rtn = new ArrayList<TagInfo>(tags.size() + deletedTags.size());
    for (Tag current : tags) {
        TagInfo toAdd = new TagInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedTags) {
        TagInfo toAdd = new TagInfo().withDeleted(true);
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}