Example usage for javax.persistence EntityManager contains

List of usage examples for javax.persistence EntityManager contains

Introduction

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

Prototype

public boolean contains(Object entity);

Source Link

Document

Check if the instance is a managed entity instance belonging to the current persistence context.

Usage

From source file:edu.vt.middleware.gator.JpaConfigManager.java

/** {@inheritDoc}. */
@Transactional(propagation = Propagation.REQUIRED)
public void delete(final ProjectConfig project) {
    final EntityManager em = getEntityManager();
    if (logger.isDebugEnabled()) {
        logger.debug("Deleting " + project);
    }//from w ww  .j  av a 2s. com

    ProjectConfig liveProject = project;
    if (!em.contains(project)) {
        liveProject = find(ProjectConfig.class, project.getId());
    }
    // Touch all collections to lazy load dependent data so complete project
    // configuration is available to event handlers
    liveProject.getAppenders();
    liveProject.getCategories();
    liveProject.getClients();
    liveProject.getPermissions();

    em.remove(liveProject);

    // Fire events on a separate thread so we do not disrupt client thread
    // (e.g. avoid subscriber blocking)
    for (ConfigChangeListener listener : getConfigChangeListeners()) {
        eventExecutor.execute(new ProjectRemovedEvent(listener, liveProject));
    }
}

From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testPersist() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager em = emf.createEntityManager();
    PObject pc = new PObject("XYZ");
    em.getTransaction().begin();/*from w ww .j  av  a2s  . c  o  m*/
    em.persist(pc);
    em.getTransaction().commit();
    Object oid = pc.getId();

    em.clear();
    // After clean the instance must not be in L1 cache
    assertFalse(em.contains(pc));
    // But it must be found in L2 cache by its OpenJPA identifier
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));

    PObject pc2 = em.find(PObject.class, oid);
    // After find(), the original instance is not in the L1 cache
    assertFalse(em.contains(pc));
    // After find(), the found instance is in the L1 cache
    assertTrue(em.contains(pc2));
    // The L2 cache must still hold the key   
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Initializes a TaskAction by denoting an EntityManager and a model.
 *
 * The model is made persistent by the EntityManager.
 * The EntityManager and the model are stored, using {@code setOwnEntityManager()} and {@code setModelAndBackup()}.
 * A Backup of the model is done.//from   www.  j  ava2  s.  co m
 *
 *
 * @param em an EntityManager, storing AbstractTasks
 * @param model an AbstractTask to be stored as model of {@code this} and to be stored in the database
 */
public void initFromModel(final EntityManager em, AbstractTask model) {

    boolean wasActive = em.getTransaction().isActive();
    if (!wasActive)
        em.getTransaction().begin();
    try {
        final boolean contained = em.contains(model);
        if (!contained) {
            try {
                em.persist(model);
            } catch (EntityExistsException e) {
                model = em.merge(model);
            }
        }
        if (!wasActive)
            em.getTransaction().commit();
        setOwnEntityManager(em);
        setModelAndBackup(model);
    } finally {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
    }
}

From source file:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);/*from w w  w . jav a2 s.  com*/

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.close();
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Stopps the computation of the model if the task lifetime is already exceeded.
 *
 * If the lifetime is exceeded, it sets the TaskState of the given model as well as the corresponding AbstractTask
 * in the database (if still present) to {@code FAILURE} by invoking {@code fail()}.
 *
 * @see #fail(RuntimeException)// w w  w.jav  a2 s.c o  m
 * @see AbstractTask#fail(Exception)
 *  
 * @param model a task with a termination time
 * @param em the entityManager storing the model
 */
