Search in sources :

Example 1 with Rank

use of eu.etaxonomy.cdm.model.name.Rank in project cdmlib by cybertaxonomy.

the class IpniService method getNameFromLine.

private IBotanicalName getNameFromLine(String line, Map<Integer, String> parameterMap, ICdmRepository repository, IpniServiceNamesConfigurator config) {
    // Id%Version%Standard form%Default author forename%Default author surname%Taxon groups%Dates%Alternative names
    String[] splits = line.split("%");
    Map<String, String> valueMap = fillValueMap(parameterMap, splits);
    IBotanicalName name = TaxonNameFactory.NewBotanicalInstance(null);
    // epithets
    name.setGenusOrUninomial(valueMap.get(GENUS));
    name.setInfraGenericEpithet(valueMap.get(INFRA_GENUS));
    name.setSpecificEpithet(valueMap.get(SPECIES));
    name.setInfraSpecificEpithet(valueMap.get(INFRA_SPECIFIC));
    // rank
    try {
        String rankStr = nomalizeRank(valueMap.get(RANK));
        Rank rank = Rank.getRankByLatinNameOrIdInVoc(rankStr, NomenclaturalCode.ICNAFP, true);
        name.setRank(rank);
    } catch (UnknownCdmTypeException e) {
        logger.warn("Rank was unknown");
    }
    // caches
    String pureName = valueMap.get(FULL_NAME_WITHOUT_FAMILY_AND_AUTHORS);
    String nameCache = name.getNameCache();
    if (!Nz(pureName).equals(nameCache)) {
        nvnParser.parseSimpleName(name, valueMap.get(FULL_NAME_WITHOUT_FAMILY_AND_AUTHORS), name.getRank(), true);
    // name.setNameCache(valueMap.get(FULL_NAME_WITHOUT_FAMILY_AND_AUTHORS), true);
    }
    String authors = "";
    // authors
    if (valueMap.get(BASIONYM_AUTHOR) != null) {
        authors = valueMap.get(BASIONYM_AUTHOR);
    // name.setBasionymAuthorship(Team.NewTitledInstance(valueMap.get(BASIONYM_AUTHOR), valueMap.get(BASIONYM_AUTHOR)));
    }
    if (valueMap.get(PUBLISHING_AUTHOR) != null) {
        authors += valueMap.get(PUBLISHING_AUTHOR);
    // name.setCombinationAuthorship(Team.NewTitledInstance(valueMap.get(PUBLISHING_AUTHOR), valueMap.get(PUBLISHING_AUTHOR)));
    }
    try {
        nvnParser.parseAuthors(name, authors);
    } catch (StringNotParsableException e1) {
    // 
    }
    if (!Nz(valueMap.get(AUTHORS)).equals(name.getAuthorshipCache())) {
        name.setAuthorshipCache(valueMap.get(AUTHORS), true);
    }
    if ("Y".equals(valueMap.get(HYBRID))) {
        if (!name.isHybrid()) {
            // Is there a concrete way to include the hybrid flag info? As it does not say which type of hybrid it seems
            // to be best to handle hybrids via parsing. But there might be a better errror handling possible.
            logger.warn("Name is flagged as hybrid at IPNI but CDM name has no hybrid flag set: " + name.getTitleCache());
        }
    }
    // publication
    if (valueMap.get(PUBLICATION) != null || valueMap.get(COLLATION) != null || valueMap.get(PUBLICATION_YEAR_FULL) != null) {
        Reference ref = ReferenceFactory.newGeneric();
        // TODO probably we can do better parsing here
        String pub = CdmUtils.concat(" ", valueMap.get(PUBLICATION), valueMap.get(COLLATION));
        if (isNotBlank(pub)) {
            String nomRefTitle = pub;
            String[] split = nomRefTitle.split(":");
            if (split.length > 1) {
                String detail = split[split.length - 1];
                name.setNomenclaturalMicroReference(detail.trim());
                nomRefTitle = nomRefTitle.substring(0, nomRefTitle.length() - detail.length() - 1).trim();
            }
            ref.setAbbrevTitle(nomRefTitle);
        }
        VerbatimTimePeriod datePublished = parsePublicationFullYear(valueMap.get(PUBLICATION_YEAR_FULL));
        ref.setDatePublished(datePublished);
        name.setNomenclaturalReference(ref);
    }
    // name status
    NomenclaturalStatusType statusType = null;
    String statusString = valueMap.get(NAME_STATUS);
    if (isNotBlank(statusString)) {
        try {
            statusType = NomenclaturalStatusType.getNomenclaturalStatusTypeByAbbreviation(statusString, name);
            NomenclaturalStatus nomStatus = NomenclaturalStatus.NewInstance(statusType);
            name.addStatus(nomStatus);
        } catch (UnknownCdmTypeException e) {
            logger.warn("Name status not recognized: " + statusString);
            Annotation annotation = Annotation.NewInstance("Name status: " + statusString, AnnotationType.EDITORIAL(), Language.ENGLISH());
            name.addAnnotation(annotation);
        }
    }
    // remarks
    String remarks = valueMap.get(REMARKS);
    if (remarks != null) {
        Annotation annotation = Annotation.NewInstance(remarks, AnnotationType.EDITORIAL(), Language.ENGLISH());
        name.addAnnotation(annotation);
    }
    // basionym
    if (config.isDoBasionyms() && valueMap.get(BASIONYM) != null) {
        TaxonName basionym = TaxonNameFactory.NewBotanicalInstance(null);
        basionym.setTitleCache(valueMap.get(BASIONYM), true);
        name.addBasionym(basionym);
    }
    // replaced synonym
    if (config.isDoBasionyms() && valueMap.get(REPLACED_SYNONYM) != null) {
        TaxonName replacedSynoynm = TaxonNameFactory.NewBotanicalInstance(null);
        replacedSynoynm.setTitleCache(valueMap.get(REPLACED_SYNONYM), true);
        name.addReplacedSynonym(replacedSynoynm, null, null, null, null);
    }
    // type information
    if (config.isDoType() && valueMap.get(COLLECTION_DATE_AS_TEXT) != null || valueMap.get(COLLECTION_NUMBER) != null || valueMap.get(COLLECTION_DAY1) != null || valueMap.get(COLLECTION_DAY2) != null || valueMap.get(COLLECTION_MONTH1) != null || valueMap.get(COLLECTION_MONTH2) != null || valueMap.get(COLLECTION_YEAR1) != null || valueMap.get(COLLECTION_YEAR2) != null || valueMap.get(COLLECTOR_TEAM_AS_TEXT) != null || valueMap.get(LOCALITY) != null || valueMap.get(LATITUDE_DEGREES) != null || valueMap.get(LATITUDE_MINUTES) != null || valueMap.get(LATITUDE_SECONDS) != null || valueMap.get(NORTH_OR_SOUTH) != null || valueMap.get(COLLECTION_YEAR1) != null || valueMap.get(COLLECTION_YEAR2) != null) // TODO TBC
    {
        DerivedUnitFacade specimen = DerivedUnitFacade.NewInstance(SpecimenOrObservationType.PreservedSpecimen);
        // gathering period
        String collectionDateAsText = valueMap.get(COLLECTION_DATE_AS_TEXT);
        TimePeriod gatheringPeriod = TimePeriodParser.parseString(collectionDateAsText);
        try {
            gatheringPeriod.setStartDay(getIntegerDateValueOrNull(valueMap, COLLECTION_DAY1));
            gatheringPeriod.setStartMonth(getIntegerDateValueOrNull(valueMap, COLLECTION_MONTH1));
            gatheringPeriod.setStartYear(getIntegerDateValueOrNull(valueMap, COLLECTION_YEAR1));
            gatheringPeriod.setEndDay(getIntegerDateValueOrNull(valueMap, COLLECTION_DAY2));
            gatheringPeriod.setEndMonth(getIntegerDateValueOrNull(valueMap, COLLECTION_MONTH2));
            gatheringPeriod.setEndYear(getIntegerDateValueOrNull(valueMap, COLLECTION_YEAR2));
        } catch (IndexOutOfBoundsException e) {
            logger.info("Exception occurred when trying to fill gathering period");
        }
        specimen.setGatheringPeriod(gatheringPeriod);
        specimen.setFieldNumber(valueMap.get(COLLECTION_NUMBER));
        // collector team
        String team = valueMap.get(COLLECTOR_TEAM_AS_TEXT);
        if (team != null) {
            Team collectorTeam = Team.NewTitledInstance(team, team);
            specimen.setCollector(collectorTeam);
        }
        specimen.setLocality(valueMap.get(LOCALITY));
        try {
            String latDegrees = CdmUtils.Nz(valueMap.get(LATITUDE_DEGREES));
            String latMinutes = CdmUtils.Nz(valueMap.get(LATITUDE_MINUTES));
            String latSeconds = CdmUtils.Nz(valueMap.get(LATITUDE_SECONDS));
            String direction = CdmUtils.Nz(valueMap.get(NORTH_OR_SOUTH));
            String latitude = latDegrees + "°" + latMinutes + "'" + latSeconds + "\"" + direction;
            String lonDegrees = CdmUtils.Nz(valueMap.get(LONGITUDE_DEGREES));
            String lonMinutes = CdmUtils.Nz(valueMap.get(LONGITUDE_MINUTES));
            String lonSeconds = CdmUtils.Nz(valueMap.get(LONGITUDE_SECONDS));
            direction = CdmUtils.Nz(valueMap.get(EAST_OR_WEST));
            String longitude = lonDegrees + "°" + lonMinutes + "'" + lonSeconds + "\"" + direction;
            specimen.setExactLocationByParsing(longitude, latitude, null, null);
        } catch (ParseException e) {
            logger.info("Parsing exception occurred when trying to parse type exact location." + e.getMessage());
        } catch (Exception e) {
            logger.info("Exception occurred when trying to read type exact location." + e.getMessage());
        }
        // type annotation
        if (valueMap.get(TYPE_REMARKS) != null) {
            Annotation typeAnnotation = Annotation.NewInstance(valueMap.get(TYPE_REMARKS), AnnotationType.EDITORIAL(), Language.DEFAULT());
            specimen.addAnnotation(typeAnnotation);
        }
    }
    // TODO  Type name
    // TODO "Type locations"  , eg. holotype   CAT  ,isotype   CAT  ,isotype   FI
    // TODO Geographic unit as text
    // source
    Reference citation = getIpniCitation(repository);
    name.addSource(OriginalSourceType.Lineage, valueMap.get(ID), "Name", citation, valueMap.get(VERSION));
    /*		EXTENDED
 *      Species author,
 *       Standardised basionym author flag,
 *       Standardised publishing author flag
	      Full name
	      Full name without family
	      Full name without authors

	      Reference
	      Standardised publication flag
	      Publication year
	      publication year note
	      Publication year text
	      Volume
	      Start page
	      End page
	      Primary pagination
	      Secondary pagination
	      Reference remarks
	      Hybrid parents
	      Replaced synonym Author team
	      Other links
	      Same citation as
	      Bibliographic reference
	      Bibliographic type info

	      Original taxon name
	      Original taxon name author team
	      Original replaced synonym
	      Original replaced synonym author team
	      Original basionym
	      Original basionym author team
	      Original parent citation taxon name author team
	      Original taxon distribution
	      Original hybrid parentage
	      Original cited type
	      Original remarks

		*/
    return name;
}
Also used : DerivedUnitFacade(eu.etaxonomy.cdm.api.facade.DerivedUnitFacade) VerbatimTimePeriod(eu.etaxonomy.cdm.model.common.VerbatimTimePeriod) Reference(eu.etaxonomy.cdm.model.reference.Reference) TimePeriod(eu.etaxonomy.cdm.model.common.TimePeriod) VerbatimTimePeriod(eu.etaxonomy.cdm.model.common.VerbatimTimePeriod) Rank(eu.etaxonomy.cdm.model.name.Rank) NomenclaturalStatusType(eu.etaxonomy.cdm.model.name.NomenclaturalStatusType) Annotation(eu.etaxonomy.cdm.model.common.Annotation) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) StringNotParsableException(eu.etaxonomy.cdm.strategy.exceptions.StringNotParsableException) UnknownCdmTypeException(eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) IBotanicalName(eu.etaxonomy.cdm.model.name.IBotanicalName) NomenclaturalStatus(eu.etaxonomy.cdm.model.name.NomenclaturalStatus) UnknownCdmTypeException(eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) Team(eu.etaxonomy.cdm.model.agent.Team) ParseException(java.text.ParseException) StringNotParsableException(eu.etaxonomy.cdm.strategy.exceptions.StringNotParsableException)

