001    //$HeadURL: https://svn.wald.intevation.org/svn/deegree/base/branches/2.3_testing/src/org/deegree/portal/standard/csw/control/SingleLayerSearchListener.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    
037    package org.deegree.portal.standard.csw.control;
038    
039    import java.io.FileNotFoundException;
040    import java.io.IOException;
041    import java.io.Reader;
042    import java.io.StringReader;
043    import java.net.MalformedURLException;
044    import java.net.URL;
045    import java.util.HashMap;
046    import java.util.Iterator;
047    import java.util.List;
048    import java.util.Map;
049    
050    import javax.servlet.http.HttpServletRequest;
051    import javax.servlet.http.HttpSession;
052    import javax.xml.transform.TransformerException;
053    
054    import org.deegree.enterprise.control.FormEvent;
055    import org.deegree.enterprise.control.RPCParameter;
056    import org.deegree.enterprise.control.RPCStruct;
057    import org.deegree.enterprise.control.RPCWebEvent;
058    import org.deegree.framework.log.ILogger;
059    import org.deegree.framework.log.LoggerFactory;
060    import org.deegree.framework.util.CharsetUtils;
061    import org.deegree.framework.util.ParameterList;
062    import org.deegree.framework.xml.DOMPrinter;
063    import org.deegree.framework.xml.XMLParsingException;
064    import org.deegree.i18n.Messages;
065    import org.deegree.ogcbase.CommonNamespaces;
066    import org.deegree.ogcwebservices.csw.discovery.GetRecordByIdResultDocument;
067    import org.deegree.portal.context.GeneralExtension;
068    import org.deegree.portal.context.Module;
069    import org.deegree.portal.context.ViewContext;
070    import org.deegree.portal.standard.csw.CatalogClientException;
071    import org.deegree.portal.standard.csw.MetadataTransformer;
072    import org.deegree.portal.standard.csw.configuration.CSWClientConfiguration;
073    import org.w3c.dom.Document;
074    import org.w3c.dom.Node;
075    
076    /**
077     * A <code>${type_name}</code> class.<br/> This class handles a CSW metadata search request for a single WMS layer.
078     * The layer for which to search the metedata needs to contain a MetadataURL tag with the address of the corresponding
079     * CSW.
080     *
081     * @author <a href="mailto:mays@lat-lon.de">Judit Mays</a>
082     * @author last edited by: $Author: mschneider $
083     *
084     * @version $Revision: 18195 $, $Date: 2009-06-18 17:55:39 +0200 (Do, 18. Jun 2009) $
085     *
086     * @deprecated Shopping cart will not be supported at the moment. update: new changes in deegree1_fork will not be
087     *             carried here, since this class is still not used. Remove when this status changes
088     */
089    @Deprecated
090    public class SingleLayerSearchListener extends OverviewMetadataListener {
091        // extends OverviewMetadataListener --> SimpleSearchListener --> AbstractListener.
092        private static final ILogger LOG = LoggerFactory.getLogger( SingleLayerSearchListener.class );
093    
094        @Override
095        public void actionPerformed( FormEvent event ) {
096    
097            HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true );
098            config = (CSWClientConfiguration) session.getAttribute( Constants.CSW_CLIENT_CONFIGURATION );
099    
100            if ( config == null ) {
101                try {
102                    config = initConfiguration( session );
103                } catch ( Exception e ) {
104                    gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_ERROR_INIT_CSWCLIENT", e.getMessage() ) );
105                    LOG.logError( e.getMessage(), e );
106                    return;
107                }
108            }
109    
110            nsContext = CommonNamespaces.getNamespaceContext();
111            RPCWebEvent rpcEvent = (RPCWebEvent) event;
112    
113            // get transformation file name
114            String fileName = "metaContent2html.xsl"; // default value
115            // FIXME replace format with current value
116            String format = "Profiles.ISO19115";
117            HashMap xslMap = config.getProfileXSL( format );
118            if ( xslMap != null ) {
119                if ( xslMap.get( "full" ) != null ) {
120                    fileName = (String) xslMap.get( "full" );
121                }
122            }
123            String pathToXslFile = "file:" + getHomePath() + "WEB-INF/conf/igeoportal/" + fileName;
124    
125            try {
126                validateRequest( rpcEvent );
127            } catch ( Exception e ) {
128                gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_INVALID_REQ", e.getMessage() ) );
129                LOG.logError( e.getMessage(), e );
130                return;
131            }
132    
133            String rpcCatalog;
134            RPCStruct rpcStruct;
135            String metadataURL;
136    
137            try {
138                rpcStruct = extractRPCStruct( rpcEvent, 0 );
139                rpcCatalog = (String) extractRPCMember( rpcStruct, RPC_CATALOG );
140                metadataURL = (String) extractRPCMember( rpcStruct, "METADATA_URL" );
141            } catch ( Exception e ) {
142                gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_INVALID_RPC_EVENT", e.getMessage() ) );
143                LOG.logError( e.getMessage(), e );
144                return;
145            }
146    
147            // "GetRecordById"-request
148            HashMap<String, Document> result = new HashMap<String, Document>( 1 );
149            try {
150                // URL url = new URL( metadataURL );
151                // Document doc = XMLTools.parse( url.openStream() );
152                GetRecordByIdResultDocument doc = new GetRecordByIdResultDocument();
153                doc.load( new URL( metadataURL ) );
154                result.put( rpcCatalog, doc.getRootElement().getOwnerDocument() );
155            } catch ( Exception e ) {
156                gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_SERVER_ERROR", e.getMessage() ) );
157                LOG.logError( e.getMessage(), e );
158                return;
159            }
160    
161            // handle result: take result and transform it to produce html output
162            try {
163                handleResult( result, pathToXslFile, "overview" );
164            } catch ( Exception e ) {
165                gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_ERROR_HANDLE_RESULT", e.getMessage() ) );
166                LOG.logError( e.getMessage(), e );
167                return;
168            }
169    
170        }
171    
172        /**
173         * @param session
174         * @return CSWClientConfiguration
175         * @throws CatalogClientException
176         */
177        private CSWClientConfiguration initConfiguration( HttpSession session )
178                                throws CatalogClientException {
179    
180            InitCSWModuleListener iml = new InitCSWModuleListener();
181            ViewContext vc = (ViewContext) session.getAttribute( org.deegree.portal.Constants.CURRENTMAPCONTEXT );
182            GeneralExtension gen = vc.getGeneral().getExtension();
183            Module module = null;
184    
185            try {
186                module = iml.findCswClientModule( gen );
187            } catch ( Exception e ) {
188                gotoErrorPage( Messages.getMessage( "IGEO_STD_CSW_CLIENT_ERROR", e.getMessage() ) );
189                LOG.logError( e.getMessage(), e );
190            }
191            CSWClientConfiguration config = new CSWClientConfiguration();
192    
193            ParameterList parList = module.getParameter();
194            iml.initConfig( config, parList );
195    
196            String srs = "EPSG:4236";
197            srs = vc.getGeneral().getBoundingBox()[0].getCoordinateSystem().getIdentifier();
198            config.setSrs( srs );
199    
200            session.setAttribute( Constants.CSW_CLIENT_CONFIGURATION, config );
201    
202            return config;
203        }
204    
205        @Override
206        protected void validateRequest( RPCWebEvent rpcEvent )
207                                throws CatalogClientException {
208    
209            RPCParameter[] params = extractRPCParameters( rpcEvent );
210            if ( params.length != 1 ) {
211                throw new CatalogClientException( Messages.getMessage( "IGEO_STD_CSW_WRONG_PARAMS_NUMBER", "1",
212                                                                       params.length ) );
213            }
214    
215            RPCStruct struct = extractRPCStruct( rpcEvent, 0 );
216    
217            extractRPCMember( struct, "METADATA_URL" );
218            extractRPCMember( struct, "METADATA_TITLE" );
219    
220            // validity check for catalog
221            String rpcCatalog = (String) extractRPCMember( struct, RPC_CATALOG );
222            String[] catalogs = config.getCatalogNames();
223            boolean containsCatalog = false;
224            for ( int i = 0; i < catalogs.length; i++ ) {
225                if ( catalogs[i].equals( rpcCatalog ) ) {
226                    containsCatalog = true;
227                    break;
228                }
229            }
230            if ( !containsCatalog ) {
231                throw new CatalogClientException( Messages.getMessage( "IGEO_STD_CSW_WRONG_CAT", rpcCatalog ) );
232            }
233    
234        }
235    
236        // super.createRequest();
237    
238        // super.performeRequest();
239    
240        /**
241         * @param result
242         * @param pathToXslFile
243         *            e.g. file://$iGeoPortal_home$/WEB-INF/conf/igeoportal/metaOverview2html.xsl
244         * @param metaVersion
245         *            e.g. overview, detailed
246         * @throws XMLParsingException
247         * @throws CatalogClientException
248         * @throws TransformerException
249         * @throws IOException
250         */
251        @Override
252        protected void handleResult( Object result, String pathToXslFile, String metaVersion )
253                                throws XMLParsingException, CatalogClientException, TransformerException, IOException {
254    
255            HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true );
256    
257            // result is a very short hashmap with only one entry!
258            Map map = (HashMap) result;
259            // key = data catalog name; value = csw:GetRecordByIdResponse
260            Iterator it = map.keySet().iterator();
261    
262            String catalog = null;
263            Document doc = null;
264            String docString = null;
265    
266            URL u = null;
267            StringBuffer htmlFragment = new StringBuffer( 5000 );
268            MetadataTransformer mt = null;
269            try {
270                u = new URL( pathToXslFile );
271                mt = new MetadataTransformer( u.getFile() );
272            } catch ( MalformedURLException e ) {
273                LOG.logError( e.getMessage(), e );
274            } catch ( FileNotFoundException e ) {
275                LOG.logError( e.getMessage(), e );
276            }
277    
278            while ( it.hasNext() ) {
279                catalog = (String) it.next();
280                doc = (Document) map.get( catalog );
281                docString = DOMPrinter.nodeToString( doc, CharsetUtils.getSystemCharset() );
282                Reader reader = new StringReader( docString );
283    
284                List nl = extractMetadata( doc );
285                if ( nl.size() > 1 ) {
286                    throw new CatalogClientException( Messages.getMessage( "IGEO_STD_CSW_ERROR_TOO_MANY_NODES" ) );
287                }
288    
289                String xPathToTitle = config.getXPathToDataTitle();
290                String title = extractValue( (Node) nl.get( 0 ), xPathToTitle );
291                String[] serviceCatalogs = null;
292                Map catalogsMap = (HashMap) session.getAttribute( SESSION_AVAILABLESERVICECATALOGS );
293                if ( catalogsMap != null ) {
294                    serviceCatalogs = extractServiceCatalogs( catalogsMap, title );
295                }
296    
297                // transformation
298                htmlFragment.append( mt.transformMetadata( reader, catalog, serviceCatalogs, 0, 0, metaVersion ) );
299            }
300    
301            this.getRequest().setAttribute( HTML_FRAGMENT, htmlFragment.toString() );
302            session.setAttribute( SESSION_METADATA, result );
303    
304            return;
305        }
306    
307    }