Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

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

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletCookieDaoImpl.java

@Override
@PortalTransactional/*ww  w  . ja  v  a  2s. c  o  m*/
public IPortalCookie addOrUpdatePortletCookie(IPortalCookie portalCookie, Cookie cookie) {
    final Set<IPortletCookie> portletCookies = portalCookie.getPortletCookies();

    boolean found = false;
    final String name = cookie.getName();
    final EntityManager entityManager = this.getEntityManager();
    for (final Iterator<IPortletCookie> portletCookieItr = portletCookies.iterator(); portletCookieItr
            .hasNext();) {
        final IPortletCookie portletCookie = portletCookieItr.next();
        if (name.equals(portletCookie.getName())) {
            //Delete cookies with a maxAge of 0
            if (cookie.getMaxAge() == 0) {
                portletCookieItr.remove();
                entityManager.remove(portletCookie);
            } else {
                portletCookie.updateFromCookie(cookie);
            }

            found = true;
            break;
        }
    }

    if (!found) {
        IPortletCookie newPortletCookie = new PortletCookieImpl(portalCookie, cookie);
        portletCookies.add(newPortletCookie);
    }

    entityManager.persist(portalCookie);

    return portalCookie;
}

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

/**
 * Transaction is not opened nor committed here but needed.
 * // w  ww  .  java2s. c  o m
 */
