001    //$HeadURL: svn+ssh://developername@svn.wald.intevation.org/deegree/base/trunk/src/org/deegree/ogcwebservices/csw/manager/Manager_2_0_0.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 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.ogcwebservices.csw.manager;
037    
038    import java.io.IOException;
039    import java.io.StringReader;
040    import java.io.StringWriter;
041    import java.net.MalformedURLException;
042    import java.net.URL;
043    import java.util.ArrayList;
044    import java.util.HashMap;
045    import java.util.Iterator;
046    import java.util.List;
047    import java.util.Map;
048    
049    import javax.xml.transform.TransformerException;
050    
051    import org.deegree.framework.log.ILogger;
052    import org.deegree.framework.log.LoggerFactory;
053    import org.deegree.framework.xml.XMLFragment;
054    import org.deegree.framework.xml.XMLParsingException;
055    import org.deegree.framework.xml.XMLTools;
056    import org.deegree.framework.xml.XSLTDocument;
057    import org.deegree.ogcbase.CommonNamespaces;
058    import org.deegree.ogcwebservices.EchoRequest;
059    import org.deegree.ogcwebservices.OGCWebServiceException;
060    import org.deegree.ogcwebservices.wfs.operation.transaction.TransactionResponse;
061    import org.w3c.dom.Document;
062    import org.w3c.dom.Element;
063    import org.w3c.dom.NamedNodeMap;
064    import org.w3c.dom.Node;
065    import org.w3c.dom.NodeList;
066    import org.xml.sax.SAXException;
067    
068    /**
069     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth </a>
070     *
071     * @author last edited by: $Author: apoth $
072     *
073     * @version 2.0, $Revision: 9359 $, $Date: 2007-12-28 16:30:52 +0100 (Fr, 28 Dez 2007) $
074     */
075    
076    public class Manager_2_0_2 extends AbstractManager {
077    
078        private static final ILogger LOG = LoggerFactory.getLogger( Manager_2_0_2.class );
079    
080        private static final URL xsltURL = Manager_2_0_2.class.getResource( "iso_ap_1_0_full2brief.xsl" );
081    
082        /*
083         * (non-Javadoc)
084         *
085         * @see org.deegree.ogcwebservices.csw.manager.Manager#harvestRecords(org.deegree.ogcwebservices.csw.manager.Harvest)
086         */
087        public EchoRequest harvestRecords( Harvest request )
088                                throws OGCWebServiceException {
089            try {
090                HarvesterFactory hf = new HarvesterFactory( harvester );
091                AbstractHarvester h = hf.findHarvester( request );
092                h.addRequest( request );
093                if ( !h.isRunning() ) {
094                    h.startHarvesting();
095                }
096                if ( request.getHarvestInterval() == null ) {
097                    // h.removeRequest( request );
098                }
099            } catch ( Exception e ) {
100                LOG.logError( "could not perform harvest operation", e );
101                throw new OGCWebServiceException( getClass().getName(), "could not perform harvest operation"
102                                                                        + e.getMessage() );
103            }
104    
105            return new EchoRequest( request.getId(), null );
106        }
107    
108        /*
109         * (non-Javadoc)
110         *
111         * @see org.deegree.ogcwebservices.csw.manager.Manager#transaction(org.deegree.ogcwebservices.csw.manager.Transaction)
112         */
113        public TransactionResult transaction( Transaction request )
114                                throws OGCWebServiceException {
115            XMLFragment wfsTransactionDocument = null;
116    
117            try {
118                XMLFragment transactionDocument = XMLFactory.export( request );
119                String nsp = getAllNamespaceDeclarations( transactionDocument.getRootElement() );
120                StringWriter sww = new StringWriter( 15000 );
121                transactionDocument.write( sww );
122                transactionDocument.load( new StringReader( sww.getBuffer().toString() ), XMLFragment.DEFAULT_URL );
123    
124                synchronized ( IN_XSL ) {
125                    Map<String, String> param = new HashMap<String, String>();
126                    param.put( "NSP", nsp );
127                    try {
128                        wfsTransactionDocument = IN_XSL.transform( transactionDocument, XMLFragment.DEFAULT_URL, null,
129                                                                   param );
130                    } catch ( MalformedURLException e ) {
131                        LOG.logError( e.getMessage(), e );
132                    }
133                }
134    
135                if ( LOG.isDebug() ) {
136                    LOG.logDebug( "The (first) resulting wfs:Transaction document will be written to file" );
137                    LOG.logDebugXMLFile( "first", wfsTransactionDocument );
138                    // LOG.logDebug( "*****First Generated WFS GetFeature request:\n"
139                    // + getFeatureDocument.getAsPrettyString() );
140                }
141                // LOG.logDebug( "The (first) resulting wfs:Transaction document: \n "
142                // + wfsTransactionDocument.getAsPrettyString() );
143    
144            } catch ( SAXException saxe ) {
145                String msg = org.deegree.i18n.Messages.get( "CSW_CREATE_TRANSACTION_ERROR", saxe.getMessage() );
146                LOG.logError( msg, saxe );
147                throw new OGCWebServiceException( msg );
148            } catch ( IOException ioe ) {
149                String msg = org.deegree.i18n.Messages.get( "CSW_CREATE_TRANSACTION_ERROR", ioe.getMessage() );
150                LOG.logError( msg, ioe );
151                throw new OGCWebServiceException( msg );
152            } catch ( TransformerException te ) {
153                String msg = org.deegree.i18n.Messages.get( "CSW_CREATE_TRANSACTION_ERROR", te.getMessage() );
154                LOG.logError( msg, te );
155                throw new OGCWebServiceException( msg );
156            } catch ( XMLParsingException xmle ) {
157                String msg = org.deegree.i18n.Messages.get( "CSW_CREATE_TRANSACTION_ERROR", xmle.getMessage() );
158                LOG.logError( msg, xmle );
159                throw new OGCWebServiceException( msg );
160            }
161    
162            org.deegree.ogcwebservices.wfs.operation.transaction.Transaction wfstrans = null;
163            try {
164                LOG.logDebug( "Creating a wfs transaction from the document" );
165                wfstrans = org.deegree.ogcwebservices.wfs.operation.transaction.Transaction.create(
166                                                                                                    request.getId(),
167                                                                                                    wfsTransactionDocument.getRootElement() );
168            } catch ( OGCWebServiceException ogcwe ) {
169                LOG.logError( ogcwe.getMessage(), ogcwe );
170                String msg = org.deegree.i18n.Messages.get( "CSW_CREATE_TRANSACTION_ERROR2", ogcwe.getMessage() );
171                throw new OGCWebServiceException( msg );
172            }
173    
174            Object wfsResponse = null;
175            try {
176                LOG.logDebug( "Sending the wfs transaction to the wfservice." );
177                wfsResponse = wfsService.doService( wfstrans );
178            } catch ( OGCWebServiceException e ) {
179                String msg = org.deegree.i18n.Messages.get( "CSW_PERFORMING_TRANSACTION_ERROR", e.getMessage() );
180                LOG.logError( msg, e );
181                throw new OGCWebServiceException( msg );
182            }
183    
184            if ( !( wfsResponse instanceof org.deegree.ogcwebservices.wfs.operation.transaction.TransactionResponse ) ) {
185                String msg = org.deegree.i18n.Messages.get( "CSW_WRONG_TRANSACTION_RESULTTYPE",
186                                                            wfsResponse.getClass().getName() );
187                LOG.logError( msg );
188                throw new OGCWebServiceException( msg );
189            }
190    
191            TransactionResponse transResp = (TransactionResponse) wfsResponse;
192            XMLFragment wfsTransRespDoc = null;
193            try {
194                LOG.logDebug( "Parsing the wfs response." );
195                wfsTransRespDoc = org.deegree.ogcwebservices.wfs.XMLFactory.export( transResp );
196            } catch ( IOException e ) {
197                String msg = "export of WFS Transaction response as XML failed: " + e.getMessage();
198                LOG.logError( msg, e );
199                throw new OGCWebServiceException( msg );
200            }
201    
202            // --------------------------------------------------------------
203            // the following section will replace the feature ids returned by
204            // the WFS for Insert requests by the ID of the inserted metadata sets
205            List<Document> briefDocs = new ArrayList<Document>();
206            List<Operation> ops = request.getOperations();
207            for ( int i = 0; i < ops.size(); i++ ) {
208                if ( ops.get( i ) instanceof Insert ) {
209                    try {
210                        briefDocs = getAsBriefDocuments( briefDocs, (Insert) ops.get( i ) );
211                    } catch ( Exception e ) {
212                        LOG.logError( e.getMessage(), e );
213                        throw new OGCWebServiceException( getClass().getName(), e.getMessage() );
214                    }
215                }
216            }
217            try {
218                if ( briefDocs.size() > 0 ) {
219                    wfsTransRespDoc = replaceIds( wfsTransRespDoc, briefDocs );
220                }
221            } catch ( Exception e ) {
222                LOG.logError( e.getMessage(), e );
223                throw new OGCWebServiceException( getClass().getName(), e.getMessage() );
224            }
225            // ---------------------------------------------------------------
226    
227            TransactionResultDocument cswTransactionDocument = null;
228            try {
229                XMLFragment tmp = OUT_XSL.transform( wfsTransRespDoc );
230                cswTransactionDocument = new TransactionResultDocument();
231                cswTransactionDocument.setRootElement( tmp.getRootElement() );
232            } catch ( TransformerException e ) {
233                String msg = org.deegree.i18n.Messages.get( "CSW_TRANSACTION_RESULT_TRANS_ERR", e.getMessage() );
234                LOG.logError( msg, e );
235                throw new OGCWebServiceException( msg );
236            }
237            TransactionResult result = null;
238            try {
239                result = cswTransactionDocument.parseTransactionResponse( request );
240            } catch ( XMLParsingException e ) {
241                String msg = org.deegree.i18n.Messages.get( "CSW_TRANSACTION_RESULT_PARSE_ERR" );
242                LOG.logError( msg, e );
243                throw new OGCWebServiceException( msg );
244            }
245            return result;
246        }
247    
248        private String getAllNamespaceDeclarations( Element doc ) {
249            Map<String, String> nsp = new HashMap<String, String>();
250            nsp = collect( nsp, doc );
251            Iterator<String> iter = nsp.keySet().iterator();
252            StringBuffer sb = new StringBuffer( 1000 );
253            while ( iter.hasNext() ) {
254                String s = iter.next();
255                String val = nsp.get( s );
256                sb.append( s ).append( ":" ).append( val );
257                if ( iter.hasNext() ) {
258                    sb.append( ';' );
259                }
260            }
261            return sb.toString();
262        }
263    
264        private Map<String, String> collect( Map<String, String> nsp, Node node ) {
265            NamedNodeMap nnm = node.getAttributes();
266            if ( nnm != null ) {
267                for ( int i = 0; i < nnm.getLength(); i++ ) {
268                    String s = nnm.item( i ).getNodeName();
269                    if ( s.startsWith( "xmlns:" ) ) {
270                        nsp.put( s.substring( 6, s.length() ), nnm.item( i ).getNodeValue() );
271                    }
272                }
273            }
274    
275            NodeList nl = node.getChildNodes();
276            if ( nl != null ) {
277                for ( int i = 0; i < nl.getLength(); i++ ) {
278                    collect( nsp, nl.item( i ) );
279                }
280            }
281            return nsp;
282        }
283    
284        /**
285         * replaces the id values of WFS Insert result with corresponding metadata brief representations
286         *
287         * @param wfsTransRespDoc
288         * @param briefDocs
289         * @return an xmlFragment with the gml:Feature ids replaced with the id' s given in the list
290         * @throws XMLParsingException
291         */
292        private XMLFragment replaceIds( XMLFragment wfsTransRespDoc, List<Document> briefDocs )
293                                throws XMLParsingException {
294    
295            List<Node> nodes = XMLTools.getRequiredNodes( wfsTransRespDoc.getRootElement(),
296                                                          "./wfs:InsertResults/wfs:Feature/ogc:FeatureId",
297                                                          CommonNamespaces.getNamespaceContext() );
298            Element parent = null;
299            for ( int i = 0; i < nodes.size(); i++ ) {
300                Element elem = (Element) nodes.get( i );
301                parent = (Element) elem.getParentNode();
302                parent.removeChild( elem );
303            }
304            if ( parent != null ) {
305                for ( int i = 0; i < briefDocs.size(); i++ ) {
306                    parent = (Element) XMLTools.insertNodeInto( briefDocs.get( i ).getDocumentElement(), parent );
307                }
308            }
309    
310            return wfsTransRespDoc;
311        }
312    
313        /**
314         * all inserted records into threir brief representation
315         *
316         * @param docs
317         * @param insert
318         * @return a list of brief metadata records
319         * @throws SAXException
320         * @throws IOException
321         * @throws TransformerException
322         */
323        private List<Document> getAsBriefDocuments( List<Document> docs, Insert insert )
324                                throws IOException, SAXException, TransformerException {
325            List<Element> records = insert.getRecords();
326    
327            XSLTDocument xslt = new XSLTDocument( xsltURL );
328    
329            for ( int i = 0; i < records.size(); i++ ) {
330                XMLFragment xml = new XMLFragment();
331                xml.setRootElement( records.get( i ) );
332                xml = xslt.transform( xml );
333                docs.add( xml.getRootElement().getOwnerDocument() );
334            }
335            return docs;
336        }
337    
338    }