Index: /branches/amp_3_7/extensions/license_server/webui/model/cm_device/__init__.py
===================================================================
--- /branches/amp_3_7/extensions/license_server/webui/model/cm_device/__init__.py	(revision 2447)
+++ /branches/amp_3_7/extensions/license_server/webui/model/cm_device/__init__.py	(working copy)
@@ -392,8 +392,7 @@
                             each['version'] = rest_body['data']['version']
                             each['connection'] = 'connected'
                     else:
-                        msg.append('device "%s" response error.')
-
+                        msg.append('device "%s" response error.' % rest_response_data['body'])
                 save_sql = "INSERT INTO device2(\
                     id, \
                     ip, \
Index: /branches/amp_3_7/src/webui/webui/htdocs/new/src/cm/router.py
===================================================================
--- /branches/amp_3_7/src/webui/webui/htdocs/new/src/cm/router.py	(revision 2447)
+++ /branches/amp_3_7/src/webui/webui/htdocs/new/src/cm/router.py	(working copy)
@@ -201,7 +201,7 @@
     device_id = request.POST["device_id"]
 
     db = DB.get_connected_db()
-    fetchall_sql = "SELECT version FROM vpn_device WHERE id = '%s'" % device_id
+    fetchall_sql = "SELECT version FROM device2 WHERE id = '%s'" % device_id
     version = db.fetchall(fetchall_sql)
     db.close()
 
@@ -217,7 +217,7 @@
     auto_mode = False
 
     db = DB.get_connected_db()
-    fetchall_sql = "SELECT auto_enable FROM vpn_cm_settings"
+    fetchall_sql = "SELECT auto_enable FROM cm_settings"
     auto_mode = db.fetchall(fetchall_sql)
     db.close()
 
@@ -233,7 +233,7 @@
 
     try:
         db = DB.get_connected_db()
-        update_sql = "UPDATE vpn_cm_settings SET auto_enable = %d" % (1 if auto_mode else 0)
+        update_sql = "UPDATE cm_settings SET auto_enable = %d" % (1 if auto_mode else 0)
         db.execute_sql(update_sql)
         db.close()
         state = True
Index: /branches/amp_3_7/src/webui/webui/htdocs/new/src/hive/model/rest.py
===================================================================
--- /branches/amp_3_7/src/webui/webui/htdocs/new/src/hive/model/rest.py	(revision 2447)
+++ /branches/amp_3_7/src/webui/webui/htdocs/new/src/hive/model/rest.py	(working copy)
@@ -1,15 +1,15 @@
 import sys
 import os
 import commands
-from hive.model.loading import get_app, get_model
+from hive.model.loading import get_app
 from hive.model.query import mark_expire_one
 from django.http import Http404, HttpResponse
 import json
-from hive.exceptions import ValidationError, ModelQueryException, ActionPerformException, FieldDoesNotExist, ManagerImplError, RestfulException
+from hive.exceptions import ValidationError, ModelQueryException, ActionPerformException, FieldDoesNotExist, \
+    ManagerImplError, RestfulException
 import copy
 import time
 from hive.utils import HiveEnvironment, andebug, url2obj, IntRange
-from hive.model.utils import reduce_asso_value_item, get_complex_field, normalize_asso_value, get_value_asso_idx
 import urllib
 from django.utils.translation import ugettext_lazy as _
 import tools.dicttoxml as dicttoxml
@@ -21,12 +21,15 @@
 import sched
 from cm.lib.postgres_db import DB
 from cm.lib.activation_server import ActivationServer
+
 try:
     from hive.model.stats import *
+
     exec "from %s.rest import *" % current_app()
 except:
     pass
 
+
 class ModelRESTResource(object):
     def __init__(self, request, session, app, model, method, action_name, meta):
         self.request = request
@@ -46,13 +49,13 @@
         else:
             msg = {'msg': unicode(_('The request method is not supported.'))}
             raise RestfulException(msg, 501)
- 
-    def serialize(self, rtn_dict):#python dict to xml or json
+
+    def serialize(self, rtn_dict):  # python dict to xml or json
         if 'HTTP_ACCEPT' in self.request.META:
             re_format = self.request.META['HTTP_ACCEPT']
             if "application/xml" in re_format:
                 xml = dicttoxml.dicttoxml(rtn_dict, attr_type=False, custom_root='rest')
-                #Pretty-Printing
+                # Pretty-Printing
                 dom = parseString(xml)
                 serialized_data = dom.toprettyxml()
             else:
