Search in sources :

Example 1 with TaxonGraphException

use of eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException in project cdmlib by cybertaxonomy.

the class TaxonGraphBeforeTransactionCompleteProcess method doBeforeTransactionCompletion.

@Override
public void doBeforeTransactionCompletion(SessionImplementor session) {
    if (logger.isDebugEnabled()) {
        String message = eventType.name() + " for ";
        message += taxonName != null ? taxonName.toString() : "";
        message += nomenclaturalSource != null ? nomenclaturalSource.toString() : "";
        if (eventType.equals(EventType.UPDATE)) {
            message += " with dirty properties: " + Arrays.stream(dirtyProperties).mapToObj(i -> propertyNames[i]).collect(Collectors.joining(", "));
        }
        logger.debug(message);
    }
    try {
        if (eventType.equals(EventType.INSERT)) {
            // ---- INSERT ----
            if (taxonName != null) {
                // 1. do the sanity checks first
                if (taxonName.getNomenclaturalSource() == null || taxonName.getNomenclaturalSource().getCitation() == null) {
                    if (failOnMissingNomRef) {
                        throw new TaxonGraphException("TaxonName.nomenclaturalSource or TaxonName.nomenclaturalSource.citation must never be null.");
                    } else {
                        logger.warn("TaxonName.nomenclaturalSource or TaxonName.nomenclaturalSource.citation must never be null. (" + taxonName.toString() + ")");
                    }
                }
                createTempSession(session);
                onNewTaxonName(taxonName);
                getSession().flush();
            } else if (nomenclaturalSource != null) {
                TaxonName taxonName = (TaxonName) findValueByName(state, NOMENCLATURALSOURCE_SOURCEDNAME);
                Reference reference = (Reference) findValueByName(state, NOMENCLATURALSOURCE_CITATION);
                if (taxonName != null && reference != null) {
                    createTempSession(session);
                    // load name and reference also into this session
                    taxonName = getSession().load(TaxonName.class, taxonName.getId());
                    reference = getSession().load(Reference.class, reference.getId());
                    onNewNomenClaturalSource(taxonName, reference);
                    getSession().flush();
                }
            }
        } else if (eventType.equals(EventType.DELETE)) {
            if (taxonName != null) {
                // handling this case explicitly should not be needed as this is expected to be done by orphan removal in
                // hibernate
                Reference reference = (Reference) oldState[Arrays.binarySearch(propertyNames, TAXONNAME_NOMENCLATURALSOURCE)];
                if (reference != null) {
                    createTempSession(session);
                    onTaxonNameDeleted(taxonName, reference);
                    getSession().flush();
                }
            } else if (nomenclaturalSource != null) {
                TaxonName taxonName = (TaxonName) findValueByName(oldState, NOMENCLATURALSOURCE_SOURCEDNAME);
                Reference reference = (Reference) findValueByName(oldState, NOMENCLATURALSOURCE_CITATION);
                if (taxonName != null && reference != null) {
                    createTempSession(session);
                    onNomReferenceRemoved(taxonName, reference);
                    getSession().flush();
                }
            }
        } else {
            // either taxonName or nomenclaturalSource not null, never both!
            if (taxonName != null) {
                // 1. do the sanity checks first
                Map<String, PropertyStateChange> changedNomenclaturalSourceProp = checkStateChange(TAXONNAME_NOMENCLATURALSOURCE);
                if (!changedNomenclaturalSourceProp.isEmpty()) {
                    if (changedNomenclaturalSourceProp.get(TAXONNAME_NOMENCLATURALSOURCE[0]).newState == null) {
                        throw new TaxonGraphException("TaxonName.nomenclaturalSource must never be reverted to null.");
                    }
                    if (((NomenclaturalSource) changedNomenclaturalSourceProp.get(TAXONNAME_NOMENCLATURALSOURCE[0]).newState).getCitation() == null) {
                        throw new TaxonGraphException("TaxonName.nomenclaturalSource.citation must never be reverted to null.");
                    }
                    createTempSession(session);
                    NomenclaturalSource oldNomenclaturalSource = (NomenclaturalSource) changedNomenclaturalSourceProp.get(TAXONNAME_NOMENCLATURALSOURCE[0]).oldState;
                    onNomReferenceChange(taxonName, oldNomenclaturalSource.getCitation());
                    getSession().flush();
                }
                // 2. update the graph
                Map<String, PropertyStateChange> changedProps = checkStateChange(TAXONNAME_NAMEPARTS_OR_RANK_PROPS);
                if (!changedProps.isEmpty()) {
                    createTempSession(session);
                    onNameOrRankChange(taxonName);
                    getSession().flush();
                }
            } else if (nomenclaturalSource != null) {
                Map<String, PropertyStateChange> changedProps = checkStateChange(CITATION_OR_SOURCEDNAME);
                if (!changedProps.isEmpty()) {
                    TaxonName newTaxonNameState = null;
                    Reference newCitationState = null;
                    TaxonName oldTaxonNameState = null;
                    Reference oldCitationState = null;
                    if (changedProps.containsKey(NOMENCLATURALSOURCE_SOURCEDNAME)) {
                        newTaxonNameState = (TaxonName) changedProps.get(NOMENCLATURALSOURCE_SOURCEDNAME).newState;
                        oldTaxonNameState = (TaxonName) changedProps.get(NOMENCLATURALSOURCE_SOURCEDNAME).oldState;
                    }
                    if (changedProps.containsKey(NOMENCLATURALSOURCE_CITATION)) {
                        newCitationState = (Reference) changedProps.get(NOMENCLATURALSOURCE_CITATION).newState;
                        oldCitationState = (Reference) changedProps.get(NOMENCLATURALSOURCE_CITATION).oldState;
                    }
                    // 1. do the sanity checks first
                    if (oldTaxonNameState != null && oldTaxonNameState.getNomenclaturalSource() == null) {
                        createTempSession(session);
                        onNomReferenceChange(oldTaxonNameState, null);
                        getSession().flush();
                    }
                    // 2. update the graph
                    if (newTaxonNameState != null && newCitationState == null) {
                        createTempSession(session);
                        onNomReferenceChange(newTaxonNameState, nomenclaturalSource.getCitation());
                        getSession().flush();
                    }
                    if (newTaxonNameState == null && newCitationState != null) {
                        createTempSession(session);
                        onNomReferenceChange(nomenclaturalSource.getSourcedName(), oldCitationState);
                        getSession().flush();
                    }
                }
            }
        }
    } catch (TaxonGraphException e) {
        throw new HibernateException(e);
    } finally {
        if (getSession() != null) {
            // temporarySession.close(); // no need to close the session since the session is configured for auto close, see createTempSession()
            if (origLoggerLevel != null) {
                Logger.getLogger("org.hibernate.SQL").setLevel(origLoggerLevel);
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) Reference(eu.etaxonomy.cdm.model.reference.Reference) Session(org.hibernate.Session) Taxon(eu.etaxonomy.cdm.model.taxon.Taxon) HashMap(java.util.HashMap) PostInsertEvent(org.hibernate.event.spi.PostInsertEvent) Logger(org.apache.log4j.Logger) NomenclaturalSource(eu.etaxonomy.cdm.model.name.NomenclaturalSource) TaxonGraphHibernateListener(eu.etaxonomy.cdm.persistence.hibernate.TaxonGraphHibernateListener) Map(java.util.Map) Level(org.apache.log4j.Level) IRunAs(eu.etaxonomy.cdm.api.application.IRunAs) AbstractHibernateTaxonGraphProcessor(eu.etaxonomy.cdm.persistence.dao.hibernate.taxonGraph.AbstractHibernateTaxonGraphProcessor) CdmHibernateListenerConfiguration(eu.etaxonomy.cdm.config.CdmHibernateListenerConfiguration) Collectors(java.util.stream.Collectors) BeforeTransactionCompletionProcess(org.hibernate.action.spi.BeforeTransactionCompletionProcess) Objects(java.util.Objects) PostUpdateEvent(org.hibernate.event.spi.PostUpdateEvent) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) HibernateException(org.hibernate.HibernateException) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) TaxonRelationship(eu.etaxonomy.cdm.model.taxon.TaxonRelationship) ArrayUtils(org.apache.commons.lang.ArrayUtils) PreDeleteEvent(org.hibernate.event.spi.PreDeleteEvent) NomenclaturalSource(eu.etaxonomy.cdm.model.name.NomenclaturalSource) HibernateException(org.hibernate.HibernateException) Reference(eu.etaxonomy.cdm.model.reference.Reference) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with TaxonGraphException

use of eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException in project cdmlib by cybertaxonomy.

the class TaxonGraphHibernateListenerTest method testNewTaxonNameMissingNomRef2.

/**
 * Test for TaxonGraphException when TaxonName.nomenclaturalSource.citation == nulll
 */
@Test
@DataSet(loadStrategy = CleanSweepInsertLoadStrategy.class, value = "TaxonGraphTest.xml")
public void testNewTaxonNameMissingNomRef2() {
    TaxonGraphBeforeTransactionCompleteProcess.setFailOnMissingNomRef(true);
    try {
        setUuidPref();
        Reference refX = ReferenceFactory.newBook();
        refX.setTitleCache("Ref-X", true);
        TaxonName n_t_argentinensis = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES(), "Trachelomonas", null, "argentinensis", null, null, refX, null, null);
        n_t_argentinensis.getNomenclaturalSource().setCitation(null);
        n_t_argentinensis = nameDao.save(n_t_argentinensis);
        Throwable expectedException = null;
        try {
            commitAndStartNewTransaction();
        } catch (Exception e) {
            expectedException = e;
            while (expectedException != null && !(expectedException instanceof TaxonGraphException)) {
                expectedException = expectedException.getCause();
            }
        }
        assertNotNull(expectedException);
    } finally {
        rollback();
    }
}
Also used : Reference(eu.etaxonomy.cdm.model.reference.Reference) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) FileNotFoundException(java.io.FileNotFoundException) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) Test(org.junit.Test) DataSet(org.unitils.dbunit.annotation.DataSet)