Example 2 with Rank

use of eu.etaxonomy.cdm.model.name.Rank in project cdmlib by cybertaxonomy.

the class GbifJsonOccurrenceParser method parseJsonRecords.

/**
 * Parses the given {@link JSONArray} for occurrences.
 * @param jsonString JSON data as an {@link JSONArray}
 * @return the found occurrences as a collection of {@link GbifResponse}
 */
private static Collection<GbifResponse> parseJsonRecords(JSONArray jsonArray) {
    Collection<GbifResponse> results = new ArrayList<>();
    String[] tripleId = new String[3];
    String string;
    for (Object o : jsonArray) {
        // parse every record
        tripleId = new String[3];
        if (o instanceof JSONObject) {
            String dataSetKey = null;
            GbifDataSetProtocol dataSetProtocol = null;
            DerivedUnitFacade derivedUnitFacade = DerivedUnitFacade.NewInstance(SpecimenOrObservationType.PreservedSpecimen);
            TaxonName name = null;
            JSONObject record = (JSONObject) o;
            if (record.has(DATASET_PROTOCOL)) {
                dataSetProtocol = GbifDataSetProtocol.parseProtocol(record.getString(DATASET_PROTOCOL));
            }
            if (record.has(DATASET_KEY)) {
                dataSetKey = record.getString(DATASET_KEY);
            }
            if (record.has(COUNTRY_CODE)) {
                string = record.getString(COUNTRY_CODE);
                Country country = Country.getCountryByIso3166A2(string);
                if (country != null) {
                    derivedUnitFacade.setCountry(country);
                }
            }
            if (record.has(LOCALITY)) {
                string = record.getString(LOCALITY);
                derivedUnitFacade.setLocality(string);
            }
            if (record.has("species")) {
                Rank rank = null;
                if (record.has(TAXON_RANK)) {
                    string = record.getString(TAXON_RANK);
                    try {
                        rank = Rank.getRankByLatinName(string);
                    } catch (UnknownCdmTypeException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (rank != null) {
                    if (record.has(NOMENCLATURALCODE)) {
                        string = record.getString(NOMENCLATURALCODE);
                        if (string.equals(NomenclaturalCode.ICZN.getTitleCache())) {
                            name = TaxonNameFactory.NewZoologicalInstance(rank);
                        } else if (string.equals(NomenclaturalCode.ICNAFP.getTitleCache())) {
                            name = TaxonNameFactory.NewBotanicalInstance(rank);
                        } else if (string.equals(NomenclaturalCode.ICNP.getTitleCache())) {
                            name = TaxonNameFactory.NewBacterialInstance(rank);
                        } else if (string.equals(NomenclaturalCode.ICNCP.getTitleCache())) {
                            name = TaxonNameFactory.NewCultivarInstance(rank);
                        } else if (string.equals(NomenclaturalCode.ICVCN.getTitleCache())) {
                            name = TaxonNameFactory.NewViralInstance(rank);
                        } else if (string.equals("ICN")) {
                            name = TaxonNameFactory.NewBotanicalInstance(rank);
                        }
                    } else {
                        if (record.has(KINGDOM)) {
                            if (record.getString(KINGDOM).equals(PLANTAE)) {
                                name = TaxonNameFactory.NewBotanicalInstance(rank);
                            } else if (record.getString(KINGDOM).equals(ANIMALIA)) {
                                name = TaxonNameFactory.NewZoologicalInstance(rank);
                            } else if (record.getString(KINGDOM).equals(FUNGI)) {
                                name = TaxonNameFactory.NewBotanicalInstance(rank);
                            } else if (record.getString(KINGDOM).equals(BACTERIA)) {
                                name = TaxonNameFactory.NewBacterialInstance(rank);
                            } else {
                                name = TaxonNameFactory.NewNonViralInstance(rank);
                            }
                        } else {
                            name = TaxonNameFactory.NewNonViralInstance(rank);
                        }
                    }
                    if (name == null) {
                        name = TaxonNameFactory.NewNonViralInstance(rank);
                    }
                    if (record.has(GENUS)) {
                        name.setGenusOrUninomial(record.getString(GENUS));
                    }
                    if (record.has(SPECIFIC_EPITHET)) {
                        name.setSpecificEpithet(record.getString(SPECIFIC_EPITHET));
                    }
                    if (record.has(INFRASPECIFIC_EPITHET)) {
                        name.setInfraSpecificEpithet(record.getString(INFRASPECIFIC_EPITHET));
                    }
                    if (record.has(SCIENTIFIC_NAME)) {
                        name.setTitleCache(record.getString(SCIENTIFIC_NAME), true);
                    }
                }
                DeterminationEvent detEvent = DeterminationEvent.NewInstance();
                if (record.has(IDENTIFIED_BY)) {
                    Person determiner = Person.NewTitledInstance(record.getString(IDENTIFIED_BY));
                    detEvent.setDeterminer(determiner);
                }
                detEvent.setTaxonName(name);
                detEvent.setPreferredFlag(true);
                derivedUnitFacade.addDetermination(detEvent);
            }
            // GPS location
            Point location = Point.NewInstance();
            derivedUnitFacade.setExactLocation(location);
            try {
                if (record.has(LATITUDE)) {
                    String lat = record.getString(LATITUDE);
                    location.setLatitudeByParsing(lat);
                }
                if (record.has(LONGITUDE)) {
                    String lon = record.getString(LONGITUDE);
                    location.setLongitudeByParsing(lon);
                }
            } catch (ParseException e) {
                logger.error("Could not parse GPS coordinates", e);
            }
            if (record.has(GEOREFERENCE_PROTOCOL)) {
                String geo = record.getString(GEOREFERENCE_PROTOCOL);
                ReferenceSystem referenceSystem = null;
                // to check which reference system is used?
                if (ReferenceSystem.WGS84().getLabel().contains(geo)) {
                    referenceSystem = ReferenceSystem.WGS84();
                } else if (ReferenceSystem.GOOGLE_EARTH().getLabel().contains(geo)) {
                    referenceSystem = ReferenceSystem.GOOGLE_EARTH();
                } else if (ReferenceSystem.GAZETTEER().getLabel().contains(geo)) {
                    referenceSystem = ReferenceSystem.GAZETTEER();
                }
                location.setReferenceSystem(referenceSystem);
            }
            if (record.has(ELEVATION)) {
                try {
                    // parse integer and strip of unit
                    string = record.getString(ELEVATION);
                    int length = string.length();
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < length; i++) {
                        if (Character.isDigit(string.charAt(i))) {
                            builder.append(string.charAt(i));
                        } else {
                            break;
                        }
                    }
                    derivedUnitFacade.setAbsoluteElevation(Integer.parseInt(builder.toString()));
                } catch (NumberFormatException e) {
                    logger.warn("Could not parse elevation", e);
                }
            }
            // Date (Gathering Period)
            TimePeriod timePeriod = TimePeriod.NewInstance();
            derivedUnitFacade.setGatheringPeriod(timePeriod);
            // TODO what happens with eventDate??
            if (record.has(YEAR)) {
                timePeriod.setStartYear(record.getInt(YEAR));
            }
            if (record.has(MONTH)) {
                timePeriod.setStartMonth(record.getInt(MONTH));
            }
            if (record.has(DAY)) {
                timePeriod.setStartDay(record.getInt(DAY));
            }
            if (record.has(RECORDED_BY)) {
                Person person = Person.NewTitledInstance(record.getString(RECORDED_BY));
                // FIXME check data base if collector already present
                derivedUnitFacade.setCollector(person);
            }
            // collector number (fieldNumber OR recordNumber)
            if (record.has(FIELD_NUMBER)) {
                derivedUnitFacade.setFieldNumber(record.getString(FIELD_NUMBER));
            }
            // collector number (fieldNumber OR recordNumber)
            if (record.has(RECORD_NUMBER)) {
                derivedUnitFacade.setFieldNumber(record.getString(RECORD_NUMBER));
            }
            if (record.has(EVENT_REMARKS)) {
                derivedUnitFacade.setGatheringEventDescription(record.getString(EVENT_REMARKS));
            }
            if (record.has(OCCURRENCE_REMARKS)) {
                derivedUnitFacade.setEcology(record.getString(OCCURRENCE_REMARKS));
            }
            if (record.has(COLLECTION_CODE)) {
                String collectionCode = record.getString(COLLECTION_CODE);
                tripleId[2] = collectionCode;
                // FIXME: check data base for existing collections
                eu.etaxonomy.cdm.model.occurrence.Collection collection = eu.etaxonomy.cdm.model.occurrence.Collection.NewInstance();
                collection.setCode(collectionCode);
                if (record.has(INSTITUTION_CODE)) {
                    Institution institution = Institution.NewNamedInstance(record.getString(INSTITUTION_CODE));
                    institution.setCode(record.getString(INSTITUTION_CODE));
                    collection.setInstitute(institution);
                }
                derivedUnitFacade.setCollection(collection);
            }
            if (record.has(CATALOG_NUMBER)) {
                derivedUnitFacade.setCatalogNumber(record.getString(CATALOG_NUMBER));
                derivedUnitFacade.setAccessionNumber(record.getString(CATALOG_NUMBER));
                tripleId[0] = record.getString(CATALOG_NUMBER);
            }
            if (record.has(INSTITUTION_CODE)) {
                derivedUnitFacade.setAccessionNumber(record.getString(INSTITUTION_CODE));
                tripleId[1] = record.getString(INSTITUTION_CODE);
            }
            if (record.has(OCCURENCE_ID)) {
                IdentifiableSource source = IdentifiableSource.NewDataImportInstance((record.getString(OCCURENCE_ID)));
                derivedUnitFacade.addSource(source);
            }
            if (record.has(MULTIMEDIA)) {
                // http://ww2.bgbm.org/herbarium/images/B/-W/08/53/B_-W_08537%20-00%201__3.jpg
                JSONArray multimediaArray = record.getJSONArray(MULTIMEDIA);
                JSONObject mediaRecord;
                SpecimenOrObservationType type = null;
                for (Object object : multimediaArray) {
                    // parse every record
                    Media media = Media.NewInstance();
                    URI uri = null;
                    CdmImageInfo imageInf = null;
                    if (object instanceof JSONObject) {
                        mediaRecord = (JSONObject) object;
                        if (mediaRecord.has("identifier")) {
                            try {
                                uri = new URI(mediaRecord.getString("identifier"));
                                imageInf = MediaInfoFileReader.legacyFactoryMethod(uri).readBaseInfo().getCdmImageInfo();
                            } catch (URISyntaxException | IOException | HttpException e) {
                                e.printStackTrace();
                            }
                        // media.addIdentifier(mediaRecord.getString("identifier"), null);
                        }
                        if (mediaRecord.has("references")) {
                        }
                        if (mediaRecord.has("format")) {
                        }
                        if (mediaRecord.has("type")) {
                            if (mediaRecord.get("type").equals("StillImage")) {
                                type = SpecimenOrObservationType.StillImage;
                            }
                        }
                    }
                    ImageFile imageFile = ImageFile.NewInstance(uri, null, imageInf);
                    MediaRepresentation representation = MediaRepresentation.NewInstance();
                    representation.addRepresentationPart(imageFile);
                    media.addRepresentation(representation);
                    derivedUnitFacade.addDerivedUnitMedia(media);
                }
            // identifier=http://ww2.bgbm.org/herbarium/images/B/-W/08/53/B_-W_08537%20-00%201__3.jpg
            // references=http://ww2.bgbm.org/herbarium/view_biocase.cfm?SpecimenPK=136628
            // format=image/jpeg
            // type=StillImage
            }
            // create dataset URL
            URI uri = null;
            try {
                uri = UriUtils.createUri(new URL(GbifQueryServiceWrapper.BASE_URL), "/v1/dataset/" + dataSetKey + "/endpoint", null, null);
            } catch (MalformedURLException e) {
                logger.error("Endpoint URI could not be created!", e);
            } catch (URISyntaxException e) {
                logger.error("Endpoint URI could not be created!", e);
            }
            results.add(new GbifResponse(derivedUnitFacade, uri, dataSetProtocol, tripleId, name));
        }
    }
    return results;
}
Also used : DerivedUnitFacade(eu.etaxonomy.cdm.api.facade.DerivedUnitFacade) MalformedURLException(java.net.MalformedURLException) ImageFile(eu.etaxonomy.cdm.model.media.ImageFile) ArrayList(java.util.ArrayList) SpecimenOrObservationType(eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType) Institution(eu.etaxonomy.cdm.model.agent.Institution) URISyntaxException(java.net.URISyntaxException) DeterminationEvent(eu.etaxonomy.cdm.model.occurrence.DeterminationEvent) ReferenceSystem(eu.etaxonomy.cdm.model.location.ReferenceSystem) URI(eu.etaxonomy.cdm.common.URI) URL(java.net.URL) CdmImageInfo(eu.etaxonomy.cdm.common.media.CdmImageInfo) UnknownCdmTypeException(eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException) MediaRepresentation(eu.etaxonomy.cdm.model.media.MediaRepresentation) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) HttpException(org.apache.http.HttpException) IdentifiableSource(eu.etaxonomy.cdm.model.common.IdentifiableSource) TimePeriod(eu.etaxonomy.cdm.model.common.TimePeriod) JSONArray(net.sf.json.JSONArray) Media(eu.etaxonomy.cdm.model.media.Media) Rank(eu.etaxonomy.cdm.model.name.Rank) Point(eu.etaxonomy.cdm.model.location.Point) IOException(java.io.IOException) Point(eu.etaxonomy.cdm.model.location.Point) JSONObject(net.sf.json.JSONObject) Country(eu.etaxonomy.cdm.model.location.Country) JSONObject(net.sf.json.JSONObject) ParseException(java.text.ParseException) Person(eu.etaxonomy.cdm.model.agent.Person)

