NanoUI the second bomb, how to graph serialization and anti-analytic

sponsored links
NanoUI second bomb: how to graph serialization and anti-analytic
All rights reserved poor desert autumn
2011-05-28 Sunday book connected to the back, in the first article, introduced NanoUI core functions of the detailed design and sample. Which left a very key question: Interface serialization primitive and anti-analytic. This according to the order from easy to difficult detailed analysis of their usage, principles, key points.

Directory
1. Beginning with the first instance of the 2
1.1. Sequence of 4
1.1.1. Sequence of the mouse to draw the components 4
1.1.2. Sequence of 13 custom components
1.2. Anti-resolution 16
2. Core Principles 17
2.1. Anti-resolution: AS3 Reflection 17
2.1.1. Core Principles 17
2.1.2. Note that point 18
2.2. Sequence: the graphics and XML 20
2.2.1. Core Principles 20
2.2.2. Note that point 21
3. Note 22 points and design improvements

1. Please note that the first component on the instance of the first sequence of the core processes:
Front interface: Component resolve XML string? Submitted to the background by SysDataMgr JSP;
Background: According to the front of the file name argument, writing XML files on the server side.
In the previous article, based on this new two JSP files:

NanoUI the second bomb, how to graph serialization and anti-analytic


getFileList.jsp used to read the current page file has already been saved;
savePage.jsp used to write the new file.
These two very simple JSP code, listed below:
getFileList.jsp:

<%@ page language="java" import="java.util.*,java.math.*,java.io.*" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.math.BigDecimal"/>
<%
    //  Get list of files  
    System.out.println("  Get list of files  ...");
    ArrayList fileNames=new ArrayList();
    String filePath=request.getRealPath("/");
    File file=new File(filePath+"\\modules");
    if(file.exists()&&file.isDirectory()){
        File[] files=file.listFiles();
        for(int i=0;i<files.length;i++){
            File subFile=files[i];
            String fileName=subFile.getName();
            if(fileName.indexOf(".xml")!=-1){
                fileNames.add(fileName);
            }
        }
    }
   
    StringBuffer result=new StringBuffer("");
    result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    result.append("<node label=\"  File List  \">");
    for(int i=0;i<fileNames.size();i++){
        String fileName=(String)fileNames.get(i);
        fileName=fileName.substring(0,fileName.indexOf(".xml"));
        result.append("<node label=\""+fileName+"\">");
        result.append("</node>");
    }
    result.append("</node>");
   
    System.out.println(result.toString());
    response.getWriter().println(result.toString());
%>


savePage.jsp:

<%@ page language="java" import="java.util.*,java.math.*,java.io.*" pageEncoding="utf-8"%>
<%
    request.setCharacterEncoding("utf-8");
    //  The request parameters for flash  
    String xml=request.getParameter("xmlData");
    if(xml!=null){
        xml=java.net.URLDecoder.decode(xml, "utf-8");
    }
    System.out.println("xml  Content  >"+xml);
   
    String fileName=request.getParameter("fileName");
    if(fileName!=null){
        fileName=java.net.URLDecoder.decode(fileName, "utf-8");
    }else{
        return;
    }
    System.out.println("  Save the file successfully, the file name  >"+fileName);
   
    String commonPath=request.getRealPath("/");
    String xmlFilePath=commonPath+"\\modules\\"+fileName+".xml";
   
    //  Write xml file  
    File file=new File(xmlFilePath);
    if(!file.exists()){
        file.createNewFile();
    }
    OutputStream os=new FileOutputStream(file);
    OutputStreamWriter ow=new OutputStreamWriter(os,"UTF-8");
    PrintWriter pr=new PrintWriter(ow);
    pr.println(xml);
    pr.close();
%>


Please note the default read and write files, the server will write XML documents in the application modules under the root directory:

NanoUI the second bomb, how to graph serialization and anti-analytic