@@ -61,7 +64,7 @@
             serialized_data = json.dumps(rtn_dict, indent=4)
         return serialized_data
 
-    def deserialize(self):#json or xml to python dict
+    def deserialize(self):  # json or xml to python dict
         rtn_dict = {}
         request_str = self.request.raw_post_data
         if request_str:
@@ -69,7 +72,7 @@
                 re_format = self.request.META['HTTP_ACCEPT']
                 if "application/xml" in re_format:
                     try:
-                        #get a OrderedDict
+                        # get a OrderedDict
                         rtn_dict = xmltodict.parse(request_str)["rest"]
                     except:
                         msg = {'msg': unicode(_('Invalid xml format!'))}
@@ -90,41 +93,43 @@
         return rtn_dict
 
     def GET(self, **kwargs):
-        #two cases:
+        # two cases:
         # 1- Query instances (filter supported)
         # 2- Query model metadata
         if self.meta:
             rtn = {}
-            #get metadata
-            rtn['meta'] = {'abstract':self.model._meta.abstract, 'verbose_name':self.model._meta.verbose_name}
-            #get field groups
+            # get metadata
+            rtn['meta'] = {'abstract': self.model._meta.abstract, 'verbose_name': self.model._meta.verbose_name}
+            # get field groups
             rtn['fieldgroups'] = []
             for group_name, field_group in self.model._meta.field_groups.iteritems():
                 field_list = []
                 for field in field_group.fields:
-                    field_list.append({'field_name':field.name, 'verbose_name':unicode(field.verbose_name)})
-                rtn['fieldgroups'].append({'group_name':group_name, 'fields':field_list})
-            #get subclasses               
+                    field_list.append({'field_name': field.name, 'verbose_name': unicode(field.verbose_name)})
+                rtn['fieldgroups'].append({'group_name': group_name, 'fields': field_list})
+            # get subclasses
             if self.model._meta.children:
                 rtn['subclasses'] = []
                 for key, val in self.model._meta.children.iteritems():
                     child_class_name = key.__name__
                     child_verbose_name = key._meta.verbose_name
-                    rtn['subclasses'].append({'class_name':child_class_name, 'verbose_name': child_verbose_name})
+                    rtn['subclasses'].append({'class_name': child_class_name, 'verbose_name': child_verbose_name})
         else:
             args = dict(kwargs)
             if args:
                 qs = self.manager.filter(args)
             else:
                 qs = self.manager.all()
-            
+
             rtn = []
             for each in qs:
                 try:
                     each_rtn = each.get_rest_field_dict(withstats=False, group='default')
                 except KeyError:
-                    groups_str = ', '.join([group_name for group_name in self.model._meta.field_groups.keys() if group_name != 'default'])
-                    msg = {'msg': unicode(_('No default field group. Please use field group: %s to query.')) %groups_str}
+                    groups_str = ', '.join(
+                        [group_name for group_name in self.model._meta.field_groups.keys() if group_name != 'default'])
+                    msg = {
+                        'msg': unicode(_('No default field group. Please use field group: %s to query.')) % groups_str}
                     raise RestfulException(msg, 404)
                 if each.pk_id():
                     instance_id_dict = {'instance_id': each.pk_id()}
@@ -133,11 +138,11 @@
             if not rtn:
                 msg = {'msg': unicode(_('The object is not found.'))}
                 raise RestfulException(msg, 404)
-        rtn_dict = {self.model._meta.object_name:rtn}
+        rtn_dict = {self.model._meta.object_name: rtn}
         return self.serialize(rtn_dict)
 
     def POST(self, **kwargs):
-        #three cases:
+        # three cases:
         # 1- Add an instance
         # 2- Perform a profile model action
         # 3- Perform a non-profile model action
@@ -166,8 +171,9 @@
                     json_dict['__pk_list'] = ['']
                 if 'asso_targets' in json_dict:
                     asso_targets_id = json_dict['asso_targets']
-                    #get asso model first
-                    asso_field = self.model._meta.get_field(self.model._meta.get_action_by_name(self.action_name).related)
+                    # get asso model first
+                    asso_field = self.model._meta.get_field(
+                        self.model._meta.get_action_by_name(self.action_name).related)
                     asso_model = asso_field.target_end[0].model
                     if type(asso_targets_id) in (str, unicode):
                         asso_pk_list = asso_model._meta.targets_id_to_pk_list(asso_targets_id, True)
@@ -184,7 +190,7 @@
                 else:
                     json_dict['__asso_pk_list'] = ['']
             else:
