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:com.jada.order.document.InvoiceEngine.java

public void saveOrder() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    if (masterHeader == null
            || !masterHeader.getRecUpdateDatetime().equals(invoiceHeader.getRecUpdateDatetime())) {
        if (invoiceHeader.getInvoiceNum() == null) {
            invoiceHeader.setInvoiceNum(
                    generateNumber(orderHeader.getSiteDomain().getSite(), Constants.SEQUENCE_INVOICE));
        }/*  w  ww  . ja va 2  s .  c o  m*/
        if (masterHeader == null) {
            masterHeader = new InvoiceHeader();
        }
        masterHeader.setInvoiceNum(invoiceHeader.getInvoiceNum());
        masterHeader.setShippingTotal(invoiceHeader.getShippingTotal());
        masterHeader.setInvoiceTotal(invoiceHeader.getInvoiceTotal());
        masterHeader.setInvoiceStatus(invoiceHeader.getInvoiceStatus());
        masterHeader.setInvoiceDate(invoiceHeader.getInvoiceDate());
        masterHeader.setRecUpdateBy(invoiceHeader.getRecUpdateBy());
        masterHeader.setRecUpdateDatetime(invoiceHeader.getRecUpdateDatetime());
        masterHeader.setRecCreateBy(invoiceHeader.getRecCreateBy());
        masterHeader.setRecCreateDatetime(invoiceHeader.getRecCreateDatetime());
        masterHeader.setOrderHeader(orderHeader);
        orderHeader.getInvoiceHeaders().add(masterHeader);

        // Copy data from invoiceHeader to masterHeader
        if (masterHeader.getInvoiceHeaderId() == null) {
            em.persist(masterHeader);
        }
        invoiceHeader.setInvoiceHeaderId(masterHeader.getInvoiceHeaderId());

        if (masterHeader != null) {
            Iterator<?> taxIterator = masterHeader.getInvoiceTaxes().iterator();
            while (taxIterator.hasNext()) {
                InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
                if (invoiceDetailTax.getInvoiceDetail() != null) {
                    continue;
                }
                em.remove(invoiceDetailTax);
                taxIterator.remove();
            }
        }

        Iterator<?> taxIterator = invoiceHeader.getInvoiceTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
            if (invoiceDetailTax.getInvoiceDetail() != null) {
                continue;
            }
            InvoiceDetailTax masterTax = new InvoiceDetailTax();
            //            masterTax.setInvoiceDetailTaxId(invoiceDetailTax.getInvoiceDetailTaxId());
            masterTax.setTaxName(invoiceDetailTax.getTaxName());
            masterTax.setTaxAmount(invoiceDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(invoiceDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(invoiceDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(invoiceDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(invoiceDetailTax.getRecCreateDatetime());
            masterTax.setTax(invoiceDetailTax.getTax());
            masterTax.setInvoiceDetail(null);
            masterTax.setInvoiceHeader(masterHeader);
            em.persist(masterTax);
        }
    }

    Iterator<?> iterator = masterHeader.getInvoiceDetails().iterator();
    while (iterator.hasNext()) {
        InvoiceDetail masterDetail = (InvoiceDetail) iterator.next();
        Iterator<?> taxIterator = masterDetail.getInvoiceDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax masterDetailTax = (InvoiceDetailTax) taxIterator.next();
            em.remove(masterDetailTax);
            taxIterator.remove();
        }
        em.remove(masterDetail);
        iterator.remove();
    }

    iterator = invoiceHeader.getInvoiceDetails().iterator();
    while (iterator.hasNext()) {
        InvoiceDetail invoiceDetail = (InvoiceDetail) iterator.next();
        InvoiceDetail masterDetail = new InvoiceDetail();
        masterDetail.setInvoiceHeader(masterHeader);
        masterDetail.setSeqNum(invoiceDetail.getSeqNum());
        masterDetail.setItemInvoiceQty(invoiceDetail.getItemInvoiceQty());
        masterDetail.setItemInvoiceAmount(invoiceDetail.getItemInvoiceAmount());
        masterDetail.setRecUpdateBy(invoiceDetail.getRecUpdateBy());
        masterDetail.setRecUpdateDatetime(invoiceDetail.getRecUpdateDatetime());
        masterDetail.setRecCreateBy(invoiceDetail.getRecCreateBy());
        masterDetail.setRecCreateDatetime(invoiceDetail.getRecCreateDatetime());
        masterDetail.setOrderItemDetail(invoiceDetail.getOrderItemDetail());
        em.persist(masterDetail);
        masterHeader.getInvoiceDetails().add(masterDetail);

        Iterator<?> taxIterator = invoiceDetail.getInvoiceDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
            InvoiceDetailTax masterTax = new InvoiceDetailTax();
            masterTax.setTaxName(invoiceDetailTax.getTaxName());
            masterTax.setTaxAmount(invoiceDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(invoiceDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(invoiceDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(invoiceDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(invoiceDetailTax.getRecCreateDatetime());
            masterTax.setInvoiceDetail(masterDetail);
            masterTax.setTax(invoiceDetailTax.getTax());
            masterDetail.getInvoiceDetailTaxes().add(masterTax);
            masterTax.setInvoiceHeader(masterHeader);
            em.persist(masterTax);
        }
    }

    PaymentTran paymentTran = invoiceHeader.getPaymentTran();
    PaymentTran masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getPaymentTran();
    }
    if (isSavePaymentTran(paymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, paymentTran);
        masterHeader.setPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }

    PaymentTran voidPaymentTran = invoiceHeader.getVoidPaymentTran();
    masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getVoidPaymentTran();
    }
    if (isSavePaymentTran(voidPaymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, voidPaymentTran);
        masterHeader.setVoidPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }
}

From source file:com.jada.content.template.TemplateEngine.java

public Hashtable<String, String> updateItemComment() throws Exception {
    Customer customer = ContentLookupDispatchAction.getCustomer(request);
    if (customer == null) {
        return null;
    }/* ww  w . j a v a  2  s .co m*/

    String itemNaturalKey = Utility.reEncode(getCategoryParameter(request, 2));
    String commentTitle = request.getParameter("commentTitle");
    commentTitle = Utility.escapeStrictHTML(commentTitle);
    String commentLine = request.getParameter("comment");
    commentLine = Utility.escapeStrictHTML(commentLine);
    String commentRating = request.getParameter("commentRating");

    Hashtable<String, String> attributes = new Hashtable<String, String>();
    if (Format.isNullOrEmpty(commentTitle)) {
        attributes.put("commentTitleMessage", getLanguage("content.error.string.required"));
    }
    if (Format.isNullOrEmpty(commentLine)) {
        attributes.put("commentMessage", getLanguage("content.error.string.required"));
    }
    if (Format.isNullOrEmpty(commentRating) || commentRating.equals("0")) {
        attributes.put("commentRatingMessage", getLanguage("content.error.string.required"));
    }

    if (attributes.size() == 0) {
        EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
        Item item = (Item) ItemDAO.loadNatural(siteDomain.getSite().getSiteId(), itemNaturalKey);
        Comment comment = new Comment();
        comment.setCommentTitle(commentTitle);
        comment.setComment(commentLine);
        comment.setCommentRating(Integer.valueOf(commentRating));
        comment.setActive(Constants.VALUE_YES);
        String custName = customer.getCustEmail();
        if (custName.length() > 20) {
            custName = custName.substring(0, 19);
        }
        comment.setRecCreateBy(custName);
        comment.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        comment.setRecUpdateBy(custName);
        comment.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        comment.setCustomer(customer);
        comment.setItem(item);
        item.getComments().add(comment);
        em.persist(comment);

        attributes.put("commentTitle", "");
        attributes.put("comment", "");
        attributes.put("commentRating", "");
    } else {
        attributes.put("commentTitle", commentTitle);
        attributes.put("comment", commentLine);
        attributes.put("commentRating", commentRating);
    }
    return attributes;
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
@Transactional/*from   w  ww  .  j ava 2  s .  c  o  m*/
public synchronized int createHotelRatePlan(HotelRatePlan hotelRatePlan) {
    int retCode = 0;

    List<HotelRatePlan> ratePlans = null;
    EntityManager em = getEm();
    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] begin: ");
    try {
        ratePlans = em.createQuery(
                "select o from HotelRatePlan o where o.ratePlanCode = :ratePlanCode and o.hotelInfo = :hotelInfo")
                .setParameter("ratePlanCode", hotelRatePlan.getRatePlanCode())
                .setParameter("hotelInfo", hotelRatePlan.getHotelInfo()).getResultList();
        if (ratePlans.size() > 0) {
            retCode = 2;
            HotelRatePlan plan0 = ratePlans.get(0);

            //booking rule
            List<HotelRatePlanBookingRule> rules0 = em
                    .createQuery("select o from HotelRatePlanBookingRule o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanBookingRule rule0 : rules0) {
                em.remove(rule0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanBookingRules() != null) {
                for (HotelRatePlanBookingRule rule : hotelRatePlan.getHotelRatePlanBookingRules()) {
                    rule.setHotelRatePlan(plan0);
                    em.persist(rule);
                }
            }

            //offer
            List<HotelRatePlanOffer> offers0 = em
                    .createQuery("select o from HotelRatePlanOffer o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanOffer offer0 : offers0) {
                em.remove(offer0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanOffers() != null) {
                for (HotelRatePlanOffer offer : hotelRatePlan.getHotelRatePlanOffers()) {
                    offer.setHotelRatePlan(plan0);
                    em.persist(offer);
                }
            }

            //rate
            List<HotelRatePlanRate> rates0 = em.createQuery(
                    "select o from HotelRatePlanRate o where o.hotelRatePlan = :plan order by o.startDate")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanRate rate0 : rates0) {
                for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                    if (rate0.getStartDate().getTime() == rate.getStartDate().getTime()) {
                        em.remove(rate0);
                        em.flush();
                        break;
                    }
                }
            }

            for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                rate.setHotelRatePlan(plan0);
                em.persist(rate);
            }
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] updated. ");
        } else {
            em.persist(hotelRatePlan);
            retCode = 1;
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] created. ");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        retCode = -1;
        logger.error(Thread.currentThread().getName() + ", createHotelRatePlan["
                + hotelRatePlan.getHotelInfo().getHotelCode() + "]: " + ex.getMessage());
    }

    getEm().detach(hotelRatePlan);
    if (ratePlans != null) {
        for (HotelRatePlan ratePlan : ratePlans) {
            getEm().detach(ratePlan);
        }
    }

    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] end. ");
    return retCode;
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * saves or updates a newscategory./*from w w w  . ja  va 2 s .  c om*/
 *
 * @param category the category
 * @return the category with the new id
 * @throws Exception the exception
 */
