001    //$HeadURL: svn+ssh://rbezema@svn.wald.intevation.org/deegree/base/branches/2.2_testing/src/org/deegree/enterprise/servlet/CSWHandler.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     ---------------------------------------------------------------------------*/
044    package org.deegree.enterprise.servlet;
045    
046    import java.io.IOException;
047    import java.io.OutputStream;
048    import java.io.PrintWriter;
049    import java.lang.reflect.Method;
050    
051    import javax.servlet.http.HttpServletResponse;
052    
053    import org.deegree.enterprise.ServiceException;
054    import org.deegree.framework.log.ILogger;
055    import org.deegree.framework.log.LoggerFactory;
056    import org.deegree.framework.util.CharsetUtils;
057    import org.deegree.framework.xml.XMLFragment;
058    import org.deegree.framework.xml.XMLParsingException;
059    import org.deegree.ogcbase.ExceptionCode;
060    import org.deegree.ogcwebservices.EchoRequest;
061    import org.deegree.ogcwebservices.InvalidParameterValueException;
062    import org.deegree.ogcwebservices.OGCWebServiceException;
063    import org.deegree.ogcwebservices.OGCWebServiceRequest;
064    import org.deegree.ogcwebservices.csw.CSWFactory;
065    import org.deegree.ogcwebservices.csw.CSWPropertiesAccess;
066    import org.deegree.ogcwebservices.csw.CatalogueService;
067    import org.deegree.ogcwebservices.csw.capabilities.CatalogueCapabilities;
068    import org.deegree.ogcwebservices.csw.capabilities.CatalogueGetCapabilities;
069    import org.deegree.ogcwebservices.csw.discovery.DescribeRecordResult;
070    import org.deegree.ogcwebservices.csw.discovery.GetRecordByIdResult;
071    import org.deegree.ogcwebservices.csw.discovery.GetRecordsResult;
072    import org.deegree.ogcwebservices.csw.manager.HarvestResult;
073    import org.deegree.ogcwebservices.csw.manager.TransactionResult;
074    
075    /**
076     * Web servlet client for CSW.
077     * 
078     * @author <a href="mailto:tfr@users.sourceforge.net">Torsten Friebe </A>
079     * @author last edited by: $Author: aschmitz $
080     * 
081     * @version $Revision: 9499 $, $Date: 2008-01-09 16:47:04 +0100 (Mi, 09 Jan 2008) $
082     * 
083     * @see <a href="http://www.dofactory.com/patterns/PatternChain.aspx">Chain of Responsibility Design
084     *      Pattern </a>
085     */
086    
087    public class CSWHandler extends AbstractOWServiceHandler {
088    
089        private static final ILogger LOG = LoggerFactory.getLogger( CSWHandler.class );
090    
091        /**
092         * @param request
093         * @param httpResponse
094         * @throws ServiceException
095         * @throws OGCWebServiceException
096         * @see "org.deegree.enterprise.servlet.ServiceDispatcher#perform(org.deegree.services.AbstractOGCWebServiceRequest,javax.servlet.http.HttpServletResponse)"
097         */
098        public void perform( OGCWebServiceRequest request, HttpServletResponse httpResponse )
099                                throws ServiceException, OGCWebServiceException {
100    
101            LOG.logDebug( "Performing request: " + request.toString() );
102    
103            try {
104                CatalogueService service = CSWFactory.getService();
105                Object response = service.doService( request );
106                if ( response instanceof OGCWebServiceException ) {
107                    sendExceptionReport( httpResponse, (OGCWebServiceException) response );
108                } else if ( response instanceof Exception ) {
109                    sendExceptionReport( httpResponse, (Exception) response );
110                } else if ( response instanceof CatalogueCapabilities ) {
111                    sendCapabilities( httpResponse, (CatalogueGetCapabilities) request, (CatalogueCapabilities) response );
112                } else if ( response instanceof GetRecordsResult ) {
113                    sendGetRecord( httpResponse, (GetRecordsResult) response );
114                } else if ( response instanceof GetRecordByIdResult ) {
115                    sendGetRecordById( httpResponse, (GetRecordByIdResult) response );
116                } else if ( response instanceof DescribeRecordResult ) {
117                    sendDescribeRecord( httpResponse, (DescribeRecordResult) response );
118                } else if ( response instanceof TransactionResult ) {
119                    sendTransactionResult( httpResponse, (TransactionResult) response );
120                } else if ( response instanceof HarvestResult ) {
121                    sendHarvestResult( httpResponse, (HarvestResult) response );
122                } else if ( response instanceof EchoRequest ) {
123                    sendHarvestResult( httpResponse );
124                } else {
125                    OGCWebServiceException e = new OGCWebServiceException(
126                                                                           this.getClass().getName(),
127                                                                           "Unknown response class: "
128                                                                                                   + ( response == null ? "null response object"
129                                                                                                                       : response.getClass().getName() )
130                                                                                                   + "." );
131                    sendExceptionReport( httpResponse, e );
132                }
133            } catch ( IOException ex ) {
134                throw new ServiceException( "Error while sending response: " + ex.getMessage(), ex );
135            } catch ( OGCWebServiceException ogc ) {
136                sendExceptionReport( httpResponse, ogc );
137            }
138    
139        }
140    
141        /**
142         * Sends the passed <tt>HarvestResult</tt> to the http client.
143         * 
144         * @param httpResponse
145         *            http connection to the client
146         * @param result
147         *            object to send
148         * @throws IOException
149         * @throws XMLParsingException
150         */
151        private void sendHarvestResult( HttpServletResponse httpResponse, HarvestResult result )
152                                throws IOException {
153            XMLFragment doc = null;
154            try {
155                doc = org.deegree.ogcwebservices.csw.manager.XMLFactory.export( result );
156            } catch ( XMLParsingException e ) {
157                throw new IOException( "could not export TransactionResult as XML: " + e.getMessage() );
158            }
159            httpResponse.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
160            OutputStream os = httpResponse.getOutputStream();
161            doc.write( os );
162            os.close();
163        }
164    
165        /**
166         * 
167         * @param httpResponse
168         * @throws IOException
169         */
170        private void sendHarvestResult( HttpServletResponse httpResponse )
171                                throws IOException {
172    
173            httpResponse.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
174            PrintWriter pw = httpResponse.getWriter();
175            pw.write( "<HarvestResponse>Harvest request has been received " );
176            pw.write( "and will be performed</HarvestResponse>" );
177            pw.close();
178        }
179    
180        /**
181         * Sends the passed <tt>TransactionResult</tt> to the http client.
182         * 
183         * @param httpResponse
184         *            http connection to the client
185         * @param result
186         *            object to send
187         * @throws XMLParsingException
188         */
189        private void sendTransactionResult( HttpServletResponse httpResponse, TransactionResult result )
190                                throws IOException {
191            XMLFragment doc = null;
192            try {
193                doc = org.deegree.ogcwebservices.csw.manager.XMLFactory.export( result );
194            } catch ( XMLParsingException e ) {
195                throw new IOException( "could not export TransactionResult as XML: " + e.getMessage() );
196            }
197            httpResponse.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
198            OutputStream os = httpResponse.getOutputStream();
199            doc.write( os );
200            os.close();
201        }
202    
203        /**
204         * Sends the passed <tt>CatalogCapabilities</tt> to the http client.
205         * 
206         * @param response
207         *            http connection to the client
208         * @param capabilities
209         *            object to send
210         */
211        private void sendCapabilities( HttpServletResponse response, CatalogueGetCapabilities getCapabilities,
212                                       CatalogueCapabilities capabilities )
213                                throws IOException {
214    
215            boolean xmlOk = false;
216            String[] formats = getCapabilities.getAcceptFormats();
217            if ( formats == null || formats.length == 0 ) {
218                xmlOk = true;
219            } else {
220                for ( int i = 0; i < formats.length; i++ ) {
221                    if ( formats[i].equals( "text/xml" ) ) {
222                        xmlOk = true;
223                        break;
224                    }
225                }
226            }
227            if ( !xmlOk ) {
228                ExceptionCode code = ExceptionCode.INVALIDPARAMETERVALUE;
229                InvalidParameterValueException e = new InvalidParameterValueException( this.getClass().getName(),
230                                                                                       "OutputFormat must be 'text/xml'.",
231                                                                                       code );
232                sendExceptionReport( response, e );
233            } else {
234                String version = getCapabilities.getVersion();
235                String className = CSWPropertiesAccess.getString( "XMLFactory" + version );
236                XMLFragment doc = null;
237                try {
238                    Class<?> clzz = Class.forName( className );
239                    Class[] parameterTypes = new Class[] { CatalogueCapabilities.class, String[].class };
240                    Object[] parameters = new Object[] { capabilities, getCapabilities.getSections() };
241                    Method method = clzz.getMethod( "export", parameterTypes );
242                    doc = (XMLFragment) method.invoke( null, parameters );
243                } catch ( Exception e ) {
244                    e.printStackTrace();
245                }
246    
247                response.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
248                OutputStream os = response.getOutputStream();
249                doc.write( os );
250                os.close();
251            }
252        }
253    
254        /**
255         * 
256         * @param response
257         * @param getRecordResponse
258         * @throws IOException
259         */
260        private void sendGetRecord( HttpServletResponse response, GetRecordsResult getRecordResponse )
261                                throws IOException {
262            XMLFragment doc = org.deegree.ogcwebservices.csw.discovery.XMLFactory.export( getRecordResponse );
263            if ( LOG.isDebug() ) {
264                LOG.logDebug( "GetRecord response", doc.getAsPrettyString() );
265            }
266            response.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
267            OutputStream os = response.getOutputStream();
268            doc.write( os );
269            os.close();
270        }
271    
272        /**
273         * 
274         * @param response
275         * @param getRecordByResponse
276         * @throws IOException
277         */
278        private void sendGetRecordById( HttpServletResponse response, GetRecordByIdResult getRecordByIdResponse )
279                                throws IOException {
280            XMLFragment doc = org.deegree.ogcwebservices.csw.discovery.XMLFactory.export( getRecordByIdResponse );
281            if ( LOG.isDebug() ) {
282                LOG.logDebug( "GetRecordById response", doc.getAsPrettyString() );
283            }
284            response.setContentType( "text/xml" );
285            OutputStream os = response.getOutputStream();
286            doc.write( os );
287            os.close();
288        }
289    
290        /**
291         * 
292         * @param response
293         * @param describeRecordRequest
294         * @param describeRecordResponse
295         * @throws IOException
296         */
297        private void sendDescribeRecord( HttpServletResponse response, DescribeRecordResult describeRecordResponse )
298                                throws IOException {
299            XMLFragment doc = org.deegree.ogcwebservices.csw.discovery.XMLFactory.export( describeRecordResponse );
300            if ( LOG.isDebug() ) {
301                LOG.logDebug( "DescribeRecord response", doc.getAsPrettyString() );
302            }
303            response.setContentType( "text/xml; charset=" + CharsetUtils.getSystemCharset() );
304            OutputStream os = response.getOutputStream();
305            doc.write( os );
306            os.close();
307        }
308    }