static History createHistory(JobInstance job, EntityManager em, State finalState, Calendar endDate) {
    History h = new History();
    h.setId(job.getId());
    h.setJd(job.getJd());
    h.setApplicationName(job.getJd().getApplicationName());
    h.setSessionId(job.getSessionID());
    h.setQueue(job.getQueue());
    h.setQueueName(job.getQueue().getName());
    h.setEnqueueDate(job.getCreationDate());
    h.setEndDate(endDate);
    h.setAttributionDate(job.getAttributionDate());
    h.setExecutionDate(job.getExecutionDate());
    h.setUserName(job.getUserName());
    h.setEmail(job.getEmail());
    h.setParentJobId(job.getParentId());
    h.setApplication(job.getJd().getApplication());
    h.setModule(job.getJd().getModule());
    h.setKeyword1(job.getJd().getKeyword1());
    h.setKeyword2(job.getJd().getKeyword2());
    h.setKeyword3(job.getJd().getKeyword3());
    h.setInstanceApplication(job.getApplication());
    h.setInstanceKeyword1(job.getKeyword1());
    h.setInstanceKeyword2(job.getKeyword2());
    h.setInstanceKeyword3(job.getKeyword3());
    h.setInstanceModule(job.getModule());
    h.setProgress(job.getProgress());
    h.setStatus(finalState);
    h.setNode(job.getNode());
    h.setNodeName(job.getNode().getName());
    h.setHighlander(job.getJd().isHighlander());

    em.persist(h);

    return h;
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Message setPublishLevel(String widgetId, int level) {
    Message msg = new Message();
    EntityManager em = this.getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();//from   ww w . j  a  va  2  s .c o m
    Widgetprofile widgetProfile = em.find(Widgetprofile.class, widgetId);
    widgetProfile.setPublish_level(level);
    em.persist(widgetProfile);
    em.getTransaction().commit();
    em.close();
    msg.setMessage("OK");
    return msg;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Refreshes the state of the given builder based on its base corpus and adds any missing documents.
 * @param em the {@link EntityManager} to use.
 * @param builder the {@link LexiconBuilderDocumentStore} to refresh.
 * @return the supplied {@link LexiconBuilderDocumentStore} object.
 *//*from w w w . j av  a 2s.  c  om*/
public LexiconBuilderDocumentStore refreshBuilder(EntityManager em, LexiconBuilderDocumentStore builder) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(builder, CannedMessages.NULL_ARGUMENT, "builder");
    Validate.notNull(builder.getCorpus(), CannedMessages.NULL_ARGUMENT, "builder.corpus");

    TypedQuery<FullTextDocument> ftdQuery = em.createQuery("SELECT d FROM FullTextDocument d "
            + "WHERE d.store=:corpus "
            + "AND NOT EXISTS (SELECT bd FROM LexiconBuilderDocument bd WHERE bd.store=:builder AND bd.baseDocument=d)",
            FullTextDocument.class);

    ftdQuery.setParameter("corpus", builder.getCorpus()).setParameter("builder", builder);

    for (FullTextDocument document : ftdQuery.getResultList()) {
        LexiconBuilderDocument lbd = new LexiconBuilderDocument(document);
        builder.addDocument(lbd);
        em.persist(lbd);
    }
    return builder;
}

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

/**
 *
 * @param request servlet request//from  ww w .ja  v  a  2 s.c o 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:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Sends out the notifications.//  w  ww  . j a v a  2s  . com
 * @param getSubscriptionResults
 * @param resultList 
 * @param notificationDate 
 */
protected void notify(GetSubscriptionResults getSubscriptionResults, SubscriptionResultsList resultList,
        Date notificationDate) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String subscriptionKey = resultList.getSubscription().getSubscriptionKey();
        org.apache.juddi.model.Subscription modelSubscription = em
                .find(org.apache.juddi.model.Subscription.class, subscriptionKey);
        Date lastNotifiedDate = modelSubscription.getLastNotified();
        //now log to the db that we are sending the notification.
        tx.begin();
        modelSubscription.setLastNotified(notificationDate);
        em.persist(modelSubscription);
        tx.commit();

        org.apache.juddi.model.BindingTemplate bindingTemplate = em
                .find(org.apache.juddi.model.BindingTemplate.class, modelSubscription.getBindingKey());
        NotifySubscriptionListener body = new NotifySubscriptionListener();
        //         if (resultList.getServiceList()!=null && resultList.getServiceList().getServiceInfos()!=null &&
        //               resultList.getServiceList().getServiceInfos().getServiceInfo().size() == 0) {
        //            resultList.getServiceList().setServiceInfos(null);
        //         }
        body.setSubscriptionResultsList(resultList);

        //TODO if the endpoint requires an auth token, look up the security endpoint of the remote registry
        //via ClientSubscriptionInfo

        if (sendToken) {
            String authorizedName = modelSubscription.getAuthorizedName();
            UDDISecurityImpl security = new UDDISecurityImpl();

            if (authorizedName != null) { // add a security token if needed
                try {
                    //obtain a token for this publisher
                    org.uddi.api_v3.AuthToken token = security.getAuthToken(authorizedName);
                    body.setAuthInfo(token.getAuthInfo());
                } catch (DispositionReportFaultMessage e) {
                    body.setAuthInfo("Failed to generate token, please contact UDDI admin");
                    log.error(e.getMessage(), e);
                }
            }
        }

        if (bindingTemplate != null) {
            if (AccessPointType.END_POINT.toString().equalsIgnoreCase(bindingTemplate.getAccessPointType())
                    || AccessPointType.WSDL_DEPLOYMENT.toString()
                            .equalsIgnoreCase(bindingTemplate.getAccessPointType())) {
                try {
                    Notifier notifier = new NotifierFactory().getNotifier(bindingTemplate);
                    if (notifier != null) {
                        log.info("Sending out notification to " + bindingTemplate.getAccessPointUrl());
                        notifier.notifySubscriptionListener(body);
                        //there maybe more chunks we have to send
                        String chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        while (chunkToken != null) {
                            UddiEntityPublisher publisher = new UddiEntityPublisher();
                            publisher.setAuthorizedName(modelSubscription.getAuthorizedName());
                            log.debug("Sending out next chunk: " + chunkToken + " to "
                                    + bindingTemplate.getAccessPointUrl());
                            getSubscriptionResults.setChunkToken(chunkToken);
                            resultList = subscriptionImpl.getSubscriptionResults(getSubscriptionResults,
                                    publisher);
                            body.setSubscriptionResultsList(resultList);
                            notifier.notifySubscriptionListener(body);
                            chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        }
                        //successful notification so remove from the badNotificationList
                        if (badNotifications.containsKey(resultList.getSubscription().getSubscriptionKey()))
                            badNotifications.remove(resultList.getSubscription().getSubscriptionKey());
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof IOException) {
                        addBadNotificationToList(subscriptionKey, bindingTemplate.getAccessPointUrl());
                        //we could not notify so compensate the transaction above
                        modelSubscription.setLastNotified(lastNotifiedDate);
                        tx.begin();
                        em.persist(modelSubscription);
                        tx.commit();
                        //} else {
                        //log.warn("Unexpected WebServiceException " + e.getMessage() + e.getCause());
                    }
                    log.error("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause());
                    log.debug("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause(), e);
                }
            } else {
                log.info("Binding " + bindingTemplate.getEntityKey() + " has an unsupported binding type of "
                        + bindingTemplate.getAccessPointType() + ". Only "
                        + AccessPointType.END_POINT.toString() + " and "
                        + AccessPointType.WSDL_DEPLOYMENT.toString() + " are supported.");
                addBadNotificationToList(subscriptionKey,
                        bindingTemplate.getAccessPointType() + " not supported");
            }
        } else {
            log.info("There is no valid binding template defined for this subscription: "
                    + modelSubscription.getBindingKey());
            addBadNotificationToList(subscriptionKey, modelSubscription.getBindingKey() + " not found");
        }

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

From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java

public Resolution save() {
    EntityManager em = Stripersist.getEntityManager();
    solrConfiguration.getIndexAttributes().clear();
    solrConfiguration.getResultAttributes().clear();
    for (int i = 0; i < indexAttributes.length; i++) {
        Long attributeId = indexAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getIndexAttributes().add(attribute);
    }/*from w  w  w.java 2  s.co  m*/

    for (int i = 0; i < resultAttributes.length; i++) {
        Long attributeId = resultAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getResultAttributes().add(attribute);
    }
    em.persist(solrConfiguration);
    em.getTransaction().commit();

    return new ForwardResolution(EDIT_JSP);
}

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

private Resource createNewResource() throws Exception {
    getTransactionManager().begin();/*from  w w w .  ja v  a2 s.  co m*/
    EntityManager em = getEntityManager();

    Resource resource;

    try {
        try {
            ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test",
                    ResourceCategory.PLATFORM, null);
            DriftDefinitionTemplate template = new DriftDefinitionTemplate();
            template.setName("test-template");
            DriftDefinition templateDef = new DriftDefinition(new Configuration());
            templateDef.setName("test-template-def");
            template.setTemplateDefinition(templateDef);
            template.setUserDefined(true);
            resourceType.addDriftDefinitionTemplate(template);
            em.persist(resourceType);

            Agent agent = new Agent("testagent", "testaddress", 1, "", "testtoken");
            em.persist(agent);
            em.flush();

            DriftDefinition test1Def = new DriftDefinition(new Configuration());
            test1Def.setName("test-1");

            DriftDefinition test2Def = new DriftDefinition(new Configuration());
            test2Def.setName("test-2");

            resource = new Resource("reskey" + System.currentTimeMillis(), "resname", resourceType);
            resource.setUuid("" + new Random().nextInt());
            resource.setAgent(agent);
            resource.setInventoryStatus(InventoryStatus.COMMITTED);
            resource.addDriftDefinition(test1Def);
            resource.addDriftDefinition(test2Def);
            em.persist(resource);

        } catch (Exception e) {
            System.out.println("CANNOT PREPARE TEST: " + e);
            getTransactionManager().rollback();
            throw e;
        }

        em.flush();
        getTransactionManager().commit();
    } finally {
        em.close();
    }

    return resource;
}

From source file:BO.UserHandler.java

public boolean respondFriendRequest(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;//from  w w w  . j  a v a2s  .  c o m
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println("Receiving friend: " + user.getEmail());
        System.out.println("Sending friend: " + user.getFriendToAdd());

        Friendship f = (Friendship) em
                .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                        + "AND f.sendingFriend.email LIKE :email2")
                .setParameter("email1", user.getEmail()).setParameter("email2", user.getFriendToAdd())
                .getSingleResult();
        f.setDidRespond(true);
        f.setDidAccept(user.isDidAccept());
        em.persist(f);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

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

public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage {

    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business Fudger request for key "
                + body.getBusinessEntity().get(0).getBusinessKey());
    }//from   ww w.  j av  a  2s.  c om
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);
            nodeId = nodeID;

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

        tx.commit();

        return result;
    } catch (DispositionReportFaultMessage drfm) {

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