-                json_dict = {'__pk_list':[''], '__asso_pk_list':['']}
+                json_dict = {'__pk_list': [''], '__asso_pk_list': ['']}
 
             try:
                 msg = self.manager.perform_action(self.action_name, json_dict)
@@ -219,7 +225,7 @@
             try:
                 new_obj.clean_fields()
             except ValidationError, e:
-                msg = {'msg': unicode(_('Fields validate failed: %s.')) % str(e) }
+                msg = {'msg': unicode(_('Fields validate failed: %s.')) % str(e)}
                 raise RestfulException(msg, 400)
             try:
                 concrete_manager.insert(new_obj)
@@ -241,6 +247,7 @@
             rtn_dict[self.model._meta.object_name] = rtn
         return self.serialize(rtn_dict)
 
+
 class InstanceRESTResource(object):
     def __init__(self, request, session, app, model, method, instance_id, attribute, action_name, target_id):
         self.request = request
@@ -285,12 +292,12 @@
             msg = {'msg': unicode(_('The request method is not supported.'))}
             raise RestfulException(msg, 501)
 
-    def serialize(self, rtn_dict):#python dict to xml or json
+    def serialize(self, rtn_dict):  # python dict to xml or json
         if 'HTTP_ACCEPT' in self.request.META:
             re_format = self.request.META['HTTP_ACCEPT']
             if "application/xml" in re_format:
                 xml = dicttoxml.dicttoxml(rtn_dict, attr_type=False, custom_root='rest')
-                #Pretty-Printing
+                # Pretty-Printing
                 dom = parseString(xml)
                 serialized_data = dom.toprettyxml()
             else:
@@ -299,7 +306,7 @@
             serialized_data = json.dumps(rtn_dict, indent=4)
         return serialized_data
 
-    def deserialize(self):#json or xml to python dict
+    def deserialize(self):  # json or xml to python dict
         rtn_dict = {}
         request_str = self.request.raw_post_data
         if request_str:
@@ -307,7 +314,7 @@
                 re_format = self.request.META['HTTP_ACCEPT']
                 if "application/xml" in re_format:
                     try:
-                        #get a OrderedDict
+                        # get a OrderedDict
                         rtn_dict = xmltodict.parse(request_str)["rest"]
                     except:
                         msg = {'msg': unicode(_('Invalid xml format!'))}
@@ -328,7 +335,7 @@
         return rtn_dict
 
     def GET(self):
-        #four cases:
+        # four cases:
         # 1- non-profile model, Query configuration (by field or by field group)
         # 2- non-profile model, Query instance status/statistics (by field or by field group)
         # 3- profile model, Query configuration (by field or by field group)
@@ -351,17 +358,18 @@
                             instance = cast(ins_head.contents.stqh_first, POINTER(ustat_model_q_item))
                             while instance:
                                 data = cast(instance.contents.data, POINTER(data_type))
-                                for field in self.object._meta.field_groups[self.attribute].fields:      
+                                for field in self.object._meta.field_groups[self.attribute].fields:
                                     rtn[field.attname] = eval('data.contents.' + field.attname)
                                 instance = cast(instance.contents.entry.stqe_next, POINTER(ustat_model_q_item))
                             libustat.read_unlock()
                         else:
                             if self.object._meta.profile:
-                                msg = {'msg': unicode(_('Statistics are not found. Please check if the setting is already turned on.'))}
+                                msg = {'msg': unicode(
+                                    _('Statistics are not found. Please check if the setting is already turned on.'))}
                                 raise RestfulException(msg, 404)
                             else:
                                 msg = {'msg': unicode(_('The object is not found.'))}
-                                raise RestfulException(msg, 404)        
+                                raise RestfulException(msg, 404)
                     else:
                         msg = {'msg': unicode(_('The object is not found.'))}
                         raise RestfulException(msg, 404)
@@ -376,23 +384,24 @@
                             libustat.read_lock()
                             instance = cast(ins_head.contents.stqh_first, POINTER(ustat_model_q_item))
                             while instance:
-                                data = cast(instance.contents.data, POINTER(data_type))     
+                                data = cast(instance.contents.data, POINTER(data_type))
                                 rtn[self.attribute] = eval('data.contents.' + self.attribute)
                                 instance = cast(instance.contents.entry.stqe_next, POINTER(ustat_model_q_item))
                             libustat.read_unlock()
                         else:
                             if self.object._meta.profile:
-                                msg = {'msg': unicode(_('Statistics are not found. Please check if the setting is already turned on.'))}
+                                msg = {'msg': unicode(
+                                    _('Statistics are not found. Please check if the setting is already turned on.'))}
                                 raise RestfulException(msg, 404)
                             else:
                                 msg = {'msg': unicode(_('The object is not found.'))}
-                                raise RestfulException(msg, 404)        
+                                raise RestfulException(msg, 404)
                     else:
                         msg = {'msg': unicode(_('The object is not found.'))}
                         raise RestfulException(msg, 404)
             else:
                 msg = {'msg': unicode(_('No such field or field group %s.')) % self.attribute}
-                raise RestfulException(msg, 404) 
+                raise RestfulException(msg, 404)
         else:
             rtn = self.object.get_rest_field_dict(withstats=False)
 
@@ -400,11 +409,11 @@
             instance_id_dict = {'instance_id': self.object.pk_id()}
             rtn = OrderedDict(instance_id_dict.items() + rtn.items())
 
-        rtn_dict = {self.model._meta.object_name:rtn}
+        rtn_dict = {self.model._meta.object_name: rtn}
         return self.serialize(rtn_dict)
 
     def DELETE(self):
-        #three case:
+        # three case:
         # 1- Delete an non-profile model's instance
         # 2- For normal * to *, 0..1 to * or * to 0..1 etc. AssoFields:
         #       "Unlink (release the association) one target instance with me."
@@ -423,12 +432,12 @@
                 f = self.concrete_model._meta.get_field(self.attribute)
                 asso_idx = f.get_asso_idx(model_path)
             f = self.concrete_model._meta.get_field(self.attribute)
-            if f.type_name == 'asso':#just for asso field
+            if f.type_name == 'asso':  # just for asso field
                 target_models = f.target_end[asso_idx].model
                 target_manager = target_models.get_manager(self.session)
                 self.target_id = target_models.asso_ref_to_instance_id(self.instance_id, self.target_id)
                 pk_list = target_models._meta.targets_id_to_pk_list(self.target_id, False)
-                if f.is_composition_asso():#for composition association field
+                if f.is_composition_asso():  # for composition association field
                     try:
                         target_manager.delete(pk_list)
                         rtn_dict = {'msg': '%s (%s) is deleted.' % (self.target_id, target_models._meta.verbose_name)}
@@ -442,7 +451,7 @@
                         else:
                             msg = {'msg': str(e)}
                             raise RestfulException(msg, 200)
-                else:# for normal asso field
+                else:  # for normal asso field
                     instance_list = []
                     update_dict = {}
                     old_instance_dict_list = self.concrete_manager.get_field(self.object.pk_dict(), self.attribute)
@@ -453,7 +462,7 @@
                         delete = False
                         for each in old_instance_dict_list:
                             if self.target_id in each.values():
-                                delete = True#delete is false means instance is not found 
+                                delete = True  # delete is false means instance is not found
                                 continue
                             instance_list.append(each)
                         if not delete:
@@ -462,7 +471,7 @@
                     update_dict[self.attribute] = instance_list
                     try:
                         old_value_dict = dict(self.object.get_field_dict(withstats=False))
-                        for key,value in update_dict.iteritems():
+                        for key, value in update_dict.iteritems():
                             setattr(self.object, key, value)
                     except KeyError as e:
                         msg = {'msg': unicode(_('No such field: %s.')) % str(e)}
@@ -474,9 +483,10 @@
                         msg = {'msg': unicode(_('Fields validate failed: %s.')) % str(e)}
                         raise RestfulException(msg, 500)
                     try:
-                        self.concrete_manager.update(self.object, field_list=update_dict.keys(), old_values=old_value_dict)
+                        self.concrete_manager.update(self.object, field_list=update_dict.keys(),
+                                                     old_values=old_value_dict)
                         rtn = self.object.get_rest_field_dict(withstats=False)
-                        rtn_dict = {self.model._meta.object_name:rtn}
+                        rtn_dict = {self.model._meta.object_name: rtn}
                     except ModelQueryException, e:
                         if e.has_error():
                             msg = {'msg': unicode(_('Delete failed: %s.')) % str(e)}
@@ -504,11 +514,11 @@
         else:
             msg = {'msg': unicode(_('The request has no field name or target ID.'))}
             raise RestfulException(msg, 400)
-        
+
         return self.serialize(rtn_dict)
 
     def PUT(self, **kwargs):
-        #three cases:
+        # three cases:
         # 1- Update a profile model's configuration
         # 2- Update a non-profile model's configuration
         # 3-  For normal * to *, 0..1 to * or * to 0..1 etc. AssoFields:
@@ -528,7 +538,7 @@
                 f = self.concrete_model._meta.get_field(self.attribute)
                 asso_idx = f.get_asso_idx(model_path)
             f = self.concrete_model._meta.get_field(self.attribute)
-            if f.type_name == 'asso':#just for asso field
+            if f.type_name == 'asso':  # just for asso field
                 if f.is_composition_asso():
                     msg = {'msg': unicode(_('No PUT function for composition association field.'))}
                     raise RestfulException(msg, 405)
@@ -548,12 +558,13 @@
 
         try:
             old_value_dict = dict(self.object.get_field_dict(withstats=False))
-            for key,value in update_dict.iteritems():
+            for key, value in update_dict.iteritems():
                 f = self.concrete_model._meta.get_field(key)
                 if f.editable:
                     setattr(self.object, key, value)
                 else:
-                    msg = {'msg': unicode(_('Update failed: The request body include non-editable field(s). Please check it.'))}
+                    msg = {'msg': unicode(
+                        _('Update failed: The request body include non-editable field(s). Please check it.'))}
                     raise RestfulException(msg, 400)
         except KeyError as e:
             msg = {'msg': unicode(_('No such field: %s.')) % str(e)}
@@ -586,7 +597,7 @@
         return self.serialize(rtn_dict)
 
     def POST(self, **kwargs):
-        #two case:
+        # two case:
         # 1. For normal * to *, 0..1 to * or * to 0..1 etc. AssoFields:
         #       Semantic meaning: "Associate one target instance with me."
         #       The input should only include the <instance_id> of the target instance.
@@ -610,9 +621,9 @@
             if f.type_name == 'asso':
                 target_models = f.target_end[asso_idx].model
                 target_manager = target_models.get_manager(self.session)
-                if f.is_composition_asso():#for composition association field
+                if f.is_composition_asso():  # for composition association field
                     # If this is a virtual super class, add a context variable
-                    if target_models._meta.abstract: 
+                    if target_models._meta.abstract:
                         try:
                             concrete_model = target_models._meta.get_child_by_field_cond(json_dict)
                         except KeyError:
@@ -622,10 +633,10 @@
                     else:
                         concrete_model = target_models
                         concrete_manager = target_manager
-                    #add ignored field
+                    # add ignored field
                     ignore_field = f.tgt_field[0].name
                     json_dict[ignore_field] = [self.object.pk_dict()]
-            
+
                     try:
                         new_obj = concrete_model(**json_dict)
                     except:
@@ -635,7 +646,7 @@
                         new_obj.clean_fields()
                     except ValidationError, e:
                         msg = {'msg': unicode(_('Fields validate failed: %s.')) % str(e)}
-                        raise RestfulException(msg, 400)            
+                        raise RestfulException(msg, 400)
                     try:
                         concrete_manager.insert(new_obj)
                         rtn = new_obj.get_rest_field_dict(withstats=False)
@@ -652,16 +663,16 @@
                             if new_obj.pk_id():
                                 instance_id_dict = {'instance_id': new_obj.pk_id()}
                                 rtn = OrderedDict(instance_id_dict.items() + rtn.items())
-                else:# for normal asso field
+                else:  # for normal asso field
                     update_dict = {}
                     new_instance_dict_list = []
                     old_instance_dict_list = []
                     new_instance_id_list = []
                     old_instance_id_list = []
                     instance_list = []
-                    #get new instance id list
+                    # get new instance id list
                     new_instance_id_list = json_dict.values()[0]
-                    #get old instance id list
+                    # get old instance id list
                     old_instance_dict_list = self.concrete_manager.get_field(self.object.pk_dict(), self.attribute)
                     if len(old_instance_dict_list) == 0:
                         instance_id_list = new_instance_id_list
@@ -678,7 +689,7 @@
 
                     try:
                         old_value_dict = dict(self.object.get_field_dict(withstats=False))
-                        for key,value in update_dict.iteritems():
+                        for key, value in update_dict.iteritems():
                             setattr(self.object, key, value)
                     except KeyError as e:
                         msg = {'msg': unicode(_('No such field: %s.')) % str(e)}
@@ -690,7 +701,8 @@
                         msg = {'msg': unicode(_('Fields validate failed: %s.')) % str(e)}
                         raise RestfulException(msg, 500)
                     try:
-                        self.concrete_manager.update(self.object, field_list=update_dict.keys(), old_values=old_value_dict)
+                        self.concrete_manager.update(self.object, field_list=update_dict.keys(),
+                                                     old_values=old_value_dict)
                         rtn = self.object.get_rest_field_dict(withstats=False)
                     except ModelQueryException, e:
                         if e.has_error():
