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.sigmah.server.servlet.exporter.models.ProjectModelHandler.java

private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, User user) {

    final HashSet<Integer> reportModelsId = new HashSet<Integer>();

    if (layoutGroups != null) {
        for (LayoutGroup layoutGroup : layoutGroups) {

            final List<LayoutConstraint> layoutConstraints;
            if (layoutGroup != null)
                layoutConstraints = layoutGroup.getConstraints();
            else//from w  w w. jav a2 s  .co  m
                layoutConstraints = null;

            if (layoutConstraints != null) {
                // Iterating over the constraints
                for (LayoutConstraint layoutConstraint : layoutConstraints) {
                    if (layoutConstraint != null && layoutConstraint.getElement() != null) {
                        final FlexibleElement element = layoutConstraint.getElement();

                        // Do not persist an element twice.
                        if (em.contains(element)) {
                            continue;
                        }

                        // Initialize export flags of flexible element
                        element.initializeExportFlags();

                        // If the current element is a QuestionElement
                        if (element instanceof QuestionElement) {
                            final QuestionElement questionElement = (QuestionElement) element;
                            List<QuestionChoiceElement> questionChoiceElements = questionElement.getChoices();
                            CategoryType type = questionElement.getCategoryType();
                            if (questionChoiceElements != null || type != null) {

                                questionElement.setChoices(null);
                                questionElement.setCategoryType(null);
                                em.persist(questionElement);

                                // Save QuestionChoiceElement with their
                                // QuestionElement parent(saved above)
                                if (questionChoiceElements != null) {
                                    for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                        if (questionChoiceElement != null) {
                                            questionChoiceElement.setId(null);
                                            questionChoiceElement.setParentQuestion(questionElement);
                                            CategoryElement categoryElement = questionChoiceElement
                                                    .getCategoryElement();
                                            if (categoryElement != null) {
                                                questionChoiceElement.setCategoryElement(null);

                                                em.persist(questionChoiceElement);
                                                saveProjectModelCategoryElement(categoryElement, em,
                                                        modelesReset, modelesImport);
                                                questionChoiceElement.setCategoryElement(categoryElement);
                                                em.merge(questionChoiceElement);
                                            } else {
                                                em.persist(questionChoiceElement);
                                            }
                                        }
                                    }
                                    // Set saved QuestionChoiceElement to
                                    // QuestionElement parent and update it
                                    questionElement.setChoices(questionChoiceElements);
                                }

                                // Save the Category type of QuestionElement
                                // parent(saved above)
                                if (type != null) {
                                    if (em.find(CategoryType.class, type.getId()) == null) {
                                        List<CategoryElement> typeElements = type.getElements();
                                        if (typeElements != null) {
                                            type.setElements(null);
                                            em.merge(type);
                                            for (CategoryElement categoryElement : typeElements) {
                                                if (em.find(CategoryElement.class,
                                                        categoryElement.getId()) == null) {
                                                    categoryElement.setParentType(type);
                                                    saveProjectModelCategoryElement(categoryElement, em,
                                                            modelesReset, modelesImport);
                                                }
                                            }
                                            type.setElements(typeElements);
                                            em.merge(type);
                                        }
                                    }
                                    // Set the saved CategoryType to
                                    // QuestionElement parent and update it
                                    questionElement.setCategoryType(type);
                                }
                                // Update the QuestionElement parent
                                em.merge(questionElement);

                            } else {
                                em.persist(element);
                            }
                        }
                        // Report element
                        else if (element instanceof ReportElement) {
                            final ReportElement reportElement = (ReportElement) element;
                            final ProjectReportModel oldModel = reportElement.getModel();

                            if (oldModel != null) {
                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(user.getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    reportElement.setModel(newModel);
                                    em.persist(reportElement);
                                    reportModelsId.add(reportElement.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    reportElement.setModel(newModel);
                                    em.persist(reportElement);
                                }

                            }

                        }
                        // Reports list element
                        else if (element instanceof ReportListElement) {
                            final ReportListElement reportListElement = (ReportListElement) element;
                            final ProjectReportModel oldModel = reportListElement.getModel();

                            if (oldModel != null) {
                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(user.getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    reportListElement.setModel(newModel);
                                    em.persist(reportListElement);
                                    reportModelsId.add(reportListElement.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    reportListElement.setModel(newModel);
                                    em.persist(reportListElement);
                                }
                            }
                        }
                        // Budget element
                        else if (element instanceof BudgetElement) {
                            final BudgetElement budgetElement = (BudgetElement) element;

                            final List<BudgetSubField> subFields = budgetElement.getBudgetSubFields();
                            final BudgetSubField ratioDividend = budgetElement.getRatioDividend();
                            final BudgetSubField ratioDivisor = budgetElement.getRatioDivisor();

                            budgetElement.setBudgetSubFields(null);
                            budgetElement.setRatioDividend(null);
                            budgetElement.setRatioDivisor(null);

                            em.persist(budgetElement);

                            final ArrayList<BudgetSubField> allSubFields = new ArrayList<BudgetSubField>(
                                    subFields);
                            allSubFields.add(ratioDividend);
                            allSubFields.add(ratioDivisor);

                            for (final BudgetSubField subField : allSubFields) {
                                subField.setBudgetElement(budgetElement);
                                em.persist(budgetElement);
                            }
                            budgetElement.setBudgetSubFields(subFields);
                            budgetElement.setRatioDividend(ratioDividend);
                            budgetElement.setRatioDivisor(ratioDivisor);
                            em.merge(budgetElement);
                        }
                        // Others elements
                        else {
                            em.persist(layoutConstraint.getElement());
                        }
                    }
                }
            }
        }
    }

}

From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * /*  www.  java2  s. co m*/
 * @param accountTransaction
 * @param user
 * @throws java.lang.Exception
 */
public synchronized void commitTransaction(Transaction accountTransaction, User user) throws Exception {
    if (!enableAccounting) {
        return;
    }

    if (accountTransaction != null) {
        //Create an EntityManager
        log.debug("Getting entity manager ......");
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        //Get the account and set the current balance. Update the class variable at the same time.
        Account account = (Account) em.find(Account.class, organizationId);
        balance = account.getCreditBalance();
        //Set the account & user for the accountTransaction.
        accountTransaction.setAccount(account);
        accountTransaction.setUser(user);

        try {
            //Run validation (checks what type of transaction is allowed..)
            accountTransaction.validate();

            //Now check if the transaction either has to deposit or withdraw...
            BigDecimal newBalance = null;
            if (accountTransaction.getType() == Transaction.DEPOSIT) {
                newBalance = balance.add(accountTransaction.getCreditAlteration());
            } else if (accountTransaction.getType() == Transaction.WITHDRAW) {
                newBalance = balance.subtract(accountTransaction.getCreditAlteration());
                if (newBalance.doubleValue() < 0) {
                    throw new TransactionDeniedException("Insufficient credits for transaction. "
                            + "Required credits: "
                            + accountTransaction.getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            + ", " + "Current balance: "
                            + balance.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }
            } else {
                log.error("Unsupported transaction type");
                throw new Exception("Unsupported transaction type");
            }

            account.setCreditBalance(newBalance);
            accountTransaction.setMutationDate(new Date());
            accountTransaction.setStatus(Transaction.ACCEPTED);

            Iterator iterPriceComp = accountTransaction.getLayerPriceCompositions().iterator();
            while (iterPriceComp.hasNext()) {
                LayerPriceComposition lpc = (LayerPriceComposition) iterPriceComp.next();
                em.persist(lpc);
            }

            em.merge(accountTransaction);
            em.flush();
            balance = newBalance;
        } catch (TransactionDeniedException tde) {
            accountTransaction.setErrorMessage(tde.getMessage());
            accountTransaction.setStatus(Transaction.REFUSED);
            em.merge(accountTransaction);
            em.flush();
            throw tde;
        }
    }
}

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

@POST
@Consumes(MediaType.APPLICATION_JSON)//w  w  w .j  a v a2  s  .co m
public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) {
    FeedCategory fc = null;
    EntityManager em;
    EntityTransaction tx;
    User user;
    FeedData feedData;
    Feed f;
    boolean createdNewFD = false;

    if (data.getUrl() == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing"))
                .build();
    }

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

    try {
        if (data.getCategoryId() != 0) {
            try {
                fc = (FeedCategory) em
                        .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class)
                        .setParameter("id", data.getCategoryId()).getSingleResult();
            } catch (NoResultException e) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity(new ErrorDescription("Feed category not found")).build();
            }

            if (!fc.getUser().equals(user)) {
                return Response.status(Response.Status.FORBIDDEN)
                        .entity(new ErrorDescription("Feed category not owned by user")).build();
            }
        }

        // Try to look up existing FeedData
        try {
            feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl())
                    .getSingleResult();
        } catch (NoResultException e) {
            feedData = new FeedData();
            feedData.setUrl(data.getUrl());

            try {
                loadFeedDetails(feedData);
            } catch (Exception ex) {
                e.printStackTrace();
                return Response.status(Response.Status.BAD_GATEWAY)
                        .entity(new ErrorDescription("Cannot fetch the feed")).build();
            }

            em.persist(feedData);
            createdNewFD = true;
        }

        f = new Feed();
        f.setUser(user);
        f.setFeedCategory(fc);
        f.setData(feedData);
        f.setName(feedData.getTitle());

        em.persist(f);

        tx.commit();

        if (createdNewFD)
            FeedsEngine.getInstance().submitFeedRefresh(feedData);

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

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