private NewsCategory saveNewsCategory(NewsCategory category) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // try loading the category for the firstspirit id
        NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em);

        if (cat != null) {

            List<NewsMetaCategory> metaCats = category.getMetaCategories();

            // the already persistent categories
            List<NewsMetaCategory> original_metaCats = cat.getMetaCategories();

            // update existing category
            cat.setMetaCategories(new ArrayList<NewsMetaCategory>());

            for (NewsMetaCategory metaCat : metaCats) {
                metaCat = saveNewsMetaCategory(metaCat, em);
                cat.getMetaCategories().add(metaCat);

                original_metaCats.remove(metaCat);
            }
            for (NewsMetaCategory mc : original_metaCats) {
                mc.setLastmodified(category.getLastmodified());
            }
            cat.getMetaCategories().addAll(original_metaCats);

            cat.setFs_id(category.getFs_id());
            cat.setLanguage(category.getLanguage());
            cat.setName(category.getName());
            cat.setVersion(category.getVersion());
            cat.setLastmodified(category.getLastmodified());

            // update
            category = em.merge(cat);
        } else {
            updateMetaCategories(category, em);
            // save to db
            em.persist(category);
        }

        tx.commit();

        return category;

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.jada.order.document.CreditEngine.java

public void saveOrder() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    if (masterHeader == null
            || !masterHeader.getRecUpdateDatetime().equals(creditHeader.getRecUpdateDatetime())) {
        if (creditHeader.getCreditNum() == null) {
            creditHeader.setCreditNum(/*  w  ww.  jav a 2s  .  c o  m*/
                    generateNumber(orderHeader.getSiteDomain().getSite(), Constants.SEQUENCE_CREDIT));
        }
        if (masterHeader == null) {
            masterHeader = new CreditHeader();
        }
        masterHeader.setCreditNum(creditHeader.getCreditNum());
        masterHeader.setShippingTotal(creditHeader.getShippingTotal());
        masterHeader.setCreditTotal(creditHeader.getCreditTotal());
        masterHeader.setCreditStatus(creditHeader.getCreditStatus());
        masterHeader.setCreditDate(creditHeader.getCreditDate());
        masterHeader.setUpdateInventory(creditHeader.getUpdateInventory());
        masterHeader.setRecUpdateBy(creditHeader.getRecUpdateBy());
        masterHeader.setRecUpdateDatetime(creditHeader.getRecUpdateDatetime());
        masterHeader.setRecCreateBy(creditHeader.getRecCreateBy());
        masterHeader.setRecCreateDatetime(creditHeader.getRecCreateDatetime());
        masterHeader.setOrderHeader(orderHeader);
        masterHeader.setInvoiceHeader(invoiceHeader);
        orderHeader.getCreditHeaders().add(masterHeader);

        // Copy data from creditHeader to masterHeader
        if (masterHeader.getCreditHeaderId() == null) {
            em.persist(masterHeader);
        }
        creditHeader.setCreditHeaderId(masterHeader.getCreditHeaderId());

        if (masterHeader != null) {
            Iterator<?> taxIterator = masterHeader.getCreditTaxes().iterator();
            while (taxIterator.hasNext()) {
                CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
                if (creditDetailTax.getCreditDetail() != null) {
                    continue;
                }
                em.remove(creditDetailTax);
                taxIterator.remove();
            }
        }

        Iterator<?> taxIterator = creditHeader.getCreditTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
            if (creditDetailTax.getCreditDetail() != null) {
                continue;
            }
            CreditDetailTax masterTax = new CreditDetailTax();
            masterTax.setCreditDetailTaxId(creditDetailTax.getCreditDetailTaxId());
            masterTax.setTaxName(creditDetailTax.getTaxName());
            masterTax.setTaxAmount(creditDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(creditDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(creditDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(creditDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(creditDetailTax.getRecCreateDatetime());
            masterTax.setCreditDetail(null);
            masterTax.setCreditHeader(masterHeader);
            masterTax.setTax(creditDetailTax.getTax());
            masterTax.setCreditDetailTaxId(null);
            em.persist(masterTax);
        }
    }

    Iterator<?> iterator = masterHeader.getCreditDetails().iterator();
    while (iterator.hasNext()) {
        CreditDetail masterDetail = (CreditDetail) iterator.next();
        Iterator<?> taxIterator = masterDetail.getCreditDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax masterDetailTax = (CreditDetailTax) taxIterator.next();
            em.remove(masterDetailTax);
            taxIterator.remove();
        }
        em.remove(masterDetail);
        iterator.remove();
    }

    iterator = creditHeader.getCreditDetails().iterator();
    while (iterator.hasNext()) {
        CreditDetail creditDetail = (CreditDetail) iterator.next();
        CreditDetail masterDetail = new CreditDetail();
        masterDetail.setCreditHeader(masterHeader);
        masterDetail.setSeqNum(creditDetail.getSeqNum());
        masterDetail.setItemCreditQty(creditDetail.getItemCreditQty());
        masterDetail.setItemCreditAmount(creditDetail.getItemCreditAmount());
        masterDetail.setRecUpdateBy(creditDetail.getRecUpdateBy());
        masterDetail.setRecUpdateDatetime(creditDetail.getRecUpdateDatetime());
        masterDetail.setRecCreateBy(creditDetail.getRecCreateBy());
        masterDetail.setRecCreateDatetime(creditDetail.getRecCreateDatetime());
        masterDetail.setOrderItemDetail(creditDetail.getOrderItemDetail());
        em.persist(masterDetail);
        masterHeader.getCreditDetails().add(masterDetail);

        Iterator<?> taxIterator = creditDetail.getCreditDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
            CreditDetailTax masterTax = new CreditDetailTax();
            masterTax.setTaxName(creditDetailTax.getTaxName());
            masterTax.setTaxAmount(creditDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(creditDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(creditDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(creditDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(creditDetailTax.getRecCreateDatetime());
            masterTax.setCreditDetail(masterDetail);
            masterDetail.getCreditDetailTaxes().add(masterTax);
            masterTax.setCreditHeader(masterHeader);
            masterTax.setTax(creditDetailTax.getTax());
            em.persist(masterTax);
        }
    }

    PaymentTran paymentTran = creditHeader.getPaymentTran();
    PaymentTran masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getPaymentTran();
    }
    if (isSavePaymentTran(paymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, paymentTran);
        masterHeader.setPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }

    PaymentTran voidPaymentTran = creditHeader.getVoidPaymentTran();
    masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getVoidPaymentTran();
    }
    if (isSavePaymentTran(voidPaymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, voidPaymentTran);
        masterHeader.setVoidPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward addCustomAttributeDetail(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    AdminBean adminBean = getAdminBean(request);

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    Long customAttribId = Format.getLong(form.getCustomAttribId());
    CustomAttribute customAttribute = (CustomAttribute) em.find(CustomAttribute.class, customAttribId);
    Long customAttribGroupId = Format.getLong(form.getCustomAttribGroupId());
    CustomAttributeGroup customAttributeGroup = (CustomAttributeGroup) em.find(CustomAttributeGroup.class,
            customAttribGroupId);/*from  www . j a  v a  2s .c om*/
    int seqNum = 0;
    Iterator<?> iterator = customAttributeGroup.getCustomAttributeDetails().iterator();
    boolean found = false;
    while (iterator.hasNext()) {
        CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) iterator.next();
        if (customAttributeDetail.getCustomAttribute().getCustomAttribId()
                .equals(customAttribute.getCustomAttribId())) {
            found = true;
        }
        if (customAttributeDetail.getSeqNum().intValue() >= seqNum) {
            seqNum = customAttributeDetail.getSeqNum() + 1;
        }
    }

    if (!found) {
        CustomAttributeDetail customAttributeDetail = new CustomAttributeDetail();
        customAttributeDetail.setCustomAttribute(customAttribute);
        customAttributeDetail.setSeqNum(seqNum);
        customAttributeDetail.setRecUpdateBy(adminBean.getUser().getUserId());
        customAttributeDetail.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        customAttributeDetail.setRecCreateBy(adminBean.getUser().getUserId());
        customAttributeDetail.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        customAttributeGroup.getCustomAttributeDetails().add(customAttributeDetail);
        em.persist(customAttributeDetail);
    }

    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

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

public void loadTax() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Tax where siteId = :siteId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Tax master = (Tax) iterator.next();
        Tax tax = new Tax();
        Set<Country> countries = tax.getCountries();
        Set<State> states = tax.getStates();
        PropertyUtils.copyProperties(tax, master);
        tax.setSite(site);/*w  ww . j  ava 2s.  co  m*/
        tax.setTaxId(null);
        tax.setRecUpdateBy(userId);
        tax.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        tax.setRecCreateBy(userId);
        tax.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        tax.setTaxLanguages(null);
        tax.setCountries(countries);
        tax.setStates(states);
        Iterator<?> it = null;
        if (master.getCountries() != null) {
            it = master.getCountries().iterator();
            while (it.hasNext()) {
                Country mc = (Country) it.next();
                Country country = CountryDAO.loadByCountryName(site.getSiteId(), mc.getCountryName());
                tax.getCountries().add(country);
            }
        }
        if (master.getStates() != null) {
            it = master.getStates().iterator();
            while (it.hasNext()) {
                State mc = (State) it.next();
                State state = StateDAO.loadByStateName(site.getSiteId(), mc.getStateName());
                tax.getStates().add(state);
            }
        }
        em.persist(tax);
    }
}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

private BaseArtifactType doPersistArtifact(final BaseArtifactType srampArtifact, final ArtifactContent content,
        final HibernateRelationshipFactory relationshipFactory, EntityManager entityManager) throws Exception {
    final ArtifactType artifactType = ArtifactType.valueOf(srampArtifact);

    if (StringUtils.isBlank(srampArtifact.getUuid())) {
        srampArtifact.setUuid(UUID.randomUUID().toString());
    } else {//from  w ww. j  a  v a 2 s .co  m
        // TODO: ugh -- ugly
        try {
            HibernateUtil.getArtifact(srampArtifact.getUuid(), entityManager, false);
            throw ArtificerConflictException.artifactConflict(srampArtifact.getUuid());
        } catch (ArtificerNotFoundException e) {
            // do nothing
        }
    }

    List<ArtifactBuilder> artifactBuilders = ExtensionFactory.createArtifactBuilders(srampArtifact, content);

    // First, need to run the artifact builders to both set metadata on srampArtifact, as well as create
    // the derived artifacts
    List<BaseArtifactType> derivedSrampArtifacts = new ArrayList<>();
    for (ArtifactBuilder artifactBuilder : artifactBuilders) {
        artifactBuilder.buildArtifacts(srampArtifact, content);
        derivedSrampArtifacts.addAll(artifactBuilder.getDerivedArtifacts());
    }

    // S-RAMP -> Hibernate
    ArtificerArtifact artificerArtifact = SrampToHibernateEntityVisitor.visit(srampArtifact, artifactType,
            classificationHelper);

    // documents
    if (artifactType.isDocument()) {
        ArtificerDocumentArtifact artificerDocumentArtifact = (ArtificerDocumentArtifact) artificerArtifact;
        processDocument(artificerDocumentArtifact, content);
        if (content != null) {
            // sets info on the artifact, so call prior to persisting
            FileManagerFactory.getInstance().write(artificerDocumentArtifact, content, entityManager);
        }
    }

    // persist and track the primary
    entityManager.persist(artificerArtifact);
    relationshipFactory.trackEntity(artificerArtifact.getUuid(), artificerArtifact);

    Map<BaseArtifactType, ArtificerArtifact> artificerDerivedArtifacts = new HashMap<>();
    for (BaseArtifactType derivedSrampArtifact : derivedSrampArtifacts) {
        // persist and track each derived
        ArtifactType derivedSrampArtifactType = ArtifactType.valueOf(derivedSrampArtifact);
        ArtificerArtifact artificerDerivedArtifact = SrampToHibernateEntityVisitor.visit(derivedSrampArtifact,
                derivedSrampArtifactType, classificationHelper);

        // Handle derivation here, rather than in the relationship visitor, in case it's an *extended*
        // derived artifact (ie, no 'relatedDocument' field).
        artificerDerivedArtifact.setDerived(true);
        artificerDerivedArtifact.setDerivedFrom(artificerArtifact);
        artificerArtifact.getDerivedArtifacts().add(artificerDerivedArtifact);

        artificerDerivedArtifacts.put(derivedSrampArtifact, artificerDerivedArtifact);
        entityManager.persist(artificerDerivedArtifact);
        relationshipFactory.trackEntity(artificerDerivedArtifact.getUuid(), artificerDerivedArtifact);
    }

    // build the relationships
    RelationshipContext relationshipContext = new HibernateRelationshipContext(entityManager);
    for (ArtifactBuilder artifactBuilder : artifactBuilders) {
        artifactBuilder.buildRelationships(relationshipContext);
    }

    // S-RAMP relationships -> Hibernate relationships
    SrampToHibernateEntityRelationshipsVisitor.visit(srampArtifact, artificerArtifact, relationshipFactory,
            entityManager);
    for (BaseArtifactType derivedSrampArtifact : artificerDerivedArtifacts.keySet()) {
        ArtificerArtifact artificerDerivedArtifact = artificerDerivedArtifacts.get(derivedSrampArtifact);
        SrampToHibernateEntityRelationshipsVisitor.visit(derivedSrampArtifact, artificerDerivedArtifact,
                relationshipFactory, entityManager);
    }

    // auditing
    if (ArtificerConfig.isAuditingEnabled()) {
        entityManager.persist(HibernateAuditor.createAddEntry(artificerArtifact));
        for (ArtificerArtifact derivedArtifact : artificerDerivedArtifacts.values()) {
            entityManager.persist(HibernateAuditor.createAddEntry(derivedArtifact));
        }
    }

    return HibernateEntityToSrampVisitor.visit(artificerArtifact, artifactType, true);
}

From source file:nl.b3p.viewer.solr.SolrUpdateJob.java

public static void insertSolrConfigurationIntoIndex(SolrConf config, EntityManager em, WaitPageStatus status,
        SolrServer solrServer, Filter filter) {
    log.info("Insert SolrConfiguration " + config.getName() + " into index.");
    org.geotools.data.FeatureSource fs = null;
    try {/*from w  w  w. j a  v a2  s  . c  o  m*/
        if (solrServer == null) {
            throw new Exception("No solr server initialized.");
        }
        status.setCurrentAction("Initialiseren...");

        status.setProgress(10);

        List<AttributeDescriptor> indexAttributesConfig = config.getIndexAttributes();
        List<AttributeDescriptor> resultAttributesConfig = config.getResultAttributes();

        SimpleFeatureType sft = config.getSimpleFeatureType();
        fs = sft.openGeoToolsFeatureSource();

        Query q = new Query();
        if (filter != null) {
            q.setFilter(filter);
        }

        if (sft.getFeatureSource() instanceof WFSFeatureSource) {
            q.setMaxFeatures(MAX_FEATURES);
            FeatureCollection fc = fs.getFeatures(q);
            FeatureIterator<SimpleFeature> iterator = fc.features();
            processFeatures(iterator, indexAttributesConfig, resultAttributesConfig, config.getId(), solrServer,
                    status, 70);
        } else {

            status.setCurrentAction("Aantal features berekenen...");

            status.setProgress(15);
            if (fs instanceof org.geotools.jdbc.JDBCFeatureSource) {
                List<String> propertyNames = new ArrayList<String>();
                for (AttributeDescriptor ad : sft.getAttributes()) {
                    propertyNames.add(ad.getName());
                }
                if (!propertyNames.isEmpty()) {
                    setSortBy(q, propertyNames.get(0));
                }
            }
            FeatureCollection fc = fs.getFeatures(q);
            int total = fc.size();
            status.setCurrentAction("Begin toevoegen");

            status.setProgress(20);
            int numIterations = (int) Math.ceil((double) total / BATCH_SIZE);
            double percentagePerBatch = (double) 70 / numIterations;
            int currentProgress = 20;
            for (int i = 0; i < numIterations; i++) {
                int start = i * BATCH_SIZE;
                q.setStartIndex(start);
                int max = (i + 1) * BATCH_SIZE > total ? total : BATCH_SIZE;
                q.setMaxFeatures(max);

                status.setCurrentAction(
                        "Bezig met verwerken features " + start + " - " + max + " van de " + total);
                currentProgress += percentagePerBatch;
                status.setProgress(currentProgress);
                fc = fs.getFeatures(q);
                processFeatures(fc.features(), indexAttributesConfig, resultAttributesConfig, config.getId(),
                        solrServer, status, percentagePerBatch);
            }
        }

        Date now = new Date();
        config.setLastUpdated(now);
        em.persist(config);
        status.setProgress(100);
        status.setFinished(true);
    } catch (Exception ex) {
        log.error("Cannot add configuration to index", ex);
        status.setCurrentAction("Mislukt.");
    } finally {
        if (fs != null && fs.getDataStore() != null) {
            fs.getDataStore().dispose();
        }
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus/*w  ww. ja va  2 s  . c  om*/
 * @param label
 * @param comment
 * @return
 */
public boolean createAnnotationStatus(String label, String comment, String color, JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            AnnotationStatus annotationstatus = (AnnotationStatus) em
                    .createQuery("from AnnotationStatus where label = ?").setParameter(1, label)
                    .getSingleResult();
            tx.commit();
            if (annotationstatus != null) {
                System.out.println(
                        "[CreateAnnotationStatus.createAnnotationStatus] this status already exists. Status : "
                                + label);
                return false;
            }
        } catch (Exception e) {
            tx.rollback();
            System.out.println(
                    "[CreateAnnotationStatus.createAnnotationStatus] this status doesn't already exist. Status : "
                            + label + " is gonna be created.");
        }
        try {
            tx.begin();
            em.persist(_as);
            tx.commit();
            //    em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}