Example 3 with TaxonGraphException

use of eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException in project cdmlib by cybertaxonomy.

the class AbstractHibernateTaxonGraphProcessor method assureSingleTaxon.

/**
 * Assurers that there is only one {@link Taxon} for the given name
 * (<code>taxonName</code>) having the the default sec reference
 * ({@link #getSecReferenceUUID()}).
 * <p>
 * If there is no such taxon it will be created when
 * <code>createMissing=true</code>. A <code>TaxonGraphException</code> is
 * thrown when more than one taxa with the default sec reference
 * ({@link #getSecReferenceUUID()}) are found for the given name
 * (<code>taxonName</code>)
 *
 * @param taxonName
 *            The name to check
 * @param createMissing
 *            A missing taxon is created when this is <code>true</code>.
 * @return
 * @throws TaxonGraphException
 *             A <code>TaxonGraphException</code> is thrown when more than
 *             one taxa with the default sec reference
 *             ({@link #getSecReferenceUUID()}) are found for the given name
 *             (<code>taxonName</code>)
 */
public Taxon assureSingleTaxon(TaxonName taxonName, boolean createMissing) throws TaxonGraphException {
    UUID secRefUuid = getSecReferenceUUID();
    Session session = getSession();
    TaxonName taxonNamePersisted = session.load(TaxonName.class, taxonName.getId());
    // filter by secRefUuid
    Taxon taxon = null;
    Set<Taxon> taxa = new HashSet<>();
    for (Taxon t : taxonName.getTaxa()) {
        if (t.getSec() != null && t.getSec().getUuid().equals(secRefUuid)) {
            taxa.add(t);
        }
    }
    if (taxa.size() == 0) {
        if (createMissing) {
            if (taxonNamePersisted != null) {
                Reference secRef = secReference();
                taxon = Taxon.NewInstance(taxonNamePersisted, secRef);
                session.saveOrUpdate(taxon);
            } else {
                throw new TaxonGraphException("Can't create taxon for deleted name: " + taxonName);
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("No taxon found for " + taxonName);
            }
        }
    } else if (taxa.size() == 1) {
        taxon = taxa.iterator().next();
    } else {
        throw new TaxonGraphException("A name to be used in a taxon graph must only have one taxon with the default sec reference [secRef uuid: " + secRefUuid.toString() + "]");
    }
    return taxon != null ? session.load(Taxon.class, taxon.getId()) : null;
}
Also used : Reference(eu.etaxonomy.cdm.model.reference.Reference) Taxon(eu.etaxonomy.cdm.model.taxon.Taxon) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) UUID(java.util.UUID) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) Session(org.hibernate.Session) HashSet(java.util.HashSet)

