    001    //$HeadURL:
    002    /*----------------------------------------------------------------------------
    003     This file is part of deegree, http://deegree.org/
    004     Copyright (C) 2001-2010 by:
    005     - Department of Geography, University of Bonn -
    006     and
    007     - lat/lon GmbH -
    008
    009     This library is free software; you can redistribute it and/or modify it under
    010     the terms of the GNU Lesser General Public License as published by the Free
    011     Software Foundation; either version 2.1 of the License, or (at your option)
    012     any later version.
    013     This library is distributed in the hope that it will be useful, but WITHOUT
    014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
    016     details.
    017     You should have received a copy of the GNU Lesser General Public License
    018     along with this library; if not, write to the Free Software Foundation, Inc.,
    019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
    020
    021     Contact information:
    022
    023     lat/lon GmbH
    024     Aennchenstr. 19, 53177 Bonn
    025     Germany
    026     http://lat-lon.de/
    027
    028     Department of Geography, University of Bonn
    029     Prof. Dr. Klaus Greve
    030     Postfach 1147, 53001 Bonn
    031     Germany
    032     http://www.geographie.uni-bonn.de/deegree/
    033
    034     e-mail: info@deegree.org
    035     ----------------------------------------------------------------------------*/
    036    package org.deegree.portal.cataloguemanager.control;
    037
    038    import java.io.ByteArrayOutputStream;
    039    import java.io.IOException;
    040    import java.net.URL;
    041    import java.nio.charset.Charset;
    042    import java.util.List;
    043
    044    import javax.xml.bind.JAXBContext;
    045    import javax.xml.bind.JAXBException;
    046    import javax.xml.bind.Marshaller;
    047    import javax.xml.bind.Unmarshaller;
    048
    049    import org.apache.commons.httpclient.HttpClient;
    050    import org.apache.commons.httpclient.HttpException;
    051    import org.apache.commons.httpclient.methods.PostMethod;
    052    import org.apache.commons.httpclient.methods.StringRequestEntity;
    053    import org.deegree.enterprise.control.ajax.ResponseHandler;
    054    import org.deegree.enterprise.control.ajax.WebEvent;
    055    import org.deegree.framework.log.ILogger;
    056    import org.deegree.framework.log.LoggerFactory;
    057    import org.deegree.framework.util.BootLogger;
    058    import org.deegree.framework.util.FileUtils;
    059    import org.deegree.framework.util.StringTools;
    060    import org.deegree.framework.util.TimeTools;
    061    import org.deegree.model.crs.CRSFactory;
    062    import org.deegree.model.crs.CRSTransformationException;
    063    import org.deegree.model.crs.CoordinateSystem;
    064    import org.deegree.model.spatialschema.Envelope;
    065    import org.deegree.model.spatialschema.GeometryFactory;
    066    import org.deegree.portal.cataloguemanager.model.Address;
    067    import org.deegree.portal.cataloguemanager.model.CICitation;
    068    import org.deegree.portal.cataloguemanager.model.CIDate;
    069    import org.deegree.portal.cataloguemanager.model.CIDateTypeCode;
    070    import org.deegree.portal.cataloguemanager.model.CIOnlineResource;
    071    import org.deegree.portal.cataloguemanager.model.CIResponsibleParty;
    072    import org.deegree.portal.cataloguemanager.model.Contact;
    073    import org.deegree.portal.cataloguemanager.model.ContactInfo;
    074    import org.deegree.portal.cataloguemanager.model.Date;
    075    import org.deegree.portal.cataloguemanager.model.DateType;
    076    import org.deegree.portal.cataloguemanager.model.DistributionFormat;
    077    import org.deegree.portal.cataloguemanager.model.EXExtent;
    078    import org.deegree.portal.cataloguemanager.model.EXGeographicBoundingBox;
    079    import org.deegree.portal.cataloguemanager.model.EXTemporalExtent;
    080    import org.deegree.portal.cataloguemanager.model.ExceptionBean;
    081    import org.deegree.portal.cataloguemanager.model.Keyword;
    082    import org.deegree.portal.cataloguemanager.model.Linkage;
    083    import org.deegree.portal.cataloguemanager.model.MDDataIdentification;
    084    import org.deegree.portal.cataloguemanager.model.MDDigitalTransferOptions;
    085    import org.deegree.portal.cataloguemanager.model.MDDistribution;
    086    import org.deegree.portal.cataloguemanager.model.MDFormat;
    087    import org.deegree.portal.cataloguemanager.model.MDMetadata;
    088    import org.deegree.portal.cataloguemanager.model.MDReferenceSystem;
    089    import org.deegree.portal.cataloguemanager.model.MDRepresentativeFraction;
    090    import org.deegree.portal.cataloguemanager.model.MetadataBean;
    091    import org.deegree.portal.cataloguemanager.model.Name;
    092    import org.deegree.portal.cataloguemanager.model.OnLine;
    093    import org.deegree.portal.cataloguemanager.model.Phone;
    094    import org.deegree.portal.cataloguemanager.model.PointOfContact;
    095    import org.deegree.portal.cataloguemanager.model.SpatialResolution;
    096    import org.deegree.portal.cataloguemanager.model.TimePeriod;
    097    import org.deegree.portal.cataloguemanager.model.TransferOptions;
    098    import org.deegree.portal.cataloguemanager.model.Version;
    099
    100    /**
    101     *
    102     *
    103     *
    104     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
    105     * @author last edited by: $Author: apoth $
    106     *
    107     * @version $Revision: 26885 $, $Date: 2010-09-21 14:41:43 +0200 (Di, 21. Sep 2010) $
    108     */
    109    public class InsertMetadataListener extends AbstractMetadataListener {
    110
    111        protected static CoordinateSystem crs;
    112
    113        static {
    114            if ( crs == null ) {
    115                try {
    116                    crs = CRSFactory.create( "EPSG:4326" );
    117                } catch ( Exception e ) {
    118                    BootLogger.logError( e.getMessage(), e );
    119                }
    120            }
    121        }
    122
    123        private static ILogger LOG = LoggerFactory.getLogger( InsertMetadataListener.class );
    124
    125        protected CatalogueManagerConfiguration conf;
    126
    127        @Override
    128        public void actionPerformed( WebEvent event, ResponseHandler responseHandler )
    129                                throws IOException {
    130
    131            try {
    132                conf = getCatalogueManagerConfiguration( event );
    133                MetadataBean bean = (MetadataBean) event.getAsBean();
    134                JAXBContext jc = JAXBContext.newInstance( "org.deegree.portal.cataloguemanager.model" );
    135                Unmarshaller u = jc.createUnmarshaller();
    136
    137                String tmp = conf.getTemplateURL( bean.getHlevel() );
    138                URL url = conf.resolve( tmp );
    139                MDMetadata mdMetadata = (MDMetadata) u.unmarshal( url );
    140
    141                // metadata settings
    142                mdMetadata.getFileIdentifier().setCharacterString( bean.getIdentifier() );
    143                mdMetadata.getHierarchyLevel().getMDScopeCode().setCodeListValue( bean.getHlevel() );
    144                tmp = bean.getHlevel();
    145                if ( "series".equalsIgnoreCase( tmp ) ) {
    146                    tmp = "datasetcollection";
    147                }
    148                mdMetadata.getHierarchyLevelName().setCharacterString( tmp );
    149                setContact( mdMetadata, bean );
    150                mdMetadata.getDateStamp().setDateTime( TimeTools.getISOFormattedTime() );
    151                if ( bean.getCrs() != null ) {
    152                    MDReferenceSystem mdRef = mdMetadata.getReferenceSystemInfo().getMDReferenceSystem();
    153                    mdRef.getReferenceSystemIdentifier().getRSIdentifier().getCode().setCharacterString( bean.getCrs() );
    154                }
    155
    156                // data identification settings
    157                MDDataIdentification mdDataId = mdMetadata.getIdentificationInfo().getMDDataIdentification();
    158                mdDataId.getAbstract().setCharacterString( bean.getAbstract_() );
    159                mdDataId.setUuid( "_" + bean.getIdentifier() );
    160                mdDataId.setId( bean.getIdentifier() );
    161                setKeywords( mdDataId, bean );
    162                setPointOfContact( mdDataId, bean );
    163                mdDataId.getTopicCategory().setMDTopicCategoryCode( bean.getTopCat() );
    164                setExtent( mdDataId, bean );
    165
    166                SpatialResolution spr = mdDataId.getSpatialResolution();
    167                if ( bean.getScale() == null || bean.getScale().trim().length() == 0 ) {
    168                    mdDataId.setSpatialResolution( null );
    169                } else {
    170                    MDRepresentativeFraction frac = spr.getMDResolution().getEquivalentScale().getMDRepresentativeFraction();
    171                    frac.getDenominator().setInteger( Integer.parseInt( bean.getScale().trim() ) );
    172                }
    173
    174                CICitation citation = mdDataId.getCitation().getCICitation();
    175                citation.getTitle().setCharacterString( bean.getDatasetTitle() );
    176                citation.getIdentifier().getMDIdentifier().getCode().setCharacterString( bean.getIdentifier() );
    177
    178                List<Date> dates = citation.getDate();
    179                dates.clear();
    180                if ( bean.getCreation() != null ) {
    181                    addDate( dates, "creation", bean.getCreation() );
    182                }
    183                if ( bean.getPublication() != null ) {
    184                    addDate( dates, "publication", bean.getPublication() );
    185                }
    186                if ( bean.getRevision() != null ) {
    187                    addDate( dates, "revision", bean.getRevision() );
    188                }
    189
    190                if ( bean.getTransferOnline() != null && bean.getTransferOnline().trim().length() > 0 ) {
    191                    setDistributionInfo( mdMetadata, bean );
    192                } else {
    193                    mdMetadata.setDistributionInfo( null );
    194                }
    195
    196                if ( bean.getLineage() != null && bean.getLineage().trim().length() > 0 ) {
    197                    mdMetadata.getDataQualityInfo().getDQDataQuality().getLineage().getLILineage().getStatement().setCharacterString(
    198                                                                                                                                      bean.getLineage() );
    199                } else {
    200                    mdMetadata.setDataQualityInfo( null );
    201                }
    202
    203                insertIntoCSW( responseHandler, mdMetadata );
    204
    205            } catch ( Exception e ) {
    206                LOG.logError( e.getMessage(), e );
    207                ExceptionBean eb = new ExceptionBean( getClass().getName(), e.getMessage() );
    208                responseHandler.writeAndClose( true, eb );
    209                return;
    210            }
    211        }
    212
    213        private void setDistributionInfo( MDMetadata mdMetadata, MetadataBean bean ) {
    214            MDDistribution mddist = mdMetadata.getDistributionInfo().getMDDistribution();
    215            if ( mddist == null ) {
    216                mddist = new MDDistribution();
    217                TransferOptions to = new TransferOptions();
    218                MDDigitalTransferOptions dto = new MDDigitalTransferOptions();
    219                OnLine ol = new OnLine();
    220                CIOnlineResource ciolr = new CIOnlineResource();
    221                ciolr.setLinkage( new Linkage() );
    222                ol.setCIOnlineResource( ciolr );
    223                dto.setOnLine( ol );
    224                to.setMDDigitalTransferOptions( dto );
    225                mddist.setTransferOptions( to );
    226            }
    227            MDDigitalTransferOptions to = mddist.getTransferOptions().getMDDigitalTransferOptions();
    228            to.getOnLine().getCIOnlineResource().getLinkage().setURL( bean.getTransferOnline() );
    229            if ( bean.getTransferFormatName() != null && bean.getTransferFormatName().length() > 0 ) {
    230                DistributionFormat format = mdMetadata.getDistributionInfo().getMDDistribution().getDistributionFormat();
    231                if ( format == null ) {
    232                    format = new DistributionFormat();
    233                    MDFormat mdf = new MDFormat();
    234                    mdf.setName( new Name() );
    235                    mdf.setVersion( new Version() );
    236                    format.setMDFormat( mdf );
    237                }
    238                format.getMDFormat().getName().setCharacterString( bean.getTransferFormatName() );
    239                if ( bean.getTransferFormatVersion() != null && bean.getTransferFormatVersion().length() > 0 ) {
    240                    format.getMDFormat().getVersion().setCharacterString( bean.getTransferFormatVersion() );
    241                } else {
    242                    format.getMDFormat().getVersion().setCharacterString( "unknown" );
    243                }
    244            } else {
    245                mdMetadata.getDistributionInfo().getMDDistribution().setDistributionFormat( null );
    246            }
    247        }
    248
    249        private String insertIntoCSW( ResponseHandler responseHandler, MDMetadata mdMetadata )
    250                                throws JAXBException, IOException, HttpException {
    251
    252            JAXBContext jc = JAXBContext.newInstance( "org.deegree.portal.cataloguemanager.model" );
    253            Marshaller m = jc.createMarshaller();
    254
    255            ByteArrayOutputStream bos = new ByteArrayOutputStream( 10000 );
    256            m.marshal( mdMetadata, bos );
    257
    258            URL url = getClass().getResource( "insert.xml" );
    259            String s = FileUtils.readTextFile( url ).toString();
    260            String t = new String( bos.toByteArray() );
    261            int c = t.indexOf( "?>" );
    262            t = t.substring( c + 2 );
    263            s = StringTools.replace( s, "$data$", t, false );
    264            String csw = conf.getCatalogueURL();
    265            PostMethod post = new PostMethod( csw );
    266            post.getParams().setContentCharset( Charset.defaultCharset().displayName() );
    267            StringRequestEntity re = new StringRequestEntity( s );
    268
    269            // FileUtils.writeToFile( "e:/temp/inspire.xml", s );
    270
    271            post.setRequestEntity( re );
    272            HttpClient client = new HttpClient();
    273            client.executeMethod( post );
    274            s = post.getResponseBodyAsString();
    275            if ( s.toLowerCase().indexOf( "exception" ) > -1 ) {
    276                ExceptionBean eb = new ExceptionBean( getClass().getName(), "insert failed" );
    277                responseHandler.writeAndClose( true, eb );
    278            } else {
    279                responseHandler.writeAndClose( "insert performed" );
    280            }
    281
    282            return s;
    283        }
    284
    285        protected void setContact( MDMetadata mdMetadata, MetadataBean bean ) {
    286            Contact contact = mdMetadata.getContact();
    287            CIResponsibleParty respParty = contact.getCIResponsibleParty();
    288            respParty.getIndividualName().setCharacterString( bean.getContactIndividualName() );
    289            respParty.getOrganisationName().setCharacterString( bean.getContactOrganisationName() );
    290            respParty.getRole().getCIRoleCode().setCodeListValue( bean.getContactRole() );
    291            ContactInfo ci = respParty.getContactInfo();
    292            Phone phone = ci.getCIContact().getPhone();
    293            phone.getCITelephone().getFacsimile().setCharacterString( bean.getContactFacsimile() );
    294            phone.getCITelephone().getVoice().setCharacterString( bean.getContactVoice() );
    295            Address address = ci.getCIContact().getAddress();
    296            address.getCIAddress().getCity().setCharacterString( bean.getContactCity() );
    297            address.getCIAddress().getCountry().setCharacterString( bean.getContactCountry() );
    298            address.getCIAddress().getDeliveryPoint().setCharacterString( bean.getContactDeliveryPoint() );
    299            address.getCIAddress().getElectronicMailAddress().setCharacterString( bean.getContactEmailAddress() );
    300            address.getCIAddress().getPostalCode().setCharacterString( bean.getContactPostalCode() );
    301        }
    302
    303        protected void setExtent( MDDataIdentification mdDataId, MetadataBean bean )
    304                                throws CRSTransformationException {
    305            EXExtent extent = mdDataId.getExtent().getEXExtent();
    306            extent.getDescription().setCharacterString( getGeogrDesc( bean.getGeogrDescription() ) );
    307            EXTemporalExtent te = extent.getTemporalElement().getEXTemporalExtent();
    308            TimePeriod tp = te.getExtent().getTimePeriod();
    309
    310            tp.setBeginPosition( bean.getBegin() );
    311            tp.setEndPosition( bean.getEnd() );
    312            EXGeographicBoundingBox bbox = extent.getGeographicElement().getEXGeographicBoundingBox();
    313            Envelope env = getEnvelope( bean.getGeogrDescription() );
    314            bbox.getWestBoundLongitude().setDecimal( (float) env.getMin().getX() );
    315            bbox.getSouthBoundLatitude().setDecimal( (float) env.getMin().getY() );
    316            bbox.getEastBoundLongitude().setDecimal( (float) env.getMax().getX() );
    317            bbox.getNorthBoundLatitude().setDecimal( (float) env.getMax().getY() );
    318        }
    319
    320        /**
    321         * @param geographicIdentifier
    322         * @return
    323         */
    324        private String getGeogrDesc( String geographicIdentifier ) {
    325            List<SpatialExtent> extents = conf.getSpatialExtents();
    326            for ( SpatialExtent spatialExtent : extents ) {
    327                if ( spatialExtent.getId().equalsIgnoreCase( geographicIdentifier ) ) {
    328                    return spatialExtent.getName();
    329                }
    330            }
    331            return "-";
    332        }
    333
    334        protected Envelope getEnvelope( String geogrDescription )
    335                                throws CRSTransformationException {
    336            List<SpatialExtent> spatialExtents = conf.getSpatialExtents();
    337            String bbox = "-180,-90,180,90";
    338            for ( SpatialExtent spatialExtent : spatialExtents ) {
    339                if ( spatialExtent.getId().equals( geogrDescription ) ) {
    340                    bbox = spatialExtent.getBbox();
    341                    break;
    342                }
    343            }
    344            return GeometryFactory.createEnvelope( bbox, crs );
    345        }
    346
    347        protected void setPointOfContact( MDDataIdentification mdDataId, MetadataBean bean ) {
    348            PointOfContact poc = mdDataId.getPointOfContact();
    349            CIResponsibleParty respParty = poc.getCIResponsibleParty();
    350            respParty.getIndividualName().setCharacterString( bean.getPocIndividualName() );
    351            respParty.getOrganisationName().setCharacterString( bean.getPocOrganisationName() );
    352            respParty.getRole().getCIRoleCode().setCodeListValue( bean.getPocRole() );
    353            ContactInfo ci = respParty.getContactInfo();
    354            Phone phone = ci.getCIContact().getPhone();
    355            phone.getCITelephone().getFacsimile().setCharacterString( bean.getPocFacsimile() );
    356            phone.getCITelephone().getVoice().setCharacterString( bean.getPocVoice() );
    357            Address address = ci.getCIContact().getAddress();
    358            address.getCIAddress().getCity().setCharacterString( bean.getPocCity() );
    359            address.getCIAddress().getCountry().setCharacterString( bean.getPocCountry() );
    360            address.getCIAddress().getDeliveryPoint().setCharacterString( bean.getPocDeliveryPoint() );
    361            address.getCIAddress().getElectronicMailAddress().setCharacterString( bean.getPocEmailAddress() );
    362            address.getCIAddress().getPostalCode().setCharacterString( bean.getPocPostalCode() );
    363        }
    364
    365        @SuppressWarnings("unchecked")
    366        protected void setKeywords( MDDataIdentification mdDataId, MetadataBean bean ) {
    367            List<Keyword> list = mdDataId.getDescriptiveKeywords().getMDKeywords().getKeyword();
    368            list.clear();
    369            List<String> kw = bean.getKeywords();
    370            for ( String keyword : kw ) {
    371                Keyword key = new Keyword();
    372                key.setCharacterString( keyword );
    373                list.add( key );
    374            }
    375            Keyword key = new Keyword();
    376            key.setCharacterString( bean.getInspireDataTheme() );
    377            list.add( key );
    378        }
    379
    380        protected void addDate( List<Date> dates, String type, String value ) {
    381            Date date = new Date();
    382            CIDate cidate = new CIDate();
    383            cidate.setDate( date );
    384            DateType dt = new DateType();
    385            CIDateTypeCode dtc = new CIDateTypeCode();
    386            dtc.setCodeList( "http://www.isotc211.org/2005/resources/codeList.xml#CI_DateTypeCode" );
    387            dtc.setCodeListValue( type );
    388            dt.setCIDateTypeCode( dtc );
    389            cidate.setDateType( dt );
    390            Date dateValue = new Date();
    391            dateValue.setDateTime( value + "T00:00:00Z" );
    392            cidate.setDate( dateValue );
    393            date.setCIDate( cidate );
    394            dates.add( date );
    395        }
    396
    397    }