[mapguide-commits] r4662 - in sandbox/rfc71: localized mapviewerjava mapviewernet mapviewerphp viewerfiles

svn_mapguide at osgeo.org svn_mapguide at osgeo.org
Mon Mar 15 06:45:35 EDT 2010


Author: jng
Date: 2010-03-15 06:45:34 -0400 (Mon, 15 Mar 2010)
New Revision: 4662

Added:
   sandbox/rfc71/mapviewerjava/getselectedfeatures.jsp
Modified:
   sandbox/rfc71/localized/en
   sandbox/rfc71/mapviewerjava/mapframe.jsp
   sandbox/rfc71/mapviewernet/getselectedfeatures.aspx
   sandbox/rfc71/mapviewerphp/getselectedfeatures.php
   sandbox/rfc71/viewerfiles/ajaxmappane.templ
Log:
#1053: This adds the java implementation. In the painful process of writing and debugging the java implementation, it was found useful to JSON serialize any caught exceptions, to be alert()'d on the client side. Thus all 3 implementations now serialize any caught exceptions and writes them to the response stream. On the client side, we now check for an "Error" property in the eval()'d result. If this property exists, a server-side error occurred and is alert()'d to the user.

Modified: sandbox/rfc71/localized/en
===================================================================
--- sandbox/rfc71/localized/en	2010-03-11 16:03:39 UTC (rev 4661)
+++ sandbox/rfc71/localized/en	2010-03-15 10:45:34 UTC (rev 4662)
@@ -251,3 +251,7 @@
 # Property Pane Toolbar
 ZOOMSELECTEDFEATUREDESC = Zoom to this feature
 NOFEATSELECTRESPONSE    = No response from feature selection request
+
+# Multiple Property Processing
+SERVERERROR             = Server Error
+ERRORSTACKTRACE         = Stack Trace

