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.apache.juddi.api.impl.UDDIPublicationImplExt.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.ja  v  a  2s.co  m*/
    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);
    }

    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.eclipse.jubula.client.core.businessprocess.TestresultSummaryBP.java

/**
 * Recursively build list of test result details to persist in database.
 * /*w ww.j a va 2  s.  com*/
 * @param result TestResultNode
 * @param sess Session
 * @param summaryId id of testrun summary
 * @param nodeLevel "Indentation"-level of the node.
 * @param startingNodeSequence Initial sequence number for this section
 *                             of the Test Results.
 *                             
 * @return the continuation of the sequence number.
 */
private int buildTestResultDetailsSession(TestResultNode result, EntityManager sess, Long summaryId,
        final int nodeLevel, final int startingNodeSequence) {
    int nodeSequence = startingNodeSequence;
    TestResultNode resultNode = result;
    ITestResultPO keyword = PoMaker.createTestResultPO();
    fillNode(keyword, resultNode);
    keyword.setKeywordLevel(nodeLevel);
    keyword.setKeywordSequence(nodeSequence);
    keyword.setInternalTestResultSummaryID(summaryId);
    keyword.setInternalParentKeywordID(m_parentKeyWordId);
    sess.persist(keyword);
    for (TestResultNode node : resultNode.getResultNodeList()) {
        m_parentKeyWordId = keyword.getId();
        nodeSequence = buildTestResultDetailsSession(node, sess, summaryId, nodeLevel + 1, nodeSequence + 1);
    }

    return nodeSequence;
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImplExt.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);/*  w  w w.j  a  va  2 s  .com*/
    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);
    }

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

/**
 * This method will either create a new rating or update an
 * existing rating//from  ww w.  j  a  v a 2 s.c  om
 * 
 * @param  Must not be null
 * @return the attached entity
 * 
 */
@Override
@PortalTransactional
public IMarketplaceRating createOrUpdateRating(IMarketplaceRating marketplaceRatingImplementation) {
    Validate.notNull(marketplaceRatingImplementation, "MarketplaceRatingImpl must not be null");
    final EntityManager entityManager = this.getEntityManager();
    IMarketplaceRating temp = this.getRating(marketplaceRatingImplementation.getMarketplaceRatingPK());
    if (!entityManager.contains(marketplaceRatingImplementation) && temp != null) {
        //Entity is not managed and there is a rating for this portlet/user - update needed
        temp = entityManager.merge(marketplaceRatingImplementation);
    } else {
        //Entity is either already managed or doesn't exist - create needed
        temp = marketplaceRatingImplementation;
    }
    entityManager.persist(temp);
    return temp;
}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

@Override
public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User user = getUser(dynaForm, request, true);
    ActionForward af = saveCheck(user, mapping, dynaForm, request);
    if (af != null) {
        return af;
        /*//  ww  w .j a v a2s.c  o m
         * Check if this user gets a valid capability when using this personalURL
         */
    }

    Organization org = user.getMainOrganization();
    if (org != null && !org.getHasValidGetCapabilities()) {
        // TODO: we should check for the combination of all organisations
        addAlternateMessage(mapping, request, CAPABILITY_WARNING_KEY);
    }

    /* controleren of er rollen zijn gekozen */
    Integer[] roleSelected = (Integer[]) dynaForm.get("roleSelected");
    int size = roleSelected.length;

    if (size < 1) {
        addAlternateMessage(mapping, request, NOROLES_WARNING_KEY);
    }

    populateUserObject(user, dynaForm, request);

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    if (user.getId() == null) {
        em.persist(user);
    } else {
        em.merge(user);
    }
    em.flush();

    updatePrincipal(request, user);

    populateUserForm(user, dynaForm, request);
    createLists(dynaForm, request);

    prepareMethod(dynaForm, request, EDIT, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public UserAction addUserTrackingEvent(UserAction a) throws UserTrackingException {
    EntityManager em = null;
    EntityTransaction tx = null;/*from w w  w.jav a2 s.  c o  m*/
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(a);
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:fr.mby.portal.coreimpl.auth.DbPortalUserAuthenticationProvider.java

/** Init the DB with default users : user:user456 & admin:admin456 */
protected void initDefaultUsers() {
    final PortalUser user = this.buildPortalUser("user", "user456");
    final PortalUser admin = this.buildPortalUser("admin", "admin456");

    final EntityManager portalUserEm = this.portalUserEmf.createEntityManager();

    // Remove transaction
    portalUserEm.getTransaction().begin();

    final PortalUser foundAdmin = this.findPortalUserByLogin(portalUserEm, "admin");
    if (foundAdmin != null) {
        portalUserEm.remove(foundAdmin);
    }//from ww  w .j  av a  2 s  .c  o m

    final PortalUser foundUser = this.findPortalUserByLogin(portalUserEm, "user");
    if (foundUser != null) {
        portalUserEm.remove(foundUser);
    }

    portalUserEm.getTransaction().commit();

    // Insert transaction
    portalUserEm.getTransaction().begin();

    portalUserEm.persist(user);
    portalUserEm.persist(admin);

    portalUserEm.getTransaction().commit();

    portalUserEm.close();
}

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

@Override
public void importModel(InputStream inputStream, EntityManager em, User user) throws Exception {
    ObjectInputStream objectInputStream;
    em.getTransaction().begin();/*from   w w w. j a va2 s.com*/
    try {
        objectInputStream = new ObjectInputStream(inputStream);
        OrgUnitModel orgUnitModel = (OrgUnitModel) objectInputStream.readObject();
        orgUnitModel.resetImport();
        saveOrgUnitFlexibleElement(orgUnitModel, em);

        // Set the staus to DRAFT
        orgUnitModel.setStatus(ProjectModelStatus.DRAFT);
        orgUnitModel.setOrganization(user.getOrganization());
        em.persist(orgUnitModel);
        em.getTransaction().commit();
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

/**
 * Main test entry point//from ww w .j  a  va2 s. c om
 * 
 * @since $version
 */
@Test
public void testJpa() {
    Thread.currentThread().setContextClassLoader(
            new TestClassLoader(BenchmarkTest.DB, Thread.currentThread().getContextClassLoader()));

    BenchmarkTest.LOG.info("Benchmark will be run for {0}@{1}",
            BenchmarkTest.TYPE.name().toLowerCase(Locale.ENGLISH), BenchmarkTest.DB);

    BenchmarkTest.LOG.info("Deploying the persistence unit...");

    final EntityManagerFactory emf = Persistence
            .createEntityManagerFactory(BenchmarkTest.TYPE.name().toLowerCase());

    BenchmarkTest.LOG.info("Done deploying the persistence unit.");

    BenchmarkTest.LOG.info("Deploying the persistence unit...");

    final EntityManager em = this.open(emf);
    this.country = new Country();

    this.country.setName("Turkey");
    em.persist(this.country);

    this.close(em);

    this.threadIds = new long[BenchmarkTest.THREAD_COUNT];
    this.currentThreadTimes = new long[BenchmarkTest.THREAD_COUNT];

    BenchmarkTest.LOG.info("Done preparing the countries");

    BenchmarkTest.LOG.info("Running the warm up phase with {0} threads, {1} iterations...",
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.ITERATIONS / 10);
    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
    ThreadPoolExecutor pool = this.createExecutor(workQueue);

    // warm mup
    this.test(emf, workQueue, BenchmarkTest.ITERATIONS / 10);
    this.waitUntilFinish(pool);

    BenchmarkTest.LOG.info("Done running warm up phase");

    BenchmarkTest.LOG.info("Starting the benchmark with {0} threads, {1} iterations...",
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.ITERATIONS);

    workQueue = new LinkedBlockingQueue<Runnable>();
    pool = this.createExecutor(workQueue);

    final long started = System.currentTimeMillis();
    // for real
    this.test(emf, workQueue, BenchmarkTest.ITERATIONS);
    this.running = true;
    this.waitUntilFinish(pool);
    this.running = false;
    this.totalTime = (System.currentTimeMillis() - started);

    BenchmarkTest.LOG.info("Benchmark has been completed...");

    try {
        Thread.sleep(1000);
    } catch (final InterruptedException e) {
    }

    emf.close();
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * //  ww w. jav  a 2s . c o  m
 * @param proj
 *            ProjectPO to be attached and saved.
 * @param newProjectName
 *            name part of the ProjectNamePO. If there is no new name, this
 *            parameter must be null (same project, different version)
 * @param mapperList mapper to resolve Parameter Names
 * @param compNameBindingList mapper to resolve Component Names
 * @param monitor The progress monitor for this potentially long-running 
 *                operation.
 * @throws PMException
 *             in case of any db error
 * @throws ProjectDeletedException if project is already deleted
 * @throws InterruptedException if the operation was canceled.
 */
public static void attachProjectToROSession(IProjectPO proj, String newProjectName,
        List<INameMapper> mapperList, List<IWritableComponentNameMapper> compNameBindingList,
        IProgressMonitor monitor) throws PMException, ProjectDeletedException, InterruptedException {

    monitor.beginTask(NLS.bind(Messages.ProjectWizardCreatingProject, newProjectName),
            getTotalWorkForSave(proj));
    // Register Persistence progress listeners
    setHbmProgressMonitor(monitor);
    GeneralStorage.getInstance().reset();
    EntityManager s = GeneralStorage.getInstance().getMasterSession();
    EntityTransaction tx = null;
    try {
        tx = Persistor.instance().getTransaction(s);

        s.persist(proj);
        proj.setParentProjectId(proj.getId());
        if (newProjectName != null) {
            ProjectNameBP.getInstance().setName(s, proj.getGuid(), newProjectName);
        }
        ProjectNameBP.getInstance().storeTransientNames(s);
        for (INameMapper mapper : mapperList) {
            mapper.persist(s, proj.getId());
        }
        for (IWritableComponentNameMapper compNameBinding : compNameBindingList) {
            CompNamePM.flushCompNames(s, proj.getId(), compNameBinding);
        }
        if (!monitor.isCanceled()) {
            Persistor.instance().commitTransaction(s, tx);
            GeneralStorage.getInstance().setProject(proj);
            for (INameMapper mapper : mapperList) {
                mapper.updateStandardMapperAndCleanup(proj.getId());
            }
            for (IComponentNameMapper compNameBinding : compNameBindingList) {
                compNameBinding.getCompNameCache().updateStandardMapperAndCleanup(proj.getId());
            }
        } else {
            Persistor.instance().rollbackTransaction(s, tx);
            GeneralStorage.getInstance().reset();
            for (INameMapper mapper : mapperList) {
                mapper.clearAllNames();
            }
            for (IComponentNameMapper compNameBinding : compNameBindingList) {
                compNameBinding.getCompNameCache().clear();
            }
            throw new InterruptedException();
        }
    } catch (PMException pme) {
        handleAlreadyLockedException(mapperList, s, tx);
    } catch (OperationCanceledException oce) {
        handleOperationCanceled(mapperList, s, tx);
    } catch (PersistenceException e) {
        handlePersistenceException(mapperList, s, tx, e);
    } catch (IncompatibleTypeException ite) {
        handleIncompatibleTypeException(mapperList, s, tx, ite);
    } finally {
        // Remove Persistence progress listeners
        setHbmProgressMonitor(null);
    }
    initBPs(proj);
}