    001    //$HeadURL: https://svn.wald.intevation.org/svn/deegree/base/branches/2.4_testing/src/org/deegree/portal/standard/wms/control/LegendListener.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.awt.Color;
    039    import java.awt.Graphics;
    040    import java.awt.Rectangle;
    041    import java.awt.geom.Rectangle2D;
    042    import java.awt.image.BufferedImage;
    043    import java.io.FileOutputStream;
    044    import java.io.IOException;
    045    import java.net.MalformedURLException;
    046    import java.net.URL;
    047    import java.util.ArrayList;
    048    import java.util.HashMap;
    049    import java.util.Map;
    050    import java.util.StringTokenizer;
    051
    052    import javax.servlet.http.HttpServletRequest;
    053    import javax.servlet.http.HttpSession;
    054
    055    import org.deegree.enterprise.control.FormEvent;
    056    import org.deegree.enterprise.control.RPCMember;
    057    import org.deegree.enterprise.control.RPCMethodCall;
    058    import org.deegree.enterprise.control.RPCParameter;
    059    import org.deegree.enterprise.control.RPCStruct;
    060    import org.deegree.enterprise.control.RPCWebEvent;
    061    import org.deegree.framework.log.ILogger;
    062    import org.deegree.framework.log.LoggerFactory;
    063    import org.deegree.framework.util.IDGenerator;
    064    import org.deegree.framework.util.ImageUtils;
    065    import org.deegree.ogcwebservices.InconsistentRequestException;
    066    import org.deegree.ogcwebservices.wms.operation.GetLegendGraphic;
    067    import org.deegree.portal.context.GeneralExtension;
    068    import org.deegree.portal.context.IOSettings;
    069    import org.deegree.portal.context.ViewContext;
    070
    071    /**
    072     * will be called if the client forces a dynamic legend.
    073     *
    074     *
    075     * @author <a href="mailto:lupp@lat-lon.de">Katharina Lupp</a>
    076     * @version $Revision: 21678 $ $Date: 2009-12-29 14:44:02 +0100 (Di, 29. Dez 2009) $
    077     */
    078    public class LegendListener extends AbstractMapListener {
    079
    080        private static final ILogger LOG = LoggerFactory.getLogger( LegendListener.class );
    081
    082        /**
    083         * the method will be called if a zoomout action/event occurs.
    084         */
    085        public void actionPerformed( FormEvent event ) {
    086
    087            super.actionPerformed( event );
    088
    089            RPCWebEvent rpc = (RPCWebEvent) event;
    090            RPCMethodCall mc = rpc.getRPCMethodCall();
    091            RPCParameter[] para = mc.getParameters();
    092            RPCStruct struct = (RPCStruct) para[0].getValue();
    093            HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true );
    094            ViewContext vc = (ViewContext) session.getAttribute( "DefaultMapContext" );
    095
    096            Map<String, String>[] model = createWMSRequestModel( struct );
    097
    098            try {
    099                GetLegendGraphic legendParam = getLegendRequestParameter();
    100                Map<String, Object> symbols = setLegend( legendParam, model );
    101                Rectangle rect = calcLegendSize( symbols );
    102                BufferedImage bi = new BufferedImage( rect.width + 30, rect.height + 50, BufferedImage.TYPE_INT_RGB );
    103                bi = drawSymbolsToBI( symbols, bi );
    104                saveImage( vc, bi );
    105            } catch ( Exception e ) {
    106                LOG.logError( "Error occurred in PrintListener: ", e );
    107            }
    108
    109        }
    110
    111        private Rectangle calcLegendSize( Map<String, Object> map ) {
    112
    113            String[] layers = (String[]) map.get( "NAMES" );
    114            BufferedImage[] legs = (BufferedImage[]) map.get( "IMAGES" );
    115
    116            int w = 0;
    117            int h = 0;
    118            for ( int i = 0; i < layers.length; i++ ) {
    119                h += legs[i].getHeight() + 6;
    120                Graphics g = legs[i].getGraphics();
    121                Rectangle2D rect = g.getFontMetrics().getStringBounds( layers[i], g );
    122                g.dispose();
    123                if ( rect.getWidth() > w ) {
    124                    w = (int) rect.getWidth();
    125                }
    126            }
    127            w += 50;
    128
    129            return new Rectangle( w, h );
    130        }
    131
    132        private BufferedImage drawSymbolsToBI( Map<String, Object> map, BufferedImage bi ) {
    133
    134            Graphics g = bi.getGraphics();
    135            g.setColor( Color.WHITE );
    136            g.fillRect( 1, 1, bi.getWidth() - 2, bi.getHeight() - 2 );
    137
    138            String[] layers = (String[]) map.get( "NAMES" );
    139            BufferedImage[] legs = (BufferedImage[]) map.get( "IMAGES" );
    140            int h = 5;
    141            for ( int i = layers.length - 1; i >= 0; i-- ) {
    142                g.drawImage( legs[i], 20, h, null );
    143                g.setColor( Color.BLACK );
    144                if ( legs[i].getHeight() < 50 ) {
    145                    g.drawString( layers[i], 30 + legs[i].getWidth(), h + (int) ( legs[i].getHeight() / 1.2 ) );
    146                }
    147                h += legs[i].getHeight() + 5;
    148            }
    149            g.dispose();
    150            return bi;
    151        }
    152
    153        @SuppressWarnings("unchecked")
    154        private Map<String, String>[] createWMSRequestModel( RPCStruct struct ) {
    155
    156            RPCMember[] member = struct.getMembers();
    157
    158            Map<String, String>[] getMR = new HashMap[member.length];
    159            for ( int i = 0; i < member.length; i++ ) {
    160                String request = (String) member[i].getValue();
    161                getMR[i] = toMap( request );
    162                StringTokenizer st = new StringTokenizer( request, "?" );
    163                getMR[i].put( "URL", st.nextToken() );
    164            }
    165            return getMR;
    166        }
    167
    168        private void saveImage( ViewContext vc, BufferedImage bg ) {
    169
    170            GeneralExtension ge = vc.getGeneral().getExtension();
    171            IOSettings ios = ge.getIOSettings();
    172            String dir = ios.getPrintDirectory().getDirectoryName();
    173            String format = "jpeg";
    174            long l = IDGenerator.getInstance().generateUniqueID();
    175            String file = "legend" + l + '.' + format;
    176            try {
    177                FileOutputStream fos = new FileOutputStream( dir + "/" + file );
    178
    179                ImageUtils.saveImage( bg, fos, format, 1 );
    180
    181                fos.close();
    182            } catch ( Exception e ) {
    183                LOG.logError( "Error occurred in saving legend image: ", e );
    184            }
    185            int pos = dir.lastIndexOf( '/' );
    186            String access = "./" + dir.substring( pos + 1, dir.length() ) + "/" + file;
    187            this.getRequest().setAttribute( "DYNLEGENDIMAGE", access );
    188
    189        }
    190
    191        private GetLegendGraphic getLegendRequestParameter()
    192                                throws InconsistentRequestException {
    193
    194            HashMap<String, String> legend = toMap( "VERSION=1.1.1&REQUEST=GetLegendGraphic&FORMAT=image/jpeg&WIDTH=50&HEIGHT=50&"
    195                                                    + "EXCEPTIONS=application/vnd.ogc.se_inimage&LAYER=europe:major_rivers&STYLE=default&"
    196                                                    + "SLD=file:///styles.xml" );
    197            legend.put( "ID", "1" );
    198            return GetLegendGraphic.create( legend );
    199
    200        }
    201
    202        /**
    203         * creates legend
    204         */
    205        private Map<String, Object> setLegend( GetLegendGraphic glr, Map<String, String>[] model )
    206                                throws MalformedURLException, IOException {
    207
    208            ArrayList<String> list1 = new ArrayList<String>();
    209            ArrayList<BufferedImage> list2 = new ArrayList<BufferedImage>();
    210
    211            StringTokenizer st = null;
    212            String format = glr.getFormat();
    213            if ( format.equals( "image/jpg" ) )
    214                format = "image/jpeg";
    215            String legendURL = "";
    216            int lgHeight = 0;
    217            for ( int i = 0; i < model.length; i++ ) {
    218
    219                String style = (String) model[i].get( "STYLE" );
    220                if ( style != null ) {
    221                    st = new StringTokenizer( style, "," );
    222                    style = st.nextToken();
    223                } else
    224                    style = "default";
    225                st = new StringTokenizer( (String) model[i].get( "LAYERS" ), "," );
    226
    227                while ( st.hasMoreTokens() ) {
    228                    String layer = st.nextToken();
    229                    legendURL = setLegendURL( layer, style, format, glr, model[0] );
    230                    lgHeight = lgHeight + 30;
    231                    BufferedImage legendGraphic = ImageUtils.loadImage( new URL( legendURL ) );
    232                    list1.add( layer );
    233                    list2.add( legendGraphic );
    234                }
    235            }
    236
    237            String[] layers = list1.toArray( new String[list1.size()] );
    238            BufferedImage[] legs = list2.toArray( new BufferedImage[list2.size()] );
    239            Map<String, Object> map = new HashMap<String, Object>();
    240            map.put( "NAMES", layers );
    241            map.put( "IMAGES", legs );
    242            return map;
    243        }
    244
    245        private String setLegendURL( String layer, String style, String format, GetLegendGraphic glr,
    246                                     Map<String, String> model ) {
    247
    248            StringBuffer sb = new StringBuffer( 500 );
    249            sb.append( model.get( "URL" ) ).append( '?' );
    250            sb.append( "&VERSION=" ).append( glr.getVersion() );
    251            sb.append( "&REQUEST=GetLegendGraphic" );
    252            sb.append( "&FORMAT=" ).append( format );
    253            sb.append( "&WIDTH=15" );
    254            sb.append( "&HEIGHT=15&EXCEPTIONS=application/vnd.ogc.se_inimage" );
    255            sb.append( "&LAYER=" ).append( layer );
    256            sb.append( "&STYLE=" ).append( style );
    257
    258            return sb.toString();
    259        }
    260
    261    }