This path can be changed, of course, find these two files in the corresponding part of the JSP, you need to read and write files into the path. Of course, the best way is to make the path to the configuration file, in order to simplify the code in the background, here is not configured to do this. After all, this concern is the front-end Flex application, rather than how to develop the server.
1.1. Serialization
1.1.1. Sequence of the mouse to draw the component will involve the following example of two mxml files, which are located in examples / common / directory SavaPage.mxml and OpenFile.mxml. Code for these files are not many, are as follows:
SavaPage.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
    title="  Save Page  " width="400" height="350" close="PopUpManager.removePopUp(this)" showCloseButton="true" borderAlpha="1">
    <mx:Script>
        <![CDATA[
            import com.nano.core.JComponent;
            import com.nano.core.SysConfMgr;
            import com.nano.core.SysDataMgr;
            import com.nano.plugins.LightMsg;
            import com.nano.serialization.xml.CompXmlParser;
            import com.nano.util.FuncUtil;
            import com.nano.widgets.JPen;
           
            import mx.controls.Alert;
            import mx.managers.PopUpManager;
           
            public var pen:JPen;
           
            /**
             *   Load a list of existing file  
             */
            private function getFileList():void{
                SysDataMgr.req({
                    url:SysConfMgr.getUrl('loadPageListURL'),
                    success:function(dataStr:String):void{
                        var objsXML:XML = new XML(dataStr);               
                        treeData = objsXML.node;
                    },
                    failure:function():void{
                        LightMsg.alert("  Warning "," can not save data  ,  Please check your network  ");
                    }
                });
            }
           
            private function expandTree():void {
                for each(var item:XML in fileTree.dataProvider){
                    fileTree.expandChildrenOf(item,true); 
                }
            }
           
            /**
             *   Analytical objects, generated  xml  String  
             *  First grouped by type object, the same type of object into a single collection  
             *   Then calls the corresponding class of static methods to resolve the object  xml  String  
             */
            private var lw:LoadingWin=null;
            private var xmlStr:String="";
            private  function encodeData():void{
                lw.setMsg("  Analysis of data began to view  ...");
                var xmlResult:XMLList=new XMLList();
                this.pen.objs.eachValue(function(item:*):void{
                    if(item is JComponent){
                        xmlResult+=CompXmlParser.xmlEncode(item as JComponent);
                        //lw.setMsg("  Resolving  >"+(item as JComponent).id);
                    }
                });
                xmlStr=xmlResult.toXMLString();
            }
           
            /**
             *   Submit button  :  Save Page  
             */
            private function saveFile(e:MouseEvent):void{
                if(fileName.text==""){
                    Alert.show("  Please enter or select a file name "," Tips  ");
                    return;
                }
                lw=LoadingWin.show({
                    msg:'  Start saving the data, please wait  ...'
                });

                //  Start saving  
                var me:SavePage=this;
                FuncUtil.delay(function():void{
                    encodeData();
                    var paramObj:*={};
                    paramObj.xmlData=xmlStr;
                    paramObj.fileName=fileName.text;
                    SysDataMgr.req({
                        url:SysConfMgr.getUrl('savePageURL'),
                        param:paramObj,
                        success:function(dataStr:String):void{
                            lw.stopLoading();
                            LightMsg.alert("  Message "," save the data successful  ");
                            dispatchEvent(new Event("save_success"));
                        },
                        failure:function():void{
                            lw.stopLoading();
                            LightMsg.alert("  Message "," save data error  ");
                            dispatchEvent(new Event("save_failure"));
                        }
                    });
                },500);
            }

            private function selectionChange():void{
                fileName.text=fileTree.selectedItem.@label;
            }
        ]]>
    </mx:Script>
   
    <mx:XMLList>
    </mx:XMLList>
   
    <mx:VBox width="100%" height="100%">
        <mx:Tree width="100%" height="200" labelField="@label"
                showRoot="true" dataProvider="{treeData}" valueCommit="expandTree()" creationComplete="getFileList()"
                change="selectionChange()"/>
        <mx:HBox width="100%" horizontalAlign="left" verticalAlign="middle">
            <mx:Label text="  Please enter the file name  :"></mx:Label>
            <mx:TextInput text="" click="{fileName.text='';}">
            </mx:TextInput>
        </mx:HBox>
        <mx:HBox width="100%" horizontalAlign="left" verticalAlign="middle">
            <mx:Label color="0xff0000" text="  Note :  The same file name will overwrite the existing file  ."></mx:Label>
        </mx:HBox>
        <mx:HBox width="100%" horizontalAlign="center" verticalAlign="middle">
            <mx:Button label="  OK  " click="saveFile(event)"/>
            <mx:Button label="  Cancel  " click="PopUpManager.removePopUp(this);"/>
        </mx:HBox>
    </mx:VBox>
</mx:TitleWindow>