Added: sandbox/rfc71/mapviewerjava/getselectedfeatures.jsp
===================================================================
--- sandbox/rfc71/mapviewerjava/getselectedfeatures.jsp	                        (rev 0)
+++ sandbox/rfc71/mapviewerjava/getselectedfeatures.jsp	2010-03-15 10:45:34 UTC (rev 4662)
@@ -0,0 +1,436 @@
+<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
+<%@ page import="org.osgeo.mapguide.*" %>
+<%@ page import="java.util.*" %>
+<%@ page import="java.lang.*" %>
+<%@ page import="java.io.*" %>
+<%@ page import="java.text.*" %>
+<%@ page import="javax.xml.parsers.DocumentBuilder" %>
+<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
+<%@ page import="org.w3c.dom.Document" %>
+<%@ page import="org.w3c.dom.Element" %>
+<%@ page import="org.w3c.dom.Node" %>
+<%@ page import="org.w3c.dom.NodeList" %>
+<%@ page import="javax.servlet.jsp.*" %>
+<%@ page import="javax.servlet.http.*" %>
+<%@ include file="common.jsp" %>
+<%@ page isThreadSafe="false" %>
+<%!
+
+    String mapName;
+    String sessionId;
+    String locale;
+
+    class SelectionSet
+    {
+        private HashMap<String, Vector<Feature>> _layers;
+
+        public SelectionSet()
+        {
+            _layers = new HashMap<String, Vector<Feature>>();
+        }
+
+        public void addFeature(Feature feat)
+        {
+            if (!_layers.containsKey(feat.LayerName))
+                _layers.put(feat.LayerName, new Vector<Feature>());
+
+            _layers.get(feat.LayerName).add(feat);
+        }
+
+        public String[] getLayers()
+        {
+            String[] layers = new String[_layers.keySet().size()];
+            _layers.keySet().toArray(layers);
+            
+            return layers;
+        }
+
+        public Feature[] getFeatures(String layerName)
+        {
+            if (_layers.containsKey(layerName))
+            {
+                Vector<Feature> layerFeatures = _layers.get(layerName);
+                Feature[] feats = new Feature[layerFeatures.size()];
+                layerFeatures.toArray(feats);
+                return feats;
+            }
+
+            return null;
+        }
+    }
+
+    class ZoomPoint
+    {
+        public double X;
+        public double Y;
+    }
+
+    class FeatureProperty
+    {
+        public String Name;
+        public String Value;
+    }
+
+    class Feature
+    {
+        public String LayerName;
+        public ZoomPoint Zoom;
+
+        private HashMap<String, FeatureProperty> _properties;
+
+        public Feature(String layerName)
+        {
+            this.LayerName = layerName;
+            _properties = new HashMap<String, FeatureProperty>();
+        }
+
+        public void addProperty(FeatureProperty prop)
+        {
+            _properties.put(prop.Name, prop);
+        }
+
+        public FeatureProperty[] getProperties()
+        {
+            Collection<FeatureProperty> values = _properties.values();
+            FeatureProperty[] props = new FeatureProperty[values.size()];
+            values.toArray(props);
+            return props;
+        }
+    }
+    
+    static String getTextValue(Element el, String tagName)
+    {
+        String textVal = null;
+        NodeList nl = el.getElementsByTagName(tagName);
+        if (nl != null && nl.getLength() > 0)
+        {
+            Element e = (Element)nl.item(0);
+            textVal = e.getFirstChild().getNodeValue();
+        }
+        return textVal;
+    }
+    
+    static HashMap<String, String> GetLayerPropertyMappings(MgResourceService resSvc, MgLayerBase layer) throws Exception
+    {
+        HashMap<String, String> mappings = new HashMap<String, String>();
+        
+        MgByteReader content = resSvc.GetResourceContent(layer.GetLayerDefinition());
+        ByteArrayInputStream contentReader = new ByteArrayInputStream(content.ToString().getBytes("UTF-8"));
+        
+        System.out.println("[DEBUG]: Got layer content");
+        
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        DocumentBuilder db = dbf.newDocumentBuilder();
+        Document doc = db.parse(contentReader);
+        
+        System.out.println("[DEBUG]: Loaded layer content into Document");
+        
+        doc.getDocumentElement().normalize();
+        NodeList propNodes = doc.getElementsByTagName("PropertyMapping");
+        
+        System.out.println("[DEBUG]: Get matching element list. Size: " + propNodes.getLength());
+        
+        for (int i = 0; i < propNodes.getLength(); i++)
+        {
+            Element propEl = (Element)propNodes.item(i);
+            String name = getTextValue(propEl, "Name");
+            String value = getTextValue(propEl, "Value");
+            
+            System.out.println("[DEBUG]: Name - " + name + "; Value - " + value);
+            if (name != null && value != null)
+                mappings.put(name, value);
+        }
+        
+        return mappings;
+    }
+    
+    String GetPropertyValueFromFeatureReader(MgFeatureReader reader, MgAgfReaderWriter agfRw, int propType, String propName) throws Exception
+    {
+        String value = "";
+        switch(propType)
+        {
+            case MgPropertyType.Boolean:
+                value = reader.GetBoolean(propName) + "";
+                break;
+            case MgPropertyType.Byte:
+                value = reader.GetByte(propName) + "";
+                break; 
+            case MgPropertyType.DateTime:
+                value = GetDateTimeString(reader.GetDateTime(propName));
+                break;
+            case MgPropertyType.Single:
+                value = reader.GetSingle(propName) + "";
+                break;
+            case MgPropertyType.Double:
+                value = reader.GetDouble(propName) + "";
+                break;
+            case MgPropertyType.Int16:
+                value = reader.GetInt16(propName) + "";
+                break;
+            case MgPropertyType.Int32:
+                value = reader.GetInt32(propName) + "";
+                break;
+            case MgPropertyType.Int64:
+                value = reader.GetInt64(propName) + "";
+                break;
+            case MgPropertyType.String:
+                value = EscapeForHtml(reader.GetString(propName));
+                break;
+            default: //NOT PRESENTABLE IN PROPERTY GRID
+                value = "";
+                break;
+        }
+        return value;   
+    }
+
+    static String GetDateTimeString(MgDateTime value) throws MgException
+    {
+        //TODO: Use current culture to determine date format?
+        return value.GetYear() + "-" + value.GetMonth() + "-" + value.GetDay();
+    }
+    
+    void GetParameters(HttpServletRequest request)
+    {
+        mapName = GetParameter(request, "MAPNAME");
+        sessionId = GetParameter(request, "SESSION");
+        locale = GetParameter(request, "LOCALE");
+        if (locale == null || locale.length() == 0)
+            locale = GetDefaultLocale();
+    }
+    
+    static String JsonifyError(Exception ex, String locale)
+    {
+        if (ex == null)
+            return "";
+        /*
+        {
+            "Error" : {
+                "Message" : <exception-message>,
+                "StackTrace" : <exception-stack-trace>
+            }
+        }
+        */
+        
+        StringBuffer sb = new StringBuffer();
+        //Use exception message or type name if no message found
+        String msg = ex.getMessage();
+        if (msg == null || msg.length() == 0)
+        {
+            msg = MgLocalizer.GetString("SERVERERROR", locale);
+        }
+        //Begin response
+        sb.append("{\"Error\":{");
+        //Exception message
+        sb.append("\"Message\":\"" + msg + "\",");
+        StringBuffer strace = new StringBuffer();
+        StackTraceElement[] st = ex.getStackTrace();
+        for (int i = 0; i < st.length; i++)
+        {
+            strace.append(st[i].getClassName() + "." + st[i].getMethodName() + "(" + st[i].getLineNumber() + ")\\n");
+        }
+        sb.append("\"StackTrace\":\"" + strace.toString() + "\"");
+        //End response
+        sb.append("}}");
+        return sb.toString();
+    }
+    
+    static String GetJson(SelectionSet set)
+    {
+        /*
+        A sample of the JSON output this method will produce:
+        
+        
+        {
+            "Layer1" : [ 
+                { 
+                    'values' { "name" : "name1" , "value" : "value1" }, 
+                    'zoom' : { x: num1, y: num2 } 
+                } , 
+                ..,
+                ..,
+                ..,
+            ],
+            "Layer2" : [ 
+                { 
+                    'values' { "name" : "name2" , "value" : "value2" }, 
+                    'zoom' : { x: num1, y: num2 } 
+                } , 
+                ..,
+                ..,
+                ..,
+            ]
+        }
+        */
+        
+        if (set == null)
+            return "";
+        
+        StringBuffer sb = new StringBuffer();
+        //Begin selection set
+        sb.append("{");
+        String[] layers = set.getLayers();
+        for (int i = 0; i < layers.length; i++)
+        {
+            //Begin layer
+            sb.append("\"" + layers[i] + "\" : [");
+            Feature[] features = set.getFeatures(layers[i]);
+            for (int j = 0; j < features.length; j++)
+            {
+                Feature feat = features[j];
+                //begin feature
+                //begin feature properties
+                sb.append("{\"values\" : [");
+                FeatureProperty[] properties = feat.getProperties();
+                for(int k = 0; k < properties.length; k++)
+                {
+                    FeatureProperty fp = properties[k];
+                    sb.append("{\"name\" : \"" + fp.Name + "\", \"value\" : \"" + fp.Value + "\" }");
+                    if (k != properties.length - 1)
+                        sb.append(",");
+                }
+                //end feature properties
+                //begin zoom
+                sb.append("], \"zoom\" : ");
+                if (feat.Zoom == null)
+                    sb.append("null");
+                else
+                    sb.append("{\"x\" : " + feat.Zoom.X + ", \"y\" : " + feat.Zoom.Y + "}");
+                //end zoom
+                //end feature
+                sb.append("}");
+                if (j != features.length - 1)
+                    sb.append(",");
+            }
+            //End Layer
+            sb.append("]");
+            if (i != layers.length - 1)
+                sb.append(",");
+        }
+        //End selection set
+        sb.append("}");
+        return sb.toString();
+    }
+%>
+<%
+    mapName = "";
+    sessionId = "";
+    locale = "en";
+
+    GetParameters(request);
+
+    try
+    {
+        MgUserInformation cred = new MgUserInformation(sessionId);
+        cred.SetClientIp(GetClientIp(request));
+        cred.SetClientAgent(GetClientAgent());
+
+        MgSiteConnection site = new MgSiteConnection();
+        site.Open(cred);
+
+        MgResourceService resSvc = (MgResourceService)site.CreateService(MgServiceType.ResourceService);
+        
+        MgMap map = new MgMap(site);
+        map.Open(mapName);
+
+        MgSelection selection = new MgSelection(map);
+        selection.Open(resSvc, mapName);
+
+        MgReadOnlyLayerCollection layers = selection.GetLayers();
+        if (layers != null && layers.GetCount() > 0)
+        {
+            int layerCount = layers.GetCount();
+            MgAgfReaderWriter agfRW = new MgAgfReaderWriter();
+            SelectionSet selectionSet = new SelectionSet();
+
+            for (int i = 0; i < layerCount; i++)
+            {
+                MgLayerBase layer = layers.GetItem(i);
+                String layerName = layer.GetName();
+
+                MgResourceIdentifier fsId = new MgResourceIdentifier(layer.GetFeatureSourceId());
+                String className = layer.GetFeatureClassName();
+                String geomName = layer.GetFeatureGeometryName();
+
+                MgFeatureQueryOptions query = new MgFeatureQueryOptions();
+                HashMap<String, String> mappings = GetLayerPropertyMappings(resSvc, layer);
+                Set<String> propNames = mappings.keySet();
+
+                for (String name : propNames)
+                {
+                    query.AddFeatureProperty(name);
+                }
+
+                query.AddFeatureProperty(geomName);
+                String filter = selection.GenerateFilter(layer, className);
+                query.SetFilter(filter);
+
+                MgFeatureReader reader = layer.SelectFeatures(query);
+
+                MgClassDefinition clsDef = reader.GetClassDefinition();
+                MgPropertyDefinitionCollection props = clsDef.GetProperties();
+
+                while (reader.ReadNext())
+                {
+                    Feature feat = new Feature(layerName);
+                    ZoomPoint zoom = null;
+
+                    for (int k = 0; k < props.GetCount(); k++)
+                    {
+                        MgPropertyDefinition propDef = props.GetItem(k);
+                        String propName = propDef.GetName();
+                        int propType = reader.GetPropertyType(propName);
+
+                        if (mappings.get(propName) != null || propType == MgPropertyType.Geometry)
+                        {
+                            String value = "";
+                            if (!reader.IsNull(propName))
+                            {
+                                if (propName.equals(geomName))
+                                {
+                                    MgByteReader agf = reader.GetGeometry(propName);
+                                    MgGeometry geom = agfRW.Read(agf);
+                                    MgCoordinate pt = geom.GetCentroid().GetCoordinate();
+
+                                    zoom = new ZoomPoint();
+                                    zoom.X = pt.GetX();
+                                    zoom.Y = pt.GetY();
+
+                                    feat.Zoom = zoom;
+                                }
+                                else
+                                {
+                                    value = GetPropertyValueFromFeatureReader(reader, agfRW, propType, propName);
+                                }
+
+                                if (mappings.get(propName) != null)
+                                {
+                                    FeatureProperty fp = new FeatureProperty();
+                                    fp.Name = propName;
+                                    fp.Value = value;
+
+                                    feat.addProperty(fp);
+                                }
+                            }
+                        }
+                    }
+                    selectionSet.addFeature(feat);
+                }
+                reader.Close();
+            }
+
+            //Now output the selection set
+            response.addHeader("Content-Type", "application/json");
+            response.addHeader("X-JSON", "true");
+
+            response.getWriter().write(GetJson(selectionSet));
+        }
+    }
+    catch (MgException ex)
+    {
+        response.getWriter().write(JsonifyError(ex, locale));
+    }
+    catch (Exception ex)
+    {
+        response.getWriter().write(JsonifyError(ex, locale));
+    }
+%>
\ No newline at end of file