private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, Authentication authentication) {

    final HashSet<Integer> reportModelsId = new HashSet<Integer>();

    if (layoutGroups != null) {
        for (LayoutGroup layoutGroup : layoutGroups) {

            final List<LayoutConstraint> layoutConstraints;
            if (layoutGroup != null)
                layoutConstraints = layoutGroup.getConstraints();
            else//from   w w w  . ja v  a 2s .c  o m
                layoutConstraints = null;

            if (layoutConstraints != null) {
                // Iterating over the constraints
                for (LayoutConstraint layoutConstraint : layoutConstraints) {
                    if (layoutConstraint != null && layoutConstraint.getElement() != null) {

                        // Do not persist an element twice.
                        if (em.contains(layoutConstraint.getElement())) {
                            continue;
                        }

                        //Initialize export flags of flexible element
                        layoutConstraint.getElement().initializeExportFlags();

                        // If the current element is a QuestionElement
                        if (layoutConstraint.getElement() instanceof QuestionElement) {
                            List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                    .getElement()).getChoices();
                            CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                    .getCategoryType();
                            if (questionChoiceElements != null || type != null) {

                                FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
                                ((QuestionElement) parent).setChoices(null);
                                ((QuestionElement) parent).setCategoryType(null);
                                em.persist(parent);

                                // Save QuestionChoiceElement with their
                                // QuestionElement parent(saved above)
                                if (questionChoiceElements != null) {
                                    for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                        if (questionChoiceElement != null) {
                                            questionChoiceElement.setId(null);
                                            questionChoiceElement.setParentQuestion((QuestionElement) parent);
                                            CategoryElement categoryElement = questionChoiceElement
                                                    .getCategoryElement();
                                            if (categoryElement != null) {
                                                questionChoiceElement.setCategoryElement(null);

                                                em.persist(questionChoiceElement);
                                                saveProjectModelCategoryElement(categoryElement, em,
                                                        modelesReset, modelesImport);
                                                questionChoiceElement.setCategoryElement(categoryElement);
                                                em.merge(questionChoiceElement);
                                            } else {
                                                em.persist(questionChoiceElement);
                                            }
                                        }
                                    }
                                    // Set saved QuestionChoiceElement to
                                    // QuestionElement parent and update it
                                    ((QuestionElement) parent).setChoices(questionChoiceElements);
                                }

                                // Save the Category type of QuestionElement
                                // parent(saved above)
                                if (type != null) {
                                    if (em.find(CategoryType.class, type.getId()) == null) {
                                        List<CategoryElement> typeElements = type.getElements();
                                        if (typeElements != null) {
                                            type.setElements(null);
                                            em.merge(type);
                                            for (CategoryElement element : typeElements) {
                                                if (em.find(CategoryElement.class, element.getId()) == null) {
                                                    element.setParentType(type);
                                                    saveProjectModelCategoryElement(element, em, modelesReset,
                                                            modelesImport);
                                                }
                                            }
                                            type.setElements(typeElements);
                                            em.merge(type);
                                        }
                                    }
                                    // Set the saved CategoryType to
                                    // QuestionElement parent and update it
                                    ((QuestionElement) parent).setCategoryType(type);
                                }
                                // Update the QuestionElement parent
                                em.merge(parent);
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                        // Report element
                        else if (layoutConstraint.getElement() instanceof ReportElement) {

                            final ReportElement element = (ReportElement) layoutConstraint.getElement();
                            final ProjectReportModel oldModel = element.getModel();

                            if (oldModel != null) {

                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(authentication.getUser().getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    element.setModel(newModel);
                                    em.persist(element);
                                    reportModelsId.add(element.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    element.setModel(newModel);
                                    em.persist(element);
                                }

                            }

                        }
                        // Reports list element
                        else if (layoutConstraint.getElement() instanceof ReportListElement) {

                            final ReportListElement element = (ReportListElement) layoutConstraint.getElement();
                            final ProjectReportModel oldModel = element.getModel();

                            if (oldModel != null) {

                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(authentication.getUser().getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    element.setModel(newModel);
                                    em.persist(element);
                                    reportModelsId.add(element.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    element.setModel(newModel);
                                    em.persist(element);
                                }

                            }

                        }
                        // Others elements
                        else {
                            em.persist(layoutConstraint.getElement());
                        }
                    }
                }
            }
        }
    }

}

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

public void setPublisherAssertions(String authInfo, Holder<List<PublisherAssertion>> publisherAssertion)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  www .  ja v  a 2s .co  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion);

        List<?> businessKeysFound = null;
        businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);

        // First, wipe out all previous assertions associated with this publisher
        DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound);

        // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new").
        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = publisherAssertion.value;
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class,
                    modelPubAssertion.getId().getFromKey());
            org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class,
                    modelPubAssertion.getId().getToKey());
            modelPubAssertion.setBusinessEntityByFromKey(beFrom);
            modelPubAssertion.setBusinessEntityByToKey(beTo);

            modelPubAssertion.setFromCheck("false");
            modelPubAssertion.setToCheck("false");

            em.persist(modelPubAssertion);

            if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                modelPubAssertion.setFromCheck("true");
            if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                modelPubAssertion.setToCheck("true");

        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Generic persist method for data set objects.
 * //from   w ww  .j  a  v  a  2  s  .  c  o  m
 * @param dataSet
 *            data set to persist
 * @param pType
 *            which type of persistence operation, new, update (i.e. overwrite existing data set), ...
 * @param out
 *            PrintWriter to log error messages which can be presented to the end user
 * @return true if persist is successful, false otherwise
 * @see #preCheckAndPersist(DataSet)
 */
