[GRASS-SVN] r61256 - in sandbox/krejcmat/src: . data

svn_grass at osgeo.org svn_grass at osgeo.org
Tue Jul 15 06:37:55 PDT 2014


Author: krejcmat
Date: 2014-07-15 06:37:55 -0700 (Tue, 15 Jul 2014)
New Revision: 61256

Modified:
   sandbox/krejcmat/src/data/grassInspireTemplate01.xml
   sandbox/krejcmat/src/editor3.py
   sandbox/krejcmat/src/g.gui.metadata.py
   sandbox/krejcmat/src/jinjainfo.py
   sandbox/krejcmat/src/mdgrass.py
   sandbox/krejcmat/src/r.info.iso.py
   sandbox/krejcmat/src/v.info.iso.py
Log:
xml save

Modified: sandbox/krejcmat/src/data/grassInspireTemplate01.xml
===================================================================
--- sandbox/krejcmat/src/data/grassInspireTemplate01.xml	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/data/grassInspireTemplate01.xml	2014-07-15 13:37:55 UTC (rev 61256)
@@ -2,57 +2,60 @@
 <!-- ISO 19115:2003 file created from OWSLib object model -->
 <gmd:MD_Metadata xsi:schemaLocation="http://www.isotc211.org/2005/gmd http://schemas.opengis.net/iso/19139/20060504/gmd/gmd.xsd" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml" xmlns:xlink="http://www.w3.org/1999/xlink">
   <gmd:fileIdentifier>