Example 3 with Rank

use of eu.etaxonomy.cdm.model.name.Rank in project cdmlib by cybertaxonomy.

the class SpecimenImportBase method addParentTaxon.

/**
 * Add the hierarchy for a Taxon(add higher taxa)
 * @param classification
 * @param taxon: a taxon to add as a node
 * @param state: the ABCD import state
 */
protected void addParentTaxon(Taxon taxon, STATE state, boolean preferredFlag, Classification classification) {
    INonViralName nvname = taxon.getName();
    Rank rank = nvname.getRank();
    Taxon genus = null;
    Taxon subgenus = null;
    Taxon species = null;
    Taxon subspecies = null;
    Taxon parent = null;
    if (rank != null) {
        if (rank.isLower(Rank.GENUS())) {
            String genusOrUninomial = nvname.getGenusOrUninomial();
            TaxonName taxonName = getOrCreateTaxonName(genusOrUninomial, Rank.GENUS(), preferredFlag, state, -1);
            genus = getOrCreateTaxonForName(taxonName, state);
            if (genus == null) {
                logger.debug("The genus should not be null " + taxonName);
            }
            if (preferredFlag) {
                parent = linkParentChildNode(null, genus, classification, state);
            }
        }
        if (rank.isLower(Rank.SUBGENUS())) {
            String prefix = nvname.getGenusOrUninomial();
            String name = nvname.getInfraGenericEpithet();
            if (name != null) {
                TaxonName taxonName = getOrCreateTaxonName(prefix + " " + name, Rank.SUBGENUS(), preferredFlag, state, -1);
                subgenus = getOrCreateTaxonForName(taxonName, state);
                if (preferredFlag) {
                    parent = linkParentChildNode(genus, subgenus, classification, state);
                }
            }
        }
        if (rank.isLower(Rank.SPECIES())) {
            if (subgenus != null) {
                String prefix = nvname.getGenusOrUninomial();
                String name = nvname.getInfraGenericEpithet();
                String spe = nvname.getSpecificEpithet();
                if (spe != null) {
                    TaxonName taxonName = getOrCreateTaxonName(prefix + " " + name + " " + spe, Rank.SPECIES(), preferredFlag, state, -1);
                    species = getOrCreateTaxonForName(taxonName, state);
                    if (preferredFlag) {
                        parent = linkParentChildNode(subgenus, species, classification, state);
                    }
                }
            } else {
                String prefix = nvname.getGenusOrUninomial();
                String name = nvname.getSpecificEpithet();
                if (name != null) {
                    TaxonName taxonName = getOrCreateTaxonName(prefix + " " + name, Rank.SPECIES(), preferredFlag, state, -1);
                    species = getOrCreateTaxonForName(taxonName, state);
                    if (preferredFlag) {
                        parent = linkParentChildNode(genus, species, classification, state);
                    }
                }
            }
        }
        if (rank.isLower(Rank.INFRASPECIES())) {
            TaxonName taxonName = getOrCreateTaxonName(nvname.getFullTitleCache(), Rank.SUBSPECIES(), preferredFlag, state, -1);
            subspecies = getOrCreateTaxonForName(taxonName, state);
            if (preferredFlag) {
                parent = linkParentChildNode(species, subspecies, classification, state);
            }
        }
    } else {
        // handle cf. and aff. taxa
        String genusEpithet = null;
        if (nvname.getTitleCache().contains("cf.")) {
            genusEpithet = nvname.getTitleCache().substring(0, nvname.getTitleCache().indexOf("cf."));
        } else if (nvname.getTitleCache().contains("aff.")) {
            genusEpithet = nvname.getTitleCache().substring(0, nvname.getTitleCache().indexOf("aff."));
        }
        if (genusEpithet != null) {
            genusEpithet = genusEpithet.trim();
            TaxonName taxonName = null;
            if (genusEpithet.contains(" ")) {
                taxonName = getOrCreateTaxonName(genusEpithet, Rank.SPECIES(), preferredFlag, state, -1);
            } else {
                taxonName = getOrCreateTaxonName(genusEpithet, Rank.GENUS(), preferredFlag, state, -1);
            }
            genus = getOrCreateTaxonForName(taxonName, state);
            if (genus == null) {
                logger.debug("The genus should not be null " + taxonName);
            }
            if (preferredFlag) {
                parent = linkParentChildNode(null, genus, classification, state);
            }
        }
    }
    if (preferredFlag && parent != taxon) {
        linkParentChildNode(parent, taxon, classification, state);
    }
}
Also used : INonViralName(eu.etaxonomy.cdm.model.name.INonViralName) Taxon(eu.etaxonomy.cdm.model.taxon.Taxon) Rank(eu.etaxonomy.cdm.model.name.Rank) TaxonName(eu.etaxonomy.cdm.model.name.TaxonName) LanguageString(eu.etaxonomy.cdm.model.common.LanguageString)