@@ -713,7 +725,7 @@
         return self.serialize(rtn_dict)
 
 
-class CLIRestResource(object): 
+class CLIRestResource(object):
     def __init__(self, request, session, method):
         self.request = request
         self.session = session
@@ -724,27 +736,26 @@
             dict_data = {}
             try:
                 dict_data = json.loads(post_data)
-            except exceptions, ex:   
-                msg  = {'contents':unicode(_('post post_data format errors ' + str(exceptions) + str(ex)))}
+            except exceptions, ex:
+                msg = {'contents': unicode(_('post post_data format errors ' + str(exceptions) + str(ex)))}
                 raise RestfulException(msg, 501)
 
             self.cmd = dict_data["cmd"]
-    
+
     def render(self):
         if hasattr(self, self.method):
             request_dict = dict(self.request.REQUEST)
             return getattr(self, self.method)(self.cmd)
         else:
-            msg = {'contents':unicode(_('The request method is not supported.'))}
+            msg = {'contents': unicode(_('The request method is not supported.'))}
             raise RestfulException(msg, 501)
 
-        
     def POST(self, cmd):
         contents = {}
         if self.cmd:
-           self.session.cli.set_config()
-           contents["contents"] = self.session.cli.cmd(cmd)
-           return json.dumps(contents)
+            self.session.cli.set_config()
+            contents["contents"] = self.session.cli.cmd(cmd)
+            return json.dumps(contents)
 
 
 class BatchCLIRestResource(object):
@@ -760,12 +771,13 @@
             with open(config_filename, 'wb') as f:
                 f.write(cmds_str)
             self.session.cli.set_config()
-            output = self.session.cli.cmd("config file %s"%config_filename)
-            return json.dumps({'CLI Output':output})
+            output = self.session.cli.cmd("config file %s" % config_filename)
+            return json.dumps({'CLI Output': output})
         else:
             msg = {'msg': unicode(_('The request body batch_cli should not be empty.'))}
             raise RestfulException(msg, 501)
 
+
 class DeviceRESTResource(object):
     def __init__(self, request, method, action_name):
         self.request = request
@@ -779,13 +791,13 @@
         else:
             msg = {'msg': unicode(_('The request method is not supported.'))}
             raise RestfulException(msg, 501)
- 
-    def serialize(self, rtn_dict):#python dict to xml or json
+
+    def serialize(self, rtn_dict):  # python dict to xml or json
         if 'HTTP_ACCEPT' in self.request.META:
             re_format = self.request.META['HTTP_ACCEPT']
             if "application/xml" in re_format:
                 xml = dicttoxml.dicttoxml(rtn_dict, attr_type=False, custom_root='rest')
-                #Pretty-Printing
+                # Pretty-Printing
                 dom = parseString(xml)
                 serialized_data = dom.toprettyxml()
             else:
@@ -794,38 +806,21 @@
             serialized_data = json.dumps(rtn_dict, indent=4)
         return serialized_data
 
-    def check_license_by_name(self, license_name):
-        session_used = 0
-        count = 0
-        db = DB.get_connected_db()
-        fetchall_sql = "SELECT persession_limit FROM vpn_device WHERE license_name = '%s'" % license_name
-        device_data = db.fetchall(fetchall_sql)
-        db.close()
-        if device_data:
-            for each in device_data:
-                session_used += each[0]
-                count += 1
-        return [session_used, count]
-
-
     def get_license(self):
         license_name = ""
         db = DB.get_connected_db()
-        fetchall_sql = "SELECT name, expiration_date, capacity, session FROM vpn_license"
+        fetchall_sql = "SELECT * FROM license"
         license_data = db.fetchall(fetchall_sql)
         db.close()
 
         if license_data:
             for each in license_data:
                 if each:
-                    now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
-                    expire_time = each[1][-8:-4] + "-" + each[1][-4:-2] + "-" + each[1][-2:] + " 00:00:00"
+                    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
+                    expire_time = each[4][-8:-4] + "-" + each[4][-4:-2] + "-" + each[4][-2:] + " 00:00:00"
                     if now > expire_time:
                         continue
-                    check_lic = self.check_license_by_name(each[0])
-                    if check_lic[0] >= each[3] or check_lic[1] >= each[2]:
-                        continue
-
+                    # for better, we should check the license has enough bandwidth for assigning.
                     license_name = each[0]
                     break
 
@@ -843,7 +838,7 @@
 
         return zone
 
-    def deserialize(self):#json or xml to python dict
+    def deserialize(self):  # json or xml to python dict
         rtn_dict = {}
         request_str = self.request.raw_post_data
         if request_str:
@@ -851,7 +846,7 @@
                 re_format = self.request.META['HTTP_ACCEPT']
                 if "application/xml" in re_format:
                     try:
-                        #get a OrderedDict
+                        # get a OrderedDict
                         rtn_dict = xmltodict.parse(request_str)["rest"]
                     except:
                         msg = {'msg': unicode(_('Invalid xml format!'))}
@@ -875,6 +870,7 @@
         data = self.deserialize()
         data['time'] = str(time.time())
         data['device_ip'] = self.request.META['REMOTE_ADDR']
+        msg = {}
         if self.action_name:
             if self.action_name == 'AutoRegistration':
                 data["status"] = "normal"
@@ -883,77 +879,88 @@
                 data["restapi_username"] = "rest"
                 data["restapi_password"] = "rest"
                 db = DB.get_connected_db()
-                select_sql = "SELECT ip FROM vpn_device;"
-                setting_sql = "SELECT auto_enable FROM vpn_cm_settings;"
+                select_sql = "SELECT ip FROM device2;"
+                setting_sql = "SELECT auto_enable FROM cm_settings;"
                 devices_data = db.fetchall(select_sql)
                 settings_data = db.fetchall(setting_sql)
                 auto_enable = int(settings_data[0][0])
                 devices_list = [each[0] for each in devices_data]
+                data['device_ip'] = data['device_ip'].split(":")[-1]
                 if data["device_ip"] in devices_list:
-                    msg = {'code': -1, 'msg': unicode(_('Deive has been registered.')), 'registered': True, 'status': True, 'device_id': data["device_ip"]}
+                    msg = {'code': -1, 'msg': unicode(_('Device has been registered.')), 'registered': True,
+                           'status': True, 'device_id': data["device_ip"]}
                 else:
                     if auto_enable:
                         auto_license = self.get_license()
-                        insert_sql = "INSERT INTO vpn_device(\
-                            id, \
-                            ip, \
-                            restapi_port, \
-                            restapi_username, \
-                            restapi_password, \
-                            connection, \
-                            status, \
-                            version, \
-                            license_name, \
-                            perbw, \
-                            error_msg, \
-                            rel_bandwith, \
-                            perbw_limit, \
-                            auto, \
-                            restapi_protocol, \
-                            persession, \
-                            persession_limit, \
-                            auto_session) Values " + \
-                            "('%s', '%s', '%s', '%s', '%s', 'connected', 'new', '%s', NULL, 0, '', NULL, 0, 1, '%s', 0, 0, 0)" % \
-                            (
-                                data["device_ip"],  
-                                data["device_ip"], 
-                                data["restapi_port"], 
-                                data["restapi_username"],
-                                data["restapi_password"],
-                                data["version"],
-                                data["restapi_protocol"]
-                            )
-                        db.execute_sql(insert_sql)
-
                         if auto_license:
+                            insert_sql = "INSERT INTO device2(\
+                                id, \
+                                ip, \
+                                restapi_port, \
+                                restapi_username, \
+                                restapi_password, \
+                                connection, \
+                                status, \
+                                version, \
+                                license_name, \
+                                perbw, \
+                                error_msg, \
+                                rel_bandwith, \
+                                perbw_limit, \
+                                auto, \
+                                restapi_protocol) Values " + \
+                                         "('%s', '%s', '%s', '%s', '%s', 'connected', 'new', '%s', NULL, 0, '', NULL, 0, 1, '%s')" % \
+                                         (
+                                             data["device_ip"],
+                                             data["device_ip"],
+                                             data["restapi_port"],
+                                             data["restapi_username"],
+                                             data["restapi_password"],
+                                             data["version"],
+                                             data["restapi_protocol"]
+                                         )
+                            db.execute_sql(insert_sql)
+
                             # activate the device after inserting successfully in auto enable mode.
-                            device_activation_result = ActivationServer.activate_device({'device_id': [data["device_ip"]], 'license_name': auto_license})
+                            device_activation_result = ActivationServer.activate_device(
+                                {'device_id': [data["device_ip"]], 'license_name': auto_license})
                             if device_activation_result:
                                 if not device_activation_result[0]["status"]:
                                     error_msg = device_activation_result[0]["msg"]