Modified: sandbox/rfc71/mapviewerjava/mapframe.jsp
===================================================================
--- sandbox/rfc71/mapviewerjava/mapframe.jsp	2010-03-11 16:03:39 UTC (rev 4661)
+++ sandbox/rfc71/mapviewerjava/mapframe.jsp	2010-03-15 10:45:34 UTC (rev 4662)
@@ -176,6 +176,7 @@
                     vpath + "setselection.jsp",
                     showSlider != 0? "true": "false",
                     locale,
+                    vpath + "getselectedfeatures.jsp",
                     scaleCreationCode,
                     vpath + "ajaxviewerabout.jsp",
                     vpath + "legendctrl.jsp",

Modified: sandbox/rfc71/mapviewernet/getselectedfeatures.aspx
===================================================================
--- sandbox/rfc71/mapviewernet/getselectedfeatures.aspx	2010-03-11 16:03:39 UTC (rev 4661)
+++ sandbox/rfc71/mapviewernet/getselectedfeatures.aspx	2010-03-15 10:45:34 UTC (rev 4662)
@@ -155,6 +155,19 @@
         else
             GetParameters(Request.QueryString);
     }
+    
+    static String JsonifyError(Exception ex)
+    {
+        /*
+        {
+            "Error" : {
+                "Message" : <exception-message>,
+                "StackTrace" : <exception-stack-trace>
+            }
+        }
+        */
+        return String.Format("{\"Error\":{\"Message\":\"{0}\",\"StackTrace\":\"{1}\"}}", ex.Message, ex.StackTrace);
+    }
 
     static String GetJson(SelectionSet set)
     {
@@ -214,7 +227,7 @@
                 //begin zoom
                 sb.Append("], \"zoom\" : ");
                 if (feat.Zoom == null)
-                    sb.Append("null}");
+                    sb.Append("null");
                 else
                     sb.Append("{\"x\" : " + feat.Zoom.X + ", \"y\" : " + feat.Zoom.Y + "}");
                 //end zoom
@@ -349,7 +362,15 @@
     }
     catch (MgException ex)
     {
-        Response.Write(ex.GetDetails());
+        Response.AddHeader("Content-Type", "application/json");
+        Response.AddHeader("X-JSON", "true");
+        Response.Write(JsonifyError(ex));
     }
