001    //$HeadURL: svn+ssh://jwilden@svn.wald.intevation.org/deegree/base/branches/2.5_testing/src/org/deegree/portal/standard/wms/control/HighlightingListener.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.portal.standard.wms.control;
037    
038    import java.io.FileOutputStream;
039    import java.io.IOException;
040    import java.io.OutputStreamWriter;
041    import java.net.URL;
042    import java.util.Map;
043    
044    import javax.servlet.http.HttpServletRequest;
045    import javax.servlet.http.HttpSession;
046    
047    import org.deegree.enterprise.control.FormEvent;
048    import org.deegree.enterprise.control.RPCMember;
049    import org.deegree.enterprise.control.RPCMethodCall;
050    import org.deegree.enterprise.control.RPCParameter;
051    import org.deegree.enterprise.control.RPCStruct;
052    import org.deegree.enterprise.control.RPCWebEvent;
053    import org.deegree.framework.log.ILogger;
054    import org.deegree.framework.log.LoggerFactory;
055    import org.deegree.framework.util.KVP2Map;
056    import org.deegree.framework.util.StringTools;
057    import org.deegree.model.spatialschema.Envelope;
058    import org.deegree.model.spatialschema.GeometryFactory;
059    import org.deegree.model.spatialschema.Position;
060    import org.deegree.ogcwebservices.OGCWebServiceException;
061    import org.deegree.ogcwebservices.OWSUtils;
062    import org.deegree.ogcwebservices.wfs.capabilities.WFSCapabilities;
063    import org.deegree.ogcwebservices.wfs.operation.GetFeature;
064    import org.deegree.ogcwebservices.wms.operation.GetMap;
065    import org.deegree.portal.context.GeneralExtension;
066    import org.deegree.portal.context.IOSettings;
067    import org.deegree.portal.context.LayerExtension;
068    import org.deegree.portal.context.ViewContext;
069    
070    /**
071     * This class is for highlighting polygons via a RPC request event from the client. A new WMS request will be created
072     * with SLD. The SLD xml file will be created and saved. The WMS request for highlighting will be set.
073     * 
074     * <p>
075     * ------------------------------------------------------------------------
076     * </p>
077     * 
078     * @author <a href="mailto:k.lupp@web.de>Katharina Lupp</a>
079     * @author last edited by: $Author: mays$
080     * 
081     * @version $Revision: 24806 $, $Date: 27.05.2008 17:13:56$
082     */
083    public class HighlightingListener extends AbstractMapListener {
084    
085        private static final ILogger LOG = LoggerFactory.getLogger( HighlightingListener.class );
086    
087        // private String sldUserStyle = "highlightingSLDUserStyle.xml";
088        private String sldUserStyle = System.currentTimeMillis() + ".xml";
089    
090        /**
091         * This method will be called by the <tt>MapListener</tt> if a highlighting action/event occurs.
092         */
093        @Override
094        public void actionPerformed( FormEvent event ) {
095    
096            // default actions
097            super.actionPerformed( event );
098            RPCWebEvent rpc = (RPCWebEvent) event;
099            RPCMethodCall mc = rpc.getRPCMethodCall();
100            RPCParameter[] para = mc.getParameters();
101            RPCStruct struct = (RPCStruct) para[0].getValue();
102    
103            HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true );
104            ViewContext vc = (ViewContext) session.getAttribute( "DefaultMapContext" );
105    
106            try {
107                GetMap wmsRequest = createRequest( para, vc );
108                Position[] coords = getCoordinates( struct );
109                String queryLayer = getQueryLayer( struct );
110                Envelope env = wmsRequest.getBoundingBox();
111                StringBuffer sld = createSLD( coords, env, queryLayer, vc );
112                saveSLD( sld, vc );
113                highlight( queryLayer, wmsRequest, vc );
114            } catch ( Exception ex ) {
115                LOG.logError( "Highlighting was not successful: ", ex );
116            }
117    
118        }
119    
120        /**
121         * creates the modified WMS Request including the URL for the SLD.
122         */
123        private GetMap createRequest( RPCParameter[] para, ViewContext vc ) {
124    
125            GeneralExtension ge = vc.getGeneral().getExtension();
126            IOSettings ios = ge.getIOSettings();
127            URL onlineResource = ios.getSLDDirectory().getOnlineResource();
128    
129            RPCStruct struct = (RPCStruct) para[1].getValue();
130            RPCMember[] member = struct.getMembers();
131            String request = (String) member[0].getValue();
132            Map<String, String> getMR = KVP2Map.toMap( request );
133            getMR.put( "ID", "id" );
134            getMR.put( "FORMAT", "image/gif" );
135            getMR.put( "TRANSPARENT", "true" );
136            getMR.put( "SLD", onlineResource.toExternalForm() + "/" + sldUserStyle );
137            GetMap modifiedRequest = null;
138            try {
139                modifiedRequest = GetMap.create( getMR );
140            } catch ( Exception e ) {
141                e.printStackTrace();
142            }
143            return modifiedRequest;
144        }
145    
146        /**
147         * calculates the coordinates of the click event.
148         */
149        private Position[] getCoordinates( RPCStruct struct ) {
150    
151            String x = (String) struct.getMember( "X" ).getValue();
152            String y = (String) struct.getMember( "Y" ).getValue();
153            String[] tmpX = StringTools.toArray( x, ",", false );
154            String[] tmpY = StringTools.toArray( y, ",", false );
155    
156            Position[] pos = new Position[tmpX.length];
157            for ( int i = 0; i < tmpX.length; i++ ) {
158                double xtmp = Double.parseDouble( tmpX[i] );
159                double ytmp = Double.parseDouble( tmpY[i] );
160                pos[i] = GeometryFactory.createPosition( xtmp, ytmp );
161            }
162    
163            return pos;
164        }
165    
166        /**
167         * gets the layer to be highlighted.
168         */
169        private String getQueryLayer( RPCStruct struct ) {
170            RPCMember queryLayers = struct.getMember( "queryLayers" );
171            String queryLay = (String) queryLayers.getValue();
172            int index = queryLay.indexOf( "|" );
173            queryLay = queryLay.substring( 0, index );
174    
175            return queryLay;
176        }
177    
178        /**
179         * sets the request for highlighting.
180         */
181        private void highlight( String queryLayer, GetMap gmr, ViewContext vc )
182                                throws OGCWebServiceException {
183    
184            URL wmsURL = vc.getLayerList().getLayer( queryLayer, null ).getServer().getOnlineResource();
185    
186            String s = OWSUtils.validateHTTPGetBaseURL( wmsURL.toExternalForm() );
187            this.getRequest().setAttribute( "HighlightingRequest", s + gmr.getRequestParameter() );
188    
189        }
190    
191        /**
192         * creates the SLD xml file.
193         */
194        private StringBuffer createSLD( Position[] coords, Envelope env, String queryLay, ViewContext vc ) {
195            GeneralExtension ge = vc.getGeneral().getExtension();
196            IOSettings ios = ge.getIOSettings();
197            URL onlineResource = ios.getSLDDirectory().getOnlineResource();
198            LayerExtension le = vc.getLayerList().getLayer( queryLay, null ).getExtension();
199    
200            WFSCapabilities capa = (WFSCapabilities) le.getDataService().getServer().getCapabilities();
201            URL wfsurl = OWSUtils.getHTTPGetOperationURL( capa, GetFeature.class );
202    
203            StringBuffer sb = new StringBuffer( 10000 );
204    
205            sb.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
206            sb.append( "<StyledLayerDescriptor version=\"1.0.0\" xmlns=\"http://www.opengis.net/sld\" " );
207            sb.append( "xmlns:gml=\"http://www.opengis.net/gml\" xmlns:wfs=\"http://www.opengis.net/wfs\" " );
208            sb.append( "xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" " );
209            sb.append( "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" );
210            sb.append( "<UserLayer><Name>MyLayer</Name><RemoteOWS>" );
211            sb.append( "<Service>WFS</Service>" );
212            sb.append( "<OnlineResource xmlns:xlink='http://www.w3.org/1999/xlink' xlink:type='simple' " );
213            sb.append( "xlink:href='" + wfsurl.toExternalForm() + "'/>" );
214            sb.append( "</RemoteOWS><LayerFeatureConstraints><FeatureTypeConstraint>" );
215            sb.append( "<FeatureTypeName>" + queryLay + "</FeatureTypeName>" );
216            sb.append( "<ogc:Filter><ogc:And>" );
217            if ( coords.length > 1 )
218                sb.append( "<ogc:Or>" );
219            for ( int k = 0; k < coords.length; k++ ) {
220                sb.append( "<ogc:Intersects><ogc:PropertyName>GEOM</ogc:PropertyName>" );
221                sb.append( "<gml:Point><gml:coordinates>" + coords[k].getX() + "," );
222                sb.append( coords[k].getY() + "</gml:coordinates></gml:Point>" );
223                sb.append( "</ogc:Intersects>" );
224            }
225            if ( coords.length > 1 )
226                sb.append( "</ogc:Or>" );
227            sb.append( "<ogc:BBOX><ogc:PropertyName>GEOM</ogc:PropertyName>" );
228            sb.append( "<gml:Box><gml:coord><gml:X>" + env.getMin().getX() );
229            sb.append( "</gml:X><gml:Y>" + env.getMin().getY() + "</gml:Y>" );
230            sb.append( "</gml:coord><gml:coord><gml:X>" + env.getMax().getX() );
231            sb.append( "</gml:X><gml:Y>" + env.getMax().getY() + "</gml:Y>" );
232            sb.append( "</gml:coord></gml:Box></ogc:BBOX></ogc:And>" );
233            sb.append( "</ogc:Filter></FeatureTypeConstraint></LayerFeatureConstraints> " );
234    
235            sb.append( "<UserStyle><FeatureTypeStyle><Rule><MinScaleDenominator>0" );
236            sb.append( "</MinScaleDenominator><MaxScaleDenominator>999999999" );
237            sb.append( "</MaxScaleDenominator><PolygonSymbolizer><Fill><GraphicFill>" );
238            sb.append( "<Graphic><ExternalGraphic><OnlineResource xmlns:xlink=" );
239            sb.append( "'http://www.w3.org/1999/xlink' xlink:type='simple' xlink:href='" );
240            sb.append( onlineResource.toExternalForm()  + "/pattern.gif' />" );
241            sb.append( "<Format>image/gif</Format></ExternalGraphic></Graphic></GraphicFill>" );
242            sb.append( "</Fill><Stroke><CssParameter name=\"stroke\">#FF0000</CssParameter>" );
243            sb.append( "<CssParameter name=\"stroke-opacity\">1.0</CssParameter>" );
244            sb.append( "<CssParameter name=\"stroke-width\">1.0</CssParameter>" );
245            sb.append( "<CssParameter name=\"stroke-dasharray\">1</CssParameter>" );
246            sb.append( "</Stroke></PolygonSymbolizer></Rule></FeatureTypeStyle>" );
247            sb.append( "</UserStyle></UserLayer></StyledLayerDescriptor>" );
248    
249            return sb;
250        }
251    
252        /**
253         * saves the created SLD file.
254         */
255        private void saveSLD( StringBuffer sld, ViewContext vc )
256                                throws IOException {
257            GeneralExtension ge = vc.getGeneral().getExtension();
258            IOSettings ios = ge.getIOSettings();
259            String dir = ios.getSLDDirectory().getDirectoryName();
260            OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream( dir + "/" + sldUserStyle ), "UTF-8" );
261            writer.write( sld.toString() );
262            writer.close();
263        }
264    
265    }