OpenFile.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
    title="  Please select a file  " width="400" height="300"
    close="PopUpManager.removePopUp(this)"
    showCloseButton="true" borderAlpha="1">
    <mx:Script>
        <![CDATA[
            import com.nano.core.NanoSystem;
            import com.nano.core.SysConfMgr;
            import com.nano.core.SysDataMgr;
            import com.nano.core.SysEventMgr;
            import com.nano.plugins.LightMsg;
            import com.nano.serialization.xml.CompXmlParser;
            import com.nano.util.FuncUtil;
            import com.nano.widgets.JPen;
            import com.nano.widgets.link.JFluxLink;
           
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.managers.PopUpManager;
            import mx.rpc.events.ResultEvent;
           
            public var pen:JPen;
           
            private function getFileList():void{
                var lw:LoadingWin=LoadingWin.show({
                    msg:'  Loading, please wait  ...'
                });
                SysDataMgr.req({
                    url:SysConfMgr.getUrl('loadPageListURL'),
                    success:function(dataStr:String):void{
                        var objsXML:XML = new XML(dataStr);               
                        treeData = objsXML.node;
                        SysEventMgr.sendMsg(new Event("closeLoading"),lw);
                    },
                    failure:function():void{
                        LightMsg.alert("  Warning "," load data failed  ,  Please check your network  ");
                        SysEventMgr.sendMsg(new Event("closeLoading"),lw);
                    }
                });
            }
           
            private function resultModelHandler(e:ResultEvent):void{
                var objsXML:XML = new XML(e.result.toString());               
                treeData = objsXML.node;
            }
           
            private function expandTree():void {
                for each(var item:XML in fileTree.dataProvider){
                    fileTree.expandChildrenOf(item,true); 
                }
            }
           
            private var lw:LoadingWin=null;
            private function loadFile(e:MouseEvent):void{
                if(fileTree.selectedItem==null){
                    Alert.show("  Please select a model, "" Tips  ");
                    return;
                }
               
                lw=LoadingWin.show({
                    msg:'  Loading, please wait  ...'
                });
                var filePath:String="modules\\"+NanoSystem.httpEncoding(fileTree.selectedItem.@label)+".xml";
                SysDataMgr.req({
                    url:SysConfMgr.getUrl("loadFileUrl"),
                    param:{fileName:filePath},
                    success:xmlDecode,
                    failure:function():void{
                        LightMsg.alert("  Warning "," load data failed  ,  Please check your network  ");
                        SysEventMgr.sendMsg(new Event("closeLoading"),lw);
                    }
                });
                PopUpManager.removePopUp(this);
            }
           
            /**
             *   Page is loaded, xml parsing  
             */
            private  function xmlDecode(str:String):void{
                SysEventMgr.sendMsg(new Event("closeLoading"),lw);
                pen.clearAll();
                var xmlList:XMLList=new XMLList(str);
                var modules:ArrayCollection=CompXmlParser.xmlDecode(xmlList);
                this.pen.addToView(modules);
            }
        ]]>
    </mx:Script>
   
    <mx:XMLList>
    </mx:XMLList>
   
    <mx:VBox width="100%" height="100%">
        <mx:Tree width="100%" height="200" labelField="@label"
                showRoot="true" dataProvider="{treeData}" valueCommit="expandTree()" creationComplete="getFileList()"
                selectedIndex="0" />
        <mx:HBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
            <mx:Button label="  Open  " click="loadFile(event)"/>
            <mx:Button label="  Cancel  " click="PopUpManager.removePopUp(this);"/>
        </mx:HBox>
    </mx:VBox>
</mx:TitleWindow>


Obviously, the two most essential part of the document, a pixel is to resolve some of XML, one is to receive the XML string into a primitive part of the analysis.
Essence of these two documents that he did not work, but the sequence of process agents and anti-analytic tools CompXmlParser given to complete:

NanoUI the second bomb, how to graph serialization and anti-analytic


CompXmlParser tool provides two core functions xmlEncode () and xmlDecode () correspond to the two serialization and anti-analytic process. CompXmlParser slightly more complex implementation code in the second section will detail one of the core principles of analysis, where the first term with effect:

NanoUI the second bomb, how to graph serialization and anti-analytic


Drawn with the mouse at the interface of two graphics

NanoUI the second bomb, how to graph serialization and anti-analytic


Click "Save" button pop-up screen

NanoUI the second bomb, how to graph serialization and anti-analytic


Save data success

NanoUI the second bomb, how to graph serialization and anti-analytic


Create the XML file server

NanoUI the second bomb, how to graph serialization and anti-analytic


Look at the contents of XML file contents from the XML file is easy to understand the process here, save for when I'll get primitive properties are out, these properties Wanzhengmiaoshu Figure Yuan characteristics, therefore, is loaded in the back when Using the XML file will be able to restore from primitives.
Of course, the pixel sequence of the process into XML string is not so simple things, which will involve a certain degree of choice and packaging, and anti-analytic process is that, in the following section will detail the second resolution.

1.1.2. Serialization custom component called "custom components" refers to the use FlashCS4 made components, and then the way to SWC library into those components in the Flex application. Obviously, these components and use the mouse directly in the "drawing board" is essentially to draw different things. However, the sequence of the process and the front of the same, or use SavaPage.mxml components to save this public interface, no need to modify the code. See screenshot of operating conditions:

