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:de.zib.gndms.dspace.service.SliceKindServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/config", method = RequestMethod.POST)
@Secured("ROLE_ADMIN")
public final ResponseEntity<Integer> setSliceKindConfig(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, final Configuration config, final String dn) {
    GNDMSResponseHeader headers = getResponseHeaders(subspaceId, sliceKindId, dn);

    SliceKindConfiguration sliceKindConfig = SliceKindConfiguration.checkSliceKindConfig(config);

    // TODO: put that to sliceKindProvider
    EntityManager entityManager = emf.createEntityManager();
    final TxFrame txf = new TxFrame(entityManager);
    try {/* w  w  w  . j  ava  2s  . c o m*/
        final SliceKind sliceKind = entityManager.find(SliceKind.class, sliceKindId);
        sliceKind.setPermission(sliceKindConfig.getPermission());
        txf.commit();
    } finally {
        txf.finish();
    }
    sliceKindProvider.invalidate(sliceKindId);

    Specifier<Void> spec = new Specifier<Void>();

    HashMap<String, String> urimap = new HashMap<String, String>(2);
    urimap.put("service", "dspace");
    urimap.put(UriFactory.SUBSPACE, subspaceId);
    urimap.put(UriFactory.SLICE_KIND, sliceKindId);
    spec.setUriMap(new HashMap<String, String>(urimap));
    spec.setUrl(uriFactory.quoteUri(urimap));

    return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
}

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 w  ww  .  j av a2s .  c o 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:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/* w ww  . j  av  a  2 s . co m*/
 */
@Override
public User getUserById(String userId) {
    try {
        EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
                .getEntityManager();
        Long id = Long.parseLong(userId);
        User user = em.find(User.class, id);
        return user;
    } catch (NumberFormatException e) {
        return null;
    }
}

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

/**
 * Get a single recipe./*  ww w.  ja  v  a 2  s. co m*/
 * @param _groupId The id of the group containing the recipe.
 * @param _recipeUUID The uuid of the requested recipe.
 */
@GET
@TokenSecured
@Path("{recipeuuid}")
@Produces({ "application/json" })
public Response getRecipe(@PathParam("groupid") int _groupId, @PathParam("recipeuuid") String _recipeUUID)
        throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_recipeUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IRecipeController recipeController = ControllerFactory.getRecipeController(manager);
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

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

    return ResponseFactory.generateOK(rtn);
}

From source file:org.sigmah.server.servlet.exporter.models.ProjectReportModelHandler.java

@Override
public String exportModel(OutputStream outputStream, String identifier, EntityManager em) throws Exception {

    String name = "";

    if (identifier != null) {
        final Integer projectReportModelId = Integer.parseInt(identifier);

        final ProjectReportModel hibernateModel = em.find(ProjectReportModel.class, projectReportModelId);

        if (hibernateModel == null)
            throw new ExportException(
                    "No project report model is associated with the identifier '" + identifier + "'.");

        name = hibernateModel.getName();

        // Stripping hibernate proxies from the model.
        final ProjectReportModel realModel = Realizer.realize(hibernateModel);
        // Serialization
        try {// w  ww  .  jav a2  s .co m
            final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(realModel);
        } catch (Exception ex) {
            throw new Exception("An error occured while serializing the project model " + projectReportModelId,
                    ex);
        }

    } else {
        throw new Exception("The identifier is missing.");
    }

    return name;
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectReportModelHandler.java

@Override
public String exportModel(OutputStream outputStream, String identifier, EntityManager em)
        throws ExportException {

    String name = "";

    if (identifier != null) {
        final Integer projectReportModelId = Integer.parseInt(identifier);

        final ProjectReportModel hibernateModel = em.find(ProjectReportModel.class, projectReportModelId);

        if (hibernateModel == null)
            throw new ExportException(
                    "No project report model is associated with the identifier '" + identifier + "'.");

        name = hibernateModel.getName();

        // Stripping hibernate proxies from the model.
        final ProjectReportModel realModel = Realizer.realize(hibernateModel);

        // Serialization
        try {/* w w w  .  ja  v a 2s .  c  o  m*/
            final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(realModel);

        } catch (IOException ex) {
            throw new ExportException(
                    "An error occured while serializing the project model " + projectReportModelId, ex);
        }

    } else {
        throw new ExportException("The identifier is missing.");
    }

    return name;
}

From source file:com.headissue.pigeon.survey.answer.AnswerSurveyTest.java

<T> T find(Class<T> type, Object key) {
    EntityManager manager = factory.createEntityManager();
    try {//from   w  w  w  .  j  av  a  2  s .  c o  m
        return manager.find(type, key);
    } finally {
        manager.close();
    }
}

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

/**
 * Get a list of recipes./*from w  w  w  .j  a va 2  s  .c om*/
 * @param _groupId The id of the group containing the recipes.
 * @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 getRecipes(@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<Recipe> recipes;
    List<DeletedObject> deletedRecipes;
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (changedSince != null) {
        TypedQuery<Recipe> recipeQuery = manager.createQuery(
                "select r from Recipe r where " + "r.group = :group and r.updated > :updated", Recipe.class);
        recipeQuery.setParameter("group", group);
        recipeQuery.setParameter("updated", changedSince);
        recipes = recipeQuery.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.RECIPE);
        deletedRecipes = deletedRecipesQuery.getResultList();
    } else {
        recipes = new ArrayList<Recipe>(group.getRecipes());

        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.RECIPE);
        deletedRecipes = deletedRecipesQuery.getResultList();
    }
    manager.close();

    ArrayList<RecipeInfo> rtn = new ArrayList<RecipeInfo>(recipes.size() + deletedRecipes.size());
    for (Recipe current : recipes) {
        RecipeInfo toAdd = new RecipeInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedRecipes) {
        RecipeInfo toAdd = new RecipeInfo().withDeleted(true);
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

From source file:com.gigglinggnus.controllers.CheckinController.java

/**
 *
 * @param request servlet request/* ww w.  j  a v  a 2  s  .  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String msg = request.getParameter("msg");
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));
    Term term = Term.getTermforInstant(em, Instant.now(clk));
    if (msg.equals("get_appointments")) {
        String userId = request.getParameter("username");
        User user = em.find(User.class, userId);

        JSONArray json = getAppointments(user, term, clk);
        response.getWriter().write(json.toString());
    } else if (msg.equals("do_checkin")) {
        String userId = request.getParameter("username");
        String examId = request.getParameter("examid");
        User admin = (User) (request.getSession().getAttribute("user"));
        User student = em.find(User.class, userId);
        Exam exam = em.find(Exam.class, examId);

        Appointment appt = student.getAppointmentByExam(exam);
        em.getTransaction().begin();
        admin.checkInStudent(appt);
        em.persist(appt);
        em.persist(student);
        em.getTransaction().commit();

        JSONArray json = getAppointments(student, term, clk);
        response.getWriter().write(json.toString());
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

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

@Override
public Long getRunTimeSeconds() {
    if (this.job.getExecutionDate() == null) {
        EntityManager em2 = Helpers.getNewEm();
        this.job.setExecutionDate(em2.find(JobInstance.class, this.job.getId()).getExecutionDate());
        em2.close();//  w w  w.ja va2s .  c  om
    }
    if (this.job.getExecutionDate() == null) {
        return 0L;
    }
    return (Calendar.getInstance().getTimeInMillis() - this.job.getExecutionDate().getTimeInMillis()) / 1000;
}