public boolean checkAndPersist(T dataSet, PersistType pType, PrintWriter out) {
    // TODO: check if version shall be excluded for some types

    if (dataSet.getRootDataStock() == null) {
        out.println("Error: root data stock must not be null!");
        return false;
    }

    // perform pre-persist actions
    this.preCheckAndPersist(dataSet);

    EntityManager em = PersistenceUtil.getEntityManager();

    // locate existing method by UUID
    T existingDataSet = this.getByUuidAndVersion(dataSet.getUuidAsString(), dataSet.getVersion());

    // if existing found ...
    if (existingDataSet != null) {
        // ... and mode is set to only new ...
        if (PersistType.ONLYNEW.equals(pType)) {
            if (out != null) {
                out.println("Warning: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                        + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                        + " already exists in database; will ignore this data set.");
            }
            // ... just ignore it
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    // now the DB interaction
    try {
        t.begin();
        // delete existing for merge operation
        if (existingDataSet != null && PersistType.MERGE.equals(pType)) {
            if (out != null) {
                out.println("Notice: " + this.getAccessedClass().getSimpleName() + " method data set with uuid "
                        + existingDataSet.getUuidAsString() + " and version "
                        + existingDataSet.getVersion().getVersionString()
                        + " already exists in database; will replace it with this data set");
            }
            em.remove(existingDataSet);
        }
        // persist the new method
        em.persist(dataSet);

        // actual write to DB
        t.commit();

        // set the most recent version flags correctly
        if (!this.setMostRecentVersionFlags(dataSet.getUuidAsString())) {
            return false;
        }

        // and return with success :)
        return true;
    } catch (Exception e) {
        DataSetDao.LOGGER.error(
                "Cannot persist " + this.getAccessedClass().getSimpleName() + " data set with uuid {}",
                dataSet.getUuidAsString());
        DataSetDao.LOGGER.error("Exception is: ", e);
        if (out != null) {
            out.println("Error: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                    + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                    + " could not be saved into database; unknown database error; Exception message: "
                    + e.getMessage());
        }
        t.rollback();
    }

    return false;
}

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

public void loadShippingRegion() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from ShippingRegion where siteId = :siteId order by shippingRegionId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRegion master = (ShippingRegion) iterator.next();
        ShippingRegion shippingRegion = new ShippingRegion();
        Set<Country> countries = shippingRegion.getCountries();
        Set<State> states = shippingRegion.getStates();
        PropertyUtils.copyProperties(shippingRegion, master);
        shippingRegion.setSite(site);// w  w w .j  a  va 2 s  . co  m
        shippingRegion.setShippingRegionId(null);
        shippingRegion.setRecUpdateBy(userId);
        shippingRegion.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        shippingRegion.setRecCreateBy(userId);
        shippingRegion.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        shippingRegion.setCountries(countries);
        shippingRegion.setStates(states);
        shippingRegion.setZipCodes(null);
        shippingRegion.setShippingMethodRegions(null);
        shippingRegion.setShippingMethodRegionTypes(null);
        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());
                shippingRegion.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());
                shippingRegion.getStates().add(state);
            }
        }
        shippingRegions.add(shippingRegion);
        em.persist(shippingRegion);
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from  www.ja v a  2 s .  com
 * 
 * @see org.opencastproject.serviceregistry.api.ServiceRegistry#registerHost(java.lang.String, int)
 */