+    catch (Exception ex)
+    { 
+        Response.AddHeader("Content-Type", "application/json");
+        Response.AddHeader("X-JSON", "true");
+        Response.Write(JsonifyError(ex));
+    }
     
 %>
\ No newline at end of file

Modified: sandbox/rfc71/mapviewerphp/getselectedfeatures.php
===================================================================
--- sandbox/rfc71/mapviewerphp/getselectedfeatures.php	2010-03-11 16:03:39 UTC (rev 4661)
+++ sandbox/rfc71/mapviewerphp/getselectedfeatures.php	2010-03-15 10:45:34 UTC (rev 4662)
@@ -104,7 +104,7 @@
     $queryInfo = false;
 
     GetRequestParameters();
-	
+   
 	try
 	{
 		InitializeWebTier();
@@ -231,9 +231,17 @@
             echo GetJson($selectionSet);
         }
     }
+    catch(Exception $e)
+    {
+        header("Content-Type: application/json");
+        header("X-JSON: true");
+        echo JsonifyError($e->getMessage(), $e->getTraceAsString());
+    }
 	catch(MgException $e)
     {
-        echo $e->GetDetails();
+        header("Content-Type: application/json");
+        header("X-JSON: true");
+        echo JsonifyError($e->GetDetails(), $e->GetStackTrace());
     }
 
 function GetJson($selectionSet)