Example 4 with TaxonGraphException

use of eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException in project cdmlib by cybertaxonomy.

the class TaxonGraphHibernateListenerTest method testNewTaxonNameMissingNomRef1.

/**
 * Test for TaxonGraphException when TaxonName.nomenclaturalSource == nulll
 */
@Test
@DataSet(loadStrategy = CleanSweepInsertLoadStrategy.class, value = "TaxonGraphTest.xml")
public void testNewTaxonNameMissingNomRef1() {
    TaxonGraphBeforeTransactionCompleteProcess.setFailOnMissingNomRef(true);
    try {
        setUuidPref();
        TaxonName n_t_argentinensis = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES(), "Trachelomonas", null, "argentinensis", null, null, null, null, null);
        n_t_argentinensis = nameDao.save(n_t_argentinensis);
        Throwable expectedException = null;
        try {
            commitAndStartNewTransaction();
        } catch (Exception e) {
            expectedException = e;
            while (expectedException != null && !(expectedException instanceof TaxonGraphException)) {
                expectedException = expectedException.getCause();
            }
        }
        assertNotNull(expectedException);
    } finally {
        rollback();
    }
}
Also used : TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) FileNotFoundException(java.io.FileNotFoundException) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) Test(org.junit.Test) DataSet(org.unitils.dbunit.annotation.DataSet)