NanoUI the second bomb, how to graph serialization and anti-analytic


Drag to the interface of a host

NanoUI the second bomb, how to graph serialization and anti-analytic


Save to background

NanoUI the second bomb, how to graph serialization and anti-analytic


New file

NanoUI the second bomb, how to graph serialization and anti-analytic


Is still an XML document, of course, if you want, you can also use the mouse to draw the interface and custom components, save the process is much the same as:

NanoUI the second bomb, how to graph serialization and anti-analytic


Mixed mode

NanoUI the second bomb, how to graph serialization and anti-analytic


Save data success

NanoUI the second bomb, how to graph serialization and anti-analytic


Encore with cable

NanoUI the second bomb, how to graph serialization and anti-analytic


One more cable movement Note: The above "mobile connection line" and a simple arrow line is different, the mobile connection line is a connection more brilliant effect, the small tranches within it can "flow" together to produce a kinds of "data flow" effect. Also, this cable velocity, color, width can be based on the actual status of the data stream corresponding changes. Therefore, this component is very suitable for production of network topology. Follow-up article in the detailed analysis of this component will be the realization of the principle.
Summary: It can be seen from the above example, the code for the use of NanoUI, the sequence of the mouse to draw the components and sequence of the custom component code is exactly the same. Therefore, the application layer to the underlying code does not deal with the different perception.
1.2. Anti-resolution
OK, before we've saved a lot of interfaces to the server:

NanoUI the second bomb, how to graph serialization and anti-analytic


Now, they can try to "load" back on the page to recover the "screen", and run your own examples see the effect.
2. The core principle of pre-knowledge of this section: proficient use of AS3 manipulate XML data. (See the annex "flash Official Guide" Chapter XI.)
Through the example of the previous section, we can already easily picture to the two-way conversion between the XML string, then the core principles of this process is God horse? This section will be from easy to difficult analytical process.
This section is essentially analytical CompXmlParser and SysClassMgr the implementation of these two tools ideas, all of the process of serialization and anti-analytic tools are the two core classes with the completion of.
Example of the first section of the first sequence, and then anti-analytic, and purpose of this section is to parse the principle behind these operations, so we need to adopt the opposite course. Only clear when the anti-parsing what information needs to guide the sequence of how to deal with the process.
Analogy to practice so-called "design" is a "gas line leading Italian" process; and "realization" process is "intended to lead the line gas." Make a design, the need for mechanisms underlying a very full understanding of, and need to make trade-offs and compromise the application, which is why do so few people who design and code work always so many reasons. Of course, this does not mean to belittle Coder, just to illustrate the difference between these two processes. After all, the drawings also need to have a good draw skilled workers to turn it into a can touch the product, the level of craftsmanship will directly determine the quality of the final product.
OK, the above is bull shit, the following core principles and to begin the design process for resolution.
2.1. Anti-resolution: AS3 reflection
2.1.1. The core principle, we know that in Java, a "reflection" one said, through the class name of a class type definition can obtain information on the class, like this:
Class.forName (classNameStr);
AS3 is also in a similar mechanism:
flash.utils.getDefinitionByName (className);
getDefinitionByName This tool will return a function object of type Class, we use this object to get a new instance of the class, the general usage is as follows:
var MyClass: Class = flash.utils.getDefinitionByName (className);
var instance: MyClass = new MyClass ();
In this way, as long as we get a class name, you can create under the name of the instance of the class. Again go over the XML generated by the first section of content:

NanoUI the second bomb, how to graph serialization and anti-analytic


XML file type information is clear, so long as we load the XML string to the front, then the type specified by type attribute name, you can re-create the graphics for example it! ! ! In the instance created, then the other property is set to the newly created instance, so that you can recover the pixel it! ! !
However, the big wet goes: the ideal is full, the reality is very skinny. While we understand the general direction of advance, but the actual implementation process is still difficult, the following is to put theory into practice by the need to check.
2.1.2. Note that point
2.1.2.1. The first point of note: the compiler is the problem we first encountered the damn flash compiler, for example, you define a class: com.namo.Test, but your application does not use the Test class, flash compiler to compile it in order to ensure the swf file small enough, it does not compile the Test to the swf file to go inside. This time the problem arises: even if you know the full type name Test, or can not flash.utils.getDefinitionByName (className) Get the Class object! ! !
So, how to force the compiler to compile these classes come in it?
We define the SysClassMgr some empty properties that are reflective of all we need to point type. Although we did not actually create an instance (not accounting for memory), but the compiler is that we use these classes, by such a "trick" to tease the compiler can successfully make it to the class we need to have compiled in reflection. See detailed code SysConfMgr:

NanoUI the second bomb, how to graph serialization and anti-analytic


SysClassMgr the trick
2.1.2.2. The second point of note: constructor arguments
var MyClass: Class = flash.utils.getDefinitionByName (className);
var instance: MyClass = new MyClass ();
As shown above, we get this type of MyClass, use the new MyClass () creates an instance of the way, but if MyClass constructor has parameters defined, then it will throw an exception it! ! !
This said, it is not simple, we imitate Java, to each class plus a default constructor with no parameters does not have to Well.
But unfortunately, AS3 does not support function overloading, the constructor does not work! ! ! Therefore, the following code can not compile:

package com.nano{
        public class Test{
            //  No argument constructor  
            public function Test(){
           
            }
            public function Test(config:Object){
            }
        }
    }

So, how to solve this problem?
The only of the solution is this: If you need to bring parameters of the class constructor, the constructor must specify a default value of all parameters in order to facilitate the time Nenggeifanshe.
As for the Test class, if you need to provide parameters to the constructor, the best written like this:

public function Test(arg1:Object=null,arg2:Object=null){}

Of course, this treatment, the class constructor which is not suitable for very complex logic, which requires you to make a specific application scenario trade-offs.

2.2. Serialization: Graphics and XML
2.2.1. Core Principles
provides a built-in flash utility functions, graphics objects used to parse XML:
var xmlData: XML = flash.utils.describeType (drawing objects);
You can try this code, view the resulting XML string:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               minWidth="955" minHeight="600"
               creationComplete="callLater(init)">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            function init():void{
                var s:Sprite=new Sprite();
                var xmlData:XML=flash.utils.describeType(s);
                var xmlStr:String=xmlData.toXMLString();
                this.log.text=xmlData;
            }
        ]]>
    </fx:Script>
    <mx:TextArea width="100%" height="100%" editable="false"/>
</s:Application>


NanoUI the second bomb, how to graph serialization and anti-analytic


Resulting XML string ah ha, with the native tools that we from the goal seems to be a step closer, but the road is still not so smooth.
2.2.2. Note that the above points carefully observe the XML string you will find the native XML tools to produce very large! ! ! Which contains a large amount of information, and our application does not need these things.
This may say: No it does not matter, ah, on the inside regardless of the line.
Of course, if you are within the network application, network bandwidth and the resulting XML file size is no limitation, direct ignore these redundant information is also possible. However, if the portal-type applications, the transmission speed and file size will have more stringent requirements. Therefore, we had better make the cut on this information, which is why there is such a bunch of head in CompXmlParser.xmlEncode delete call reasons:

NanoUI the second bomb, how to graph serialization and anti-analytic


We do not need to delete the information by this group of delete, we can delete a lot of redundant information --- not the whole. Of course, if you wish, you can further fine tailoring is needed before the cut structure of the resulting XML to make a more detailed analysis to determine what information needs to be retained.
Here, CompXmlParser order to give the process of anti-analytic convenience, and do not use native access to the XML structure, but in the cut, after formatting the information into this structure:

<instance type="com.nano.widgets::JRect" base="com.nano.widgets::JFilledShape">
  <variable>
    <name> </name>
    <value> </value>
    <type> </type>
  </variable>
</instance>


All the attributes are formatted as name, value, type these three attributes. After this, after some processing, the XML string to get the volume has been greatly reduced, then we can submit it to the server it! ! !

3. Attention to this point and design improvements, we have completed pixel sequence of the entire process and anti-analytic. Of course, throughout the processing chain, there are still some places can be reconstructed and improved. Of these, you are wise to leave to complete it! ! !

NanoUI series of articles will have the following themes, recently released, so stay tuned:
Utility functions of the design;
How to design a high-level semantic event mechanism;

UI components and UI components inherit the general design of the structure;

Topology of how to design your own layout algorithm;

And so on ...

Relevant interest in the script into the baby may be discussed group 3: 91508669. Note: Please read the script doll online community exchange agreement, offenders will be no survivors.
Finally, the last, do not try to contact Columbia, Costa Rica is only a legend.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of NanoUI the second bomb, how to graph serialization and anti-analytic

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Spring2.0 + hibernate3.1 + log4j + mysql demo

    applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Sign in spring struts2.0 hibernate user authentication

    Engage in a day has finally put the ghost of a user log in to engage in things out. . Ah first experience with a spring to manage the bean is a good tool. Of course, far more than this spring profound role in it. This is called a simple sense of the ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries