001    //$HeadURL: svn+ssh://rbezema@svn.wald.intevation.org/deegree/base/branches/2.2_testing/src/org/deegree/ogcwebservices/csw/manager/XMLFactory.java $
002    /*----------------    FILE HEADER  ------------------------------------------
003    
004     This file is part of deegree.
005     Copyright (C) 2001-2008 by:
006     EXSE, Department of Geography, University of Bonn
007     http://www.giub.uni-bonn.de/deegree/
008     lat/lon GmbH
009     http://www.lat-lon.de
010    
011     This library is free software; you can redistribute it and/or
012     modify it under the terms of the GNU Lesser General Public
013     License as published by the Free Software Foundation; either
014     version 2.1 of the License, or (at your option) any later version.
015    
016     This library is distributed in the hope that it will be useful,
017     but WITHOUT ANY WARRANTY; without even the implied warranty of
018     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
019     Lesser General Public License for more details.
020    
021     You should have received a copy of the GNU Lesser General Public
022     License along with this library; if not, write to the Free Software
023     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
024    
025     Contact:
026    
027     Andreas Poth
028     lat/lon GmbH
029     Aennchenstr. 19
030     53115 Bonn
031     Germany
032     E-Mail: poth@lat-lon.de
033    
034     Prof. Dr. Klaus Greve
035     Department of Geography
036     University of Bonn
037     Meckenheimer Allee 166
038     53115 Bonn
039     Germany
040     E-Mail: greve@giub.uni-bonn.de
041    
042     ---------------------------------------------------------------------------*/
043    package org.deegree.ogcwebservices.csw.manager;
044    
045    import java.net.URI;
046    import java.util.List;
047    
048    import org.deegree.framework.log.ILogger;
049    import org.deegree.framework.log.LoggerFactory;
050    import org.deegree.framework.xml.XMLException;
051    import org.deegree.framework.xml.XMLParsingException;
052    import org.deegree.framework.xml.XMLTools;
053    import org.deegree.model.filterencoding.Filter;
054    import org.deegree.ogcbase.CommonNamespaces;
055    import org.deegree.ogcwebservices.OGCWebServiceException;
056    import org.deegree.ogcwebservices.wfs.operation.transaction.TransactionResponse;
057    import org.w3c.dom.Document;
058    import org.w3c.dom.Element;
059    import org.w3c.dom.Node;
060    import org.w3c.dom.NodeList;
061    
062    /**
063     * 
064     * @version $Revision: 9561 $
065     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
066     * @author last edited by: $Author: lbuesching $
067     * 
068     * @version $Revision: 9561 $, $Date: 2008-01-16 13:42:50 +0100 (Mi, 16 Jan 2008) $
069     * 
070     */
071    public class XMLFactory {
072    
073        private static ILogger LOG = LoggerFactory.getLogger( XMLFactory.class );
074    
075        private static final URI CSWNS = CommonNamespaces.CSWNS;
076    
077        /**
078         * @return a XML representation of a {@link Transaction} object
079         * 
080         * @param transaction
081         * @throws XMLParsingException
082         * @throws XMLException
083         * @throws OGCWebServiceException
084         */
085        public static final TransactionDocument export( Transaction transaction )
086                                throws XMLParsingException, OGCWebServiceException {
087    
088            TransactionDocument transDoc = new TransactionDocument();
089            try {
090                transDoc.createEmptyDocument();
091            } catch ( Exception e ) {
092                throw new XMLParsingException( e.getMessage() );
093            }
094    
095            transDoc.getRootElement().setAttribute( "service", "CSW" );
096            String version = transaction.getVersion();
097            if ( version == null || "".equals( version.trim() ) ) {
098                version = "2.0.0";
099            }
100            transDoc.getRootElement().setAttribute( "version", version );
101            transDoc.getRootElement().setAttribute( "verboseResponse", "" + transaction.verboseResponse() );
102    
103            List<Operation> ops = transaction.getOperations();
104            for ( int i = 0; i < ops.size(); i++ ) {
105                Operation operation = ops.get( i );
106                appendOperation( transDoc.getRootElement(), operation );
107            }
108    
109            return transDoc;
110    
111        }
112    
113        /**
114         * @return an XML representation of a {@link TransactionResponse} object
115         * 
116         * @param response
117         * @throws XMLParsingException
118         * @throws OGCWebServiceException
119         */
120        public static final HarvetResultDocument export( HarvestResult response )
121                                throws XMLParsingException {
122    
123            String version = response.getRequest().getVersion();
124            if ( version == null || "".equals( version.trim() ) ) {
125                version = "2.0.1";
126            }
127    
128            HarvetResultDocument harvestRespDoc = new HarvetResultDocument();
129            try {
130                harvestRespDoc.createEmptyDocument( version );
131            } catch ( Exception e ) {
132                throw new XMLParsingException( e.getMessage() );
133            }
134    
135            Element root = harvestRespDoc.getRootElement();
136            root.setAttribute( "version", version );
137    
138            URI namespaceURI = ( version.equals( "2.0.2" ) ) ? CommonNamespaces.CSW202NS : CommonNamespaces.CSWNS;
139    
140            Element elem = XMLTools.appendElement( root, namespaceURI, "csw:TransactionSummary" );
141            root.appendChild( elem );
142            XMLTools.appendElement( elem, namespaceURI, "csw:totalInserted", Integer.toString( response.getTotalInserted() ) );
143            XMLTools.appendElement( elem, namespaceURI, "csw:totalUpdated", Integer.toString( response.getTotalUpdated() ) );
144            XMLTools.appendElement( elem, namespaceURI, "csw:totalDeleted", Integer.toString( response.getTotalDeleted() ) );
145    
146            List<Node> records = response.getResults().getRecords();
147            if ( records.size() > 0 ) {
148                elem = XMLTools.appendElement( root, namespaceURI, "csw:InsertResult" );
149                Element briefRecord = XMLTools.appendElement( elem, namespaceURI, "csw:BriefRecord" );
150                Document owner = root.getOwnerDocument();
151                for ( int i = 0; i < records.size(); ++i ) {
152                    LOG.logDebug( "(" + i + " of " + records.size() + ") trying to insert xmlnode: "
153                                  + records.get( i ).getNodeName() );
154                    NodeList childs = records.get( i ).getChildNodes();
155                    for ( int j = 0; j < childs.getLength(); j++ ) {
156                        Node a = owner.importNode( childs.item( j ), true );
157                        briefRecord.appendChild( a );
158                    }
159                }
160            }
161    
162            return harvestRespDoc;
163        }
164    
165        /**
166         * @return an XML representation of a {@link TransactionResponse} object
167         * 
168         * @param response
169         * @throws XMLParsingException
170         * @throws OGCWebServiceException
171         */
172        public static final TransactionResultDocument export( TransactionResult response )
173                                throws XMLParsingException {
174    
175            String version = response.getRequest().getVersion();
176            if ( version == null || "".equals( version.trim() ) ) {
177                version = "2.0.1";
178            }
179    
180            TransactionResultDocument transRespDoc = new TransactionResultDocument();
181            try {
182                transRespDoc.createEmptyDocument( version );
183            } catch ( Exception e ) {
184                throw new XMLParsingException( e.getMessage() );
185            }
186    
187            Element root = transRespDoc.getRootElement();
188            root.setAttribute( "version", version );
189    
190            URI namespaceURI = ( version.equals( "2.0.2" ) ) ? CommonNamespaces.CSW202NS : CommonNamespaces.CSWNS;
191    
192            Element elem = XMLTools.appendElement( root, namespaceURI, "csw:TransactionSummary" );
193            root.appendChild( elem );
194            XMLTools.appendElement( elem, namespaceURI, "csw:totalInserted", Integer.toString( response.getTotalInserted() ) );
195            XMLTools.appendElement( elem, namespaceURI, "csw:totalUpdated", Integer.toString( response.getTotalUpdated() ) );
196            XMLTools.appendElement( elem, namespaceURI, "csw:totalDeleted", Integer.toString( response.getTotalDeleted() ) );
197    
198            List<Node> records = response.getResults().getRecords();
199            if ( records.size() > 0 ) {
200                elem = XMLTools.appendElement( root, namespaceURI, "csw:InsertResult" );
201                Element briefRecord = XMLTools.appendElement( elem, namespaceURI, "csw:BriefRecord" );
202                Document owner = root.getOwnerDocument();
203                for ( int i = 0; i < records.size(); ++i ) {
204                    LOG.logDebug( "(" + i + " of " + records.size() + ") trying to insert xmlnode: "
205                                  + records.get( i ).getNodeName() );
206                    NodeList childs = records.get( i ).getChildNodes();
207                    for ( int j = 0; j < childs.getLength(); j++ ) {
208                        Node a = owner.importNode( childs.item( j ), true );
209                        briefRecord.appendChild( a );
210                    }
211                }
212                LOG.logDebug( "Successfully inserted " + records.size() + " brief records into the result documents" );
213                // root.appendChild( elem );
214            }
215    
216            return transRespDoc;
217    
218        }
219    
220        /**
221         * 
222         * @param root
223         * @param operation
224         * @throws OGCWebServiceException
225         */
226        public static void appendOperation( Element root, Operation operation )
227                                throws OGCWebServiceException {
228    
229            if ( "Insert".equals( operation.getName() ) ) {
230                appendInsert( root, (Insert) operation );
231            } else if ( "Update".equals( operation.getName() ) ) {
232                appendUpdate( root, (Update) operation );
233            } else if ( "Delete".equals( operation.getName() ) ) {
234                appendDelete( root, (Delete) operation );
235            } else {
236                throw new OGCWebServiceException( "unknown CS-W transaction operation: " + operation.getName() );
237            }
238        }
239    
240        /**
241         * appends an Delete operation to the passed root element
242         * 
243         * @param root
244         * @param delete
245         */
246        public static void appendDelete( Element root, Delete delete ) {
247            Document doc = root.getOwnerDocument();
248            Element op = doc.createElementNS( CSWNS.toASCIIString(), "csw:" + delete.getName() );
249            if ( delete.getHandle() != null ) {
250                op.setAttribute( "handle", delete.getHandle() );
251            }
252            if ( delete.getTypeName() != null ) {
253    
254                op.setAttribute( "typeName", delete.getTypeName().toASCIIString() );
255            }
256    
257            Filter filter = delete.getConstraint();
258            Element constraint = doc.createElementNS( CSWNS.toASCIIString(), "csw:Constraint" );
259            constraint.setAttribute( "version", "1.0.0" );
260            op.appendChild( constraint );
261            org.deegree.model.filterencoding.XMLFactory.appendFilter( constraint, filter );
262            root.appendChild( op );
263    
264        }
265    
266        /**
267         * appends an Update operation to the passed root element
268         * 
269         * @param root
270         * @param update
271         */
272        public static void appendUpdate( Element root, Update update ) {
273            Document doc = root.getOwnerDocument();
274            Element op = doc.createElementNS( CSWNS.toASCIIString(), "csw:" + update.getName() );
275            if ( update.getHandle() != null ) {
276                op.setAttribute( "handle", update.getHandle() );
277            }
278            if ( update.getTypeName() != null ) {
279                op.setAttribute( "typeName", update.getTypeName().toASCIIString() );
280            }
281            XMLTools.insertNodeInto( update.getRecord(), op );
282            Filter filter = update.getConstraint();
283            Element constraint = doc.createElementNS( CSWNS.toASCIIString(), "csw:Constraint" );
284            constraint.setAttribute( "version", "1.0.0" );
285            op.appendChild( constraint );
286            org.deegree.model.filterencoding.XMLFactory.appendFilter( constraint, filter );
287            root.appendChild( op );
288        }
289    
290        /**
291         * appends an Insert operation to the passed root element
292         * 
293         * @param root
294         * @param insert
295         */
296        public static void appendInsert( Element root, Insert insert ) {
297            Document doc = root.getOwnerDocument();
298            Element tmp = doc.createElementNS( CSWNS.toASCIIString(), "csw:" + insert.getName() );
299            Element op = (Element) root.appendChild( tmp );
300            if ( insert.getHandle() != null ) {
301                op.setAttribute( "handle", insert.getHandle() );
302            }
303            List<Element> list = insert.getRecords();
304            for ( Element e : list ) {
305                Node copy = doc.importNode( e, true );
306                op.appendChild( copy );
307            }
308            // for ( int i = 0; i < list.size(); i++ ) {
309            // XMLTools.insertNodeInto( list.get( i ), op );
310            // }
311    
312        }
313    }