Example 4 with Rank

use of eu.etaxonomy.cdm.model.name.Rank in project cdmlib by cybertaxonomy.

the class MarkupImportBase method handleFullName.

protected void handleFullName(MarkupImportState state, XMLEventReader reader, INonViralName name, XMLEvent event) throws XMLStreamException {
    String fullNameStr;
    Map<String, Attribute> attrs = getAttributes(event);
    String rankStr = getAndRemoveRequiredAttributeValue(event, attrs, "rank");
    String hybridClass = getAndRemoveAttributeValue(attrs, "hybridClass");
    Rank rank = makeRank(state, rankStr, false);
    name.setRank(rank);
    if (rank == null) {
        String message = "Rank was computed as null. This must not be.";
        fireWarningEvent(message, event, 6);
        name.setRank(Rank.UNKNOWN_RANK());
    }
    if (!attrs.isEmpty()) {
        handleUnexpectedAttributes(event.getLocation(), attrs);
    }
    fullNameStr = getCData(state, reader, event, false);
    NonViralNameParserImpl.NewInstance().parseFullName(name, fullNameStr, rank, false);
    if (hybridClass != null) {
        if ("hybrid formula".equals(hybridClass)) {
            if (!name.isHybridFormula()) {
                fireWarningEvent("Hybrid formula is not set though requested: " + fullNameStr, event, 4);
            }
        } else if ("hybrid".equals(hybridClass)) {
            if (!name.isHybridName()) {
                fireWarningEvent("Hybrid name is recognized: " + fullNameStr, event, 4);
            }
        } else {
            handleNotYetImplementedAttributeValue(event, "hybridClass", hybridClass);
        }
    }
}
Also used : Attribute(javax.xml.stream.events.Attribute) Rank(eu.etaxonomy.cdm.model.name.Rank)