-                                    msg = {'code': -1, 'msg': error_msg, 'registered': True, 'status': True, 'device_id': data["device_ip"]}
+                                    msg = {'code': -1, 'msg': error_msg, 'registered': True, 'status': True,
+                                           'device_id': data["device_ip"]}
                                 else:
-                                    msg = {'code': 0, 'msg': 'Successfully.', 'registered': True, 'status': True, 'device_id': data["device_ip"]}
+                                    msg = {'code': 0, 'msg': 'Successfully.', 'registered': True, 'status': True,
+                                           'device_id': data["device_ip"]}
                             else:
-                                msg = {'code': 0, 'msg': 'Successfully.', 'registered': True, 'status': True, 'device_id': data["device_ip"]}
+                                msg = {'code': 0, 'msg': 'Successfully.', 'registered': True, 'status': True,
+                                       'device_id': data["device_ip"]}
                         else:
-                            msg = {'code': 0, 'msg': 'Successfully.', 'registered': True, 'status': True, 'device_id': data["device_ip"]}
+                            if not auto_license:
+                                msg = {'code': -1, 'msg': unicode(_('There is no vaild license.')), 'registered': False,
+                                       'status': False, 'device_id': data["device_ip"]}
                     else:
                         try:
-                            save_sql = "INSERT INTO vpn_discover_device(ip, restapi_port, restapi_username, restapi_password, status, version, timestamp, restapi_protocol) Values " + "('%(device_ip)s', '%(restapi_port)d', '%(restapi_username)s', '%(restapi_password)s', '%(status)s', '%(version)s', '%(time)s', '%(restapi_protocol)s')" % data
+                            save_sql = "INSERT INTO discover_device(ip, restapi_port, restapi_username, restapi_password, status, version, timestamp, restapi_protocol) Values " + "('%(device_ip)s', '%(restapi_port)d', '%(restapi_username)s', '%(restapi_password)s', '%(status)s', '%(version)s', '%(time)s', '%(restapi_protocol)s')" % data
                             db.execute_sql(save_sql)
                         except Exception, e:
-                            if "UNIQUE constraint failed" in str(e):
-                                save_sql = "REPLACE INTO vpn_discover_device(ip, restapi_port, restapi_username, restapi_password, status, version, timestamp, restapi_protocol) Values " + "('%(device_ip)s', '%(restapi_port)d', '%(restapi_username)s', '%(restapi_password)s', '%(status)s', '%(version)s', '%(time)s', '%(restapi_protocol)s')" % data
-                                db.execute_sql(save_sql)
+                            if "unique constraint" in str(e):
+                                pass # The device already exists.
+                                # The following approach was deprecated.
+                                # save_sql = "REPLACE INTO discover_device(ip, restapi_port, restapi_username, restapi_password, status, version, timestamp, restapi_protocol) Values " + "('%(device_ip)s', '%(restapi_port)d', '%(restapi_username)s', '%(restapi_password)s', '%(status)s', '%(version)s', '%(time)s', '%(restapi_protocol)s')" % data
+                                # db.execute_sql(save_sql)
                             else:
-                                msg = {'code': -1, 'msg': unicode(_('Insert device into DB failed.')), 'registered': False, 'status': False, 'device_id': data["device_ip"]}
-                        msg = {'code': 0, 'msg': 'Successfully.', 'registered': False, 'status': True, 'device_id': data["device_ip"]}
+                                msg = {'code': -1, 'msg': unicode(_('Insert device into DB failed.')),
+                                       'registered': False, 'status': False, 'device_id': data["device_ip"]}
+                        msg = {'code': 0, 'msg': 'Successfully.', 'registered': False, 'status': True,
+                               'device_id': data["device_ip"]}
                 db.close()
             else:
-                msg = {'code': -1, 'msg': unicode(_('No such action %s.')) % self.action_name, 'registered': False, 'status': False, 'device_id': data["device_ip"]}
-                raise RestfulException(msg, 404)                 
+                msg = {'code': -1, 'msg': unicode(_('No such action %s.')) % self.action_name, 'registered': False,
+                       'status': False, 'device_id': data["device_ip"]}
+                raise RestfulException(msg, 404)
         else:
-            msg = {'code': -1, 'msg': unicode(_('The request has no action name.')), 'registered': False, 'status': False, 'device_id': data["device_ip"]}
-            raise RestfulException(msg, 400)            
+            msg = {'code': -1, 'msg': unicode(_('The request has no action name.')), 'registered': False,
+                   'status': False, 'device_id': data["device_ip"]}
+            raise RestfulException(msg, 400)
         return self.serialize(msg)