-    <gco:CharacterString>{{ md.identifier }}{# tag='md.identifier',  name ='Resource Identifier', desc ='Unique Resource Identifier', example ='286c0725-146e-4533-b1bf-d6e367f6c342', type = 'CharacterString', multi = 0, group = 'Identification', multiline=True #}</gco:CharacterString>
+    <gco:CharacterString>{{ md.identifier }}{# tag="md.identifier",  name ="Resource Identifier", desc ="Unique Resource Identifier", example ="286c0725-146e-4533-b1bf-d6e367f6c342", type = "CharacterString", multi = 0, group = "Identification", multiline=False #}</gco:CharacterString>
   </gmd:fileIdentifier>
   <gmd:language>
-    <gmd:LanguageCode codeList="http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#LanguageCode" codeListValue="eng">{{ md.languagecode }}{# tag='md.languagecode', name ='Metadata language', desc ='Language(s) used within the datasets', example ='eng', type = 'CharacterString', multi = 0, group = 'Metadata',multiline=False #}</gmd:LanguageCode>
+    <gmd:LanguageCode codeList="http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#LanguageCode" codeListValue="eng">{{ md.languagecode }}{# tag="md.languagecode", name ="Metadata language", desc ="Language(s) used within the datasets", example ="eng", type = "CharacterString", multi = 0, group = "Metadata",multiline=False #}</gmd:LanguageCode>
   </gmd:language>
   <gmd:hierarchyLevel>
-    <gmd:MD_ScopeCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode" codeListValue="dataset" codeSpace="ISOTC211/19115">{{ md.identification.identtype }}{# tag='md.identification.identtype', name ='Resource Type', desc ='Scope to which metadata applies', example ='dataset', type = 'CharacterString', multi = 0, group = 'Identification',multiline=True #}</gmd:MD_ScopeCode>
+    <gmd:MD_ScopeCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#MD_ScopeCode" codeListValue="dataset" codeSpace="ISOTC211/19115">{{ md.identification.identtype }}{# tag="md.identification.identtype", name ="Resource Type", desc ="Scope to which metadata applies", example ="dataset", type = "CharacterString", multi = 0, group = "Identification",multiline=True #}</gmd:MD_ScopeCode>
   </gmd:hierarchyLevel>
-  {% for co in md.contact -%}{# tag='md.contact',group = 'Identification' ,inbox='contact'  #}
+
+
+  {% for co in md.contact -%}{# tag="for co in md.contact",group = "Identification" ,object="CI_ResponsibleParty()", inbox="contact"  #}
   <gmd:contact>
     <gmd:CI_ResponsibleParty>
       <gmd:organisationName>
-        <gco:CharacterString>{{ co.organization }}{# tag='co.organization', name ='Organisation Name', desc ='todo' , type = 'CharacterString', multi = 0, group = 'Metadata',multiline=True, inbox='contact' #}</gco:CharacterString>
+        <gco:CharacterString>{{ co.organization }}{# tag="co.organization", name ="Organisation Name", desc ="todo" ,object="CI_ResponsibleParty()", type = "CharacterString", multi = 0, group = "Metadata",multiline=True, inbox="contact" #}</gco:CharacterString>
       </gmd:organisationName>
-      <gmd:contactInfo>
         <gmd:CI_Contact>
           <gmd:address>
             <gmd:CI_Address>
               <gmd:electronicMailAddress>
-                <gco:CharacterString>{{ co.email }}{# tag='co.email', name ='E-mail', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Metadata',multiline=True, inbox='contact' #}</gco:CharacterString>
+                <gco:CharacterString>{{ co.email }}{# tag="co.email", name ="E-mail", desc ="todo" , type = "CharacterString",object="CI_ResponsibleParty()", multi = 1, group = "Metadata",multiline=True, inbox="contact" #}</gco:CharacterString>
               </gmd:electronicMailAddress>
             </gmd:CI_Address>
           </gmd:address>
         </gmd:CI_Contact>
       </gmd:contactInfo>
       <gmd:role>
-        <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue={{ "\"%s\"" % co.role }}{# tag='co.role', name ='role', desc ='todo' , type = 'CharacterString', multi = 0, group = 'Identification',multiline=True, inbox='contact' #} codeSpace="ISOTC211/19115">{{ co.role }}</gmd:CI_RoleCode>
+        <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue={{ "\"%s\"" % co.role }}{# tag="co.role", name ="role", desc ="todo" , type = "CharacterString", multi = 0, group = "Identification",object="CI_ResponsibleParty()",multiline=True, inbox="contact" #} codeSpace="ISOTC211/19115"></gmd:CI_RoleCode>
       </gmd:role>
     </gmd:CI_ResponsibleParty>
   </gmd:contact>
   {% endfor -%}
-      {% for k in md.identification.keywords -%}{# tag='md.identification.keywords' ,group = 'Keywords',inbox='descriptiveKeywords' #}
+
+
+      {% for k in md.identification.keywords -%}{# tag="for k in md.identification.keywords" ,group = "Keywords",inbox="descriptiveKeywords" #}
       <gmd:descriptiveKeywords>
         <gmd:MD_Keywords>
-{% for kw in k['keywords'] -%}{# tag='k["keywords"]',group = 'Keywords',inbox='descriptiveKeywords'  #}
+{% for kw in k["keywords"] -%}{# tag='for kw in k["keywords"]',group = "Keywords",inbox="descriptiveKeywords"  #}
           <gmd:keyword>
-            <gco:CharacterString>{{ kw }}{# tag='kw', name ='keyword', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Keywords', multiline=True, inbox='descriptiveKeywords' #}</gco:CharacterString>
+            <gco:CharacterString>{{ kw }}{# tag="kw", name ="keyword", desc ="todo" , type = "CharacterString", multi = 1, group = "Keywords", multiline=True, inbox="descriptiveKeywords" #}</gco:CharacterString>
           </gmd:keyword>
           {% endfor -%}
           <gmd:thesaurusName>
             <gmd:CI_Citation>
               <gmd:title>
-                <gco:CharacterString>{{ k['thesaurus']['title'] }}{# tag="k['thesaurus']['title']", name ='title', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Keywords', multiline=True, inbox='descriptiveKeywords'#}</gco:CharacterString>
+                <gco:CharacterString>{{ k["thesaurus"]["title"] }}{# tag='k["thesaurus"]["title"]', name ="title", desc ="todo" , type = "CharacterString", multi = 1, group = "Keywords", multiline=True, inbox="descriptiveKeywords"#}</gco:CharacterString>
               </gmd:title>
               <gmd:date>
                 <gmd:CI_Date>
                   <gmd:date>
-                    <gco:Date>{{ k['thesaurus']['date'] }}{# tag="k['thesaurus']['date'] ", name ='date', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Keywords', multiline=True, inbox='descriptiveKeywords'#}</gco:Date>
+                    <gco:Date>{{ k["thesaurus"]["date"] }}{# tag='k["thesaurus"]["date"] ', name ="date", desc ="todo" , type = "CharacterString", multi = 1, group = "Keywords", multiline=True, inbox="descriptiveKeywords"#}</gco:Date>
                   </gmd:date>
                   <gmd:dateType>
-                    <gmd:CI_DateTypeCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode" codeListValue={{ "\"%s\"" % k['thesaurus']['datetype'] }}>{{ k['thesaurus']['datetype'] }}{# tag="k['thesaurus']['datetype'] ", name ='datetype', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Keywords', multiline=True, inbox='descriptiveKeywords'#}</gmd:CI_DateTypeCode>
+                    <gmd:CI_DateTypeCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_DateTypeCode" codeListValue={{ "\"%s\"" % k["thesaurus"]["datetype"] }}>{{ k["thesaurus"]["datetype"] }}{# tag='k["thesaurus"]["datetype"] ', name ="datetype", desc ="todo" , type = "CharacterString", multi = 1, group = "Keywords", multiline=True, inbox="descriptiveKeywords"#}</gmd:CI_DateTypeCode>
                   </gmd:dateType>
                 </gmd:CI_Date>
               </gmd:date>
@@ -61,14 +64,14 @@
         </gmd:MD_Keywords>
       </gmd:descriptiveKeywords>
       {% endfor -%}
-      {% if md.identification.denominators|length > 0 -%}{# tag='md.identification.denominators',group = 'Keywords',inbox='descriptiveKeywords' #}
-      {% for den in md.identification.denominators -%}{# tag="md.identification.denominators",group = 'Keywords',inbox='descriptiveKeywords' #}
+      {% if md.identification.denominators|length > 0 -%}{# tag="if md.identification.denominators|length",group = "Keywords",inbox="descriptiveKeywords" #}
+      {% for den in md.identification.denominators -%}{# tag="for den in md.identification.denominators",group = "Keywords",inbox="descriptiveKeywords" #}
       <gmd:spatialResolution>
         <gmd:MD_Resolution>
           <gmd:equivalentScale>
             <gmd:MD_RepresentativeFraction>
               <gmd:denominator>
-                <gco:Integer>{{ den }}</gco:Integer>{# tag="den ", name ='denominator', desc ='todo' , type = 'CharacterString', multi = 1, group = 'Keywords', multiline=True, inbox='descriptiveKeywords'#}
+                <gco:Integer>{{ den }}</gco:Integer>{# tag="den ", name ="denominator", desc ="todo" , type = "CharacterString", multi = 1, group = "Keywords", multiline=True, inbox="descriptiveKeywords"#}
               </gmd:denominator>
             </gmd:MD_RepresentativeFraction>
           </gmd:equivalentScale>
@@ -76,3 +79,63 @@
       </gmd:spatialResolution>
       {% endfor -%}
       {% endif -%}
+ {% for (t,d,dt,dg) in zip(md.dataquality.conformancetitle,md.dataquality.conformancedate,md.dataquality.conformancedatetype,md.dataquality.conformancedegree) -%}{# tag="for (t,d,dt,dg) in zip(md.dataquality.conformancetitle,md.dataquality.conformancedate,md.dataquality.conformancedatetype,md.dataquality.conformancedegree", group = "data quality", inbox="measureIdentification"#}
+      <gmd:report>
+        <gmd:DQ_DomainConsistency xsi:type="gmd:DQ_DomainConsistency_Type">
+          <gmd:measureIdentification>
+            <gmd:RS_Identifier>
+              <gmd:code>
+                <gco:CharacterString>Conformity</gco:CharacterString>
+              </gmd:code>
+              <gmd:codeSpace>
+                <gco:CharacterString>INSPIRE</gco:CharacterString>
+              </gmd:codeSpace>
+            </gmd:RS_Identifier>
+          </gmd:measureIdentification>
+          <gmd:result>
+            <gmd:DQ_ConformanceResult xsi:type="gmd:DQ_ConformanceResult_Type">
+              <gmd:specification>
+                <gmd:CI_Citation>
+                  <gmd:title>
+                    <gco:CharacterString>{{ t }}{# tag="t", name ="title", desc ="todo" , type = "CharacterString", multi = 1, group = "data quality", multiline=True, inbox="measureIdentification"#}</gco:CharacterString>
+                  </gmd:title>
+                  <gmd:date>
+                    <gmd:CI_Date>
+                      <gmd:date>
+                        <gco:Date>{{ d }}{# tag="d", name ="date", desc ="todo" , type = "CharacterString", multi = 1, group = "data quality", multiline=False, inbox="measureIdentification"#}</gco:Date>
+                      </gmd:date>
+                      <gmd:dateType>
+                        <gmd:CI_DateTypeCode codeList="http://www.isotc211.org/2005/resources/Codelist/ML_gmxCodelists.xml#CI_DateTypeCode" codeListValue={{ "\"%s\"" % dt }}>{{ dt }}{# tag="d", name ="date", desc ="todo" , type = "CharacterString", multi = 1, group = "data quality", multiline=False, inbox="measureIdentification"#}</gmd:CI_DateTypeCode>
+                      </gmd:dateType>
+                    </gmd:CI_Date>
+                  </gmd:date>
+                </gmd:CI_Citation>
+              </gmd:specification>
+              <gmd:explanation>
+                <gco:CharacterString>See the referenced specification</gco:CharacterString>
+              </gmd:explanation>
+              <gmd:pass>
+                <gco:Boolean>{{ dg }}{# tag="dg", name ="explanation", desc ="todo" , type = "CharacterString", multi = 1, group = "data quality", multiline=False, inbox="measureIdentification"#}</gco:Boolean>
+              </gmd:pass>
+            </gmd:DQ_ConformanceResult>
+          </gmd:result>
+        </gmd:DQ_DomainConsistency>
+      </gmd:report>
+      {% endfor -%}
+      {% if md.identification.temporalextent_start != None -%}{# tag="if md.identification.temporalextent_start != None", group = "extent", inbox="TemporalExtent"#}
+      <gmd:extent>
+        <gmd:EX_Extent>
+          <gmd:temporalElement>
+            <gmd:EX_TemporalExtent>
+              <gmd:extent>
+                <gml:TimePeriod xsi:type="gml:TimePeriodType">
+                  <gml:beginPosition>{{ md.identification.temporalextent_start }}{# tag="md.identification.temporalextent_start", name ="beginPosition", desc ="todo" , type = "CharacterString", multi = 1, group = "extent", multiline=False, inbox="TemporalExtent"#}</gml:beginPosition>
+                  <gml:endPosition>{{ md.identification.temporalextent_end }}{# tag="md.identification.temporalextent_end ", name ="endPosition", desc ="todo" , type = "CharacterString", multi = 1, group = "extent", multiline=False, inbox="TemporalExtent"#}</gml:endPosition>
+                </gml:TimePeriod>
+              </gmd:extent>
+            </gmd:EX_TemporalExtent>
+          </gmd:temporalElement>
+        </gmd:EX_Extent>
+      </gmd:extent>
+      {% endif -%}
+

Modified: sandbox/krejcmat/src/editor3.py
===================================================================
--- sandbox/krejcmat/src/editor3.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/editor3.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -5,90 +5,153 @@
 
 from owslib.iso import *
 from jinjainfo  import JinjaTemplateInfo as jt
+from jinja2 import Environment, FileSystemLoader
 
 from lxml import etree as ET
 import contextlib
 from wxPython._core import wxBoxSizer
 
+import copy
+import re     
+import os  
+
 #===============================================================================
-#EDITOR                   
+# MD blah blah                   
 #===============================================================================
 class MD():
-    def __init__(self,pathToXml=None):
+    def __init__(self, pathToXml=None):
 
-        self.path=pathToXml
-        self.owslibInfo=None
-        self.initMD()
+        self.path = pathToXml
+        self.owslibInfo = None
+        # self.readXML()
  
-    def initMD(self):        
-        self.path='INStest.xml'
-        tree = ET.parse(self.path)
-        root = tree.getroot()
-        self.md = MD_Metadata(root)
-        #self.md = MD_Metadata(md=None)  
+    def initMD(self, path=None):        
+        if path == None:
+            self.md = MD_Metadata(md=None)
+            return  self.md
+        else:
+            tree = ET.parse(path)
+            root = tree.getroot()
+            self.md = MD_Metadata(root)
+            return self.md
+        #  
+        
+    def saveToXML(self, md, path=None, xml_out_name=None):
+                # if  output file name is None, use map name and add postfix
+        self.dirpath = os.path.dirname(os.path.realpath(__file__))        
+        self.md = md
+        self.template = 'data/grassInspireTemplate01.xml'
+        if xml_out_name is None:
+            xml_out_name = 'testExportMD' 
+        if not xml_out_name.lower().endswith('.xml'):
+            xml_out_name += '.xml'
+        # if path is None, use lunch. dir
+        # TODO change default folder to mapset location
+        if not path:
+            path = os.path.join(self.dirpath, xml_out_name)
+        else:
+            path = os.path.join(path, xml_out_name)
 
-#-------------------------------------------------------------------- CREATE BOX
+        # generate xml using jinja tempaltes
+        env = Environment(loader=FileSystemLoader(self.dirpath))
+        env.globals.update(zip=zip)
+        template = env.get_template(self.template)
+        iso_xml = template.render(md=self.md)
+        xml_file = xml_out_name
+        
+        # write xml to flat file
+        try:
+            xml_file = open(path, "w")
+            xml_file.write(iso_xml)
+            xml_file.close()
+            print 'metadata exported: \n%s' % (str(path))
+                                         
+        except IOError as e:
+            print "I/O error({0}): {1}".format(e.errno, e.strerror)
+            grass.fatal('error: cannot write xml file')
+        return  path
+
+#===============================================================================
+# CREATE BOX (staticbox+button(optional)
+#===============================================================================
 class Box(wx.Panel):
-    def __init__(self,parent,label='label'):
-        wx.Panel.__init__(self,parent=parent,id=wx.ID_ANY) 
+    def __init__(self, parent, label='label'):
+        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) 
 
-        self.stbox= wx.StaticBox(self, label=label,id=ID_ANY, style=wx.RAISED_BORDER)
-        self.stbox.SetForegroundColour((0,0,0))
-        self.stbox.SetBackgroundColour((200,200,200))
-        self.stbox.SetFont(wx.Font(12,wx.NORMAL, wx.NORMAL, wx.NORMAL))
+        self.mdItems = []
+        self.stbox = wx.StaticBox(self, label=label, id=ID_ANY, style=wx.RAISED_BORDER)
+        self.stbox.SetForegroundColour((0, 0, 0))
+        self.stbox.SetBackgroundColour((200, 200, 200))
+        self.stbox.SetFont(wx.Font(12, wx.NORMAL, wx.NORMAL, wx.NORMAL))
 
-    def addItems(self,items,multi=True):
-        self.panelSizer=wx.BoxSizer(wx.VERTICAL)
+    def addItems(self, items, multi=True):
+        self.panelSizer = wx.BoxSizer(wx.VERTICAL)
         self.SetSizer(self.panelSizer)
         
-        self.boxButtonSizer=wx.BoxSizer(wx.HORIZONTAL)
+        self.boxButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
         
         self.panelSizer.AddSpacer(10 , 10, 1, wx.EXPAND) 
-        self.panelSizer.Add(self.boxButtonSizer,flag=wx.EXPAND,proportion=1)
-        self.stBoxSizer = wx.StaticBoxSizer( self.stbox, orient=wx.VERTICAL)
-        self.boxButtonSizer.Add(self.stBoxSizer,flag=wx.EXPAND,proportion=1)
+        self.panelSizer.Add(self.boxButtonSizer, flag=wx.EXPAND, proportion=1)
+        self.stBoxSizer = wx.StaticBoxSizer(self.stbox, orient=wx.VERTICAL)
+        self.boxButtonSizer.Add(self.stBoxSizer, flag=wx.EXPAND, proportion=1)
         self.stBoxSizer.AddSpacer(5 , 5, 1, wx.EXPAND)
         
         for item in items:
-            self.stBoxSizer.Add(item,flag=wx.EXPAND,proportion=1)
-            self.stBoxSizer.AddSpacer(5 , 5, 1, wx.EXPAND)             
+                self.mdItems.append(item)
+                self.stBoxSizer.Add(item, flag=wx.EXPAND, proportion=1)
+                self.stBoxSizer.AddSpacer(5 , 5, 1, wx.EXPAND)         
 
         if multi:
-            self.addBoxButt=wx.Button(self,id=ID_ANY,size=(20,20),label='+')
-            self.boxButtonSizer.Add(self.addBoxButt,0)
-            
-    def addItem(self,item):
+            self.addBoxButt = wx.Button(self, id=ID_ANY, size=(20, 20), label='+')
+            self.boxButtonSizer.Add(self.addBoxButt, 0)
+            self.addBoxButt.Bind(EVT_BUTTON, self.duplicateBox)   
+    
+    
+    def duplicateBox(self, evt):
+        mdDescription = []
+        for item in self.mdItems:
+            mdDescription.append(item.itemObject)
+        
+        child = self.stbox.GetChildren()
+        self.GetParent().addItemMulti(copy.copy(self), child)
+        # self.GetParent().GetParent().GetParent().test(mdDescription)
+
+        
+    def addItem(self, item):
         pass
 
-#--------------------------------------------------------------------- ADD ITEM
+#===============================================================================
+# ADD METADATA ITEM (label+ctrlText+button(optional)
+#===============================================================================
 class MdItem(wx.BoxSizer):
-    def __init__(self,parent,item):
-        wx.BoxSizer.__init__(self,wx.VERTICAL)    
-        self.itemObject=item
-        self.multiple=item.multiplicity
+    def __init__(self, parent, item):
+        wx.BoxSizer.__init__(self, wx.VERTICAL)    
+        self.itemObject = item
+        self.multiple = item.multiplicity
+        # info=self.createInfo(item)  
+        # print item.name
+        # print item.tag
+        self.tagText = wx.StaticText(parent=parent, id=ID_ANY, label=item.name)
         
-        #info=self.createInfo(item)  
-            
-        self.tagText= wx.StaticText(parent=parent,id=ID_ANY,label=item.name)
-        
         if item.multiline is True:
-            self.valueCtrl = wx.TextCtrl(parent, id=ID_ANY,  size=(0, 55),
+            self.valueCtrl = wx.TextCtrl(parent, id=ID_ANY, size=(0, 55),
                        style=wx.VSCROLL | 
-                       wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.ST_NO_AUTORESIZE|
-                       wx.TAB_TRAVERSAL|wx.RAISED_BORDER|wx.HSCROLL)       
+                       wx.TE_MULTILINE | wx.TE_NO_VSCROLL | 
+                       wx.TAB_TRAVERSAL | wx.RAISED_BORDER | wx.HSCROLL)       
         else:
-            self.valueCtrl = wx.TextCtrl(parent, id=wx.ID_ANY,  
-                       style=wx.VSCROLL |  wx.TE_DONTWRAP | 
-                       wx.TAB_TRAVERSAL|wx.RAISED_BORDER|wx.HSCROLL)  
+            
+            self.valueCtrl = wx.TextCtrl(parent, id=wx.ID_ANY,
+                       style=wx.VSCROLL | wx.TE_DONTWRAP | 
+                       wx.TAB_TRAVERSAL | wx.RAISED_BORDER | wx.HSCROLL)  
 
         if self.multiple:
-            self.addItemButt=wx.Button(parent,-1,size=(20,20),label='+')
-            #self.addInfoButt=wx.Button(self,-1,size=(20,20),label='I')
-            #BINDS    
+            self.addItemButt = wx.Button(parent, -1, size=(20, 20), label='+')
+            # self.addInfoButt=wx.Button(self,-1,size=(20,20),label='I')
+            # BINDS    
             
         self._addItemLay(item.multiline)
     
-    def setValue(self,value):
+    def setValue(self, value):
         self.valueCtrl.SetValue(value)
         
     def getValue(self):
@@ -103,206 +166,631 @@
         else:
             return None
                  
-    def _addItemLay(self,multiline): 
+    def _addItemLay(self, multiline): 
 
         if multiline is True:
             self.textFieldSizer = wx.BoxSizer(wx.HORIZONTAL)  
-            self.textFieldSizer.Add(self.valueCtrl,proportion=1,flag=wx.EXPAND)
+            self.textFieldSizer.Add(self.valueCtrl, proportion=1, flag=wx.EXPAND)
             if self.multiple:
-                self.textFieldSizer.Add(self.addItemButt,0)
-            self.Add(item=self.tagText,proportion=0)
-            self.Add(item=self.textFieldSizer,proportion=0,flag=wx.EXPAND)
+                self.textFieldSizer.Add(self.addItemButt, 0)
+            self.Add(item=self.tagText, proportion=0)
+            self.Add(item=self.textFieldSizer, proportion=0, flag=wx.EXPAND)
         else:
             self.textFieldSizer = wx.BoxSizer(wx.HORIZONTAL)  
-            self.textFieldSizer.Add(self.valueCtrl,proportion=1)
+            self.textFieldSizer.Add(self.valueCtrl, proportion=1)
             if self.multiple:
-                self.textFieldSizer.Add(self.addItemButt,0)
-            self.Add(item=self.tagText,proportion=0)
-            self.Add(item=self.textFieldSizer,proportion=0,flag=wx.EXPAND)
-
-
+                self.textFieldSizer.Add(self.addItemButt, 0)
+            self.Add(item=self.tagText, proportion=0)
+            self.Add(item=self.textFieldSizer, proportion=0, flag=wx.EXPAND)
+            
+    def Refresh(self):
+        self.valueCtrl.Refresh()
+        self.tagText.Refresh()
+                
+#===============================================================================
+# ADD NOTEBOOK PAGE
+#===============================================================================
 class NotebookPage(scrolled.ScrolledPanel):
-    def __init__(self,parent):
-            scrolled.ScrolledPanel.__init__(self,parent=parent,id=wx.ID_ANY)
-            
+    def __init__(self, parent):
+            scrolled.ScrolledPanel.__init__(self, parent=parent, id=wx.ID_ANY)
+            self.items = []
             self.SetupScrolling()       
             self._addNotebookPageLay()
     
     def _addNotebookPageLay(self):   
-            self.mainSizer=wx.BoxSizer(wx.VERTICAL)
-            self.SetSizer(self.mainSizer)
+        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
+        self.SetSizer(self.mainSizer)
             
-    def addItem(self,item):
-        self.mainSizer.Add(item,proportion=0,flag=wx.EXPAND)
+    def addItem(self, item):
+        if isinstance(item, list):
+            for i in item:
+                 self.items.append(i)
+                 self.mainSizer.Add(i, proportion=0, flag=wx.EXPAND)
+        else:
+            self.items.append(item)
+            self.mainSizer.Add(item, proportion=0, flag=wx.EXPAND)
+    
         
+    def addItemMulti(self, item, child):
+        self.items.append(item)
+        
+        for ch in child:
+            print ch
+            ch.Destroy()
+             
+        # self.mainSizer.Destroy()
+        # self._addNotebookPageLay()    
+        itemsTMP = []   
+        for item1 in self.items:
+            i = copy.copy(item1)
+            i.Refresh()
+            itemsTMP.append(i)
+            
+            print item1
+            # addBoxButt=wx.Button(self,id=ID_ANY,size=(20,20),label='+')
+            self.mainSizer.Add(i, proportion=0, flag=wx.EXPAND)  
+                               
+        self.items = []
+        self.items = itemsTMP
+        self.SetSizerAndFit(self.mainSizer)
+        # self.Layout()
+        # self.Fit()
+        # self.GetParent().GetParent()
+
 #===============================================================================
 # MAIN FRAME            
 #===============================================================================
 class MainFrame(wx.Frame):
     def __init__(self):
         wx.Frame.__init__(self, None, title="Metadata Editor",
-                  size=(500 ,500))
+                  size=(500 , 500))
         
-        mdo=MD()
-        self.md=mdo.md  #instance of 
-        self.comboItems=[]  #list in combobox
-        self.templatePath='data/grassInspireTemplate01.xml'
-        #self.templatePath='data/jinjatest.xml'
-        jinj=jt(self.templatePath)
-        self.mdDescription=jinj.mdDescription     #list of object MdDescription
-        self.mdOWSTagStr=jinj.mdOWSTagStr         #string of tags from jinja template (loops and OWSLib objects)   
-        self.mdOWSTagStrList=jinj.mdOWSTagStrList #
-        self.valueStorageWxID={}
-        self.mdDescriptionList=[]
-        self.currWXid=None
+        mdo = MD()
+        self.md = mdo.initMD('INStest.xml')
+
+        self.templatePath = 'data/grassInspireTemplate01.xml'
+        # self.templatePath='data/jinjatest.xml'
         
+        jinj = jt(self.templatePath)
+        self.mdDescription = jinj.mdDescription  # list of object MdDescription
+        self.mdOWSTagStr = jinj.mdOWSTagStr  # string of tags from jinja template (loops and OWSLib objects)   
+        self.mdOWSTagStrList = jinj.mdOWSTagStrList  #
+        
         self.initCreatorMD()
         self._layout()
-    
-
-#===============================================================================
-# GUI GENERATOR
-#===============================================================================
-    def executeStr(self,stri,linfo):
+        
+#----------------------------------------------------------- GUI GENERATOR START
+    def executeStr(self, stri, linfo):
         print stri
         exec stri
-        
+
     def plusC(self):
-        self.c+=1
+        self.c += 1
         if self.c >= self.max:
-            self.c-=1
-            self.stop=True    
+            self.c -= 1
+            self.stop = True    
+            
                                        
     def initCreatorMD(self):  
         '''
-             @var var:   self.c        index of lstruct and self.mdDescription
-                        lstruct        lstruct is self.mdOWSTagStr in list. Item=line from jinja template(only lines with owslib objects and loops)
-                        linfo          list of MdDescription() objects inicialized by information from jinja t.
-                        markgroup       markers of created list in GUI notebook
-                        self.max        length of lstruct and linfo
-                        self.stop       index self.c is increasing  by function plusC(), that care about  not exceeding the index
-        '''   
-
-        self.notebook=wx.Notebook(self)
-        markgroup=[]    #notebok panel marker
-        lstruct=self.mdOWSTagStrList   
-        linfo=self.mdDescription        #from jinja
-
-        self.c=0        #this valus is the index of self.mdOWSTagStrList and also in self.mdDescription
-        self.stop=False
-        self.max=len(linfo)      
-
-        def chckLen():
+        @var var:    self.c:        index of lstruct and self.mdDescription
+                    lstruct:        lstruct is self.mdOWSTagStr in list. \
+                                    Item=line from jinja template(only lines\
+                                    with owslib objects and loops)
+                    linfo:          list of MdDescription() objects inicialized\
+                                    by information from jinja t.                        
+                    markgroup:      markers of created list in GUI notebook
+                    self.max:       length of lstruct and linfo
+                    self.stop:      index self.c is increasing  by function plusC(),\
+                                    that care about  not exceeding the index
+        '''         
+        def prepareStatements():
             '''
-            @note: -length of list in jinja template is provided by |length.
-                    -need to convert to python len() 
+            @note: 
             '''
-            try:
-                    if '|length' in str(lstruct[self.c-1])and self.stop is False:
-                         a=lstruct[self.c-1]
-                         a=a.replace('|length',')').replace('if ','if len(self.')
-                         lstruct[self.c-1]=a
-            except:   
-                 self.stop=True
-                 #print '='*60
-                 
-        def inBox2(): #function in def initCreatorMD(self):   !!!
+            for c in range(self.max):
+                if '|length' in str(lstruct[c]):
+                     a = lstruct[c]
+                     a = a.replace('|length', ')').replace('if ', 'if len(self.')
+                     lstruct[c] = a
+                     
+                if 'zip(' in lstruct[c]:
+                    sta = lstruct[c ]
+                    lstruct[c] = sta.replace('md.', 'self.md.')
+                    
+        def inBlock():  #function in def initCreatorMD(self):   !!!
             '''
             @note: 
             '''
-            self.k=0
-            loop = lstruct[self.c-1]
-            str2=loop.replace(' md.',' self.md.')+':\n'
-            str2+='\t' +'box=Box(self.nbPage,linfo[' + str(self.c) + '].inbox)\n' #add box
-            str2+='\t' +'self.boxItemList=[]\n' #initialize list
+            IFStatements = False
+            statements = lstruct[self.c - 1]
+            if 'if' in statements.split():
+               IFStatements = True
+
+            str2 = statements.replace(' md.', ' self.md.')
+            looptmp = str2
+            str2 += ':\n'
+            str2 += '\t' + 'self.ItemList=[]\n'  # initialize list
             
-            str1=str2
+            box = False
+            if self.mdDescription[self.c].inbox:
+                box = True
+                str2 += '\t' + 'box=Box(self.nbPage,linfo[' + str(self.c) + '].inbox)\n'  # add box
+            str1 = str2
+
             while '\t' in lstruct[self.c] and self.stop is False:
-                if not 'for' in str(lstruct[self.c]).split() or 'if' in str(lstruct[self.c]).split():
-                    value= str(self.mdOWSTagStrList[self.c])
-                    str1+= '\t' + 'self.mdDescription['+str(self.c)+'].addValue('+str(value)+')\n'
-                    str1+= '\t' + 'self.cTmp='+str(self.c)+'\n'
-                    str1+= '\t' + 'it=MdItem(box,linfo[' + str(self.c) + '])\n'
-                    str1+= '\t' + 'it.setValue(' + str(value)+')\n'                         
-                    str1+= '\t' + 'self.boxItemList.append(it)\n'
-                    tab='\t'
+                if  'for' not in str(lstruct[self.c]).split()\
+                    and 'if' not in str(lstruct[self.c]).split():
+                    value = str(self.mdOWSTagStrList[self.c])
+                    str1 += '\t' + 'self.mdDescription[' + str(self.c) + '].addStatements("' + looptmp + '")\n'
+                    str1 += '\t' + 'self.cTmp=' + str(self.c) + '\n'
                     
-                else:                       #if loop in loop
-                    loop = lstruct[self.c]
-                    str2=loop.replace(' md.',' self.md.')+':\n'
+                    if box:
+                        str1 += '\t' + 'it=MdItem(box,linfo[' + str(self.c) + '])\n'
+                    else:
+                        str1 += '\t' + 'it=MdItem(self.nbPage,linfo[' + str(self.c) + '])\n' 
+                         
+                    if IFStatements:   
+                        str1 += '\t' + 'it.setValue(self.' + str(value) + ')\n'
+                    else: 
+                        str1 += '\t' + 'it.setValue(' + str(value) + ')\n'       
+                        
+                    str1 += '\t' + 'self.mdDescription[' + str(self.c) + '].addMdItem(it)\n'                                     
+                    str1 += '\t' + 'self.ItemList.append(it)\n'
+                    tab = '\t'
+                    
                     self.plusC()
-                    str1+=str2
-                    
+                else:  # if statements in statements
+                    statements = lstruct[self.c]
+                    str2 = ''
+                    keyword = False
+                    if '["keywords"]' in statements:
+                        keyword = True
+                        str2 += '\t' + 'self.keywordsList=[]\n'
+                        
+                    str2 += statements.replace(' md.', ' self.md.')
+                    looptmp1 = statements.replace(' md.', ' self.md.')
+                    str2 += ':\n'
+                    self.plusC()
+                    str1 += str2
                     while '\t\t' in lstruct[self.c] and self.stop is False:
-                        value= str(self.mdOWSTagStrList[self.c])
-                        str1+= '\t\t' +'self.mdDescription['+str(self.c)+'].addValue('+str(value)+')\n'
-                        str1+= '\t\t' +'self.cTmp='+str(self.c)+'\n'                         #save wx id
-                        str1+= '\t\t' + 'it=MdItem(box,linfo[' + str(self.c) + '])\n'
-                        str1+= '\t\t' + 'it.setValue(' + str(value)+')\n'                         
-                        str1+= '\t\t' + 'self.boxItemList.append(it)\n'
-                        tab='\t\t'   
                         
-                        self.plusC()
-                self.plusC()
-            self.c-=1 
-            str1+= tab+'box.addItems(self.boxItemList)\n'
-            str1+= tab+'self.nbPage.addItem(box)\n'   
-            str1+= tab+'self.plusC()\n'
+                        value = str(self.mdOWSTagStrList[self.c])
+                        # save information about loops
+                        str1 += '\t\t' + 'self.mdDescription[' + str(self.c) + "].addStatements('" + looptmp + "')\n"
+                        str1 += '\t\t' + 'self.mdDescription[' + str(self.c) + "].addStatements1('" + looptmp1 + "')\n" 
+                        str1 += '\t\t' + 'self.cTmp=' + str(self.c) + '\n'  # save wx id
+                        
+                        if box:
+                            str1 += '\t\t' + 'it=MdItem(box,linfo[' + str(self.c) + '])\n'
+                        else:
+                            str1 += '\t\t' + 'it=MdItem(self.nbPage,linfo[' + str(self.c) + '])\n'
+                            
+                        str1 += '\t\t' + 'it.setValue(' + str(value) + ')\n'  
+                        str1 += '\t\t' + 'self.ItemList.append(it)\n'
+                        if keyword:
+                            str1 += '\t\t' + 'self.keywordsList.append(it)\n'
+                            str1 += '\t' + 'self.mdDescription[' + str(self.c) + '].addMdItem(self.keywordsList)\n'
+                        else:
+                            str1 += '\t\t' + 'self.mdDescription[' + str(self.c) + '].addMdItem(it)\n'
+
+                        
+                        tab = '\t\t'   
+                         
+                        self.plusC() 
+
+            self.c -= 1 
             
-            self.executeStr(str1,linfo)
-   
-        #START of the looop of genereator
-        while self.stop is False: #self.stop is managed by   def plusC(self):
-#+ADD NOTEBOOK PAGE            
-            group=linfo[self.c].group
-            if group not in markgroup:          #if group is not created
-                markgroup.append(group)         #mark group
-                self.nbPage=NotebookPage(self.notebook)
-                self.notebook.AddPage(self.nbPage,linfo[self.c].group)
-#-ADD NOTEBOOK PAGE
+            if box:
+                str1 += tab + 'box.addItems(self.ItemList)\n'
+                str1 += tab + 'self.nbPage.addItem(box)\n'   
+            else:        
+                str1 += tab + 'self.nbPage.addItem(self.ItemList)\n'  
                  
-            if '\t' in lstruct[self.c]and self.stop is False: #if starting the loop
-                    inBox2()                
-                    chckLen()
+            str1 += tab + 'self.plusC()\n'
+            self.executeStr(str1, linfo)
+            
+#--------------------------------------------------------------------- INIT VARS
+        self.notebook = wx.Notebook(self)
+        markgroup = []  # notebok panel marker
+        lstruct = self.mdOWSTagStrList   
+        linfo = self.mdDescription  # from jinja      
+        self.c = 0  # this valus is the index of self.mdOWSTagStrList and also in self.mdDescription
+        self.stop = False
+        self.max = len(linfo)      
+        prepareStatements()
+#--------------------------------------------- #START of the looop of genereator        
+        while self.stop is False:  # self.stop is managed by   def plusC(self):
+            group = linfo[self.c].group
+    
+            if group not in markgroup:  # if group is not created
+                markgroup.append(group)  # mark group
+                self.nbPage = NotebookPage(self.notebook)
+                self.notebook.AddPage(self.nbPage, linfo[self.c].group)
+
+            if '\t' in lstruct[self.c]and self.stop is False:  # if starting the statements
+                    inBlock()                
                     
-            elif not 'for' in str(lstruct[self.c]).split() or 'if' in str(lstruct[self.c]).split(): # if just singe item without loop
-                    value= 'self.'+str(self.mdOWSTagStrList[self.c]).replace('\n','')
-                    addStr='self.mdDescription['+str(self.c)+'].addValue('+str(value)+')'
-                    self.executeStr(addStr,False)
+            elif   'for' not in str(lstruct[self.c]).split()\
+                    and 'if' not in str(lstruct[self.c]).split():  # if just singe item without statements
                     
-                    self.cTmp=self.c        
-                    item=MdItem(self.nbPage,linfo[self.c])
-                    item.setValue(eval(value))
-                        
-                    self.nbPage.addItem(item)    
+                    self.cTmp = self.c       
+                    it = MdItem(self.nbPage, linfo[self.c])
+                    value = 'self.' + str(self.mdOWSTagStrList[self.c]).replace('\n', '')
+                    it.setValue(eval(value))
+                    
+                    self.mdDescription[self.c].addMdItem(it)
+                    self.nbPage.addItem(it)  
                     self.plusC()
             else:
-
                 self.plusC()
 
+#----------------------------------------------------------- GUI GENERATOR END
+
 #------------------------------------------------------------------------ LAYOUT
     def _layout(self):
-        self.mainSizer=wx.BoxSizer(wx.VERTICAL)
+        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
         self.SetSizer(self.mainSizer)
         
-        noteSizer=wx.BoxSizer(wx.VERTICAL)
+        noteSizer = wx.BoxSizer(wx.VERTICAL)
         self.notebook.SetSizer(noteSizer)
-        self.mainSizer.Add(self.notebook,proportion=1,flag=wx.EXPAND)  
+        self.mainSizer.Add(self.notebook, proportion=1, flag=wx.EXPAND)  
+        but = wx.Button(self, id=ID_ANY, size=(20, 20), label='+')
+        but.Bind(EVT_BUTTON, self.createNewMD())
+        buts = wx.Button(self, id=ID_ANY, size=(20, 20), label='-')
+        buts.Bind(EVT_BUTTON, self.exportToXml)
+        self.mainSizer.Insert(0, but)
         self.Show()
- #-------------------------------------------------------------------------- INFO
+        
+    def executeStr1(self, stri, item):
+        print stri
+        exec stri         
+    
+    def exportToXml(self):
+        self.mdo.saveToXML(self.md)
+            
+    def createNewMD(self): 
+        def prepareStatements():
+            '''
+            @note: 
+            '''
+            for c in range(self.max):
+                if '|length' in str(mdDes[c].tag):
+                     a = mdDes[c].tag
+                     a = a.replace('|length', ')').replace('if ', 'if len(self.')
+                     mdDes[c].tag = a
+                if '|length' in str(mdDes[c].statements):
+                     a = mdDes[c].statements
+                     a = a.replace('|length', ')').replace('if ', 'if len(self.')
+                     mdDes[c].statements = a 
+                if '|length' in str(mdDes[c].statements1):
+                     a = mdDes[c].statements1
+                     a = a.replace('|length', ')').replace('if ', 'if len(self.')
+                     mdDes[c].statements1 = a                      
+                     
+                if 'zip(' in str(mdDes[c].tag):
+                    sta = str(mdDes[c ].statements)
+                    mdDes[c].tag = sta.replace('md.', 'self.md.')
+                if 'zip(' in str(mdDes[c].statements):
+                    sta = str(mdDes[c ].statements)
+                    mdDes[c].statements = sta.replace('md.', 'self.md.') 
+                if 'zip(' in str(mdDes[c].statements1):
+                    sta = str(mdDes[c ].statements1)
+                    mdDes[c].statements1 = sta.replace('md.', 'self.md.')                                                 
+        #=======================================================================
+        # def chckCondition(condition):
+        #     self.bool=False
+        #     if 'if' in condition.split():
+        #         condition+='\n\tself.bool=True'
+        #         self.executeStr1(condition, false)
+        #         return self.bool  
+        #=======================================================================
+        def chckIf1Statements():
+            try:
+                if md[self.c + 1].statement:
+                    return True
+                else:
+                    return False
+            except:
+                return False
+        def chckIf2xStatements():
+            if 'if'in  mdDes[self.c].tag.split()  or 'for'in  mdDes[self.c].tag.split():
+                try:
+                     if 'if'in  mdDes[self.c + 1].tag.split()  or 'for'in  mdDes[self.c + 1].tag.split():
+                         return True
+                     else:
+                        return False
+                except:
+                    return False    
+                       
+        def noneStatements():
+            '''Without condition or loop
+            '''
+            str1 = ''
+            for wxCtrl in mdDes[self.c].mdItem:
+                print "item"
+                if wxCtrl.getValue() != None:
+                    str1 += 'self.' + mdDes[self.c].tag + '="' + str(wxCtrl.getValue()) + '"\n'
+                    self.executeStr1(str1, mdDes[self.c])                         
+                    str1 = ''
+            self.plusC() 
+    
+        def inStatements():
+            '''possible combinations of statements
+            (1)    IF
+                        item
+                ----------------------------------------------------
+            (2)    for
+            (2.1)          item (with init OWSLib object)
+                       "or"
+            (2.2)          item (without init)
+            '''
+            cTmp = self.c
+            tag = str(mdDes[cTmp].tag).split()
+            
+            tag1 = 'self.' + str(tag[-1])
+            tag = 'self.' + str(tag[-1]) + '.append(self.val)\n'
+            print '---'
+            print mdDes[cTmp - 1].statements
+            print mdDes[cTmp - 1].tag
+            print '---'
+            self.plusC()
+            # statements of current item
+            stat = mdDes[self.c].statements
+
+            str1 = ''
+            # how many MdItem() is in object 
+            leng = len(mdDes[self.c].mdItem)
+            
+            # (2.1) IF NECESSARY TO INITIALIZE OWSLIB OBJECT
+            if mdDes[cTmp].object and 'if' not in mdDes[cTmp].tag.split() :
+                print 'init'
+                objStr = 'self.val=' + mdDes[cTmp].object + '\n'
+                for n in range(leng): 
+                    numOfItems = 0       
+                    str1 += objStr       
+                     
+                    while mdDes[self.c].statements == stat and self.stop is False:
+                        metadata = re.split(r'[.]', mdDes[self.c].tag)
+                        metadata[0] = 'self.val.'
+                        str1 += ''.join(metadata) + "='"\
+                             + str(mdDes[self.c].mdItem[n].getValue()) + "'\n"
+                        self.plusC()
+                        numOfItems += 1 
+                        
+                    str1 += tag
+                    self.executeStr1(str1, False) 
+                    str1 = ''
+                    self.c -= numOfItems
+                self.c += leng
+                
+            # (2.2)
+            elif 'for' in mdDes[cTmp].tag.split() and mdDes[cTmp].object == None:
+                
+                print 'no init'
+                leng = len(mdDes[self.c].mdItem)
+                for n in range(leng): 
+                    numOfItems = 0               
+                    while mdDes[self.c].statements == stat and self.stop is False:
+                        metadata = re.split(r'[.]', mdDes[self.c].tag)
+                        metadata[0] = 'self.val.'
+                        str1 += tag1 + ".append('" + mdDes[self.c].mdItem[n].getValue() + "')\n"
+                        #----------------------------------- !!!!!!!!!!!!!!!!!!! getval
+                        self.plusC()
+                        numOfItems += 1 
+                    self.executeStr1(str1, False) 
+                    str1 = ''
+                    self.c -= numOfItems
+                self.c += leng                
+            # (1)   
+            elif 'if' in mdDes[cTmp].tag.split():
+
+                print 'no init IF'
+                objStr = mdDes[cTmp].tag.replace(' md.', ' self.md.') + ':\n'
+
+                for n in range(leng): 
+                    numOfItems = 0       
+                    #str1 += objStr        
+                    while mdDes[self.c].statements == stat and self.stop is False:
+                        metadata = 'self.'+mdDes[self.c].tag
+                       
+                        str1 += ''.join(metadata) + "='"\
+                             + str(mdDes[self.c].mdItem[n].getValue()) + "'\n"
+                             
+                        self.plusC()
+                        numOfItems += 1
+                    self.c -= numOfItems
+                    self.executeStr1(str1, False) 
+                    str1 = ''
+                self.c += leng
+     
+      
+                          
+        def in2Statements():
+            '''possible combinations of statements
+            (1)    IF:
+                       FOR:
+            (1.1)           item (with init OWSLib object)
+                        "or"
+            (1.2)           item (without init)                    
+                ----------------------------------------------------
+            (2)     FOR:
+                        FOR:
+            (2.1)            item (with init OWSLib object)
+                        "or"
+            (2.2)            item (without init)                           
+            '''
+            prepareStatements()
+            cTmp = self.c 
+
+            cTmp1 = self.c + 1
+            tag = str(mdDes[cTmp].tag).split() 
+            tag1 = str(mdDes[cTmp1].tag).split()   
+            print '-'
+            print tag
+            print tag1
+            stat = mdDes[self.c + 2].statements
+            # how many MdItem() is in object 
+            append = 'self.' + str(tag1[-1]) + '.append(self.val)\n'
+            appendNoInit = 'self.' + str(tag1[-1])
+             # (1)
+            if 'if' in tag and 'for' in tag1:  # if 'if' in jinja=skip and do single loop
+                print 'iffor'
+                leng = len(mdDes[self.c + 2].mdItem)
+                print mdDes[self.c + 2].tag
+                # (1.1)
+                if mdDes[cTmp1].object:
+                    print "if and for in object"
+                    condition = mdDes[cTmp].tag.replace(' md.', ' self.md.') + ':\n'
+                    object = '\t' + 'self.val=' + mdDes[cTmp1].object + '\n'
+                    condition2 = '\t' + mdDes[cTmp1].tag.replace(' md.', ' self.md.') + ':\n'
+                    self.plusC()
+                    self.plusC()
+                    for n in range(leng): 
+                        numOfItems = 0  
+                        str1 = condition + '\n'
+                        str1 += condition2 + '\n'
+                        str1 += '\t' + object + '\n'     
+                        while mdDes[self.c].statements == stat and self.stop is False:
+                            metadata = re.split(r'[.]', mdDes[self.c].tag)
+                            metadata[0] = '\t\tself.val'
+                            str1 += ''.join(metadata) + "='"\
+                                 + str(mdDes[self.c].mdItem[n].getValue()) + "'\n"
+                            self.plusC()
+                            numOfItems += 1                                 
+                        str1 += '\t\t' + append 
+                        self.executeStr1(str1, False) 
+                        str1 = ''
+                        self.c -= numOfItems
+                    self.c += leng  
+                # (1.2)                      
+                else:
+                    print "if and for "
+                    condition = mdDes[cTmp].tag.replace(' md.', ' self.md.') + ':\n'
+                    condition2 = mdDes[cTmp1].tag.replace(' md.', ' self.md.') + ':\n'
+                    self.plusC()
+                    self.plusC()
+                    print mdDes[self.c].mdItem
+                    numOfkwGroup = len(mdDes[self.c].mdItem)
+                    print numOfkwGroup
+                    for n in range(numOfkwGroup): 
+                        numOfItems = 0  
+                        str1 = condition2 + '\n'
+                        print str1
+                        #print stat
+                        #print mdDes[self.c].statements
+                        while mdDes[self.c].statements == stat and self.stop is False:
+                            str1 += '\t\t' + appendNoInit + '.append(' + mdDes[self.c].mdItem[n].getValue() + ')\n'
+                            self.plusC()
+                            numOfItems += 1                                 
+                        self.executeStr1(str1, False) 
+                        str1 = ''
+                        self.c -= numOfItems-1
+                    self.c += numOfkwGroup    
+                    self.plusC()
+            # (2) only keywords  (dict)
+            elif 'for' in tag and 'for' in tag1:  #
+                print 'for-for statement'
+
+                
+                self.plusC()  # skip staementes 2x 
+                self.plusC()
+                loop2 = mdDes[self.c].statements1
+                loop1 = mdDes[self.c].statements
+                # var=loop2.find('[')
+                # var=loop2[var:].strip(' ')
+
+
+                numOfkwGroup = len(mdDes[self.c + 1].mdItem)
+                for n in range(numOfkwGroup):   
+                    kw = {}
+                    kw['keywords'] = []   
+                    # print '---'       
+                    for k in range(len(mdDes[self.c].mdItem[n])):
+                        kw['keywords'].append('"' + mdDes[self.c].mdItem[n][k].getValue() + '"')
+                        # print mdDes[self.c].mdItem[k]
+                   
+                    kw['type'] = None 
+                    kw['thesaurus'] = {}
+    
+                    kw['thesaurus']['title'] = '"' + mdDes[self.c + 1].mdItem[n].getValue() + '"'
+                    # print  mdDes[self.c+1].mdItem[n].getValue()   
+                    kw['thesaurus']['date'] = '"' + mdDes[self.c + 2].mdItem[n].getValue() + '"'
+                    # print  mdDes[self.c+2].mdItem[n].getValue()       
+                    kw['thesaurus']['datetype'] = '"' + mdDes[self.c + 3].mdItem[n].getValue() + '"'
+                    # print  mdDes[self.c+3].mdItem[n].getValue()           
+                    self.md.identification.keywords.append(kw)    
+                    # print '---'
+                    
+                self.plusC()
+                self.plusC()
+                self.plusC()
+                self.plusC()
+  
+
+
+        self.mdo = MD()
+        # TODO define this in flat file
+        self.md = self.mdo.initMD()
+        self.md.identification = MD_DataIdentification()
+        self.md.dataquality = DQ_DataQuality()
+        self.md.distribution = MD_Distribution()
+        self.md.identification.extent = EX_Extent()
+        self.md.identification.extent.boundingBox = EX_GeographicBoundingBox()
+        
+        statements = None
+        subLoop = None
+        initMDStr = None
+        self.c = 0                        
+        self.stop = False
+        self.max = len(self.mdDescription) 
+        mdDes = self.mdDescription
+        
+        while self.stop is False: 
+            
+            # if no statements
+            if mdDes[self.c].statements is None\
+                and 'if' not in mdDes[self.c].tag.split()\
+                and 'for' not in mdDes[self.c].tag.split():
+                #===============================================================
+                # print '0x statements'
+                # print mdDes[self.c].tag
+                # print mdDes[self.c].statements
+                # print mdDes[self.c].mdItem
+                #===============================================================
+                noneStatements()
+    
+            # if 2x statements        
+            elif  chckIf2xStatements():
+                print '2x statements'
+                in2Statements()
+                # break
+            elif  chckIf1Statements :  # if 1x statements
+                print '1x statements'
+                
+                inStatements()
+                
+            # print mdDes[self.c].statements
+            # self.plusC()   
+            print '=' * 50               
+
+            
+#===============================================================================
+# CREATE INFO
+#===============================================================================
 class MetadataUserInfo():
-    def __init__(self,item):
-        self.item=item
+    def __init__(self, item):
+        self.item = item
         self.createInfo()
     
     def createInfo(self):
-        string=''
+        string = ''
         if item.name != None:
-            string+='name: '+ item.name + '\n' 
+            string += 'name: ' + item.name + '\n' 
         if item.desc != None:
-            string+='description: ' + item.desc + '\n'
-        if item.example  != None:
-            string+='example: ' + item.example + '\n'   
+            string += 'description: ' + item.desc + '\n'
+        if item.example != None:
+            string += 'example: ' + item.example + '\n'   
         return string   
     
 #----------------------------------------------------------------------
@@ -310,4 +798,4 @@
     app = wx.App(False)
     frame = MainFrame()
     app.MainLoop()
-     
\ No newline at end of file
+     

Modified: sandbox/krejcmat/src/g.gui.metadata.py
===================================================================
--- sandbox/krejcmat/src/g.gui.metadata.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/g.gui.metadata.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -14,23 +14,18 @@
            for details.
 """
 
-import os
+# from grass.pygrass.gis import Mapset
 from lxml import etree as et
-
-#from grass.pygrass.gis import Mapset
-
-import wx
 from wx.lib.splitter import MultiSplitterWindow
-
+import wx
 import editor
-
 ########################################################################
 class MapTree(wx.Panel):
     def __init__(self, parent):    
         wx.Panel.__init__(self, parent)
         
         self.panel1 = wx.Panel(self, -1)
-        self.tree = wx.TreeCtrl(self.panel1, 1, wx.DefaultPosition, (-1,-1), wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)
+        self.tree = wx.TreeCtrl(self.panel1, 1, wx.DefaultPosition, (-1, -1), wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS)
         self.initMaps()
         self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)
         self._layout()
@@ -45,7 +40,7 @@
         self.Centre()
         
     def OnSelChanged(self, event):
-        item =  event.GetItem()
+        item = event.GetItem()
         self.display.SetLabel(self.tree.GetItemText(item))
  
     def initMaps(self):
@@ -65,7 +60,7 @@
             #---------------------------------- self.tree.AppendItem(vect, vmap)
             
             
-         self.tree = wx.TreeCtrl(self.panel1, wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)
+         self.tree = wx.TreeCtrl(self.panel1, wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS)
          root = self.tree.AddRoot('Programmer')
          os = self.tree.AppendItem(root, 'Operating Systems')
          self.tree.AppendItem(os, 'Linux')
@@ -87,14 +82,14 @@
         self.SetBackgroundColour(color)
 
 class TreeEditor(wx.TreeCtrl):
-    def __init__(self,parent):
-        wx.TreeCtrl.__init__(self, parent=parent,id=wx.ID_ANY, style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS)
+    def __init__(self, parent):
+        wx.TreeCtrl.__init__(self, parent=parent, id=wx.ID_ANY, style=wx.TR_HAS_BUTTONS | wx.TR_EDIT_LABELS)
         
-        self.parent=parent
-        self.fpath = os.path.join(os.path.dirname(__file__), 'series.xml')
+        self.parent = parent
+        self.fpath = '/home/matt/Dropbox/gsoc/gsoc2014-krejci/src/series.xml'
         self.xml = et.parse(self.fpath)
         
-        #wx.TreeCtrl(parent=self.parent,
+        # wx.TreeCtrl(parent=self.parent,
         root = self.fillmeup()
         self.Expand(root)
 
@@ -108,12 +103,12 @@
         root = tree.AddRoot(xml.tag)
         
         def add(parent, elem):
-            count=0                                                                         # do not make empty field after  <appointment> or <item> etc
+            # count=0 # do not make empty field after  <appointment> or <item> etc
             for e in elem:
-                if str(e).find("<!--")!=-1:     #skip comments
+                if str(e).find("<!--") != -1:  # skip comments
                     continue
                 tag = et.QName(e)
-                item = tree.AppendItem(parent, tag.localname, data = None)
+                item = tree.AppendItem(parent, tag.localname, data=None)
                 if e.text:
                     text = e.text.strip()
                 else:
@@ -121,7 +116,7 @@
                 if text:
                     val = tree.AppendItem(item, text)
                     tree.SetPyData(val, e)
-                    count+=1
+                    # count+=1
                 
                 add(item, e) 
         add(root, xml)
@@ -133,13 +128,13 @@
         print elm 
         if elm is not None:
             elm.text = evt.Label
-            self.xml.write(self.fpath, encoding="UTF-8",xml_declaration=True)
-            #self.validate()
+            self.xml.write(self.fpath, encoding="UTF-8", xml_declaration=True)
+            # self.validate()
             
     def OnClose(self, evt):
         self.Destroy()
         
-    def OnRClickAllChildren(self,evt):
+    def OnRClickAllChildren(self, evt):
         if not self.IsExpanded(evt.Item):
             self.ExpandAllChildren(evt.Item)
         else:
@@ -173,12 +168,12 @@
         def __init__(self, parent):
             wx.Panel.__init__(self, parent)
             
-            self.toolbar = wx.ToolBar(self, 1, wx.DefaultPosition,(-1,-1),  wx.NO_BORDER)
+            self.toolbar = wx.ToolBar(self, 1, wx.DefaultPosition, (-1, -1), wx.NO_BORDER)
             self.toolbar.AddSimpleTool(1, wx.Image('icon/create.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '')
             self.toolbar.AddSimpleTool(2, wx.Image('icon/open-trad.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Open', '')
             self.toolbar.AddSimpleTool(3, wx.Image('icon/save-trad.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Save', '')
             self.toolbar.AddSeparator()
-            #toolbar.AddSimpleTool(4, wx.Image('stock_exit.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Exit', '')
+            # toolbar.AddSimpleTool(4, wx.Image('stock_exit.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Exit', '')
             self.toolbar.Realize()
             
 
@@ -187,7 +182,7 @@
             self.Bind(wx.EVT_TOOL, self.OnNew, id=1)
             self.Bind(wx.EVT_TOOL, self.OnOpen, id=2)
             self.Bind(wx.EVT_TOOL, self.OnSave, id=3)
-            #self.Bind(wx.EVT_TOOL, self.OnExit, id=4)
+            # self.Bind(wx.EVT_TOOL, self.OnExit, id=4)
             
         def _layout(self):
             vbox = wx.BoxSizer(wx.VERTICAL)
@@ -206,15 +201,15 @@
 
 class NotebookRight(wx.Notebook):
     def __init__(self, parent):        
-        wx.Notebook.__init__(self, parent=parent,id=wx.ID_ANY, style=0)
-        #first panel
+        wx.Notebook.__init__(self, parent=parent, id=wx.ID_ANY, style=0)
+        # first panel
         self.notebook_panel1 = wx.Panel(self, wx.ID_ANY)
-        self.tree =  TreeEditor(self.notebook_panel1 )
+        self.tree = TreeEditor(self.notebook_panel1)
         
-        #second panel
-        self.notebook_panel2 =  wx.Panel(self, wx.ID_ANY, style=0)
+        # second panel
+        self.notebook_panel2 = wx.Panel(self, wx.ID_ANY, style=0)
 
-        #self.notebook_panel1.SetSizer(sizer_2)
+        # self.notebook_panel1.SetSizer(sizer_2)
         self.AddPage(self.notebook_panel1, "Tree editor")
         self.AddPage(self.notebook_panel2, "Help")
 
@@ -233,12 +228,12 @@
     def __init__(self):
         """Constructor"""
         wx.Frame.__init__(self, None, title="Metadata Editor",
-                          size=(1000,1000))
+                          size=(1000, 1000))
 
         splitter = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
         
         splitter.AppendWindow(MapTree(splitter))
-        splitter.AppendWindow(RandomPanel(splitter,'gray'))
+        splitter.AppendWindow(RandomPanel(splitter, 'gray'))
         splitter.AppendWindow(NotebookRight(splitter))   
 
         self.Show()

Modified: sandbox/krejcmat/src/jinjainfo.py
===================================================================
--- sandbox/krejcmat/src/jinjainfo.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/jinjainfo.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -14,99 +14,67 @@
            for details.
 """
 
-#from grass.pygrass.gis import Mapset
+# from grass.pygrass.gis import Mapset
 from lxml import etree as et
 import os
 from jinja2 import Environment, FileSystemLoader
 
 
-class OWSLibInfo():
-    def __init__(self):
-        self.mdMultiple=[]
-        self.mdSingle=[]
-        
-        #self.initSingle()
-        
-    def initSingle(self):
-        #=======================================================================
-        # self.mdSingle.append('identifier')
-        # self.mdSingle.append('parentidentifier')
-        # 
-        # self.mdSingle.append('language')
-        # self.mdSingle.append('dataseturi')
-        # self.mdSingle.append('languagecode')
-        # self.mdSingle.append('datestamp')
-        # self.mdSingle.append('charset')
-        # self.mdSingle.append('hierarchy')
-        # self.mdSingle.append('datetimestamp')
-        # self.mdSingle.append('stdver')
-        # self.mdSingle.append('stdname')
-        # self.mdSingle.append('referencesystem')
-        # self.mdSingle.append('parentidentifier')
-        # self.mdSingle.append('identification')
-        # self.mdSingle.append('serviceidentification')
-        #=======================================================================
-        pass
-        
-        
-
 class MdDescription():
-     def __init__(self,tag= None, name = None, desc = None, example = None, type = None, multi = 0, inboxmulti=None, group = None, inbox = None, multiline = None, value=[],id=[],num=None ):
-         
-         self.tag=tag
+     def __init__(self, tag=None, object=None, name=None, desc=None, example=None, type=None, multi=0, inboxmulti=None, group=None, inbox=None, multiline=None, num=None):
+         # ++info from jinja start
+         self.tag = tag
+         self.object = object
          self.name = name
          self.desc = desc
          self.example = example
          self.type = type
-         self.multiplicity = multi #multiplicity of MD item
+         self.multiplicity = multi  # multiplicity of MD item
          self.group = group
          self.inbox = inbox
-         self.inboxmulti=inboxmulti #multiplicity in subrotoup (in static box)
-         self.multiline=multiline       #type of ctrl text
-         self.num=num
-         self.value=list(value)
-         self.id=list(id)
+         self.inboxmulti = inboxmulti  # multiplicity in subrotoup (in static box)
+         self.multiline = multiline  # type of ctrl text
+         # --info from jinja -end
          
-         self.valueIndex=-1
-         self.idIndex=-1
-     
-     def addValue(self,value):
-         self.value.append(value)
-         self.valueIndex+=1
-         #print self.valueIndex 
+         self.statements = None
+         self.statements1 = None
+         self.num = num
+         self.mdItem = list()
+
+     def addMdItem(self, mditem):
+         '''list of objects MdItem()
+         '''
+         self.mdItem.append(mditem)
          
-     def addId(self,id):
-         self.id.append(id)
-         self.idIndex+=1
-     
-     def getId(self):
-         self.idIndex-=1
-         return self.id[self.idIndex]
-     
-     def getValue(self):
-         self.valueIndex-=1
-         return self.value[self.valueIndex]
+     def addStatements(self, stat):
+         if self.statements is None:
+             self.statements = stat
+             
+     def addStatements1(self, stat):
+         if self.statements1 is None:
+             self.statements1 = stat    
         
 class JinjaTemplateInfo():
-    def __init__(self,template):
+    def __init__(self, template):
         
-        self.mdDescription=[]     #list of object MdDescription
-        self.mdOWSTag=[]         #list of object in jinja template
-        self.template=template
+        self.mdDescription = []  # list of object MdDescription
+        self.mdOWSTag = []  # list of object in jinja template
+        self.template = template
         
-        self.mdOWSTagStr=''
-        self.mdOWSTagStrList=[] 
-        #self.mdDescriptionStr=''
+        self.mdOWSTagStr = ''
+        
+        self.mdOWSTagStrList = [] 
+        # self.mdDescriptionStr=''
           
         self._readJinjaInfo()
         self._readJinjaTags()
         self._domdOWSTagStr()
         
 
-    def cretemdDescriptionDict(self,akey):
-        box={}
+    def cretemdDescriptionDict(self, akey):
+        box = {}
         for md in self.mdDescription:
-            skey='md.'+str(akey)
+            skey = 'md.' + str(akey)
            # print skey
             key = eval(skey)
             if key is not None:
@@ -117,67 +85,68 @@
     
    
     def _domdOWSTagStr(self):
-        self.mdOWSTagStr=""
-        tab=0
+        self.mdOWSTagStr = ""
+        tab = 0
         for item in self.mdOWSTag:
             if str(item).find(" endfor ") != -1 or \
                     str(item).find(" endif ") != -1 or \
                     str(item).find(" endwhile ") != -1:
-                tab-=1
+                tab -= 1
                 continue
             
-            tabstr='\t'*tab
-            str1=tabstr + item[1:] + '\n' 
-            self.mdOWSTagStr+=str1
+            tabstr = '\t' * tab
+            str1 = tabstr + item[1:] + '\n' 
+            self.mdOWSTagStr += str1
             self.mdOWSTagStrList.append(tabstr + item[1:])
             
             if str(item).find(" for ") != -1 or \
                     str(item).find(" if ") != -1 or \
                     str(item).find(" while ") != -1:
-                tab+=1
+                tab += 1
                 
     def _readJinjaTags(self):
             try:
-                with open( self.template, "r") as f:
+                with open(self.template, "r") as f:
                     for line in f:
 
-                        if str(line).find("{{")!=-1:#if found start of comments
-                            object = self._findBetween(line,"{{","}}")
+                        if str(line).find("{{") != -1:  # if found start of comments
+                            object = self._findBetween(line, "{{", "}}")
                             self.mdOWSTag.append(object)
                                 
-                        if str(line).find("{%")!=-1:
-                            object = self._findBetween(line,"{%","-%}")
+                        if str(line).find("{%") != -1:
+                            object = self._findBetween(line, "{%", "-%}")
                             self.mdOWSTag.append(object)
                                    
             except IOError as e:
                 print "I/O error({0}): {1}".format(e.errno, e.strerror)
 
     def _readJinjaInfo(self):
-            #template = 'data/grassBasicISOTemplate01.xml'
-            counter=1
+            # template = 'data/grassBasicISOTemplate01.xml'
+            counter = 1
             
             try:
-                with open( self.template, "r") as f:
+                with open(self.template, "r") as f:
                     for line in f:
 
-                            if str(line).find("{#")!=-1:#if found start of comments
+                            if str(line).find("{#") != -1:  # if found start of comments
                                 
-                                #print 'num' + str(counter)
-                                values = self._findBetween(line,"{#","#}")
-                                values+=',num='+str(counter)
-                                exe_str = "self.mdDescription.append(MdDescription(%s))"%values
+                                # print 'num' + str(counter)
+                                values = self._findBetween(line, "{#", "#}")
+                                values += ',num=' + str(counter)
+                                # print values
+                                exe_str = "self.mdDescription.append(MdDescription(%s))" % values
    
                                 eval(exe_str)
-                                counter+=1
+                                counter += 1
             except IOError as e:
                 print "I/O error({0}): {1}".format(e.errno, e.strerror)
     
 
     
-    def _findBetween(self, s, first, last ):
+    def _findBetween(self, s, first, last):
         try:
-            start = s.index( first ) + len( first )
-            end = s.index( last, start )
+            start = s.index(first) + len(first)
+            end = s.index(last, start)
             return s[start:end]
         except ValueError:
             return ""        
@@ -251,4 +220,32 @@
 #         self.grupedList=finalList
 #         return  finalList
 #===============================================================================
-            
+ #==============================================================================
+ # class OWSLibInfo():
+ #    def __init__(self):
+ #        self.mdMultiple=[]
+ #        self.mdSingle=[]
+ #        
+ #        #self.initSingle()
+ #        
+ #    def initSingle(self):
+ #        #=======================================================================
+ #        # self.mdSingle.append('identifier')
+ #        # self.mdSingle.append('parentidentifier')
+ #        # 
+ #        # self.mdSingle.append('language')
+ #        # self.mdSingle.append('dataseturi')
+ #        # self.mdSingle.append('languagecode')
+ #        # self.mdSingle.append('datestamp')
+ #        # self.mdSingle.append('charset')
+ #        # self.mdSingle.append('hierarchy')
+ #        # self.mdSingle.append('datetimestamp')
+ #        # self.mdSingle.append('stdver')
+ #        # self.mdSingle.append('stdname')
+ #        # self.mdSingle.append('referencesystem')
+ #        # self.mdSingle.append('parentidentifier')
+ #        # self.mdSingle.append('identification')
+ #        # self.mdSingle.append('serviceidentification')
+ #        #=======================================================================
+ #        pass           
+ #==============================================================================

Modified: sandbox/krejcmat/src/mdgrass.py
===================================================================
--- sandbox/krejcmat/src/mdgrass.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/mdgrass.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -2,11 +2,13 @@
 # -*- coding: utf-8
 
 """
+MODULE:    v.info.iso, r.info.iso
+
 AUTHOR(S): Matej Krejci <matejkrejci gmail.com>
 
-PURPOSE:   Library for creating ISO metadata for GRASS GIS
+PURPOSE:   Module for creating metadata based on ISO
 
-COPYRIGHT: (C) 2007 Matej Krejci, and by the GRASS Development Team
+COPYRIGHT: (C) 2014 Matej Krejci, and by the GRASS Development Team
 
            This program is free software under the GNU General Public
            License (>=v2). Read the file COPYING that comes with GRASS
@@ -25,8 +27,8 @@
 from grass.pygrass.modules import Module
 from grass.script import parse_key_val
 from subprocess import PIPE
-from datetime import date,datetime
-import getpass # whoami for linux and  ms-win
+from datetime import date, datetime
+import getpass  # whoami for linux and  ms-win
 from grass.script import parser
 from grass.script import core as grass
 import StringIO
@@ -36,24 +38,24 @@
 class GrassMD():
     def __init__(self, map, type):
 
-        self.map = map                    #name of choosen map by user
-        self.type = type                  #typ of map representation(cell, vector, r3)
-        self.isMapExist()                 #function to check if map exist
-        self.md_grass = {}                #dict with metadata from r.info v.info  except "r.info flag=h"        
-        self.md_abstract = ''             #create abstract from self.md_grass - key: source1, source2 and descriptio etc.
-        self.md_vinfo_h = ''              #v.info flag=h" - parse
-        self.gisenv_grass = grass.gisenv()#dict with gisenv information
-        self.schema_type='_md_GRASS.xml'  #postfix of output xml file (variables)
+        self.map = map  # name of choosen map by user
+        self.type = type  # typ of map representation(cell, vector, r3)
+        self.isMapExist()  # function to check if map exist
+        self.md_grass = {}  # dict with metadata from r.info v.info  except "r.info flag=h"        
+        self.md_abstract = ''  # create abstract from self.md_grass - key: source1, source2 and descriptio etc.
+        self.md_vinfo_h = ''  # v.info flag=h" - parse
+        self.gisenv_grass = grass.gisenv()  # dict with gisenv information
+        self.schema_type = '_md_GRASS.xml'  # postfix of output xml file (variables)
         self.dirpath = os.path.dirname(os.path.realpath(__file__))
-        self.md = MD_Metadata(md=None)            #metadata object from OWSLIB ( for define md values)
-        self.template = None               #path to file with xml templates
+        self.md = MD_Metadata(md=None)  # metadata object from OWSLIB ( for define md values)
+        self.template = None  # path to file with xml templates
         
         if self.type == "cell":
             self.parseRast()
         elif self.type == "vector":
             self.parseVect()
         elif self.type == "r3??":
-            #TODO   
+            # TODO   
             self.parseRast3D()
             
             
@@ -63,7 +65,7 @@
         if not self.mapset:
             grass.fatal(_("Map <%s> doesn't exist"), self.map)
                    
-    def readXML(self,xml_file):
+    def readXML(self, xml_file):
         '''create instance of metadata(owslib) from xml file'''
         self.md = MD_Metadata(etree.parse(xml_file))
         
@@ -74,12 +76,12 @@
         '''Read metadata from v.info
         #self.md_grass dictionary of metadata from v.info '''
         
-        #parse md from v.info flags=-g -e -t
-        vinfo = Module('v.info', self.map, flags='get', quiet = True, stdout_=PIPE)
+        # parse md from v.info flags=-g -e -t
+        vinfo = Module('v.info', self.map, flags='get', quiet=True, stdout_=PIPE)
         self.md_grass = parse_key_val(vinfo.outputs.stdout)
         
-        #parse md from v.info flag h (history of map in grass)
-        rinfo_h = Module('v.info', self.map, flags='h', quiet = True, stdout_=PIPE)
+        # parse md from v.info flag h (history of map in grass)
+        rinfo_h = Module('v.info', self.map, flags='h', quiet=True, stdout_=PIPE)
         md_h_grass = rinfo_h.outputs.stdout
         buf = StringIO.StringIO(md_h_grass)
         line = buf.readline().splitlines()
@@ -89,8 +91,8 @@
             line = buf.readline().splitlines()
         buf.close()
         
-        #change grass generated date format to iso format
-        #if date format is diverse from standard, use them
+        # change grass generated date format to iso format
+        # if date format is diverse from standard, use them
         self._createISODate('source_date')
             
     def _createISODate(self, key):
@@ -109,80 +111,32 @@
         #self.md_grass       dictionary of metadata from v.info 
         #self.md_abstract    string created by merge information from 'description' and 'source'
         '''
-        rinfo = Module('r.info', self.map, flags='gre', quiet = True, stdout_=PIPE)
+        rinfo = Module('r.info', self.map, flags='gre', quiet=True, stdout_=PIPE)
         self.md_grass = parse_key_val(rinfo.outputs.stdout)
                    
-        #convert date to iso format
+        # convert date to iso format
         self._createISODate('date')
             
-        #create abstract
+        # create abstract
         if self.md_grass['description'] != '""':
             self.md_abstract = self.md_grass['description'] + '\n'
         if self.md_grass['source1'] != '""':
             self.md_abstract += self.md_grass['source1'] + '\n'
         if self.md_grass['source2'] != '""':
-            self.md_abstract += self.md_grass['source2'] +'\n'
-        self.md_abstract += 'Total cells: '+ self.md_grass['cells']
+            self.md_abstract += self.md_grass['source2'] + '\n'
+        self.md_abstract += 'Total cells: ' + self.md_grass['cells']
         self.md_abstract += 'A range of values: min: ' + self.md_grass['min'] + '  max: ' + self.md_grass['max']
-        
 
-    def createGrassInspireISO(self):
-        '''Create valid INSPIRE profile and fill it as much as possible by GRASS metadata. Missing values is $NULL
-        -create basic md profile and add INSPIRE mandatory attributes
-        '''
-        
-        self.schema_type= '_md_INSPIRE.xml'
-        #create basic profile
-        self.createGrassBasicISO() 
-        self.template = 'data/grassInspireTemplate.xml'
-       
-        n = '$NULL'
-        self.md.datestamp = n
-        # Classification/Topic Category
-        self.md.identification.topiccategory.append(n)
-        self.md.identification.resourcelanguage.append(n)
-        
-        # Keyword/Keyword 
-        kw = {}
-        kw['keywords'] = []
-        kw['keywords'].append(n)
-        kw['keywords'].append(n)
-        kw['type'] = None
-        kw['thesaurus'] = {}
-        kw['thesaurus']['date'] = n
-        kw['thesaurus']['datetype'] = n
-        kw['thesaurus']['title'] = n
-        self.md.identification.keywords.append(kw)
-        # Conformity/Title 
-        self.md.dataquality.conformancetitle.pop() #remove value from basic profile
-        self.md.dataquality.conformancetitle.append('Commission Regulation (EU) No 1089/2010 of 23 November 2010 implementing Directive 2007/2/EC of the European Parliament and of the Council as regards interoperability of spatial data sets and services')
-        
-        # Conformity/Date 
-        self.md.dataquality.conformancedate.append(n)
-        self.md.dataquality.conformancedatetype.append(n)
-    
-         # Conformity/Degree 
-        self.md.dataquality.conformancedegree.append(n)
-        
-        # Constraints/Limitations on public access
-        self.md.identification.accessconstraints.append(n)
-        self.md.identification.otherconstraints.append(n)
-        
-        # Constraints/Conditions for access and use-general 
-        self.md.identification.uselimitation.append(n)
-        # Temporal/Temporal Extent 
-        self.md.identification.temporalextent_start = n
-        self.md.identification.temporalextent_end = n
-        
     def createGrassBasicISO(self):
         '''Create basic/essential profile based on ISO
-        - unknown values fill in by n = '$NULL'
+        - unknown values are filling by n = '$NULL'
         '''
         
         n = '$NULL'
-        #jinja templates
+        # jinja templates
         self.template = 'data/grassBasicISOTemplate.xml'
-        #OWSLib md object 
+        
+        # OWSLib md object 
         self.md.identification = MD_DataIdentification()
         self.md.dataquality = DQ_DataQuality()
         self.md.distribution = MD_Distribution()
@@ -203,24 +157,25 @@
         
         # Identification/Resource Locator 
         val = CI_OnlineResource()
-        val.url =n = '$NULL'
+        val.url = n 
         self.md.distribution.online.append(val)
         
         # Identification/Resource Type 
         self.md.identification.identtype = 'dataset'
         
         # Identification/Unique Resource Identifier 
-        #TODO GENERATOR
         self.md.identifier = n 
         self.md.identification.uricode.append(n)
         
-        #Geographic/BB
+        # Geographic/BB
         self.md.identification.extent.boundingBox.minx = self.md_grass['south']
         self.md.identification.extent.boundingBox.maxx = self.md_grass['north']
         self.md.identification.extent.boundingBox.miny = self.md_grass['west']
         self.md.identification.extent.boundingBox.maxy = self.md_grass['east']
+        
         # Conformity/Title 
         self.md.dataquality.conformancetitle.append('GRASS basic metadata profile based on ISO 19115, 19139')
+        
         # Conformity/Date:
         self.md.dataquality.conformancedate.append(date.today().isoformat())
         self.md.dataquality.conformancedatetype.append('publication')
@@ -231,13 +186,14 @@
         val.type = 'creation'
         self.md.identification.date.append(val)
 
-        #different metadata sources for vector and raster 
+        # different metadata sources for vector and raster 
         if self.type == 'cell':
             # Identification/Resource Abstract 
             self.md.identification.abstract = self.md_abstract
-            #Geographic/resolution
+            
+            # Geographic/resolution
             self.md.identification.uom.append(' ')
-            self.md.identification.distance.append(self.md_grass['nsres'])      #TODO for discuss
+            self.md.identification.distance.append(self.md_grass['nsres'])  # TODO for discuss
 
             # Quality/Lineage
             self.md.dataquality.lineage = self.md_grass['comments']
@@ -250,7 +206,7 @@
             
         if self.type == 'vector':
             # Identification/Resource Abstract 
-            self.md.identification.abstract = self.md_grass['name']  #TODO not enough sources for crate abstarce 
+            self.md.identification.abstract = self.md_grass['name']  # TODO not enough sources for crate abstarce 
             self.md.dataquality.lineage = self.md_vinfo_h
             
             # Organisation/Responsible Party:
@@ -258,36 +214,91 @@
             val.organization = self.md_grass['creator']
             val.role = 'owner'
             self.md.identification.contact.append(val)
+        
 
-    def saveXML(self, path = None, xml_out_name = None):
+    def createGrassInspireISO(self):
+        '''Create valid INSPIRE profile and fill it as much as possible by GRASS metadata. Missing values is $NULL
+        -create basic md profile and add INSPIRE mandatory attributes
+        '''
+        
+        self.schema_type = '_md_INSPIRE.xml'
+        
+        # create basic profile
+        self.createGrassBasicISO() 
+        self.template = 'data/grassInspireTemplate.xml'
+       
+        n = '$NULL'
+        self.md.datestamp = n
+        
+        # Classification/Topic Category
+        self.md.identification.topiccategory.append(n)
+        self.md.identification.resourcelanguage.append(n)
+        
+        # Keyword/Keyword 
+        kw = {}
+        kw['keywords'] = []
+        kw['keywords'].append(n)
+        kw['keywords'].append(n)
+        
+        kw['type'] = None
+        kw['thesaurus'] = {}
+        kw['thesaurus']['date'] = n
+        kw['thesaurus']['datetype'] = n
+        kw['thesaurus']['title'] = n
+        self.md.identification.keywords.append(kw)
+        
+        # Conformity/Title 
+        self.md.dataquality.conformancetitle.pop()  # remove value from basic profile
+        self.md.dataquality.conformancetitle.append('Commission Regulation (EU) No 1089/2010 of 23 November 2010 implementing Directive 2007/2/EC of the European Parliament and of the Council as regards interoperability of spatial data sets and services')
+        
+        # Conformity/Date 
+        self.md.dataquality.conformancedate.append(n)
+        self.md.dataquality.conformancedatetype.append(n)
+    
+         # Conformity/Degree 
+        self.md.dataquality.conformancedegree.append(n)
+        
+        # Constraints/Limitations on public access
+        self.md.identification.accessconstraints.append(n)
+        self.md.identification.otherconstraints.append(n)
+        
+        # Constraints/Conditions for access and use-general 
+        self.md.identification.uselimitation.append(n)
+        
+        # Temporal/Temporal Extent 
+        self.md.identification.temporalextent_start = n
+        self.md.identification.temporalextent_end = n
+        
+
+    def saveXML(self, path=None, xml_out_name=None):
         ''' Save custom record to ISO XML file''' 
         
-        #if  output file name is None, use map name and add postfix
+        # if  output file name is None, use map name and add postfix
         if xml_out_name is None:
             xml_out_name = str(self.map) + self.schema_type
         if not xml_out_name.lower().endswith('.xml'):
-            xml_out_name +='.xml'
-        #if path is None, use lunch. dir
-        #TODO change default folder to mapset location
+            xml_out_name += '.xml'
+        # if path is None, use lunch. dir
+        # TODO change default folder to mapset location
         if not path:
-            path = os.path.join(self.dirpath,xml_out_name)
+            path = os.path.join(self.dirpath, xml_out_name)
         else:
-            path = os.path.join(path,xml_out_name)
+            path = os.path.join(path, xml_out_name)
 
-        #generate xml using jinja tempaltes
-        env = Environment(loader = FileSystemLoader(self.dirpath))
+        # generate xml using jinja tempaltes
+        env = Environment(loader=FileSystemLoader(self.dirpath))
         env.globals.update(zip=zip)
         template = env.get_template(self.template)
         iso_xml = template.render(md=self.md)
         xml_file = xml_out_name
         
-        #write xml to flat file
+        # write xml to flat file
         try:
             xml_file = open(path, "w")
             xml_file.write(iso_xml)
             xml_file.close()
             Module('g.message', message='metadata exported: \n\
-                                         %s'%(str(path)))
+                                         %s' % (str(path)))
         except IOError as e:
             print "I/O error({0}): {1}".format(e.errno, e.strerror)
             grass.fatal('error: cannot write xml file')

Modified: sandbox/krejcmat/src/r.info.iso.py
===================================================================
--- sandbox/krejcmat/src/r.info.iso.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/r.info.iso.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -52,18 +52,18 @@
     if not options['mdout']:
         mdout = None
     else:
-        mdout=options['mdout']    
+        mdout = options['mdout']    
   
   
     md = GrassMD(options['map'], 'cell')        
-    if options['profil']=='inspire':
+    if options['profil'] == 'inspire':
         md.createGrassInspireISO()
-        xml_file=md.saveXML(destination,mdout)
+        xml_file = md.saveXML(destination, mdout)
         md.readXML(xml_file)
         print md.validate_inspire()
     else:    
         md.createGrassBasicISO()
-        md.saveXML(destination,mdout)
+        md.saveXML(destination, mdout)
     
 
 if __name__ == "__main__":

Modified: sandbox/krejcmat/src/v.info.iso.py
===================================================================
--- sandbox/krejcmat/src/v.info.iso.py	2014-07-14 19:03:34 UTC (rev 61255)
+++ sandbox/krejcmat/src/v.info.iso.py	2014-07-15 13:37:55 UTC (rev 61256)
@@ -51,19 +51,19 @@
     if not options['mdout']:
         mdout = None
     else:
-        mdout=options['mdout']   
+        mdout = options['mdout']   
     
-    #create instance of metadata in owslib
+    # create instance of metadata in owslib
     md = GrassMD(options['map'], 'vector') 
            
-    if options['profil']=='inspire':
+    if options['profil'] == 'inspire':
         md.createGrassInspireISO()
-        xml_file=md.saveXML(options['destination'],options['mdout'])
+        xml_file = md.saveXML(options['destination'], options['mdout'])
         md.readXML(xml_file)
         print md.validate_inspire()
     else:    
         md.createGrassBasicISO()
-        md.saveXML(options['destination'],options['mdout'])
+        md.saveXML(options['destination'], options['mdout'])
     
 if __name__ == "__main__":
     options, flags = parser()



More information about the grass-commit mailing list