Example 5 with Rank

use of eu.etaxonomy.cdm.model.name.Rank in project cdmlib by cybertaxonomy.

the class MarkupNomenclatureImport method makeRankDecision.

/**
 * @param state
 * @param nameMap
 * @param name
 * @param event
 * @param infrankStr
 */
private void makeRankDecision(MarkupImportState state, Map<String, String> nameMap, INonViralName name, XMLEvent event, String infrankStr) {
    // TODO ranks
    for (String key : nameMap.keySet()) {
        Rank rank = makeRank(state, key, false);
        if (rank == null) {
            handleNotYetImplementedAttributeValue(event, CLASS, key);
        } else {
            if (name.getRank() == null || rank.isLower(name.getRank())) {
                name.setRank(rank);
            }
            String value = nameMap.get(key);
            if (rank.isSupraGeneric() || rank.isGenus()) {
                if ((key.equalsIgnoreCase(GENUS_ABBREVIATION) && isNotBlank(state.getLatestGenusEpithet()) || isGenusAbbrev(value, state.getLatestGenusEpithet()))) {
                    value = state.getLatestGenusEpithet();
                }
                name.setGenusOrUninomial(toFirstCapital(value));
            } else if (rank.isInfraGeneric()) {
                name.setInfraGenericEpithet(toFirstCapital(value));
            } else if (rank.isSpecies()) {
                if (state.getConfig().isAllowCapitalSpeciesEpithet() && isFirstCapitalWord(value)) {
                    // capital letters
                    // are allowed for
                    // species epithet
                    // in case of person
                    // names (e.g.
                    // Manilkara
                    // Welwitschii Engl.
                    name.setSpecificEpithet(value);
                } else {
                    name.setSpecificEpithet(value.toLowerCase());
                }
            } else if (rank.isInfraSpecific()) {
                name.setInfraSpecificEpithet(value.toLowerCase());
            } else {
                String message = "Invalid rank '%s'. Can't decide which epithet to fill with '%s'";
                message = String.format(message, rank.getTitleCache(), value);
                fireWarningEvent(message, event, 4);
            }
        }
    }
    // handle given infrank marker
    if (StringUtils.isNotBlank(infrankStr)) {
        Rank infRank = makeRank(state, infrankStr, true);
        if (infRank == null) {
            String message = "Infrank '%s' rank not recognized";
            message = String.format(message, infrankStr);
            fireWarningEvent(message, event, 4);
        } else {
            if (name.getRank() == null) {
                name.setRank(infRank);
            } else if (infRank.isLower(name.getRank())) {
                String message = "InfRank '%s' is lower than existing rank ";
                message = String.format(message, infrankStr);
                fireWarningEvent(message, event, 2);
                name.setRank(infRank);
            } else if (infRank.equals(name.getRank())) {
            // nothing
            } else {
                String message = "InfRank '%s' is higher than existing rank ";
                message = String.format(message, infrankStr);
                fireWarningEvent(message, event, 2);
            }
        }
    }
}
Also used : Rank(eu.etaxonomy.cdm.model.name.Rank)

