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:op.users.PnlUser.java

private java.util.List<Component> addCommands() {

    java.util.List<Component> list = new ArrayList<Component>();

    /***/*from w w w  . j av a2 s  .  c om*/
     *         _       _     _ _   _
     *        / \   __| | __| | | | |___  ___ _ __
     *       / _ \ / _` |/ _` | | | / __|/ _ \ '__|
     *      / ___ \ (_| | (_| | |_| \__ \  __/ |
     *     /_/   \_\__,_|\__,_|\___/|___/\___|_|
     *
     */
    final JideButton btnAddUser = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddUser"),
            SYSConst.icon22addUser, null);
    btnAddUser.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (tabMain.getSelectedIndex() != TAB_USER) {
                tabMain.setSelectedIndex(TAB_USER);
            }
            new DlgUser(new Users(), new Closure() {
                @Override
                public void execute(Object o) {
                    if (o != null) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            Users user = em.merge((Users) o);
                            // Put everyone into >>everyone<<
                            Groups everyone = em.find(Groups.class, "everyone");
                            em.lock(everyone, LockModeType.OPTIMISTIC);
                            user.getGroups().add(everyone);
                            everyone.getMembers().add(user);

                            em.getTransaction().commit();
                            lstUsers.add(user);
                            reloadDisplay();
                        } catch (Exception e) {
                            em.getTransaction().rollback();
                        } finally {
                            em.close();
                        }
                    }
                }
            });

        }
    });
    list.add(btnAddUser);

    /***
     *         _       _     _  ____
     *        / \   __| | __| |/ ___|_ __ ___  _   _ _ __
     *       / _ \ / _` |/ _` | |  _| '__/ _ \| | | | '_ \
     *      / ___ \ (_| | (_| | |_| | | | (_) | |_| | |_) |
     *     /_/   \_\__,_|\__,_|\____|_|  \___/ \__,_| .__/
     *                                              |_|
     */
    final JideButton btnAddGroup = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddGroup"),
            SYSConst.icon22addGroup, null);
    btnAddGroup.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (tabMain.getSelectedIndex() != TAB_GROUPS) {
                tabMain.setSelectedIndex(TAB_GROUPS);
            }
            new DlgGroup(new Groups(), new Closure() {
                @Override
                public void execute(Object o) {
                    if (o != null) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            Groups myGroup = em.merge((Groups) o);
                            em.getTransaction().commit();
                            createCP4(myGroup);
                            lstGroups.add(myGroup);
                            Collections.sort(lstGroups);
                            buildPanel();
                        } catch (Exception e) {
                            //                                em.getTransaction().rollback();
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                }
            });

        }
    });
    list.add(btnAddGroup);

    /***
     *      _     _         ____       _       _
     *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
     *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
     *     | |_) | |_| | | |  __/| |  | | | | | |_
     *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
     *
     */
    //        JideButton btnPrint = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.print"), SYSConst.icon22print2, new ActionListener() {
    //            @Override
    //            public void actionPerformed(ActionEvent actionEvent) {
    //
    //            }
    //        });
    //        list.add(btnPrint);

    return list;
}

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

/**
 * Deletes publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required.
 *
 * @param body/*from  w w  w.ja v  a 2 s.  c o  m*/
 * @throws DispositionReportFaultMessage
 */
public void deletePublisher(DeletePublisher body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateDeletePublisher(em, body);

        List<String> entityKeyList = body.getPublisherId();
        for (String entityKey : entityKeyList) {
            Publisher obj = em.find(org.apache.juddi.model.Publisher.class, entityKey);

            //get an authtoken for this publisher so that we can get its registeredInfo
            UDDISecurityImpl security = new UDDISecurityImpl();
            AuthToken authToken = security.getAuthToken(entityKey);

            GetRegisteredInfo r = new GetRegisteredInfo();
            r.setAuthInfo(authToken.getAuthInfo());
            r.setInfoSelection(InfoSelection.ALL);

            log.info("removing all businesses owned by publisher " + entityKey + ".");
            UDDIPublicationImpl publish = new UDDIPublicationImpl();
            RegisteredInfo registeredInfo = publish.getRegisteredInfo(r);
            BusinessInfos businessInfos = registeredInfo.getBusinessInfos();
            if (businessInfos != null && businessInfos.getBusinessInfo() != null) {
                Iterator<BusinessInfo> iter = businessInfos.getBusinessInfo().iterator();
                while (iter.hasNext()) {
                    BusinessInfo businessInfo = iter.next();
                    Object business = em.find(org.apache.juddi.model.BusinessEntity.class,
                            businessInfo.getBusinessKey());
                    em.remove(business);
                }
            }

            log.info("mark all tmodels for publisher " + entityKey + " as deleted.");
            TModelInfos tmodelInfos = registeredInfo.getTModelInfos();
            if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) {
                Iterator<TModelInfo> iter = tmodelInfos.getTModelInfo().iterator();
                while (iter.hasNext()) {
                    TModelInfo tModelInfo = iter.next();
                    Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class,
                            tModelInfo.getTModelKey());
                    tmodel.setDeleted(true);
                    em.persist(tmodel);
                }
            }
            log.info("remove all persisted AuthTokens for publisher " + entityKey + ".");
            Query q1 = em
                    .createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = '" + entityKey + "'");
            q1.executeUpdate();

            log.info("removing publisher " + entityKey + ".");
            //delete the publisher
            em.remove(obj);
        }

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

