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:nl.b3p.viewer.admin.stripes.LayoutManagerActionBean.java

public Resolution saveComponentConfig() {
    EntityManager em = Stripersist.getEntityManager();
    if (component == null) {
        component = new ConfiguredComponent();
    }//from  w w  w  . j  av  a  2  s  .  c  om
    component.setConfig(configObject);
    component.setName(name);
    component.setClassName(className);
    component.setApplication(application);
    Map<String, String> compDetails = new HashMap<String, String>();
    try {
        if (componentLayout != null) {
            JSONObject compLayout = new JSONObject(componentLayout);
            for (Iterator<String> it = compLayout.keys(); it.hasNext();) {
                String key = it.next();
                Object val = compLayout.get(key);
                compDetails.put(key, val.toString());
            }
        }
    } catch (JSONException ex) {
        Logger.getLogger(LayoutManagerActionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    //        details.put("layout", componentLayout);
    component.setDetails(compDetails);

    component.getReaders().clear();
    component.setReaders(new HashSet<String>(groups));
    em.persist(component);
    application.authorizationsModified();
    em.getTransaction().commit();

    return config();
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Path("{id}/markAllRead")
public Response markAllRead(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("allBefore") long timeMillis) {
    EntityManager em;
    EntityTransaction tx;/*from  w  w  w . j  a  v  a2s .co  m*/
    User user;
    Feed feed;
    Date newDate;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();

    tx.begin();

    try {
        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        newDate = new Date(timeMillis);
        if (feed.getReadAllBefore() == null || feed.getReadAllBefore().before(newDate)) {
            feed.setReadAllBefore(newDate);
            em.persist(feed);
        }

        em.createQuery(
                "delete from FeedItem fi where fi.feed = :feed and fi.data.date < :date and not fi.starred and not fi.exported and size(fi.tags) = 0")
                .setParameter("feed", feed).setParameter("date", newDate).executeUpdate();

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:com.jada.admin.contactus.ContactUsMaintAction.java

private void saveDefault(ContactUs contactUs, ContactUsMaintActionForm form, AdminBean adminBean)
        throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    ContactUsLanguage contactUsLanguage = contactUs.getContactUsLanguage();
    if (contactUsLanguage == null) {
        contactUsLanguage = new ContactUsLanguage();
        contactUsLanguage.setContactUs(contactUs);
        contactUs.getContactUsLanguages().add(contactUsLanguage);
        SiteProfileClass siteProfileClass = em.find(SiteProfileClass.class,
                form.getSiteProfileClassDefaultId());
        contactUsLanguage.setSiteProfileClass(siteProfileClass);
        contactUsLanguage.setRecCreateBy(adminBean.getUser().getUserId());
        contactUsLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        contactUs.setContactUsLanguage(contactUsLanguage);
    }/*from www.j a v  a2s.  co  m*/
    contactUsLanguage.setContactUsName(form.getContactUsName());
    contactUsLanguage.setContactUsDesc(form.getContactUsDesc());
    contactUsLanguage.setRecUpdateBy(adminBean.getUser().getUserId());
    contactUsLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
    em.persist(contactUsLanguage);
}

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

/**
 * Save the category element of a question choice element.
 * /*w w w . j  a v  a 2  s.  com*/
 * @param categoryElement
 *          the category element to save.
 * @param em
 *          the entity manager.
 */
private void saveProjectModelCategoryElement(CategoryElement categoryElement, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport) {
    if (!modelesImport.contains(categoryElement)) {
        modelesImport.add(categoryElement);

        if (!modelesReset.containsKey(categoryElement)) {
            CategoryElement key = categoryElement;
            modelesReset.put(key, categoryElement);
            categoryElement.setId(null);

            CategoryType parentType = categoryElement.getParentType();
            if (!modelesImport.contains(parentType)) {
                modelesImport.add(parentType);

                if (!modelesReset.containsKey(parentType)) {
                    CategoryType parentKey = parentType;
                    modelesReset.put(parentKey, parentType);
                    parentType.setId(null);

                    List<CategoryElement> elements = parentType.getElements();
                    if (elements != null) {
                        parentType.setElements(null);
                        em.persist(parentType);
                        for (CategoryElement element : elements) {
                            categoryElement.setParentType(parentType);
                            saveProjectModelCategoryElement(element, em, modelesReset, modelesImport);
                        }
                        parentType.setElements(elements);
                        em.merge(parentType);
                    } else {
                        em.persist(parentType);
                    }
                } else {
                    parentType = (CategoryType) modelesReset.get(parentType);
                }
            }
            categoryElement.setParentType(parentType);
            em.persist(categoryElement);
        } else {
            categoryElement = (CategoryElement) modelesReset.get(categoryElement);
        }
    }
}

From source file:com.webbfontaine.valuewebb.timer.RatesUpdater.java

@Asynchronous
@Transactional// www.j  a  va  2  s  .c  o  m
public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) {

    HashMap<String, BigDecimal> ratesFromBank = ratesFromBank();
    if (ratesFromBank.isEmpty()) {
        LOGGER.error("No rates passed to update, check web site and source code!");
        return null;
    }

    EntityManager entityManager = Utils.getEntityManager();

    List<Rate> existingRates = entityManager.createQuery("from Rate r where r.eov is null").getResultList();

    Transaction tx = ((org.jboss.seam.persistence.HibernateSessionProxy) entityManager.getDelegate())
            .getTransaction();

    try {

        tx.begin();

        for (Rate existingRecord : existingRates) {

            BigDecimal latestRateForCurrency = ratesFromBank.get(existingRecord.getCod());

            if (latestRateForCurrency == null) {
                LOGGER.warn("Currency code '{0}' exists but absent in updates", existingRecord.getCod());
                continue;
            }

            if (existingRecord.getExch().doubleValue() != latestRateForCurrency.doubleValue()) { //i get double value because bigdecimal can return 0.2240 which is not equal to 0.224 when comparing BD values
                /* close existing rate and open new one from today */
                Date tomorrowDate = Utils.getTomorrowDate();
                existingRecord.setEov(tomorrowDate); // since scheduler works at 21:00
                Rate newRecord = new Rate(null, existingRecord.getCod(), 1, latestRateForCurrency, tomorrowDate,
                        null);
                entityManager.persist(existingRecord);
                entityManager.persist(newRecord);
                LOGGER.info("Updated Exchange rate for {0}, old: {1}, new: {2}", newRecord.getCod(),
                        existingRecord.unitRate(), newRecord.unitRate());
            }
        }

        entityManager.flush();
        tx.commit();

    } catch (Exception e) {
        LOGGER.error("Exception on updating rates", e);
        if (tx != null) {
            tx.rollback();
        }
    }

    return null;
}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessService uddiEntity,
        UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*  w ww  .j  av  a2s . c  om*/
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class,
                uddiEntity.getBusinessEntity().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);
    }

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BusinessService existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null) {
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    } else
        uddiEntity.setCreated(now);

    List<org.apache.juddi.model.BindingTemplate> bindingList = uddiEntity.getBindingTemplates();
    for (org.apache.juddi.model.BindingTemplate binding : bindingList)
        setOperationalInfo(em, binding, publisher, true);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity,
        UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);//from  ww w  .j  av  a 2s  . co m
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class,
                uddiEntity.getBusinessService().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);

        // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
        org.apache.juddi.model.BusinessEntity businessParent = em
                .find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey());
        businessParent.setModifiedIncludingChildren(now);
        em.persist(businessParent);
    }

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:com.jada.admin.site.SiteLoader.java

public void loadCurrency() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Currency where siteId = :siteId order by currencyCode";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Currency master = (Currency) iterator.next();
        Currency currency = new Currency();
        PropertyUtils.copyProperties(currency, master);
        currency.setSite(site);//from ww w .java2  s  . co m
        currency.setCurrencyId(null);
        currency.setRecUpdateBy(userId);
        currency.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        currency.setRecCreateBy(userId);
        currency.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        em.persist(currency);
    }
}

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

@Override
public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    String http_header_name = null;
    try {//  w w w  . j av a2s.  c o  m
        http_header_name = AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME);
        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);
    }
    if (http_header_name == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!"));
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;

        MessageContext mc = ctx.getMessageContext();
        HttpServletRequest req = null;
        if (mc != null) {
            req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            user = req.getHeader(http_header_name);
        }

        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:org.jasig.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

@Override
@PortalTransactional//from   www  . java2  s.c  o  m
public void aggregateMarketplaceRating() {
    //setup
    EntityManager em = this.getEntityManager();

    //get list of average ratings
    Query aggregatedQuery = em.createQuery("SELECT AVG(m.rating) as rating, "
            + "       count(m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId) as theCount, "
            + "       m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId as portletId "
            + "  FROM MarketplaceRatingImpl m "
            + " GROUP BY m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId");

    List<Object[]> aggregatedResults = aggregatedQuery.getResultList();

    //update the portlet definition with the average rating
    for (Object[] result : aggregatedResults) {
        if (result != null && result.length == 3) {
            try {
                Double averageRating = (Double) result[0];
                Long usersRated = (Long) result[1];
                String portletId = ((Long) result[2]).toString();

                IPortletDefinition portletDefinition = portletDefinitionDao.getPortletDefinition(portletId);
                if (portletDefinition != null) {
                    portletDefinition.setRating(averageRating);
                    portletDefinition.setUsersRated(usersRated);
                    em.persist(portletDefinition);
                }
            } catch (Exception ex) {
                logger.warn("Issue aggregating portlet ratings, recoverable", ex);
            }
        }

    }
}