Aggregations

Rank (eu.etaxonomy.cdm.model.name.Rank)78 Taxon (eu.etaxonomy.cdm.model.taxon.Taxon)20 UnknownCdmTypeException (eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException)19 TaxonName (eu.etaxonomy.cdm.model.name.TaxonName)17 Test (org.junit.Test)17 INonViralName (eu.etaxonomy.cdm.model.name.INonViralName)15 TaxonNode (eu.etaxonomy.cdm.model.taxon.TaxonNode)15 ArrayList (java.util.ArrayList)15 Reference (eu.etaxonomy.cdm.model.reference.Reference)12 CdmTransactionalIntegrationTest (eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest)12 UUID (java.util.UUID)11 Classification (eu.etaxonomy.cdm.model.taxon.Classification)10 NomenclaturalCode (eu.etaxonomy.cdm.model.name.NomenclaturalCode)8 DataSet (org.unitils.dbunit.annotation.DataSet)7 Person (eu.etaxonomy.cdm.model.agent.Person)4 Synonym (eu.etaxonomy.cdm.model.taxon.Synonym)4 TaxonBase (eu.etaxonomy.cdm.model.taxon.TaxonBase)4 IOException (java.io.IOException)4 GroupedTaxonDTO (eu.etaxonomy.cdm.api.service.dto.GroupedTaxonDTO)3 URI (eu.etaxonomy.cdm.common.URI)3