private void checkTimeout(@NotNull AbstractTask model, @NotNull EntityManager em) {

    // check the task lifetime
    if (model.getTerminationTime().compareTo(new GregorianCalendar()) < 1) {
        getLog().debug("Task lifetime exceeded");
        TxFrame tx = new TxFrame(em);
        boolean containt = false;
        try {
            // check if model is still there
            containt = em.contains(model);
            if (containt) {
                model.fail(new RuntimeException("Task lifetime exceeded"));
                getLog().debug("Try to persist task");
            }
            tx.commit();
        } catch (Exception e) {
            // exception here  doesn't really matter
            // task is doomed anyway
            getLog().warn(e);
        } finally {
            tx.finish();
        }
        // interrupt this thread
        getLog().debug("Stopping task thread");
        //Thread.currentThread().interrupt();
        if (containt)
            refreshTaskResource();
        fail(new RuntimeException("Task lifetime exceeded"));
    }
}

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 ww.  ja v a2  s.  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:de.zib.gndms.logic.model.TaskAction.java

/**
 * Retrieves the current model and checks if its lifetime is already exceeded.
 * In this case the model's TaskState will be set to {@code failed} and a {@link FailedException} is thrown,
 * which will stop the the main loop in {@code execute()}.
 *
 * Otherwise, the model's TaskState is set to {@code newState} and {@link #transit(TaskState, AbstractTask)}
 * will be invoked,/*from   www. j  a  va2s.c o  m*/
 * which calls a method corresponding to the TaskState {@code newState} and throws a {@code TransitException} after its
 * execution specifying the next TaskSate value for the model.
 *
 * The model is made persistent by the EntityManager and the changed model will be 
 * commited to the database.
 * If something goes wrong while commiting the new model, a stable rollback is assured.
 *
 * @param newState the new TaskState for the model
 */
@SuppressWarnings({ "CaughtExceptionImmediatelyRethrown", "ThrowableInstanceNeverThrown" })
private void transit(final TaskState newState) {

    if (getCancelled()) {
        log.debug("cancelled");
        throw new StopException(TaskState.IN_PROGRESS_UNKNOWN);
    }

    EntityManager em = getEntityManager();
    @NotNull
    AbstractTask model = getModel();

    // this throws a stop exception on timeout
    if (!(TaskState.FINISHED.equals(newState) || TaskState.FAILED.equals(newState)))
        checkTimeout(model, em);

    try {
        em.getTransaction().begin();
        if (newState != null) {
            if (!em.contains(model)) {
                log.debug("model not in EntityManager");
                try {
                    try {
                        em.persist(model);
                    } catch (EntityExistsException e) {
                        log.debug("persisting failed merging", e);
                        rewindTransaction(em.getTransaction());
                        em.merge(model);
                    }
                } catch (RuntimeException e2) {
                    log.debug("probably persisting and merging failed", e2);
                    rewindTransaction(em.getTransaction());
                    final @NotNull AbstractTask newModel = em.find(AbstractTask.class, model.getId());
                    model.mold(newModel);
                    newModel.refresh(em);
                    setModel(newModel);
                    model = getModel();
                    log.debug("completed renewing of model");
                }
            }
        }

        model.transit(newState);

        boolean committed = false;
        try {
            em.getTransaction().commit();
            //                em.flush( );
            committed = true;
        } catch (Exception e) {
            log.debug("commit of transit (" + newState.name() + ") model failed ", e);
            try {
                rewindTransaction(em.getTransaction());
                // if this point is reached s.th. is terribly foobared
                // restore backup and fail
                model = Copier.copy(false, backup);
                em.merge(model);
                // backup should be clean so commit mustn't fail.
                model.fail(e);
                em.getTransaction().commit();
            } catch (Exception e2) {
                log.debug("restoring previous version failed", e2);
                try {
                    // refresh em for final commit
                    EntityManagerAux.rollbackAndClose(em);
                } catch (RuntimeException e3) {
                    log.debug("rollback old em failed", e3);
                }

                EntityManager nem = emf.createEntityManager();
                TxFrame tx = new TxFrame(nem);
                try {
                    log.debug("loading fresh model");
                    model = nem.find(model.getClass(), backup.getId());
                    boolean unkown = (model == null);
                    model = Copier.copy(false, backup);
                    model.fail(e2);
                    if (unkown)
                        nem.persist(model);
                    //     else
                    //         nem.merge( model );
                    tx.commit();
                    setModel(model);
                } catch (RuntimeException e3) {
                    log.debug("exception during refresh: ", e3);
                    throw e3;
                } finally {
                    tx.finish();
                    setOwnEntityManager(nem);
                    em = nem;
                }
            }
        }

        // if model could be commited it has a clean state
        // refresh backup
        if (committed)
            setBackup(Copier.copy(false, model));

        final TaskState modelState = model.getState();
        refreshTaskResource();
        //noinspection HardcodedFileSeparator
        trace("on" + modelState + "()", null);
        transit(modelState, model);
    }
    // for debugging
    catch (RuntimeException e) {
        throw e;
    } finally {
        try {
            // for debuggin'
            boolean ta = em.getTransaction().isActive();
            if (ta) {
                log.debug("final rollback");
                em.getTransaction().rollback();
            }
        } catch (Exception e) {
            log.debug("final rollback failed", e);
        }
    }
}

From source file:sf.net.experimaestro.scheduler.Resource.java

public void save(Transaction transaction) {
    final EntityManager em = transaction.em();

    // Lock all the dependencies
    // This avoids to miss any notification
    List<EntityLock> locks = new ArrayList<>();
    lockDependencies: while (true) {
        // We loop until we get all the locks - using a timeout just in case
        for (Dependency dependency : getDependencies()) {
            final EntityLock lock = dependency.from.lock(transaction, false, 100);
            if (lock == null) {
                for (EntityLock _lock : locks) {
                    _lock.close();//from   www  .  j  a  va 2  s .c  om
                }
                continue lockDependencies;
            }

            locks.add(lock);
        }

        break;
    }

    for (Dependency dependency : getDependencies()) {
        if (!em.contains(dependency.from)) {
            dependency.from = em.find(Resource.class, dependency.from.getId());
        } else {
            em.refresh(dependency.from);
        }
    }

    prepared = true;
    em.persist(this);

    // Update the status
    updateStatus();
}

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/*  w w w .j  a va 2s.com*/
                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:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Sets the provided document and all tokens contained therein as having been seen.
 * @param em the {@link EntityManager} to use.
 * @param document the {@link LexiconBuilderDocument} object to mark as seen.
 * @param seenTags a delimited list of POS tags to mark as seen.
 * @return the supplied {@link LexiconBuilderDocument}.
 *///from  www  .j a  va2s  .c o  m
public LexiconBuilderDocument setSeenDocument(EntityManager em, LexiconBuilderDocument document,
        String seenTags) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(document, CannedMessages.NULL_ARGUMENT, "document");
    Validate.notNull(document.getStore(), CannedMessages.NULL_ARGUMENT, "document.store");
    Validate.notNull(document.getBaseDocument(), CannedMessages.NULL_ARGUMENT, "document.baseDocument");

    document.setSeen(true);

    if (document.getBaseDocument() instanceof FullTextDocument
            && document.getStore() instanceof LexiconBuilderDocumentStore) {
        List<LexiconDocument> seenTokens = this.getSeenTokens(em,
                (LexiconBuilderDocumentStore) document.getStore());
        FullTextDocument ftDoc = (FullTextDocument) document.getBaseDocument();
        for (final LinguisticToken token : ftDoc.getParsedContent().getTokens()) {
            if (seenTags != null && !token.getPosTag().is(seenTags)) {
                continue;
            }

            LexiconDocument seenToken = Iterables.find(seenTokens, new Predicate<LexiconDocument>() {
                @Override
                public boolean apply(LexiconDocument seenToken) {
                    return seenToken.getContent().equalsIgnoreCase(token.toString());
                }
            }, null);

            if (seenToken == null) {
                seenToken = (LexiconDocument) new LexiconDocument().setContent(token.toString())
                        .setStore(document.getStore());

                em.persist(seenToken);
            }
        }
    }

    if (em.contains(document)) {
        em.refresh(document);
    } else {
        em.persist(document);
    }

    return document;
}