Example 5 with TaxonGraphException

use of eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException in project cdmlib by cybertaxonomy.

the class TaxonGraphServiceImpl method listIncludedNames.

@Override
public List<TaxonName> listIncludedNames(String queryString, MatchMode matchMode) {
    if (matchMode == null) {
        matchMode = MatchMode.BEGINNING;
    }
    List<TaxonName> includedNames = new ArrayList<>();
    IncludedTaxonConfiguration configuration = new IncludedTaxonConfiguration(null, false, false, false);
    List<TaxonName> matchingNames = nameService.findNamesByTitleCache(queryString, matchMode, null);
    for (TaxonName name : matchingNames) {
        if (logger.isDebugEnabled()) {
            logger.debug("pageIncludedNames() - matching name: " + name.getTitleCache());
        }
        try {
            Taxon graphTaxon = taxonGraphDao.assureSingleTaxon(name, false);
            if (graphTaxon != null) {
                IncludedTaxaDTO includedTaxaDTO = taxonService.listIncludedTaxa(graphTaxon.getUuid(), configuration);
                List<UUID> includedTaxaUUIDs = includedTaxaDTO.getIncludedTaxa().stream().map(IncludedTaxon::getTaxonUuid).collect(Collectors.toList());
                List<TaxonBase> includedTaxa = taxonService.load(includedTaxaUUIDs, null);
                List<TaxonName> iclNames = includedTaxa.stream().map(TaxonBase::getName).collect(Collectors.toList());
                includedNames.addAll(iclNames);
            }
        } catch (TaxonGraphException e) {
            logger.error(e.getMessage());
        }
    }
    return includedNames;
}
Also used : TaxonBase(eu.etaxonomy.cdm.model.taxon.TaxonBase) Taxon(eu.etaxonomy.cdm.model.taxon.Taxon) IncludedTaxon(eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO.IncludedTaxon) ArrayList(java.util.ArrayList) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) IncludedTaxonConfiguration(eu.etaxonomy.cdm.api.service.config.IncludedTaxonConfiguration) UUID(java.util.UUID) TaxonGraphException(eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException) IncludedTaxaDTO(eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO)

Aggregations

TaxonName (eu.etaxonomy.cdm.model.name.TaxonName)5 TaxonGraphException (eu.etaxonomy.cdm.persistence.dao.taxonGraph.TaxonGraphException)5 Reference (eu.etaxonomy.cdm.model.reference.Reference)3 Taxon (eu.etaxonomy.cdm.model.taxon.Taxon)3 FileNotFoundException (java.io.FileNotFoundException)2 UUID (java.util.UUID)2 Session (org.hibernate.Session)2 Test (org.junit.Test)2 DataSet (org.unitils.dbunit.annotation.DataSet)2 IRunAs (eu.etaxonomy.cdm.api.application.IRunAs)1 IncludedTaxonConfiguration (eu.etaxonomy.cdm.api.service.config.IncludedTaxonConfiguration)1 IncludedTaxaDTO (eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO)1 IncludedTaxon (eu.etaxonomy.cdm.api.service.dto.IncludedTaxaDTO.IncludedTaxon)1 CdmHibernateListenerConfiguration (eu.etaxonomy.cdm.config.CdmHibernateListenerConfiguration)1 NomenclaturalSource (eu.etaxonomy.cdm.model.name.NomenclaturalSource)1 TaxonBase (eu.etaxonomy.cdm.model.taxon.TaxonBase)1 TaxonRelationship (eu.etaxonomy.cdm.model.taxon.TaxonRelationship)1 AbstractHibernateTaxonGraphProcessor (eu.etaxonomy.cdm.persistence.dao.hibernate.taxonGraph.AbstractHibernateTaxonGraphProcessor)1 TaxonGraphHibernateListener (eu.etaxonomy.cdm.persistence.hibernate.TaxonGraphHibernateListener)1 ArrayList (java.util.ArrayList)1