From source file:portal.api.impl.PortalJpaController.java

public void deleteUser(int userid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    PortalUser u = entityManager.find(PortalUser.class, userid);

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from  ww w  . j  a v  a  2s  .  c  o m*/

    entityManager.remove(u);

    entityTransaction.commit();
}

From source file:org.rhq.enterprise.server.drift.DriftManagerBeanTest.java

private void deleteNewResource(Resource resource) throws Exception {
    if (null != resource) {
        EntityManager em = null;

        try {/* w  ww.  j  a v a  2s  .  c  o  m*/
            ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();

            // invoke bulk delete on the resource to remove any dependencies not defined in the hibernate entity model
            // perform in-band and out-of-band work in quick succession
            List<Integer> deletedIds = resourceManager.uninventoryResource(overlord, resource.getId());
            for (Integer deletedResourceId : deletedIds) {
                resourceManager.uninventoryResourceAsyncWork(overlord, deletedResourceId);
            }

            // now dispose of other hibernate entities
            getTransactionManager().begin();
            em = getEntityManager();

            ResourceType type = em.find(ResourceType.class, resource.getResourceType().getId());
            Agent agent = em.find(Agent.class, resource.getAgent().getId());
            if (null != agent) {
                em.remove(agent);
            }
            if (null != type) {
                em.remove(type);
            }

            getTransactionManager().commit();
        } catch (Exception e) {
            try {
                System.out
                        .println("CANNOT CLEAN UP TEST (" + this.getClass().getSimpleName() + ") Cause: " + e);
                getTransactionManager().rollback();
            } catch (Exception ignore) {
            }
        } finally {
            if (null != em) {
                em.close();
            }
        }
    }
}

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

/**
 * Retrieves publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required. 
 * @param body/*  www.j  av  a  2  s  .c  o m*/
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage 
 */
public PublisherDetail getPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage {

    new ValidatePublisher(null).validateGetPublisherDetail(body);

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());

        PublisherDetail result = new PublisherDetail();

        List<String> publisherIdList = body.getPublisherId();
        for (String publisherId : publisherIdList) {
            org.apache.juddi.model.Publisher modelPublisher = null;
            try {
                modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId);
            } catch (ClassCastException e) {
            }
            if (modelPublisher == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId));
            }

            org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher();

            MappingModelToApi.mapPublisher(modelPublisher, apiPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

}

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

@Override
public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {/*from   ww  w.  ja  v a  2s .  co m*/
        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;
        log.error("config exception! ", ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;
        if (ctx == null)
            throw new UnknownUserException(
                    new ErrorMessage("errors.auth.NoPublisher", "no web service context!"));
        if (ctx.getUserPrincipal() != null) {
            user = ctx.getUserPrincipal().getName();
        }
        if (user == null) {
            MessageContext mc = ctx.getMessageContext();
            HttpServletRequest req = null;
            if (mc != null) {
                req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            }
            if (req != null && req.getUserPrincipal() != null) {
                user = req.getUserPrincipal().getName();
            }
        }
        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            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();
        }

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

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> T find(Class<T> clazz, long id) throws Exception {
    T res = null;/*from   w  w  w. jav  a 2  s . c  o  m*/

    testClazz(clazz);

    EntityManager em = getEntityManager();

    try {

        res = em.find(clazz, id);

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> T find(Class<T> clazz, int id) throws Exception {
    T res = null;//w  ww.  jav  a 2 s .c  o  m

    testClazz(clazz);

    EntityManager em = getEntityManager();

    try {

        res = em.find(clazz, id);

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> T find(Class<T> clazz, String id) throws Exception {
    T res = null;/*from   w  w w.  ja v  a2  s. co m*/

    testClazz(clazz);

    EntityManager em = getEntityManager();

    try {

        res = em.find(clazz, id);

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

/**
 * This method will not hydrate TicketProp.geTTicket because no type information is available
 * @param id/*from   w  w  w.j a  v a  2 s. co  m*/
 * @return the ticketProp, null if not found
 */
@Override
public TicketProp getTicketProp(Object id) {
    EntityManager em = this.emf.createEntityManager();
    try {
        TicketProp prop = em.find(TicketProp.class, LongUserType.massageToLong(id));
        return prop;
    } finally {
        cleanup(em);
    }
}