Search in sources :

Example 1 with UnitsGatheringEvent

use of eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent in project cdmlib by cybertaxonomy.

the class SpecimenSythesysExcelImport method start.

/*
     * Store the unit with it's Gathering informations in the CDM
     */
public boolean start(SpecimenSynthesysExcelImportConfigurator config) {
    boolean result = true;
    // refreshTransaction();
    try {
        /**
         * SPECIMEN OR OBSERVATION OR LIVING
         */
        DerivedUnitFacade derivedUnitFacade = getFacade();
        derivedUnitBase = derivedUnitFacade.innerDerivedUnit();
        // set catalogue number (unitID)
        derivedUnitFacade.setCatalogNumber(unitID);
        derivedUnitFacade.setAccessionNumber(accessionNumber);
        if (!originalsource.isEmpty()) {
            Reference reference = ReferenceFactory.newGeneric();
            reference.setTitleCache(originalsource, true);
            derivedUnitBase.addSource(OriginalSourceType.Import, originalsource, "", reference, "");
        } else {
            derivedUnitBase.addSource(OriginalSourceType.Import, unitID, "", ref, ref.getCitation());
        }
        // manage institution
        if (!institutionCode.isEmpty()) {
            Institution institution = getInstitution(config);
            // manage collection
            if (!collectionCode.isEmpty()) {
                Collection collection = getCollection(institution, config);
                // link specimen & collection
                derivedUnitFacade.setCollection(collection);
            }
        }
        /**
         * GATHERING EVENT
         */
        // gathering event
        UnitsGatheringEvent unitsGatheringEvent = new UnitsGatheringEvent(getTermService(), locality, languageIso, longitude, latitude, gatheringAgent, gatheringTeam, config);
        // country
        UnitsGatheringArea unitsGatheringArea = new UnitsGatheringArea();
        unitsGatheringArea.useTDWGareas(this.useTDWGarea);
        // unitsGatheringArea.setConfig(config, getOccurrenceService(),getTermService());
        unitsGatheringArea.setParams(isocountry, country, config, getTermService(), getVocabularyService());
        DefinedTermBase areaCountry = unitsGatheringArea.getCountry();
        // copy gathering event to facade
        GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
        // join gatheringEvent to fieldObservation
        derivedUnitFacade.setGatheringEvent(gatheringEvent);
        derivedUnitFacade.setLocality(gatheringEvent.getLocality());
        derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
        // derivedUnitFacade.setCollector(gatheringEvent.getCollector());
        derivedUnitFacade.setCountry((NamedArea) areaCountry);
        for (DefinedTermBase<?> area : unitsGatheringArea.getAreas()) {
            derivedUnitFacade.addCollectingArea((NamedArea) area);
        }
        if (gatheringNotes != null && !gatheringNotes.isEmpty()) {
            derivedUnitFacade.setFieldNotes(gatheringNotes);
        }
        /*
             * merge AND STORE DATA
             */
        // getTermService().saveOrUpdate(areaCountry);// TODO save area sooner
        getTermService().saveLanguageData(unitsGatheringEvent.getLocality());
        // add gathering date
        if (keepAtomisedDate && (!gatheringYear.isEmpty() || !gatheringMonth.isEmpty() || !gatheringDay.isEmpty())) {
            Calendar calendar = Calendar.getInstance();
            if (!gatheringYear.isEmpty()) {
                TimePeriod tp = TimePeriod.NewInstance(Integer.parseInt(gatheringYear));
                if (!gatheringMonth.isEmpty()) {
                    tp.setStartMonth(Integer.parseInt(gatheringMonth));
                    if (!gatheringDay.isEmpty()) {
                        tp.setStartDay(Integer.parseInt(gatheringDay));
                    }
                }
                unitsGatheringEvent.setGatheringDate(tp);
            }
        } else {
            if (!gatheringDate.isEmpty()) {
                TimePeriod tp = TimePeriodParser.parseString(gatheringDate);
                unitsGatheringEvent.setGatheringDate(tp);
            }
        }
        // add fieldNumber
        derivedUnitFacade.setFieldNumber(fieldNumber);
        // add Multimedia URLs
        if (multimediaObjects.size() > 0) {
            for (String multimediaObject : multimediaObjects) {
                Media media;
                try {
                    media = getImageMedia(multimediaObject, READ_MEDIA_DATA);
                    derivedUnitFacade.addDerivedUnitMedia(media);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        getOccurrenceService().saveOrUpdate(derivedUnitBase);
        setTaxonName(config);
        // refreshTransaction();
        if (DEBUG) {
            logger.info("saved new specimen ...");
        }
    } catch (Exception e) {
        logger.warn("Error when reading record!!");
        e.printStackTrace();
        result = false;
    }
    if (DEBUG) {
        logger.info("commit done");
    }
    // app.close();
    return result;
}
Also used : DerivedUnitFacade(eu.etaxonomy.cdm.api.facade.DerivedUnitFacade) GatheringEvent(eu.etaxonomy.cdm.model.occurrence.GatheringEvent) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) MalformedURLException(java.net.MalformedURLException) UnitsGatheringArea(eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea) Reference(eu.etaxonomy.cdm.model.reference.Reference) TimePeriod(eu.etaxonomy.cdm.model.common.TimePeriod) Calendar(java.util.Calendar) Media(eu.etaxonomy.cdm.model.media.Media) Institution(eu.etaxonomy.cdm.model.agent.Institution) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) DefinedTermBase(eu.etaxonomy.cdm.model.term.DefinedTermBase) Collection(eu.etaxonomy.cdm.model.occurrence.Collection)

Example 2 with UnitsGatheringEvent

use of eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent in project cdmlib by cybertaxonomy.

the class Abcd206Import method handleSingleUnit.

@SuppressWarnings("rawtypes")
public void handleSingleUnit(Abcd206ImportState state, Object itemObject, boolean handleAssociatedUnits) {
    Element item = (Element) itemObject;
    Abcd206ImportConfigurator config = state.getConfig();
    if (logger.isDebugEnabled()) {
        logger.info("handleSingleUnit " + state.getRef());
    }
    try {
        ICdmRepository cdmAppController = state.getConfig().getCdmAppController();
        if (cdmAppController == null) {
            cdmAppController = this;
        }
        // check if unit already exists
        DerivedUnitFacade derivedUnitFacade = null;
        if (state.getConfig().isIgnoreImportOfExistingSpecimen() && state.getDataHolder().getUnitID() != null) {
            SpecimenOrObservationBase<?> existingSpecimen = findExistingSpecimen(state.getDataHolder().getUnitID(), state);
            if (existingSpecimen != null && existingSpecimen.isInstanceOf(DerivedUnit.class)) {
                DerivedUnit derivedUnit = HibernateProxyHelper.deproxy(existingSpecimen, DerivedUnit.class);
                state.setDerivedUnitBase(derivedUnit);
                derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
                if (handleAssociatedUnits) {
                    importAssociatedUnits(state, item, derivedUnitFacade);
                }
                if (state.getConfig().getDnaSoure() != null) {
                    importAssociatedDna(state, item, derivedUnitFacade);
                }
                state.getReport().addAlreadyExistingSpecimen(SpecimenImportUtility.getUnitID(derivedUnit, config), derivedUnit);
                return;
            }
        } else {
            System.err.println("dataholder does not contain unit id");
        }
        // import DNA unit
        if (state.getDataHolder().getKindOfUnit() != null && state.getDataHolder().getKindOfUnit().equalsIgnoreCase("dna")) {
            AbcdDnaParser dnaParser = new AbcdDnaParser(state.getPrefix(), state.getReport(), state.getCdmRepository());
            DnaSample dnaSample = dnaParser.parse(item, state);
            // dnaSample.addSource(OriginalSourceType.Import, dnaSample.getAccessionNumber(), "", state.getImportReference(state.getActualAccessPoint()), "");
            save(dnaSample, state);
            // set dna as derived unit to avoid creating an extra specimen
            // for this dna sample (instead just the field unit will be
            // created)
            state.setDerivedUnitBase(dnaSample);
            derivedUnitFacade = DerivedUnitFacade.NewInstance(state.getDerivedUnitBase());
        } else {
            // create facade
            derivedUnitFacade = getFacade(state);
            state.setDerivedUnitBase(derivedUnitFacade.innerDerivedUnit());
        }
        /**
         * GATHERING EVENT
         */
        // look for existing fieldUnit
        FieldUnit fieldUnit = null;
        if (StringUtils.isNotBlank(state.getDataHolder().getFieldNumber())) {
            fieldUnit = state.getFieldUnit(state.getDataHolder().getFieldNumber());
            if (fieldUnit != null) {
                state.setLastFieldUnit(fieldUnit);
            }
        } else {
            fieldUnit = state.getLastFieldUnit();
        }
        if (fieldUnit == null) {
            fieldUnit = FieldUnit.NewInstance();
            fieldUnit.setFieldNumber(state.getDataHolder().getFieldNumber());
            state.setLastFieldUnit(fieldUnit);
        }
        // gathering event
        UnitsGatheringEvent unitsGatheringEvent = new UnitsGatheringEvent(cdmAppController.getTermService(), state.getDataHolder().locality, state.getDataHolder().languageIso, state.getDataHolder().longitude, state.getDataHolder().latitude, state.getDataHolder().getGatheringCoordinateErrorMethod(), state.getDataHolder().getGatheringElevationText(), state.getDataHolder().getGatheringElevationMin(), state.getDataHolder().getGatheringElevationMax(), state.getDataHolder().getGatheringElevationUnit(), state.getDataHolder().getGatheringDateText(), state.getDataHolder().getGatheringNotes(), state.getDataHolder().getGatheringMethod(), state.getTransformer().getReferenceSystemByKey(state.getDataHolder().getGatheringSpatialDatum()), state.getConfig());
        unitsGatheringEvent.setGatheringDepth(state.getDataHolder().getGatheringDepthText(), state.getDataHolder().getGatheringDepthMin(), state.getDataHolder().getGatheringDepthMax(), state.getDataHolder().getGatheringDepthUnit());
        // heightUnit);
        if (state.getDataHolder().gatheringAgentsList.isEmpty()) {
            TeamOrPersonBase team = state.getPersonStore().get(state.getDataHolder().gatheringAgentsText);
            if (team == null) {
                team = parseAuthorString(state.getDataHolder().gatheringAgentsText);
                if (team != null) {
                    state.getPersonStore().put(team.getTitleCache(), team);
                }
            }
            if (team != null) {
                unitsGatheringEvent.setCollector(team, config);
            }
        } else {
            TeamOrPersonBase team = state.getPersonStore().get(state.getDataHolder().gatheringAgentsList.toString());
            if (team == null) {
                team = parseAuthorString(state.getDataHolder().gatheringAgentsList.toString());
                if (team != null) {
                    state.getPersonStore().put(team.getTitleCache(), team);
                }
            }
            if (team != null) {
                unitsGatheringEvent.setCollector(team, config);
            }
        }
        // count
        UnitsGatheringArea unitsGatheringArea = new UnitsGatheringArea();
        // unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),
        // getTermService());
        unitsGatheringArea.setParams(state.getDataHolder().isocountry, state.getDataHolder().country, (state.getConfig()), cdmAppController.getTermService(), cdmAppController.getVocabularyService());
        DefinedTermBase<?> areaCountry = unitsGatheringArea.getCountry();
        // other areas
        unitsGatheringArea = new UnitsGatheringArea();
        // unitsGatheringArea.setConfig(state.getConfig(),getOccurrenceService(),getTermService());
        unitsGatheringArea.setAreas(state.getDataHolder().getNamedAreaList(), (state.getConfig()), cdmAppController.getTermService(), cdmAppController.getVocabularyService());
        ArrayList<DefinedTermBase> nas = unitsGatheringArea.getAreas();
        for (DefinedTermBase namedArea : nas) {
            unitsGatheringEvent.addArea(namedArea);
        }
        // copy gathering event to facade
        GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
        if (fieldUnit != null) {
            derivedUnitFacade.setFieldUnit(fieldUnit);
            if (derivedUnitFacade.getGatheringPeriod() == null && gatheringEvent.getTimeperiod() != null) {
                derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
            }
            if (derivedUnitFacade.getLocality() == null && gatheringEvent.getLocality() != null) {
                derivedUnitFacade.setLocality(gatheringEvent.getLocality());
            }
            if (derivedUnitFacade.getExactLocation() == null && gatheringEvent.getExactLocation() != null) {
                derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
            }
            if (derivedUnitFacade.getCollector() == null && gatheringEvent.getCollector() != null) {
                derivedUnitFacade.setCollector(gatheringEvent.getCollector());
            }
            if (derivedUnitFacade.getCountry() == null && areaCountry != null) {
                derivedUnitFacade.setCountry((NamedArea) areaCountry);
            }
            if (StringUtils.isBlank(derivedUnitFacade.getAbsoluteElevationText()) && StringUtils.isNotBlank(gatheringEvent.getAbsoluteElevationText())) {
                derivedUnitFacade.setAbsoluteElevationText(gatheringEvent.getAbsoluteElevationText());
            }
            if (derivedUnitFacade.getAbsoluteElevation() == null && gatheringEvent.getAbsoluteElevation() != null) {
                derivedUnitFacade.setAbsoluteElevation(gatheringEvent.getAbsoluteElevation());
            }
            if (derivedUnitFacade.getAbsoluteElevationMaximum() == null && gatheringEvent.getAbsoluteElevationMax() != null) {
                derivedUnitFacade.setAbsoluteElevationMax(gatheringEvent.getAbsoluteElevationMax());
            }
            if (StringUtils.isBlank(derivedUnitFacade.getDistanceToGroundText()) && StringUtils.isNotBlank(gatheringEvent.getDistanceToGroundText())) {
                derivedUnitFacade.setDistanceToGroundText(gatheringEvent.getDistanceToGroundText());
            }
            if (derivedUnitFacade.getDistanceToGroundMax() == null && gatheringEvent.getDistanceToGroundMax() != null) {
                derivedUnitFacade.setDistanceToGroundMax(gatheringEvent.getDistanceToGroundMax());
            }
            if (derivedUnitFacade.getDistanceToGround() == null && gatheringEvent.getDistanceToGround() != null) {
                derivedUnitFacade.setDistanceToGround(gatheringEvent.getDistanceToGround());
            }
            if (StringUtils.isBlank(derivedUnitFacade.getDistanceToWaterSurfaceText()) && StringUtils.isNotBlank(gatheringEvent.getDistanceToWaterSurfaceText())) {
                derivedUnitFacade.setDistanceToWaterSurfaceText(gatheringEvent.getDistanceToWaterSurfaceText());
            }
            if (derivedUnitFacade.getDistanceToWaterSurfaceMax() == null && gatheringEvent.getDistanceToWaterSurfaceMax() != null) {
                derivedUnitFacade.setDistanceToWaterSurfaceMax(gatheringEvent.getDistanceToWaterSurfaceMax());
            }
            if (derivedUnitFacade.getDistanceToWaterSurface() == null && gatheringEvent.getDistanceToWaterSurface() != null) {
                derivedUnitFacade.setDistanceToWaterSurface(gatheringEvent.getDistanceToWaterSurface());
            }
            if (derivedUnitFacade.getGatheringPeriod() == null && gatheringEvent.getTimeperiod() != null) {
                derivedUnitFacade.setGatheringPeriod(gatheringEvent.getTimeperiod());
            }
            if (derivedUnitFacade.getCollectingMethod() == null && gatheringEvent.getCollectingMethod() != null) {
                derivedUnitFacade.setCollectingMethod(gatheringEvent.getCollectingMethod());
            }
            for (DefinedTermBase<?> area : unitsGatheringArea.getAreas()) {
                derivedUnitFacade.addCollectingArea((NamedArea) area);
            }
            // add unitNotes
            if (state.getDataHolder().getUnitNotes() != null) {
                derivedUnitFacade.addAnnotation(Annotation.NewDefaultLanguageInstance(NB(state.getDataHolder().getUnitNotes())));
            }
            if (gatheringEvent.getAnnotations() != null) {
                for (Annotation annotation : gatheringEvent.getAnnotations()) {
                    derivedUnitFacade.getGatheringEvent(true).addAnnotation(annotation);
                }
            }
        } else {
        // TODO??
        }
        // derivedUnitFacade.addCollectingAreas(unitsGatheringArea.getAreas());
        // TODO exsiccatum
        // add fieldNumber
        String fieldNumber = null;
        if (derivedUnitFacade.getFieldUnit(false) != null) {
            fieldNumber = derivedUnitFacade.getFieldUnit(false).getFieldNumber();
            if (fieldNumber == null) {
                derivedUnitFacade.setFieldNumber(NB(state.getDataHolder().getFieldNumber()));
            }
        }
        save(unitsGatheringEvent.getLocality(), state);
        // //add Multimedia URLs
        if (state.getDataHolder().getMultimediaObjects().size() != -1) {
            for (String multimediaObject : state.getDataHolder().getMultimediaObjects().keySet()) {
                Media media;
                try {
                    media = extractMedia(state, multimediaObject);
                    if (media == null) {
                        continue;
                    }
                    if (!state.getConfig().isAddMediaAsMediaSpecimen()) {
                        derivedUnitFacade.addDerivedUnitMedia(media);
                    } else {
                        // add media also as specimen scan
                        MediaSpecimen mediaSpecimen = MediaSpecimen.NewInstance(SpecimenOrObservationType.StillImage);
                        mediaSpecimen.setMediaSpecimen(media);
                        // do it only once!!
                        DefinedTermBase specimenScanTerm = getTermService().load(SPECIMEN_SCAN_TERM);
                        if (specimenScanTerm instanceof DefinedTerm) {
                            mediaSpecimen.setKindOfUnit((DefinedTerm) specimenScanTerm);
                        }
                        DerivationEvent derivationEvent = DerivationEvent.NewInstance(DerivationEventType.PREPARATION());
                        derivationEvent.addDerivative(mediaSpecimen);
                        derivedUnitFacade.innerDerivedUnit().addDerivationEvent(derivationEvent);
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        // multimedia for fieldUnit
        if (state.getDataHolder().getGatheringMultimediaObjects().size() != -1) {
            for (String multimediaObject : state.getDataHolder().getGatheringMultimediaObjects().keySet()) {
                Media media;
                try {
                    media = extractMedia(state, multimediaObject);
                    if (media == null) {
                        continue;
                    }
                    derivedUnitFacade.addFieldObjectMedia(media);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (derivedUnitFacade.getFieldUnit(false) != null) {
            state.setFieldUnit(derivedUnitFacade.getFieldUnit(false));
        }
        // handle collection data
        setCollectionData(state, derivedUnitFacade);
        // Reference stuff
        SpecimenUserInteraction sui = config.getSpecimenUserInteraction();
        Map<String, OriginalSourceBase> sourceMap = new HashMap<>();
        state.getDataHolder().setDocSources(new ArrayList<>());
        IdentifiableSource sour = getIdentifiableSource(state.getImportReference(state.getActualAccessPoint()), null);
        String idInSource = derivedUnitFacade.getAccessionNumber() != null ? derivedUnitFacade.getAccessionNumber() : derivedUnitFacade.getCatalogNumber() != null ? derivedUnitFacade.getCatalogNumber() : derivedUnitFacade.getBarcode();
        // sour.getCitation().setUri(state.getActualAccessPoint());
        sour.setIdInSource(idInSource);
        try {
            if (sour.getCitation() != null) {
                if (StringUtils.isNotBlank(sour.getCitationMicroReference())) {
                    state.getDataHolder().getDocSources().add(sour.getCitation().getTitleCache() + "---" + sour.getCitationMicroReference());
                } else {
                    state.getDataHolder().getDocSources().add(sour.getCitation().getTitleCache());
                }
            }
        } catch (Exception e) {
            logger.warn("oups");
        }
        derivedUnitFacade.addSource(sour);
        save(state.getDerivedUnitBase(), state);
        if (logger.isDebugEnabled()) {
            logger.info("saved ABCD specimen ...");
        }
        // handle identifications
        handleIdentifications(state, derivedUnitFacade);
        // associatedUnits
        if (handleAssociatedUnits) {
            importAssociatedUnits(state, item, derivedUnitFacade);
        }
        if (state.getConfig().getDnaSoure() != null) {
            boolean uriCorrect = true;
            try {
                state.getConfig().getDnaSoure().toString();
            } catch (Exception e) {
                uriCorrect = false;
            }
            if (uriCorrect) {
                try {
                    importAssociatedDna(state, item, derivedUnitFacade);
                } catch (Exception e) {
                    String message = "Error when importing Dna! " + itemObject.toString();
                    state.getReport().addException(message, e);
                    state.setUnsuccessfull();
                }
            }
        }
        // siblings/ other children
        if (derivedUnitFacade.getType() != null && (derivedUnitFacade.getType().equals(SpecimenOrObservationType.LivingSpecimen) || derivedUnitFacade.getType().equals(SpecimenOrObservationType.TissueSample) || derivedUnitFacade.getType().equals(SpecimenOrObservationType.OtherSpecimen) || derivedUnitFacade.getType().equals(SpecimenOrObservationType.MaterialSample)) && state.getConfig().isGetSiblings()) {
            getSiblings(state, item, derivedUnitFacade);
        }
    } catch (Exception e) {
        String message = "Error when reading record! " + itemObject.toString();
        state.getReport().addException(message, e);
        state.setUnsuccessfull();
    }
    return;
}
Also used : DerivedUnitFacade(eu.etaxonomy.cdm.api.facade.DerivedUnitFacade) TeamOrPersonBase(eu.etaxonomy.cdm.model.agent.TeamOrPersonBase) MalformedURLException(java.net.MalformedURLException) OriginalSourceBase(eu.etaxonomy.cdm.model.reference.OriginalSourceBase) UnitsGatheringArea(eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) LanguageString(eu.etaxonomy.cdm.model.common.LanguageString) DerivedUnit(eu.etaxonomy.cdm.model.occurrence.DerivedUnit) DefinedTermBase(eu.etaxonomy.cdm.model.term.DefinedTermBase) DnaSample(eu.etaxonomy.cdm.model.molecular.DnaSample) IdentifiableSource(eu.etaxonomy.cdm.model.common.IdentifiableSource) GatheringEvent(eu.etaxonomy.cdm.model.occurrence.GatheringEvent) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) FieldUnit(eu.etaxonomy.cdm.model.occurrence.FieldUnit) DerivationEvent(eu.etaxonomy.cdm.model.occurrence.DerivationEvent) Media(eu.etaxonomy.cdm.model.media.Media) ICdmRepository(eu.etaxonomy.cdm.api.application.ICdmRepository) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) SpecimenUserInteraction(eu.etaxonomy.cdm.io.specimen.SpecimenUserInteraction) Annotation(eu.etaxonomy.cdm.model.common.Annotation) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) AbcdDnaParser(eu.etaxonomy.cdm.io.specimen.abcd206.in.molecular.AbcdDnaParser) MediaSpecimen(eu.etaxonomy.cdm.model.occurrence.MediaSpecimen) DefinedTerm(eu.etaxonomy.cdm.model.term.DefinedTerm)

Example 3 with UnitsGatheringEvent

use of eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent in project cdmlib by cybertaxonomy.

the class TaxonXExtractor method extractSpecimenOrObservation.

@SuppressWarnings({ "unused", "rawtypes" })
protected MySpecimenOrObservation extractSpecimenOrObservation(Node specimenObservationNode, DerivedUnit derivedUnitBase, SpecimenOrObservationType defaultAssociation, TaxonName typifiableName) {
    String country = null;
    String locality = null;
    String stateprov = null;
    String collector = null;
    String fieldNumber = null;
    Double latitude = null, longitude = null;
    TimePeriod tp = null;
    String day, month, year = "";
    String descr = "not available";
    String type = "";
    boolean asso = false;
    NodeList eventContent = null;
    // create facade
    DerivedUnitFacade derivedUnitFacade = null;
    UnitsGatheringEvent unitsGatheringEvent;
    UnitsGatheringArea unitsGatheringArea;
    DefinedTermBase areaCountry;
    MySpecimenOrObservation specimenOrObservation = new MySpecimenOrObservation();
    NodeList xmldata = specimenObservationNode.getChildNodes();
    for (int n = 0; n < xmldata.getLength(); n++) {
        eventContent = xmldata.item(n).getChildNodes();
        if (xmldata.item(n).getNodeName().equalsIgnoreCase("tax:xmldata")) {
            asso = true;
            country = null;
            locality = null;
            stateprov = null;
            collector = null;
            fieldNumber = null;
            latitude = null;
            longitude = null;
            day = "";
            month = "";
            year = "";
            type = "";
            for (int j = 0; j < eventContent.getLength(); j++) {
                if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:country")) {
                    country = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:locality")) {
                    locality = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:stateprovince")) {
                    stateprov = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:collector")) {
                    collector = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:yearcollected")) {
                    year = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:monthcollected")) {
                    month = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:daycollected")) {
                    day = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:decimallongitude")) {
                    String tmp = eventContent.item(j).getTextContent().trim();
                    try {
                        longitude = Double.valueOf(tmp);
                    } catch (Exception e) {
                        logger.warn("longitude is not a number");
                    }
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:decimallatitude")) {
                    String tmp = eventContent.item(j).getTextContent().trim();
                    try {
                        latitude = Double.valueOf(tmp);
                    } catch (Exception e) {
                        logger.warn("latitude is not a number");
                    }
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("dwc:TypeStatus")) {
                    type = eventContent.item(j).getTextContent().trim();
                } else if (eventContent.item(j).getNodeName().equalsIgnoreCase("#text") && StringUtils.isBlank(eventContent.item(j).getTextContent())) {
                // do nothing
                } else {
                    logger.info("UNEXTRACTED FIELD FOR SPECIMEN " + eventContent.item(j).getNodeName() + ", " + eventContent.item(j).getTextContent());
                }
            }
            if (!day.isEmpty() || !month.isEmpty() || !year.isEmpty()) {
                try {
                    if (!year.isEmpty()) {
                        tp = TimePeriod.NewInstance(Integer.parseInt(year));
                        if (!month.isEmpty()) {
                            tp.setStartMonth(Integer.parseInt(month));
                            if (!day.isEmpty()) {
                                tp.setStartDay(Integer.parseInt(day));
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.warn("Collection date error " + e);
                }
            }
        }
        if (xmldata.item(n).getNodeName().equalsIgnoreCase("#text")) {
            descr = xmldata.item(n).getTextContent().replaceAll(";", "").trim();
            if (descr.length() > 1 && containsDistinctLetters(descr)) {
                specimenOrObservation.setDescr(descr);
                asso = true;
            }
        }
        if (xmldata.item(n).getNodeName().equalsIgnoreCase("tax:p")) {
            descr = xmldata.item(n).getTextContent().replaceAll(";", "").trim();
            if (descr.length() > 1 && containsDistinctLetters(descr)) {
                specimenOrObservation.setDescr(descr);
                asso = true;
            }
        }
    }
    // logger.info("DESCR: "+descr);
    if (!type.isEmpty()) {
        if (!containsDistinctLetters(type)) {
            type = "no description text";
        }
        derivedUnitFacade = getFacade(type.replaceAll(";", ""), defaultAssociation);
        SpecimenTypeDesignation designation = SpecimenTypeDesignation.NewInstance();
        if (typifiableName != null) {
            typifiableName.addTypeDesignation(designation, true);
        } else {
            logger.warn("No typifiable name available");
        }
        SpecimenTypeDesignationStatus stds = getSpecimenTypeDesignationStatusByKey(type);
        if (stds != null) {
            stds = (SpecimenTypeDesignationStatus) importer.getTermService().find(stds.getUuid());
        }
        designation.setTypeStatus(stds);
        derivedUnitFacade.innerDerivedUnit().addSpecimenTypeDesignation(designation);
        derivedUnitBase = derivedUnitFacade.innerDerivedUnit();
    // System.out.println("derivedUnitBase: "+derivedUnitBase);
    // designation.setTypeSpecimen(derivedUnitBase);
    // TaxonName name = taxon.getName();
    // name.addTypeDesignation(designation, true);
    } else {
        if (!containsDistinctLetters(descr.replaceAll(";", ""))) {
            descr = "no description text";
        }
        derivedUnitFacade = getFacade(descr.replaceAll(";", ""), defaultAssociation);
        derivedUnitBase = derivedUnitFacade.innerDerivedUnit();
    // System.out.println("derivedUnitBase2: "+derivedUnitBase);
    }
    unitsGatheringEvent = new UnitsGatheringEvent(importer.getTermService(), locality, collector, longitude, latitude, state2.getConfig(), importer.getAgentService());
    if (tp != null) {
        unitsGatheringEvent.setGatheringDate(tp);
    }
    // country
    unitsGatheringArea = new UnitsGatheringArea();
    unitsGatheringArea.setParams(null, country, state2.getConfig(), importer.getTermService(), importer.getVocabularyService());
    // TODO other areas
    if (StringUtils.isNotBlank(stateprov)) {
        Map<String, String> namedAreas = new HashMap<>();
        namedAreas.put(stateprov, null);
        unitsGatheringArea.setAreaNames(namedAreas, state2.getConfig(), importer.getTermService(), importer.getVocabularyService());
    }
    areaCountry = unitsGatheringArea.getCountry();
    // // other areas
    // unitsGatheringArea = new UnitsGatheringArea(namedAreaList,dataHolder.getTermService());
    // ArrayList<DefinedTermBase> nas = unitsGatheringArea.getAreas();
    // for (DefinedTermBase namedArea : nas) {
    // unitsGatheringEvent.addArea(namedArea);
    // }
    // copy gathering event to facade
    GatheringEvent gatheringEvent = unitsGatheringEvent.getGatheringEvent();
    derivedUnitFacade.setGatheringEvent(gatheringEvent);
    derivedUnitFacade.setLocality(gatheringEvent.getLocality());
    derivedUnitFacade.setExactLocation(gatheringEvent.getExactLocation());
    derivedUnitFacade.setCollector(gatheringEvent.getCollector());
    derivedUnitFacade.setCountry((NamedArea) areaCountry);
    for (DefinedTermBase<?> area : unitsGatheringArea.getAreas()) {
        derivedUnitFacade.addCollectingArea((NamedArea) area);
    }
    // add fieldNumber
    if (fieldNumber != null) {
        derivedUnitFacade.setFieldNumber(fieldNumber);
    }
    specimenOrObservation.setDerivedUnitBase(derivedUnitBase);
    // }
    return specimenOrObservation;
}
Also used : DerivedUnitFacade(eu.etaxonomy.cdm.api.facade.DerivedUnitFacade) GatheringEvent(eu.etaxonomy.cdm.model.occurrence.GatheringEvent) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) UnitsGatheringArea(eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea) HashMap(java.util.HashMap) TimePeriod(eu.etaxonomy.cdm.model.common.TimePeriod) NodeList(org.w3c.dom.NodeList) SpecimenTypeDesignationStatus(eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus) UnitsGatheringEvent(eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent) TransformerException(javax.xml.transform.TransformerException) UnknownCdmTypeException(eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException) DefinedTermBase(eu.etaxonomy.cdm.model.term.DefinedTermBase) SpecimenTypeDesignation(eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation)

Aggregations

DerivedUnitFacade (eu.etaxonomy.cdm.api.facade.DerivedUnitFacade)3 UnitsGatheringArea (eu.etaxonomy.cdm.io.specimen.UnitsGatheringArea)3 UnitsGatheringEvent (eu.etaxonomy.cdm.io.specimen.UnitsGatheringEvent)3 GatheringEvent (eu.etaxonomy.cdm.model.occurrence.GatheringEvent)3 DefinedTermBase (eu.etaxonomy.cdm.model.term.DefinedTermBase)3 TimePeriod (eu.etaxonomy.cdm.model.common.TimePeriod)2 Media (eu.etaxonomy.cdm.model.media.Media)2 MalformedURLException (java.net.MalformedURLException)2 HashMap (java.util.HashMap)2 ICdmRepository (eu.etaxonomy.cdm.api.application.ICdmRepository)1 SpecimenUserInteraction (eu.etaxonomy.cdm.io.specimen.SpecimenUserInteraction)1 AbcdDnaParser (eu.etaxonomy.cdm.io.specimen.abcd206.in.molecular.AbcdDnaParser)1 Institution (eu.etaxonomy.cdm.model.agent.Institution)1 TeamOrPersonBase (eu.etaxonomy.cdm.model.agent.TeamOrPersonBase)1 Annotation (eu.etaxonomy.cdm.model.common.Annotation)1 IdentifiableSource (eu.etaxonomy.cdm.model.common.IdentifiableSource)1 LanguageString (eu.etaxonomy.cdm.model.common.LanguageString)1 DnaSample (eu.etaxonomy.cdm.model.molecular.DnaSample)1 SpecimenTypeDesignation (eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation)1 SpecimenTypeDesignationStatus (eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus)1