@Override
public void registerHost(String host, int maxJobs) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing registrations for this host and if it exists, update it
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, host);
        if (hostRegistration == null) {
            hostRegistration = new HostRegistrationJpaImpl(host, maxJobs, true, false);
            em.persist(hostRegistration);
        } else {
            hostRegistration.setMaxJobs(maxJobs);
            hostRegistration.setOnline(true);
            em.merge(hostRegistration);
        }
        logger.info("Registering {} with a maximum load of {}", host, maxJobs);
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);//from w ww .  j a va2 s .  c  o m
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

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

public void saveSubscription(String authInfo, Holder<List<Subscription>> subscription)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  w  w w .  j  a v a2  s.  c  o  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);
        new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value);

        List<org.uddi.sub_v3.Subscription> apiSubscriptionList = subscription.value;
        for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) {

            org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription();

            Object existing = em.find(org.apache.juddi.model.Subscription.class,
                    apiSubscription.getSubscriptionKey());
            if (existing != null) {
                org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing;
                doRenewal(existingEntity, apiSubscription);
                //carrying over the created and last notified dates if this is a renewal.
                modelSubscription.setCreateDate(existingEntity.getCreateDate());
                modelSubscription.setLastNotified(existingEntity.getLastNotified());
                em.remove(existing);
            } else {
                modelSubscription.setCreateDate(new Date());
            }

            doSubscriptionExpirationDate(apiSubscription);

            MappingApiToModel.mapSubscription(apiSubscription, modelSubscription);

            modelSubscription.setAuthorizedName(publisher.getAuthorizedName());

            // Add the matching keys to the match collection
            List<?> keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em);
            if (keys != null && keys.size() > 0) {
                for (Object key : keys) {
                    SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String) key);
                    modelSubscription.getSubscriptionMatches().add(subMatch);
                }
            }

            em.persist(modelSubscription);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}