@@ -306,7 +314,7 @@
                     if($feat->zoom != null)
                         array_push($totalFeaturesOnLayer, "{\"values\" : [".join(",", $featureProperties)."], \"zoom\" : { \"x\": ".$feat->zoom->x.", \"y\": ".$feat->zoom->y." } }");
                     else
-                        array_push($totalFeaturesOnLayer, "{\"values\" : [".join(",", $featureProperties)."], \"zoom\" : null } }");
+                        array_push($totalFeaturesOnLayer, "{\"values\" : [".join(",", $featureProperties)."], \"zoom\" : null }");
                         
                     //FB::log("Feature processed on layer: $layerName");
                 }
@@ -429,6 +437,19 @@
 	//$selText = UnescapeMagicQuotes($params['selection']);
 }
 
+function JsonifyError($msg, $st)
+{
+    /*
+    {
+        "Error" : {
+            "Message" : <exception-message>,
+            "StackTrace" : <exception-stack-trace>
+        }
+    }
+    */
+    $json = "{\"Error\":{\"Message\":\"$msg\",\"StackTrace\":\"$st\"}}";
+    return $json;
+}
 
 function UnescapeMagicQuotes($str)
 {

Modified: sandbox/rfc71/viewerfiles/ajaxmappane.templ
===================================================================
--- sandbox/rfc71/viewerfiles/ajaxmappane.templ	2010-03-11 16:03:39 UTC (rev 4661)
+++ sandbox/rfc71/viewerfiles/ajaxmappane.templ	2010-03-15 10:45:34 UTC (rev 4662)
@@ -3839,7 +3839,11 @@
     if (respText && respText.length > 0)
     {
         var resp = eval('(' + respText + ')');
-        ProcessSelectedFeatureSet(resp);
+        //If an error occurred server-side, it is written as the error property of the JSON response
+        if (resp.Error)
+            RequestFailed(resp.Error.Message + "\n\n__#ERRORSTACKTRACE#__:\n\n" + resp.Error.StackTrace);
+        else
+            ProcessSelectedFeatureSet(resp);
     }
     else
         RequestFailed("__#NOFEATSELECTRESPONSE#__");



More information about the mapguide-commits mailing list