예제 #1
0
def build_rules(rules):
  rules_objs = []
  for head, body in rules.items():
    rule = Rule(head)
    body = build_body(body)
    rule.add(body=body)
    rules_objs.append(rule)
  return rules_objs
예제 #2
0
    def _model_from_data(self,  cleaned_data, src_model = None):
        """
            Получаем модель с заполненными полями из очищенных данных
        """
        if src_model:
            model = src_model
        else:
            model = Rule()
        # заполняем поля
        if cleaned_data: # если модель была валидирована
            model.enabled = (self.cleaned_data.get("enabled") == "True")


            model.from_number = self.cleaned_data.get("from_number")
            model.to_number = self.cleaned_data.get("to_number")
            model.busy_flags = self.cleaned_data.get("busy_flags")
            model.busy_wait_time = int(self.cleaned_data.get("busy_wait_time"))*1000

            if cleaned_data.get("time_enabled") == "True": # проверяем на переадресацию по времени
                model.SetTimeOfDayCondition(True) # Сохраняем в модель тот факт, что у нас переадресация по времени суток
                model.date_time_begin = cleaned_data.get("date_time_begin") # сохраняем начальное время
                model.date_time_end = cleaned_data.get("date_time_end") # сохраняем конечное время
            else:                                       # иначе
                model.SetTimeOfDayCondition(False) # Сохраняем в модель тот факт, что у нас нет переадресации по времени суток
                model.date_time_begin = None # сбиваем начальное время
                model.date_time_end = None # сбиваем конечное время

            if cleaned_data.get("dayofweek_enabled") == "True": # проверяем на переадресацию по дню недели
                model.SetDayOfWeekCondition(True)
                model.SetDaysOfWeekEnabled(
                    StrToBool(cleaned_data.get("dayofweek_monday")),
                    StrToBool(cleaned_data.get("dayofweek_tuesday")),
                    StrToBool(cleaned_data.get("dayofweek_wednesday")),
                    StrToBool(cleaned_data.get("dayofweek_thursday")),
                    StrToBool(cleaned_data.get("dayofweek_friday")),
                    StrToBool(cleaned_data.get("dayofweek_saturday")),
                    StrToBool(cleaned_data.get("dayofweek_sunday"))
                )
            else: # иначе - отключаем ее
                model.SetDayOfWeekCondition(False)
                model.SetDaysOfWeekEnabled(
                    False,
                    False,
                    False,
                    False,
                    False,
                    False,
                    False
                )


            return model
예제 #3
0
def save_test(request):
    print 'POST: ', request.POST
    rule = None
    if request.POST['pattern']:
        rule = Rule(pattern=request.POST['pattern'], replacement=request.POST['replacement'])
        rule.save()
    if rule:
        test = Test(input=request.POST['input'], output=request.POST['output'], rule=rule)
    else:
        test = Test(input=request.POST['input'], output=request.POST['output'])
    test.save()
    response_data = {}

    return HttpResponse(simplejson.dumps(response_data), mimetype="application/json")
예제 #4
0
파일: functions.py 프로젝트: byackee/LISA
def install(plugin_url=None, plugin_sha=None, plugin_name=None):
    if plugin_url and plugin_sha:
        repo = git.Repo.clone_from(plugin_url, LISA_PATH + '/plugins/' + plugin_name)
        repo.git.checkout(plugin_sha)
    metadata = json.load(open(LISA_PATH + '/plugins/' + plugin_name + '/' + str(plugin_name).lower() + '.json'))

    if Plugin.objects(name=plugin_name):
        return {'status': 'fail', 'log': 'Plugin already installed'}
    else:
        plugin = Plugin()
        description_list = []
        for item in metadata:
            if item != 'cron' or item != 'rules':
                if item == 'description':
                    for description in metadata[item]:
                        oDescription = Description()
                        for k,v in description.iteritems():
                            setattr(oDescription, k, v)
                        description_list.append(oDescription)
                    setattr(plugin, item, description_list)
                elif item == 'enabled':
                    if metadata[item] == 0:
                        setattr(plugin, item, False)
                    else:
                        setattr(plugin, item, True)
                else:
                    setattr(plugin, item, metadata[item])
        plugin.save()
        for item in metadata:
            if item == 'rules':
                for rule_item in metadata['rules']:
                    rule = Rule()
                    for parameter in rule_item:
                        setattr(rule, parameter, rule_item[parameter])
                    rule.plugin = plugin
                    rule.save()
            if item == 'crons':
                for cron_item in metadata['crons']:
                    cron = Cron()
                    for parameter in cron_item:
                        setattr(cron, parameter, cron_item[parameter])
                    cron.plugin = plugin
                    cron.save()
        return {'status': 'success', 'log': 'Plugin installed'}
예제 #5
0
파일: api.py 프로젝트: YohannsMonnier/LISA
    def install(self, request, **kwargs):
        self.method_check(request, allowed=['post','get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        from tastypie.http import HttpCreated, HttpNotModified

        try:
            plugin_url = request.POST.get("url")
            plugin_sha = request.POST.get("sha")
            plugin_name = kwargs['plugin_name']
            repo = git.Repo.clone_from(plugin_url, LISA_PATH + '/Plugins/' + plugin_name)
            repo.git.checkout(plugin_sha)
            metadata = json.load(open(LISA_PATH + '/Plugins/' + plugin_name + '/' + str(plugin_name).lower() + '.json'))
            plugin = Plugin()
            for item in metadata:
                if item != 'cron' or item != 'rules':
                    setattr(plugin, item, metadata[item])
            plugin.save(validate=False)
            for item in metadata:
                if item == 'rules':
                    for rule_item in metadata['rules']:
                        rule = Rule()
                        for parameter in rule_item:
                            setattr(rule, parameter, rule_item[parameter])
                        rule.plugin = plugin
                        rule.save(validate=False)
                if item == 'crons':
                    for cron_item in metadata['crons']:
                        cron = Cron()
                        for parameter in cron_item:
                            setattr(cron, parameter, cron_item[parameter])
                        cron.plugin = plugin
                        cron.save(validate=False)
        except:
            pass
        #except FailedException as failure:
        #    return self.create_response(request, { 'status' : 'failure', 'reason' : failure }, HttpNotModified
        self.log_throttled_access(request)
        LisaInstance.SchedReload()
        LisaInstance.LisaReload()
        return self.create_response(request, { 'status': 'success', 'log': "Plugin Installed"}, HttpCreated)
예제 #6
0
파일: views.py 프로젝트: xunyuw/iFlyQA
def api(request):
    user = request.user
    if not user:
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user = authenticate(username= username, password=password)
    if user is not None and user.has_perm("apps.add_task"):
        method = request.POST.get("method")
        if method == "create_task":
            task_data = request.POST.get("task", "")
            sites_data = request.POST.get("sites", "")
            try:
                task = Task(**json.loads(task_data))
                task.user = user
                task.clean_fields()
                sites = []
                sites_data = json.loads(sites_data)
                for site_data in sites_data:
                    site = Site(**site_data)
                    site.clean_fields(exclude=['task'])
                    sites.append(site)
                task.save()
                for site in sites:
                    site.task = task
                    site.save()
                    rule = Rule(**Constants.DEFAULT_RULE)
                    rule.site = site
                    rule.save()
                controller = TaskController(task)
                controller.runTask()
                ret = {"status":"ok", "task":task.id}
            except Exception, e:
                ret = {"status":"InputError", "error_details":str(e)}
        elif method == "run_task":
            try:
                id = request.POST.get("id")
                task = Task.objects.get(id=id)
                controller = TaskController(task)
                controller.runTask()
                ret = {"status":"ok"}
            except Exception, e:
                ret = {"status":"RunError", "error_details":str(e)}
예제 #7
0
def left_factor(rules):
  '''rules: List of Rule objects'''
  common_prefix_count = 1
  while common_prefix_count:
    common_prefix_count = 0
    for rule in list(rules):
      terms = rule.get_terms()
      # print('terms--', terms)
      common_prefixes = {}
      common_prefixes = get_common_prefixes(terms)
      max_prefix, max_count = get_max_prefix(common_prefixes)
      print(common_prefixes)
      print(max_count, max_prefix)
      common_prefix_count += max_count - 1
      if max_count < 2:  # we don't need to do anymore work if the max count of prefix occurence is 1 or 0
        continue
      mod_terms, new_head, new_terms = _left_factor(rule.head, terms, max_prefix, max_count)
      rule.set_terms(mod_terms)
      new_rule = Rule(new_head, [])
      new_rule.set_terms(new_terms)
      rules.append(new_rule)
    print('reloop')
예제 #8
0
def postNewRule(request):
    #Modification.objects.all().delete()
    #Rule.objects.all().delete()
    
    if request.is_ajax():
        if request.method == 'POST':
            jdata = json.loads(request.raw_post_data)
            print jdata

            # if jdata['rules'][0]['scope'] == 'this_place':
            #     filteredRuleSet = RuleSet.objects.filter(userId=jdata['userName']).filter(\
            #                     appliesTo=jdata['urn']).filter(name=jdata['ruleSetName'])
            # elif jdata['rules'][0]['scope'] == 'this_entity':
            #     print "this_entity"
            # elif jdata['rules'][0]['scope'] == 'this_place':
            #     print "all_places"

            filteredRuleSet = RuleSet.objects.filter(userId=jdata['userName']).filter(\
                             appliesTo=jdata['urn']).filter(name=jdata['ruleSetName'])

            if filteredRuleSet and filteredRuleSet.count() == 1:
                filteredModifications = Modification.objects.filter(userId=jdata['userName']).filter(\
                    modification_type=jdata['rules'][0]['modifications'][0]['modification_type']).filter(\
                    dateTime=jdata['rules'][0]['modifications'][0]['dateTime'])
                
                found = False
                for rule in filteredRuleSet[0].rules.all():
                    if (rule.appliesTo == jdata['urn'] and rule.action == \
                        jdata['rules'][0]['action'] and rule.scope == jdata['rules'][0]['scope'] \
                        and rule.token == jdata['rules'][0]['token']):
                        found = True
                        
                if not filteredModifications and not found:
                    m = Modification()
                    m.userId = jdata['userName']
                    m.modification_type = jdata['rules'][0]['modifications'][0]['modification_type']
                    m.dateTime = jdata['rules'][0]['modifications'][0]['dateTime']
                    m.save()
                    
                    r = Rule()
                    r.appliesTo = jdata['urn']
                    r.action = jdata['rules'][0]['action']
                    r.scope = jdata['rules'][0]['scope']
                    r.token = jdata['rules'][0]['token']
                    r.save()
                    r.modifications.add(m)
                    filteredRuleSet[0].rules.add(r)
                else:
                    print "error: filteredModifications OR filteredRules"
            else:
                print "error: filteredRuleSet"
                
    return HttpResponse("OK")
예제 #9
0
    def got_password_entries(self, entries):
        rules = Rule.load_rules()
        matched_entries = []
        for entry in entries:
            for rule in rules:
                if rule.applies_to(entry):
                    matched_entries.append([rule, entry])
                    break

        if not matched_entries:
            show_error("We have no rules matching these logins. See [TK] for a list of currently supported sites.")
            return

        self.matched_entries = matched_entries
        self.show_panel(views.CreateLogPanel)
예제 #10
0
파일: functions.py 프로젝트: byackee/LISA
def uninstall(plugin_name=None, plugin_pk=None):
    if plugin_pk:
        plugin_list = Plugin.objects(pk=plugin_pk)
    else:
        plugin_list = Plugin.objects(name=plugin_name)
    if not plugin_list:
        return {'status': 'fail', 'log': 'Plugin not installed'}
    else:
        for plugin in plugin_list:
            rmtree(LISA_PATH + '/plugins/' + plugin['name'])
            plugin.delete()
            for cron in Cron.objects(plugin=plugin):
                cron.delete()
            for rule in Rule.objects(plugin=plugin):
                rule.delete()
        return {'status': 'success', 'log': 'Plugin uninstalled'}
예제 #11
0
파일: functions.py 프로젝트: byackee/LISA
def disable(plugin_name=None, plugin_pk=None):
    if plugin_pk:
        plugin_list = Plugin.objects(pk=plugin_pk)
    else:
        plugin_list = Plugin.objects(name=plugin_name)
    for plugin in plugin_list:
        if not plugin.enabled:
            return {'status': 'fail', 'log': 'Plugin already disabled'}
        else:
            plugin.enabled = False
            plugin.save()
            for cron in Cron.objects(plugin=plugin):
                cron.enabled = False
                cron.save()
            for rule in Rule.objects(plugin=plugin):
                rule.enabled = False
                rule.save()
            return {'status': 'success', 'log': 'Plugin disabled'}
예제 #12
0
    def post(self):
        # args = self.reqparser.parse_args()
        args = request.get_json(force=True)
        rule = Rule()
        rule.protocol = args['protocol']
        rule.port = str(args['port'])
        rule.action = args['action']

        ip = args.get('ip', None)
        mac = args.get('mac', None)

        # Check if ip and mac is passed and created by these things.
        if ip:
            rule.ip = IP(ip['ip'], ip['ipv4'])
        if mac:
            rule.mac = MAC(mac['mac'])

        session.begin()
        session.add(rule)
        session.commit()
예제 #13
0
def run(rules,
        scoring='rrs',
        name=None,
        oracle=None,
        tr=None,
        vl=None,
        coverage_weight=1.,
        sparsity_weight=1.,
        alpha=0,
        beta=0,
        gamma=-1,
        max_len=-1,
        debug=20):
    """Run the Scoring framework on a set of rules.
    Arguments:
        rules (str): JSON file with the train set.
        scoring (str): Type of scoring to perform. Available names are 'rrs', which includes fidelity scoring, and
                        'coverage'. Defaults to 'rrs'.
        oracle (Union(str, None)): Oracle to score against.
        tr (str): Training set.
        vl (str): Validation set, if any.
        name (str): Name for the output logs.
        coverage_weight (float): Coverage weight vector.
        sparsity_weight (float): Sparsity weight vector.
        alpha (float): Pruning hyperparameter, rules with score less than `alpha` are removed from the result.
        beta (float): Pruning hyperparameter, rules with score less than the `beta`-percentile are removed from the
                        result.
        gamma (int): Maximum number of rules to use.
        max_len (int): Pruning hyperparameter, rules with length more than `max_len` are removed from the result.
        debug (int): Minimum debug level.
    """
    # Set-up debug
    if debug == 10:
        min_log = logzero.logging.DEBUG
    elif debug == 20:
        min_log = logzero.logging.INFO
    elif debug == 30:
        min_log = logzero.logging.WARNING
    elif debug == 40:
        min_log = logzero.logging.ERROR
    elif debug == 50:
        min_log = logzero.logging.CRITICAL
    else:
        min_log = 0

    logzero.loglevel(min_log)

    if name is None:
        name = tr + str(time.time())

    # Info LOG
    logger.info('Rules: ' + str(rules))
    logger.info('name: ' + str(name))
    logger.info('score: ' + str(scoring))
    logger.info('oracle: ' + str(oracle))
    logger.info('vl: ' + str(vl))
    logger.info('coverage weight: ' + str(coverage_weight))
    logger.info('sparsity weight: ' + str(sparsity_weight))
    logger.info('alpha: ' + str(alpha))
    logger.info('beta: ' + str(beta))
    logger.info('max len: ' + str(max_len))

    logger.info('Loading validation... ')
    data = genfromtxt(tr, delimiter=',', names=True)
    names = data.dtype.names
    training_set = data.view(np_float).reshape(data.shape + (-1, ))
    if vl is not None:
        data = genfromtxt(vl, delimiter=',', names=True)
        validation_set = data.view(np_float).reshape(data.shape + (-1, ))
    else:
        validation_set = None

    # Run Scoring
    logger.info('Loading ruleset...')
    rules = Rule.from_json(rules, names)
    rules = [r for r in rules if len(r) > 0]

    logger.info('Loading oracle...')
    if oracle is not None:
        if oracle.endswith('.h5'):
            oracle = load_model(oracle)
        elif oracle.endswith('.pickle'):
            with open(oracle, 'rb') as log:
                oracle = pickle.load(log)
        else:
            return
        if validation_set is not None:
            validation_set = hstack(
                (validation_set[:, :-1],
                 oracle.predict(validation_set[:, :-1].round()).reshape(
                     (validation_set.shape[0], 1))))
        training_set = hstack(
            (training_set[:, :-1],
             oracle.predict(training_set[:, :-1].round()).reshape(
                 (training_set.shape[0], 1))))

    logger.info('Creating scorer...')
    evaluator = MemEvaluator(oracle=oracle)
    scorer = Scorer(score=scoring, evaluator=evaluator, oracle=oracle)

    logger.info('Scoring...')
    scores = scorer.score(rules, training_set, coverage_weight,
                          sparsity_weight)

    logger.info('Storing scores...')
    storage_file = name + '.csv'
    scorer.save(scores=scores, path=storage_file)

    # Validation
    logger.info('Validating...')
    validation_dic = validate(
        rules,
        scores,
        oracle=oracle,
        vl=validation_set if validation_set is not None else training_set,
        scoring=scoring,
        alpha=alpha,
        beta=beta,
        gamma=len(rules) if gamma < 0 else int(gamma),
        max_len=inf if max_len <= 0 else max_len)
    validation_dic['coverage'] = coverage_weight
    validation_dic['sparsity'] = sparsity_weight
    validation_dic['scoring'] = scoring

    # Store info on JSON
    out_str = name + '.results.json'
    if os.path.isfile(out_str):
        with open(out_str, 'r') as log:
            out_dic = json.load(log)
        out_dic['runs'].append({
            'scoring': scoring,
            'coverage': coverage_weight,
            'sparsity': sparsity_weight,
            'alpha': alpha,
            'beta': beta,
            'gamma': gamma,
            'max_len': max_len,
            'results': validation_dic
        })
    else:
        out_dic = {
            'name':
            name,
            'runs': [{
                'scoring': scoring,
                'coverage': coverage_weight,
                'sparsity': sparsity_weight,
                'alpha': alpha,
                'beta': beta,
                'gamma': gamma,
                'max_len': max_len,
                'results': validation_dic
            }]
        }
    with open(out_str, 'w') as log:
        json.dump(out_dic, log)

    pretty_print_results(validation_dic, out_str)
예제 #14
0
def list_rules():
    for rule in Rule.load_rules():
        print "* %s" % rule.name
예제 #15
0
def update_style(request,
                 json_data,
                 layer,
                 gs,
                 style,
                 is_preview=False,
                 has_custom_legend=None):
    is_default = json_data.get('is_default', False)
    is_default = utils.set_default_style(layer,
                                         gs,
                                         style=style,
                                         is_preview=is_preview,
                                         is_default=is_default)

    if has_custom_legend == 'true':
        style.has_custom_legend = True
        legend_name = 'legend_' + ''.join(
            random.choice(string.ascii_uppercase) for i in range(6)) + '.png'
        legend_path = utils.check_custom_legend_path()
        if 'file' in request.FILES:
            style.custom_legend_url = utils.save_custom_legend(
                legend_path, request.FILES['file'], legend_name)

    else:
        style.has_custom_legend = False

    style.title = json_data.get('title')
    if json_data.get('minscale') != '':
        style.minscale = json_data.get('minscale')
    else:
        style.minscale = -1
    if json_data.get('maxscale') != '':
        style.maxscale = json_data.get('maxscale')
    else:
        style.maxscale = -1
    style.is_default = is_default
    style.save()

    json_rule = json_data.get('rule')

    filter_text = ""
    if json_rule.get('filter').__len__() != 0:
        filter_text = str(json.dumps(json_rule.get('filter')))

    if json_data.get('minscale') != '':
        minscale = json_rule.get('minscale')
    else:
        minscale = -1
    if json_data.get('maxscale') != '':
        maxscale = json_rule.get('maxscale')
    else:
        maxscale = -1

    rule_old = Rule.objects.get(style=style)
    rule_old.delete()

    rule = Rule(style=style,
                name=json_rule.get('name'),
                title=json_rule.get('title'),
                abstract='',
                filter=filter_text,
                minscale=minscale,
                maxscale=maxscale,
                order=json_rule.get('order'))
    rule.save()

    for s in Symbolizer.objects.filter(rule=rule):
        s.rastersymbolizer.color_map.delete()
        s.delete()

    color_map = ColorMap(type='ramp', extended=False)
    color_map.save()

    symbolizer = RasterSymbolizer(rule=rule,
                                  color_map=color_map,
                                  order=0,
                                  opacity=1.0)
    symbolizer.save()

    color_map_entry_list = []
    for entry in json_data.get('entries'):
        json_entry = json.loads(entry.get('json'))
        color_map_entry = ColorMapEntry(color_map=color_map,
                                        order=int(json_entry.get('order')),
                                        color=json_entry.get('color'),
                                        quantity=json_entry.get('quantity'),
                                        label=json_entry.get('label'),
                                        opacity=json_entry.get('opacity'))

        color_map_entry_list.append(color_map_entry)

    order = 0
    color_map_entry_list = sorted(
        color_map_entry_list,
        key=lambda color_map_entry: float(color_map_entry.quantity))
    for cme in color_map_entry_list:
        cme.order = order
        cme.save()
        order = order + 1

    sld_body = sld_builder.build_sld(layer, style)

    if is_preview:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            return style
    else:
        if gs.updateStyle(layer, style.name, sld_body):
            gs.setLayerStyle(layer, style.name, style.is_default)
            return style
예제 #16
0
def create_style(request, json_data, layer, gs, is_preview=False):
    name = json_data.get('name')
    if is_preview:
        name = name + '__tmp'
    is_default = json_data.get('is_default', False)
    is_default = utils.set_default_style(layer,
                                         gs,
                                         is_preview=is_preview,
                                         is_default=is_default)

    style = Style(name=name,
                  title=json_data.get('title'),
                  is_default=is_default,
                  minscale=json_data.get('minscale'),
                  maxscale=json_data.get('maxscale'),
                  type='US')
    style.save()
    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    for r in json_data.get('rules'):
        json_rule = r.get('rule')

        filter_text = ""
        if json_rule.get('filter').__len__() != 0:
            filter_text = str(json.dumps(json_rule.get('filter')))

        rule = Rule(style=style,
                    name=json_rule.get('name'),
                    title=json_rule.get('title'),
                    abstract='',
                    filter=filter_text,
                    minscale=json_rule.get('minscale'),
                    maxscale=json_rule.get('maxscale'),
                    order=json_rule.get('order'))
        rule.save()

        for sym in r.get('symbolizers'):
            if sym.get('type') == 'PolygonSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'LineSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'MarkSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    well_known_name=json_sym.get('well_known_name'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'ExternalGraphicSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

            elif sym.get('type') == 'TextSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = TextSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    label=json_sym.get('label'),
                    font_family=json_sym.get('font_family'),
                    font_size=json_sym.get('font_size'),
                    font_weight=json_sym.get('font_weight'),
                    font_style=json_sym.get('font_style'),
                    halo_fill=json_sym.get('halo_fill'),
                    halo_fill_opacity=json_sym.get('halo_fill_opacity'),
                    halo_radius=json_sym.get('halo_radius'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                )
                symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style)

    if is_preview:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            return style
    else:
        if gs.createStyle(style.name, sld_body):
            if not is_preview:
                gs.setLayerStyle(layer, style.name, style.is_default)
            return style
예제 #17
0
def create_style(request, json_data, layer_id, is_preview=False):

    layer = Layer.objects.get(id=int(layer_id))
    datastore = layer.datastore
    workspace = datastore.workspace
    gs = geographic_servers.get_instance().get_server_by_id(
        workspace.server.id)

    layer_styles = StyleLayer.objects.filter(layer=layer)
    is_default = False
    if not is_preview:
        is_default = json_data.get('is_default')
    if is_default:
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            s.is_default = False
            s.save()
    else:
        has_default_style = False
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            if s.is_default:
                has_default_style = True
        if not has_default_style:
            is_default = True

    name = json_data.get('name')
    if is_preview:
        name = name + '__tmp'
        is_default = False

    style = Style(name=name,
                  title=json_data.get('title'),
                  is_default=is_default,
                  type='IN')
    if json_data.get('minscale') != '':
        style.minscale = json_data.get('minscale')
    else:
        style.minscale = -1
    if json_data.get('maxscale') != '':
        style.maxscale = json_data.get('maxscale')
    else:
        style.maxscale = -1

    style.save()
    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    for r in json_data.get('rules'):
        json_rule = r.get('rule')

        filter_text = ""
        if json_rule.get('filter').__len__() != 0:
            filter_text = str(json.dumps(json_rule.get('filter')))

        rule = Rule(style=style,
                    name=json_rule.get('name'),
                    title=json_rule.get('title'),
                    abstract='',
                    filter=filter_text,
                    minscale=json_rule.get('minscale'),
                    maxscale=json_rule.get('maxscale'),
                    order=json_rule.get('order'))
        rule.save()

        for sym in r.get('symbolizers'):
            if sym.get('type') == 'PolygonSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'LineSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'MarkSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    well_known_name=json_sym.get('well_known_name'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'ExternalGraphicSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

            elif sym.get('type') == 'TextSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = TextSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    label=json_sym.get('label'),
                    font_family=json_sym.get('font_family'),
                    font_size=json_sym.get('font_size'),
                    font_weight=json_sym.get('font_weight'),
                    font_style=json_sym.get('font_style'),
                    halo_fill=json_sym.get('halo_fill'),
                    halo_fill_opacity=json_sym.get('halo_fill_opacity'),
                    halo_radius=json_sym.get('halo_radius'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                )
                symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style)

    if is_preview:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            return True
        else:
            return False
    else:
        if gs.createStyle(style.name, sld_body):
            if not is_preview:
                gs.setLayerStyle(layer, style.name, style.is_default)
            return True

        else:
            return False
    def setUp(self):
        self.set_application(tst_app)
        self.setup_testbed()
        self.init_datastore_stub()
        self.init_memcache_stub()
        self.init_taskqueue_stub()
        self.init_mail_stub()
        self.register_search_api_stub()
        self.init_urlfetch_stub()
        self.init_modules_stub()

        # Create enterprise, sensortype and sensor
        self.e = Enterprise.Create()
        self.e.Update(name="Test Ent", timezone="Africa/Nairobi")
        self.e.put()

        self.tracker = SensorType.Create(self.e)
        schema = {
            'speed': {
                'unit': 'kph'
            },
            'ign_on': {
                'unit': 'boolean'
            },
            'ign_off': {
                'unit': 'boolean'
            }

        }
        self.tracker.Update(name="Tracker Sensor", schema=json.dumps(schema))
        self.tracker.put()

        self.vehicle_1 = Sensor.Create(self.e, TEST_SENSOR_ID, self.tracker.key().id())
        self.vehicle_1.Update(
            sensortype_id=self.tracker.key().id(),
            name="Vehicle Sensor 1"
            )
        self.vehicle_1.put()

        # Create alarm
        self.ign_on_alarm = Rule.Create(self.e)
        self.ign_on_alarm.Update(
            name="Ignition On",
            sensortype_id=self.tracker.key().id(),
            column="ign_on",
            trigger=RULE.CEILING,
            value2=0,
            consecutive_limit=-1,
            duration=0)
        self.ign_on_alarm.put()
        self.ign_off_alarm = Rule.Create(self.e)
        self.ign_off_alarm.Update(
            name="Ignition Off",
            sensortype_id=self.tracker.key().id(),
            column="ign_off",
            trigger=RULE.CEILING,
            value2=0,
            consecutive_limit=-1,
            duration=0,
            spec=json.dumps({'processers': [
                {
                    'analysis_key_pattern': ANALYSIS_KEY_PATTERN,
                    'expr': '. + SINCE(LAST_ALARM(%d)) / 1000' % self.ign_on_alarm.key().id(),
                    'column': 'on_secs'
                }
            ]}))
        self.ign_off_alarm.put()
예제 #19
0
파일: views.py 프로젝트: xunyuw/iFlyQA
def site(request, task_id, site_id):
    user = request.user
    site = Site.objects.select_related().get(id=site_id)
    task = site.task
    if task.user != user and not user.has_perm('apps.list_all_task'):
        raise PermissionDenied
    if request.method == 'POST':
        errors = {}
        data = {}
        if not user.has_perm("apps.change_site"):
            raise PermissionDenied
        method = request.POST['method']
        if method == "save_site":
            if not user.has_perm("apps.add_rule"):
                raise PermissionDenied
            post_site = json.loads(request.POST['site'])
            post_rules = json.loads(request.POST['rules'])
            form = SiteForm(post_site, instance=site)
            if form.is_valid():
                site = form.save()
            else:
                errors['site'] = form.errors
            for post_rule in post_rules:
                if post_rule.get('status', None) == "removed":
                    if post_rule['id'].isdigit():
                        if not user.has_perm("apps.delete_rule"):
                            raise PermissionDenied
                        rule_id = int(post_rule['id'])
                        try:
                            rule = Rule.objects.get(id=rule_id)
                            rule.delete()
                        except Rule.DoesNotExist:
                            errors['other'] = "not exist"
                        continue
                    else:
                        continue
                if post_rule['id'].isdigit():
                    rule_ins = Rule.objects.get(id=int(post_rule['id']))
                    form = RuleForm(post_rule, instance=rule_ins)
                else:
                    rule_ins = Rule()
                    rule_ins.site = site
                    form = RuleForm(post_rule, instance=rule_ins)
                if form.is_valid():
                    rule = form.save()
                else:
                    errors[post_rule['id']] = {
                        "cnName":post_rule['cnName'],
                        "error":form.errors
                    }
        elif method == "upload":
            controller = SiteController(site)
            file_type = request.POST['filetype']
            data['filename'] = controller.save_upload_file(request.FILES['files[]'], file_type)
        return HttpResponse(json.dumps({"status":"ok", "errors":errors, "data":data}))
    else:
        all_rules = site.rules.all()
        rules_list = RuleListForm()
        rules_list.fields['rules'].choices = [(rule.id, rule.name) for rule in all_rules]
        rules = [{"rule":rule, "form":RuleForm(instance=rule)} for rule in all_rules]
        new_rule = RuleForm()
        form = SiteForm(instance=site)
    return render_to_response('site.html', {
        'site':site,
        'post_url':reverse("site", args=(task.pk, site.pk,)),
        'form': form,
        'rules_list':rules_list,
        'rules':rules,
        'new_rule':new_rule,
        'task': task
    }, RequestContext(request))
예제 #20
0
    new_items['atv'] = (items['atv'] // 3 * 2) + (items['atv'] % 3)
    return new_items


def ipad_discount(items, catalogue):
    new_catalogue = catalogue.copy()
    if items['ipd'] > 4:
        new_catalogue['ipd'] = 499.99
    return new_catalogue


def free_vga(items, catalogue):
    new_items = items.copy()
    mbp_count = items['mbp']
    vga_count = items['vga']
    if vga_count < mbp_count:
        new_items['vga'] = 0
    else:
        new_items['vga'] = vga_count - mbp_count

    return new_items


# Append accordingly whether special rule affects price or quantity
qty_rules.append(apple_tv_discount)
price_rules.append(ipad_discount)
qty_rules.append(free_vga)

# Import pricingRules to checkout system
pricingRules = Rule(catalogue, {'price': price_rules, 'qty': qty_rules})
예제 #21
0
def get_sld(request, type, json_data, layer_id, single_symbol=False):

    layer = Layer.objects.get(id=layer_id)
    layer.name = layer.datastore.workspace.name + ':' + layer.name
    is_default = False
    if json_data.get('is_default'):
        is_default = json_data.get('is_default')
    style = Style(name=json_data.get('name'),
                  title=json_data.get('title'),
                  is_default=is_default,
                  type=type)
    style.save()

    for r in json_data.get('rules'):
        json_rule = r.get('rule')

        filter_text = ""
        if json_rule.get('filter').__len__() != 0:
            filter_text = str(json.dumps(json_rule.get('filter')))

        rule = Rule(style=style,
                    name=json_rule.get('name'),
                    title=json_rule.get('title'),
                    abstract='',
                    filter=filter_text,
                    minscale=json_rule.get('minscale'),
                    maxscale=json_rule.get('maxscale'),
                    order=json_rule.get('order'))
        rule.save()

        for sym in r.get('symbolizers'):
            if sym.get('type') == 'PolygonSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'LineSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'MarkSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    well_known_name=json_sym.get('well_known_name'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'ExternalGraphicSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

            elif sym.get('type') == 'TextSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = TextSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    label=json_sym.get('label'),
                    font_family=json_sym.get('font_family'),
                    font_size=json_sym.get('font_size'),
                    font_weight=json_sym.get('font_weight'),
                    font_style=json_sym.get('font_style'),
                    halo_fill=json_sym.get('halo_fill'),
                    halo_fill_opacity=json_sym.get('halo_fill_opacity'),
                    halo_radius=json_sym.get('halo_radius'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    anchor_point_x=json_sym.get('anchor_point_x'),
                    anchor_point_y=json_sym.get('anchor_point_y'),
                )
                symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style, single_symbol)

    style.delete()
    return sld_body
예제 #22
0
def add_symbol(request, json_rule, library_id, symbol_type):
    gs = geographic_servers.get_instance().get_default_server()

    name = json_rule.get('name')
    title = json_rule.get('title')

    if _valid_name_regex.search(name) == None:
        raise InvalidValue(
            -1,
            _("Invalid name: '{value}'. Name should not contain any special characters"
              ).format(value=name))

    #if _valid_title_regex.search(title) == None:
    #    raise InvalidValue(-1, _("Invalid title: '{value}'. Title should not contain any special characters").format(value=title))

    style = Style(name=name, title=title, is_default=False, type="US")
    style.save()

    rule = Rule(style=style,
                name=name,
                title=title,
                abstract="",
                filter=str(""),
                minscale=json_rule.get('minscale'),
                maxscale=json_rule.get('maxscale'),
                order=json_rule.get('order'))
    rule.save()

    library = Library.objects.get(id=int(library_id))

    library_rule = LibraryRule(library=library, rule=rule)
    library_rule.save()

    symbs = json_rule.get('symbolizers')
    for sym in symbs:
        json_sym = json.loads(sym.get('json'))
        if symbol_type == 'ExternalGraphicSymbolizer':
            library_path = utils.check_library_path(library)
            file_name = name + '.png'
            if utils.save_external_graphic(library_path,
                                           request.FILES['eg-file'],
                                           file_name):
                online_resource = utils.get_online_resource(library, file_name)
                json_sym['online_resource'] = json_sym[
                    'online_resource'].replace("online_resource_replace",
                                               online_resource)

                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=json_rule.get('order'),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

        if symbol_type == 'PolygonSymbolizer':
            symbolizer = PolygonSymbolizer(
                rule=rule,
                order=json_sym.get('order'),
                fill=json_sym.get('fill'),
                fill_opacity=json_sym.get('fill_opacity'),
                stroke=json_sym.get('stroke'),
                stroke_width=json_sym.get('stroke_width'),
                stroke_opacity=json_sym.get('stroke_opacity'),
                stroke_dash_array=json_sym.get('stroke_dash_array'))
            symbolizer.save()

        elif symbol_type == 'LineSymbolizer':
            symbolizer = LineSymbolizer(
                rule=rule,
                order=json_sym.get('order'),
                stroke=json_sym.get('stroke'),
                stroke_width=json_sym.get('stroke_width'),
                stroke_opacity=json_sym.get('stroke_opacity'),
                stroke_dash_array=json_sym.get('stroke_dash_array'))
            symbolizer.save()

        elif symbol_type == 'MarkSymbolizer' or symbol_type == 'PointSymbolizer':
            symbolizer = MarkSymbolizer(
                rule=rule,
                order=json_sym.get('order'),
                opacity=json_sym.get('opacity'),
                size=json_sym.get('size'),
                rotation=json_sym.get('rotation'),
                well_known_name=json_sym.get('well_known_name'),
                fill=json_sym.get('fill'),
                fill_opacity=json_sym.get('fill_opacity'),
                stroke=json_sym.get('stroke'),
                stroke_width=json_sym.get('stroke_width'),
                stroke_opacity=json_sym.get('stroke_opacity'),
                stroke_dash_array=json_sym.get('stroke_dash_array'))
            symbolizer.save()

    sld_body = sld_builder.build_library_symbol(rule)

    if gs.createStyle(style.name, sld_body):
        return True

    else:
        gs.updateStyle(None, style.name, sld_body)
        return True
예제 #23
0
def upload_library(name, description, file):
    gs = geographic_servers.get_instance().get_default_server()

    library = Library(name=name, description=description)
    library.save()

    library_path = utils.check_library_path(library)
    file_path = utils.__get_uncompressed_file_upload_path(file)
    utils.copyrecursively(file_path + "/resources/", library_path)

    file_list = os.listdir(file_path)
    for file in file_list:
        if not os.path.isdir(file_path + "/" + file):
            f = open(file_path + "/" + file, 'r')
            sld = sld_reader.parse(f)

            style_name = remove_accents(sld.NamedLayer[0].Name)
            sld.NamedLayer[0].Name = style_name
            style_title = sld.NamedLayer[0].UserStyle[0].FeatureTypeStyle[
                0].Rule[0].Title
            r = sld.NamedLayer[0].UserStyle[0].FeatureTypeStyle[0].Rule[0]

            style = Style(name=style_name,
                          title=style_title,
                          is_default=True,
                          type="US")
            style.save()

            rule = Rule(style=style,
                        name=style_name,
                        title=style_title,
                        abstract='',
                        filter=str(""),
                        minscale=-1 if r.MinScaleDenominator is None else
                        r.MinScaleDenominator,
                        maxscale=-1 if r.MaxScaleDenominator is None else
                        r.MaxScaleDenominator,
                        order=0)
            rule.save()

            library_rule = LibraryRule(library=library, rule=rule)
            library_rule.save()

            scount = r.Symbolizer.__len__() - 1
            for s in r.Symbolizer:
                if s.original_tagname_ == 'PointSymbolizer':
                    opacity = s.Graphic.Opacity.valueOf_
                    rotation = s.Graphic.Rotation.valueOf_
                    size = s.Graphic.Size.valueOf_
                    if len(s.Graphic.Mark) >= 1:
                        mark = s.Graphic.Mark[0]

                        stroke = '#000000'
                        if mark.Stroke.CssParameter.__len__() > 0:
                            stroke = mark.Stroke.CssParameter[0].valueOf_

                        stroke_width = 1
                        if mark.Stroke.CssParameter.__len__() > 1:
                            stroke_width = mark.Stroke.CssParameter[1].valueOf_

                        stroke_opacity = 1
                        if mark.Stroke.CssParameter.__len__() > 2:
                            stroke_opacity = mark.Stroke.CssParameter[
                                2].valueOf_

                        stroke_dash_array = 'none'
                        if mark.Stroke.CssParameter.__len__() > 3:
                            stroke_dash_array = mark.Stroke.CssParameter[
                                3].valueOf_

                        symbolizer = MarkSymbolizer(
                            rule=rule,
                            order=scount,
                            opacity=opacity,
                            size=size,
                            rotation=rotation,
                            well_known_name=mark.WellKnownName,
                            fill=mark.Fill.CssParameter[0].valueOf_,
                            fill_opacity=mark.Fill.CssParameter[1].valueOf_,
                            stroke=stroke,
                            stroke_width=stroke_width,
                            stroke_opacity=stroke_opacity,
                            stroke_dash_array=stroke_dash_array)
                        symbolizer.save()

                    if len(s.Graphic.ExternalGraphic) >= 1:
                        external_graphic = s.Graphic.ExternalGraphic[0]
                        online_resource = external_graphic.OnlineResource.href.split(
                            '/')
                        online_resource[-2] = library.name
                        new_online_resource = settings.MEDIA_URL + online_resource[
                            -3] + '/' + library.name + '/' + remove_accents(
                                online_resource[-1])
                        symbolizer = ExternalGraphicSymbolizer(
                            rule=rule,
                            order=scount,
                            opacity=opacity,
                            size=size,
                            rotation=rotation,
                            online_resource=new_online_resource,
                            format=external_graphic.Format)
                        symbolizer.save()

                elif s.original_tagname_ == 'LineSymbolizer':
                    stroke = '#000000'
                    if s.Stroke:
                        if s.Stroke.CssParameter.__len__() > 0:
                            stroke = s.Stroke.CssParameter[0].valueOf_

                        stroke_width = 1
                        if s.Stroke.CssParameter.__len__() > 1:
                            stroke_width = s.Stroke.CssParameter[1].valueOf_

                        stroke_opacity = 1
                        if s.Stroke.CssParameter.__len__() > 2:
                            stroke_opacity = s.Stroke.CssParameter[2].valueOf_

                        stroke_dash_array = 'none'
                        if s.Stroke.CssParameter.__len__() > 3:
                            stroke_dash_array = s.Stroke.CssParameter[
                                3].valueOf_

                        symbolizer = LineSymbolizer(
                            rule=rule,
                            order=scount,
                            stroke=stroke,
                            stroke_width=stroke_width,
                            stroke_opacity=stroke_opacity,
                            stroke_dash_array=stroke_dash_array)
                        symbolizer.save()

                elif s.original_tagname_ == 'PolygonSymbolizer':
                    stroke = '#000000'
                    if s.Stroke.CssParameter.__len__() > 0:
                        stroke = s.Stroke.CssParameter[0].valueOf_

                    stroke_width = 1
                    if s.Stroke.CssParameter.__len__() > 1:
                        stroke_width = s.Stroke.CssParameter[1].valueOf_

                    stroke_opacity = 1
                    if s.Stroke.CssParameter.__len__() > 2:
                        stroke_opacity = s.Stroke.CssParameter[2].valueOf_

                    stroke_dash_array = 'none'
                    if s.Stroke.CssParameter.__len__() > 3:
                        stroke_dash_array = s.Stroke.CssParameter[3].valueOf_

                    symbolizer = PolygonSymbolizer(
                        rule=rule,
                        order=scount,
                        fill=s.Fill.CssParameter[0].valueOf_,
                        fill_opacity=s.Fill.CssParameter[1].valueOf_,
                        stroke=stroke,
                        stroke_width=stroke_width,
                        stroke_opacity=stroke_opacity,
                        stroke_dash_array=stroke_dash_array)
                    symbolizer.save()

                scount -= 1

            output = StringIO.StringIO()
            sld.export(output, 0)
            sld_body = output.getvalue()
            output.close()

            gs.createStyle(style.name, sld_body)
    gs.reload_nodes()

    utils.__delete_temporaries(file_path)
예제 #24
0
    'variation': 1.5
}, {
    'city': 'Nueva Guinea',
    'country': 'ni',
    'sku': 'AZ00001',
    'min_condition': 800,
    'max_condition': 810,
    'variation': 0.5
}]
# Create the database
db.create_all()

# Iterate over the PEOPLE structure and populate the database
for product in PRODUCTS:
    p = Product(sku=product['sku'],
                description=product['description'],
                price=product['price'])
    db.session.add(p)

db.session.commit()

for rule in RULES:
    r = Rule(city=rule['city'],
             country=rule['country'],
             sku=rule['sku'],
             min_condition=rule['min_condition'],
             max_condition=rule['max_condition'],
             variation=rule['variation'])
    db.session.add(r)

db.session.commit()
예제 #25
0
def rule_add(request):  # OK!
    """
        Добавляем правило
    """


    if request.user.get_profile().is_card:
        raise Http404
    context = {}
    context["title"] = _(u"Adding call forwarding rule")
    context["adding_new"] = True
    try:
        user_guide_article = Article.objects.get(slug="call_forwarding_add_user_guide")
        user_guide = user_guide_article.text
        context["user_guide"] = user_guide
    except:
        pass

    model = Rule()

    profile = request.user.get_profile()  # получаем профиль текущего пользователя

    if not request.POST:
        # Первый вызов. Просто отобразить пустую форму.
        form = RuleEditForm(model=model, profile=profile, request=request)
    else:
        # Пришли данные в POST-запросе.
        # Надо проверить форму на валижность,
        # потом проверить на пересекаемость временных интервалов
        # потом добавить в базу


        if request.POST.get("submit"):  # если нажали Submit а не Cancel
            rule_number = request.POST.get("from_number")
            to_number = request.POST.get("to_number")

            try:
                getfax = fax_numbers.objects.get(number=rule_number, enabled=True)
            except:
                getfax = None
            if getfax != None:
                request.notifications.add(_(u"On this issue of the fax function"), "warning")
                return HttpResponseRedirect("/account/call_forwarding/add_rule/")


            temp_ivr = create_myivr_temp.objects.filter(billing_account_id_temp=profile.billing_account_id, enabled=True, number__tel_number=rule_number)
            if temp_ivr:
                request.notifications.add(_(u"On this issue is included ivr"), "warning")
                return HttpResponseRedirect("/account/call_forwarding/add_rule/")
            # получаем форму из запроса
            form = RuleEditForm(model=model, data=request.POST, profile=profile, request=request)
            flag = recursive(to_number)
            if not flag:
                gr_id = TelNumbersGroupNumbers.objects.filter(telnumber__tel_number=rule_number)
                print rule_number
                gateway = None
                for g_id in gr_id:
                    gateway = GatewayModel.objects.filter(tel_group=g_id.telnumbersgroup_id, enabled=True)
                if gateway:
                    request.notifications.add(_(u"Данный номер или номер, участвующий в цепочке из переадресаций, задействован в регистрации на внешних Sip сервисах"), "warning")
                    context['form'] = form
                    return context
            # проверяем на валидность
            if form.is_valid():  # если форма верная
                # model = form.GetModel()         # получить модель
                model = form.ok_model
                if model:
                    if profile:
                        if profile.has_billing_account:
                            model.billing_account_id = profile.billing_account_id
                            model.save()  # Сохранить ее в базе
                            request.notifications.add(_(u"Rule was succesfuly added."), "success")
                            return HttpResponseRedirect("/account/call_forwarding/")  # перейти на страницу со списком правил
                        else:
                            raise Error("Current user don't have a billing account!")
                    else:
                        raise Error("Cannot get current user's profile!")
                else:
                    return HttpResponseRedirect("/account/call_forwarding/add_rule/")
        else:
            return HttpResponseRedirect("/account/call_forwarding/")

    context["current_view_name"] = "callforwarding_rules_list"
    context["form"] = form
    return context
def update_style(request, json_data, layer_id, style_id, is_preview=False):
    style = Style.objects.get(id=int(style_id))
    layer = Layer.objects.get(id=int(layer_id))

    layer_styles = StyleLayer.objects.filter(layer=layer)
    style_is_default = False
    if not is_preview:
        style_is_default = json_data.get('is_default')

    if style_is_default:
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            s.is_default = False
            s.save()
        datastore = layer.datastore
        workspace = datastore.workspace
        mapservice.setLayerStyle(layer, style.name, style.is_default)
    else:
        has_default_style = False
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            if s != style and s.is_default:
                has_default_style = True
        if not has_default_style:
            datastore = layer.datastore
            workspace = datastore.workspace
            style_is_default = True
            mapservice.setLayerStyle(layer, style.name, True)

    style.title = json_data.get('title')
    if json_data.get('minscale') != '':
        style.minscale = json_data.get('minscale')
    else:
        style.minscale = -1
    if json_data.get('maxscale') != '':
        style.maxscale = json_data.get('maxscale')
    else:
        style.maxscale = -1
    style.is_default = style_is_default
    style.save()

    rules = Rule.objects.filter(style=style)
    for ru in rules:
        symbolizers = Symbolizer.objects.filter(rule=ru)
        for symbolizer in symbolizers:
            symbolizer.delete()
        ru.delete()

    for r in json_data.get('rules'):
        json_rule = r.get('rule')

        filter_text = ""
        if json_rule.get('filter').__len__() != 0:
            filter_text = str(json.dumps(json_rule.get('filter')))

        if json_data.get('minscale') != '':
            minscale = json_rule.get('minscale')
        else:
            minscale = -1
        if json_data.get('maxscale') != '':
            maxscale = json_rule.get('maxscale')
        else:
            maxscale = -1

        rule = Rule(style=style,
                    name=json_rule.get('name'),
                    title=json_rule.get('title'),
                    abstract='',
                    filter=filter_text,
                    minscale=minscale,
                    maxscale=maxscale,
                    order=json_rule.get('order'))
        rule.save()

        for sym in r.get('symbolizers'):
            if sym.get('type') == 'PolygonSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'LineSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'MarkSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    well_known_name=json_sym.get('well_known_name'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'ExternalGraphicSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

            elif sym.get('type') == 'TextSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = TextSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    label=json_sym.get('label'),
                    font_family=json_sym.get('font_family'),
                    font_size=json_sym.get('font_size'),
                    font_weight=json_sym.get('font_weight'),
                    font_style=json_sym.get('font_style'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    halo_fill=json_sym.get('halo_fill'),
                    halo_fill_opacity=json_sym.get('halo_fill_opacity'),
                    halo_radius=json_sym.get('halo_radius'),
                    anchor_point_x=json_sym.get('anchor_point_x'),
                    anchor_point_y=json_sym.get('anchor_point_y'),
                )
                symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style)
    if is_preview:
        if mapservice.createOverwrittenStyle(style.name, sld_body, True):
            return True
        else:
            return False
    else:
        if mapservice.updateStyle(layer, style.name, sld_body):
            mapservice.setLayerStyle(layer, style.name, style.is_default)
            return True
        else:
            return False
예제 #27
0
def add(request):  # brace yourself traveler, scary code ahead

    if request.method == 'POST':
        form = NewRuleForm(request.POST)

        if form.is_valid():

            rule = Rule()
            rule.name = form.cleaned_data["name"]

            for app in core.get_apps():
                for model in app.get_models():
                    for inst in model.objects.all():
                        if inst == form.cleaned_data["origin_instance"]:
                            rule.origin_device_type = ContentType.objects.get(app_label=app.name, model=model.__name__.lower())
                            break

            rule.option = form.cleaned_data["option"]
            # rule.origin_object_id = rule.origin_device_type.get_object_for_this_type().__cls__.objects.filter(name=form.cleaned_data["origin_instance"].name)
            rule.origin_object_id = form.cleaned_data["origin_instance"].pk
            rule.origin_attribute = form.cleaned_data["origin_attribute"]

            for app in core.get_apps():
                for model in app.get_models():
                    for inst in model.objects.all():
                        if inst == form.cleaned_data["destination_instance"]:
                            rule.destination_device_type = ContentType.objects.get(app_label=app.name, model=model.__name__.lower())
                            break

            rule.destination_object_id = form.cleaned_data["destination_instance"].pk
            rule.destination_method = form.cleaned_data["destination_method"]

            rule.save()

            return HttpResponseRedirect('/rule/')
        else:
            # TODO: a bit hacky
            request.include_form = True
            return index(request)

    else:
        return HttpResponseRedirect('/rule/')
예제 #28
0
def sld_import(name, is_default, layer_id, file, mapservice):

    layer = Layer.objects.get(id=int(layer_id))

    ### write the data to a temp file
    tup = tempfile.mkstemp()  # make a tmp file
    f = os.fdopen(tup[0], 'w')  # open the tmp file for writing
    f.write(file.read())  # write the tmp file
    f.close()

    filepath = tup[1]
    tmp_sld = open(filepath, 'r')

    sld = sld_builder.parse_sld(tmp_sld)

    style = Style(name=name,
                  title=sld.NamedLayer[0].UserStyle[0].Title,
                  is_default=is_default,
                  type="EX")
    style.save()

    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    rules = sld.NamedLayer[0].UserStyle[0].FeatureTypeStyle[0].Rule
    for r in rules:
        filter = utils.filter_to_json(r.Filter)
        rule = Rule(style=style,
                    name=r.Name,
                    title=r.Title,
                    abstract='',
                    filter=json.dumps(filter),
                    minscale=-1 if r.MinScaleDenominator is None else
                    r.MinScaleDenominator,
                    maxscale=-1 if r.MaxScaleDenominator is None else
                    r.MaxScaleDenominator,
                    order=0)
        rule.save()

        scount = 0
        for s in r.Symbolizer:
            if s.original_tagname_ == 'PointSymbolizer':
                opacity = s.Graphic.Opacity.valueOf_
                rotation = s.Graphic.Rotation.valueOf_
                size = s.Graphic.Size.valueOf_
                if len(s.Graphic.Mark) >= 1:
                    mark = s.Graphic.Mark[0]

                    fill = '#383838'
                    fill_opacity = 0.5
                    if len(mark.Fill.CssParameter) > 0:
                        for css_parameter in mark.Fill.CssParameter:
                            if css_parameter.name == 'fill':
                                fill = css_parameter.valueOf_
                            if css_parameter.name == 'fill-opacity':
                                fill_opacity = css_parameter.valueOf_

                    stroke = '#ffffff'
                    stroke_width = 1
                    stroke_opacity = 0.0
                    stroke_dash_array = 'none'
                    if len(mark.Stroke.CssParameter) > 0:
                        for css_parameter in mark.Stroke.CssParameter:
                            if css_parameter.name == 'stroke':
                                stroke = css_parameter.valueOf_
                            if css_parameter.name == 'stroke-width':
                                stroke_width = css_parameter.valueOf_
                            if css_parameter.name == 'stroke-opacity':
                                stroke_opacity = css_parameter.valueOf_
                            if css_parameter.name == 'stroke-dasharray':
                                stroke_dash_array = css_parameter.valueOf_

                    symbolizer = MarkSymbolizer(
                        rule=rule,
                        order=scount,
                        opacity=opacity,
                        size=size,
                        rotation=rotation,
                        well_known_name=mark.WellKnownName,
                        fill=fill,
                        fill_opacity=fill_opacity,
                        stroke=stroke,
                        stroke_width=stroke_width,
                        stroke_opacity=stroke_opacity,
                        stroke_dash_array=stroke_dash_array)
                    symbolizer.save()

                if len(s.Graphic.ExternalGraphic) >= 1:
                    print 'ExternalGraphic'

            elif s.original_tagname_ == 'LineSymbolizer':
                stroke = '#ffffff'
                stroke_width = 1
                stroke_opacity = 0.0
                stroke_dash_array = 'none'
                if len(s.Stroke.CssParameter) > 0:
                    for css_parameter in s.Stroke.CssParameter:
                        if css_parameter.name == 'stroke':
                            stroke = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-width':
                            stroke_width = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-opacity':
                            stroke_opacity = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-dasharray':
                            stroke_dash_array = css_parameter.valueOf_

                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=scount,
                    stroke=stroke,
                    stroke_width=stroke_width,
                    stroke_opacity=stroke_opacity,
                    stroke_dash_array=stroke_dash_array)
                symbolizer.save()

            elif s.original_tagname_ == 'PolygonSymbolizer':

                fill = '#383838'
                fill_opacity = 0.5
                if len(s.Fill.CssParameter) > 0:
                    for css_parameter in s.Fill.CssParameter:
                        if css_parameter.name == 'fill':
                            fill = css_parameter.valueOf_
                        if css_parameter.name == 'fill-opacity':
                            fill_opacity = css_parameter.valueOf_

                stroke = '#ffffff'
                stroke_width = 1
                stroke_opacity = 0.0
                stroke_dash_array = 'none'
                if len(s.Stroke.CssParameter) > 0:
                    for css_parameter in s.Stroke.CssParameter:
                        if css_parameter.name == 'stroke':
                            stroke = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-width':
                            stroke_width = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-opacity':
                            stroke_opacity = css_parameter.valueOf_
                        if css_parameter.name == 'stroke-dasharray':
                            stroke_dash_array = css_parameter.valueOf_

                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=scount,
                    fill=fill,
                    fill_opacity=fill_opacity,
                    stroke=stroke,
                    stroke_width=stroke_width,
                    stroke_opacity=stroke_opacity,
                    stroke_dash_array=stroke_dash_array)
                symbolizer.save()

            scount += 1

    sld_body = sld_builder.build_sld(layer, style)
    if mapservice.createStyle(style.name, sld_body):
        mapservice.setLayerStyle(layer, style.name, style.is_default)
        utils.__delete_temporaries(filepath)
        return True

    else:
        utils.__delete_temporaries(filepath)
        return False
def create_style(request,
                 json_data,
                 layer_id,
                 is_preview=False,
                 has_custom_legend=None):

    layer = Layer.objects.get(id=int(layer_id))
    datastore = layer.datastore
    workspace = datastore.workspace

    layer_styles = StyleLayer.objects.filter(layer=layer)
    is_default = False
    if not is_preview:
        is_default = json_data.get('is_default')
    if is_default:
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            s.is_default = False
            s.save()
    else:
        has_default_style = False
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            if s.is_default:
                has_default_style = True
        if not has_default_style:
            is_default = True

    name = json_data.get('name')
    if is_preview:
        name = name + '__tmp'
        is_default = False

    style = Style(name=name,
                  title=json_data.get('title'),
                  is_default=is_default,
                  type='CT')

    if has_custom_legend == 'true':
        style.has_custom_legend = True
        legend_name = 'legend_' + ''.join(
            random.choice(string.ascii_uppercase) for i in range(6)) + '.png'
        legend_path = utils.check_custom_legend_path()
        style.custom_legend_url = utils.save_custom_legend(
            legend_path, request.FILES['file'], legend_name)

    else:
        style.has_custom_legend = False

    style.save()
    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    json_rule = json_data.get('rule')

    filter_text = ""
    if json_rule.get('filter').__len__() != 0:
        filter_text = str(json.dumps(json_rule.get('filter')))

    rule = Rule(style=style,
                name=json_rule.get('name'),
                title=json_rule.get('title'),
                abstract="",
                filter=filter_text,
                minscale=json_rule.get('minscale'),
                maxscale=json_rule.get('maxscale'),
                order=json_rule.get('order'))
    rule.save()

    color_map = ColorMap(type='ramp', extended=False)
    color_map.save()

    symbolizer = RasterSymbolizer(rule=rule,
                                  color_map=color_map,
                                  order=0,
                                  opacity=1.0)
    symbolizer.save()

    color_map_entry_list = []
    for entry in json_data.get('entries'):
        json_entry = json.loads(entry.get('json'))
        color_map_entry = ColorMapEntry(color_map=color_map,
                                        order=int(json_entry.get('order')),
                                        color=json_entry.get('color'),
                                        quantity=json_entry.get('quantity'),
                                        label=json_entry.get('label'),
                                        opacity=json_entry.get('opacity'))
        color_map_entry_list.append(color_map_entry)

    order = 0
    color_map_entry_list = sorted(
        color_map_entry_list,
        key=lambda color_map_entry: float(color_map_entry.quantity))
    for cme in color_map_entry_list:
        cme.order = order
        cme.save()
        order = order + 1

    sld_body = sld_builder.build_sld(layer, style)
    if is_preview:
        if mapservice.createOverwrittenStyle(style.name, sld_body, True):
            return True
        else:
            return False
    else:
        if mapservice.createOverwrittenStyle(style.name, sld_body, True):
            if not is_preview:
                mapservice.setLayerStyle(layer, style.name, style.is_default)
            return True

        else:
            return False
예제 #30
0
def clone_style(mapservice, layer, original_style_name, cloned_style_name):
    exists_cloned_style = False
    try:
        original_style = Style.objects.filter(
            name__exact=original_style_name)[0]
    except Exception as e:
        print str(e)
        return False

    try:
        style = Style.objects.filter(name__exact=cloned_style_name)[0]
        exists_cloned_style = True
    except Exception as e:
        print "DEBUG: Problem getting style .." + cloned_style_name
        print str(e)

    if exists_cloned_style:
        print "DEBUG: Exists cloned style .." + cloned_style_name
        rule = Rule.objects.filter(style=style)[0]
        symbolizers_to_delete = Symbolizer.objects.filter(rule=rule)
        for i in symbolizers_to_delete:
            i.delete()
    else:
        print "DEBUG: Not existe cloned style .." + cloned_style_name
        style = Style(name=cloned_style_name,
                      title=original_style_name,
                      is_default=True,
                      type='US')
        style.save()

        style_layer = StyleLayer(style=style, layer=layer)
        style_layer.save()

        rule = Rule(style=style,
                    name='Default symbol',
                    title=original_style_name,
                    abstract='',
                    filter=str(""),
                    minscale=-1,
                    maxscale=-1,
                    order=0)
        rule.save()

    original_rules = Rule.objects.filter(
        style=original_style).order_by('order')
    for original_rule in original_rules:
        original_symbolizers = Symbolizer.objects.filter(rule=original_rule)
        for original_symbolizer in original_symbolizers:
            if hasattr(original_symbolizer, 'externalgraphicsymbolizer'):
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=original_symbolizer.externalgraphicsymbolizer.order,
                    opacity=original_symbolizer.externalgraphicsymbolizer.
                    opacity,
                    size=original_symbolizer.externalgraphicsymbolizer.size,
                    rotation=original_symbolizer.externalgraphicsymbolizer.
                    rotation,
                    online_resource=original_symbolizer.
                    externalgraphicsymbolizer.online_resource,
                    format=original_symbolizer.externalgraphicsymbolizer.
                    format,
                )
                symbolizer.save()

            elif hasattr(original_symbolizer, 'polygonsymbolizer'):
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=original_symbolizer.polygonsymbolizer.order,
                    fill=original_symbolizer.polygonsymbolizer.fill,
                    fill_opacity=original_symbolizer.polygonsymbolizer.
                    fill_opacity,
                    stroke=original_symbolizer.polygonsymbolizer.stroke,
                    stroke_width=original_symbolizer.polygonsymbolizer.
                    stroke_width,
                    stroke_opacity=original_symbolizer.polygonsymbolizer.
                    stroke_opacity,
                    stroke_dash_array=original_symbolizer.polygonsymbolizer.
                    stroke_dash_array)
                symbolizer.save()

            elif hasattr(original_symbolizer, 'linesymbolizer'):
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=original_symbolizer.linesymbolizer.order,
                    stroke=original_symbolizer.linesymbolizer.stroke,
                    stroke_width=original_symbolizer.linesymbolizer.
                    stroke_width,
                    stroke_opacity=original_symbolizer.linesymbolizer.
                    stroke_opacity,
                    stroke_dash_array=original_symbolizer.linesymbolizer.
                    stroke_dash_array)
                symbolizer.save()

            elif hasattr(original_symbolizer, 'marksymbolizer'):
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=original_symbolizer.marksymbolizer.order,
                    opacity=original_symbolizer.marksymbolizer.opacity,
                    size=original_symbolizer.marksymbolizer.size,
                    rotation=original_symbolizer.marksymbolizer.rotation,
                    well_known_name=original_symbolizer.marksymbolizer.
                    well_known_name,
                    fill=original_symbolizer.marksymbolizer.fill,
                    fill_opacity=original_symbolizer.marksymbolizer.
                    fill_opacity,
                    stroke=original_symbolizer.marksymbolizer.stroke,
                    stroke_width=original_symbolizer.marksymbolizer.
                    stroke_width,
                    stroke_opacity=original_symbolizer.marksymbolizer.
                    stroke_opacity,
                    stroke_dash_array=original_symbolizer.marksymbolizer.
                    stroke_dash_array)
                symbolizer.save()

    sld_body = sld_builder.build_library_symbol(rule)
    s = mapservice.getStyle(style.name)
    if s is None:
        print "DEBUG: style not exists in Geoserver .. " + style.name
        if mapservice.createStyle(style.name, sld_body):
            mapservice.setLayerStyle(layer, cloned_style_name,
                                     style.is_default)
        else:
            "DEBUG: problem creating style !!!!!" + style.name
    else:
        print "DEBUG: Style exists in Geoserver .. " + style.name
        if not mapservice.createStyle(cloned_style_name, sld_body):
            mapservice.updateStyle(layer, cloned_style_name, sld_body)
        mapservice.setLayerStyle(layer, cloned_style_name, style.is_default)

    return True
예제 #31
0
def update_style(request, json_data, layer, gs, style, is_preview=False):
    is_default = json_data.get('is_default', False)
    is_default = utils.set_default_style(layer,
                                         gs,
                                         style=style,
                                         is_preview=is_preview,
                                         is_default=is_default)

    style.title = json_data.get('title')
    if json_data.get('minscale') != '':
        style.minscale = json_data.get('minscale')
    else:
        style.minscale = -1
    if json_data.get('maxscale') != '':
        style.maxscale = json_data.get('maxscale')
    else:
        style.maxscale = -1
    style.is_default = is_default
    style.save()

    rules = Rule.objects.filter(style=style)
    for ru in rules:
        symbolizers = Symbolizer.objects.filter(rule=ru)
        for symbolizer in symbolizers:
            symbolizer.delete()
        ru.delete()

    for r in json_data.get('rules'):
        json_rule = r.get('rule')

        filter_text = ""
        if json_rule.get('filter').__len__() != 0:
            filter_text = str(json.dumps(json_rule.get('filter')))

        if json_data.get('minscale') != '':
            minscale = json_rule.get('minscale')
        else:
            minscale = -1
        if json_data.get('maxscale') != '':
            maxscale = json_rule.get('maxscale')
        else:
            maxscale = -1

        rule = Rule(style=style,
                    name=json_rule.get('name'),
                    title=json_rule.get('title'),
                    abstract='',
                    filter=filter_text,
                    minscale=minscale,
                    maxscale=maxscale,
                    order=json_rule.get('order'))
        rule.save()

        for sym in r.get('symbolizers'):
            if sym.get('type') == 'PolygonSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = PolygonSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'LineSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = LineSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'MarkSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = MarkSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    well_known_name=json_sym.get('well_known_name'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                    stroke=json_sym.get('stroke'),
                    stroke_width=json_sym.get('stroke_width'),
                    stroke_opacity=json_sym.get('stroke_opacity'),
                    stroke_dash_array=json_sym.get('stroke_dash_array'))
                symbolizer.save()

            elif sym.get('type') == 'ExternalGraphicSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = ExternalGraphicSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    opacity=json_sym.get('opacity'),
                    size=json_sym.get('size'),
                    rotation=json_sym.get('rotation'),
                    online_resource=json_sym.get('online_resource'),
                    format=json_sym.get('format'))
                symbolizer.save()

            elif sym.get('type') == 'TextSymbolizer':
                json_sym = json.loads(sym.get('json'))
                symbolizer = TextSymbolizer(
                    rule=rule,
                    order=int(sym.get('order')),
                    label=json_sym.get('label'),
                    font_family=json_sym.get('font_family'),
                    font_size=json_sym.get('font_size'),
                    font_weight=json_sym.get('font_weight'),
                    font_style=json_sym.get('font_style'),
                    halo_fill=json_sym.get('halo_fill'),
                    halo_fill_opacity=json_sym.get('halo_fill_opacity'),
                    halo_radius=json_sym.get('halo_radius'),
                    fill=json_sym.get('fill'),
                    fill_opacity=json_sym.get('fill_opacity'),
                )
                symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style)

    if is_preview:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            return style
    else:
        if gs.updateStyle(layer, style.name, sld_body):
            gs.setLayerStyle(layer, style.name, style.is_default)
            return style
        else:
            # try to recover from inconsistent gvsigol - geoserver status
            if utils.reset_geoserver_style(gs, layer, style):
                gs.setLayerStyle(layer, style.name, style.is_default)
                return style
예제 #32
0
def create_default_style(layer_id, style_name, style_type, geom_type, count):
    layer = Layer.objects.get(id=int(layer_id))

    minscaledenominator = -1
    maxscaledenominator = -1
    if count and count > 200000:
        minscaledenominator = 0
        maxscaledenominator = 50000

    style = Style(name=style_name,
                  title=_('Default style for: ') + layer.title,
                  is_default=True,
                  type=style_type,
                  minscale=minscaledenominator,
                  maxscale=maxscaledenominator)
    style.save()
    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    if style.is_default:
        layer_styles = StyleLayer.objects.filter(layer=layer)
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            s.is_default = False

    symbol_type = None
    if geom.isPoint(geom_type):
        symbol_type = 'MarkSymbolizer'
    elif geom.isLine(geom_type):
        symbol_type = 'LineSymbolizer'
    elif geom.isPolygon(geom_type):
        symbol_type = 'PolygonSymbolizer'
    elif geom.isRaster(geom_type):
        symbol_type = 'RasterSymbolizer'

    rule = Rule(style=style,
                name='Default symbol',
                title=_('Default symbol'),
                abstract='',
                filter=str(""),
                minscale=minscaledenominator,
                maxscale=maxscaledenominator,
                order=0)
    rule.save()

    if symbol_type == 'PolygonSymbolizer':
        symbolizer = PolygonSymbolizer(rule=rule,
                                       order=0,
                                       fill='#383838',
                                       fill_opacity=0.6,
                                       stroke='#000000',
                                       stroke_width=1,
                                       stroke_opacity=1.0,
                                       stroke_dash_array='none')
        symbolizer.save()

    elif symbol_type == 'LineSymbolizer':
        symbolizer = LineSymbolizer(rule=rule,
                                    order=0,
                                    stroke='#000000',
                                    stroke_width=1,
                                    stroke_opacity=1.0,
                                    stroke_dash_array='none')
        symbolizer.save()

    elif symbol_type == 'MarkSymbolizer':
        symbolizer = MarkSymbolizer(rule=rule,
                                    order=0,
                                    opacity=1.0,
                                    size=8,
                                    rotation=0,
                                    well_known_name='circle',
                                    fill='#383838',
                                    fill_opacity=0.6,
                                    stroke='#000000',
                                    stroke_width=1,
                                    stroke_opacity=1.0,
                                    stroke_dash_array='none')
        symbolizer.save()

    elif symbol_type == 'RasterSymbolizer':
        color_map = ColorMap(type='ramp', extended=False)
        color_map.save()

        symbolizer = RasterSymbolizer(rule=rule,
                                      color_map=color_map,
                                      order=0,
                                      opacity=1.0)
        symbolizer.save()

    sld_body = sld_builder.build_sld(layer, style)
    return sld_body
예제 #33
0
    def testGeoRadiusAlarm(self):
        # Create in radius alarm
        self.in_radius_alarm = Rule.Create(self.e)
        self.in_radius_alarm.Update(
            name="In Town",
            sensortype_id=self.tracker.key().id(),
            column="location",
            trigger=RULE.GEORADIUS_IN,
            value2=RADIUS,  # m
            value_complex=json.dumps(RADIUS_CENTER),
            alert_contacts=["owner"],
            consecutive_limit=RULE.DISABLED,
            duration=0)
        self.in_radius_alarm.put()

        self.process = ProcessTask.Create(self.e)
        self.process.Update(rule_ids=[self.in_radius_alarm.key().id()])
        self.process.put()

        self.vehicle_2 = Sensor.Create(self.e, TEST_SENSOR_ID,
                                       self.tracker.key().id())
        self.vehicle_2.Update(name="Vehicle Sensor 2")

        # Apply our process to our sensor
        self.sp = SensorProcessTask.Create(self.e, self.process,
                                           self.vehicle_2)
        self.sp.put()

        INTERVAL_SECS = 4
        test_data_start = datetime.now() - timedelta(minutes=20)

        # Process first data points entering radius
        BATCH_1 = {
            'location':
            ["%s,%s" % (coord[0], coord[1]) for coord in ENTERS_RADIUS]
        }
        last_record = self.__createNewRecords(BATCH_1,
                                              first_dt=test_data_start,
                                              interval_secs=INTERVAL_SECS)
        self.__runProcessing()

        # Confirm in-radius alarm fired upon datapoint 4...
        alarms = Alarm.Fetch(self.vehicle_2, self.in_radius_alarm)
        self.assertEqual(len(alarms), 1)
        a = alarms[0]

        # Process second batch of data points exiting radius
        BATCH_2 = {
            'location':
            ["%s,%s" % (coord[0], coord[1]) for coord in EXITS_RADIUS]
        }
        self.__createNewRecords(BATCH_2, interval_secs=INTERVAL_SECS)
        self.__runProcessing()

        # Confirm we still just have the single alarm record
        alarms = Alarm.Fetch(self.vehicle_2, self.in_radius_alarm)
        self.assertEqual(len(alarms), 1)
        a = alarms[0]
        duration_td = a.duration()
        self.assertIsNotNone(duration_td)
        # 3 datapoints in radius
        print a.json()
예제 #34
0
파일: sync.py 프로젝트: yidun55/crawler
#!/usr/bin/env python
# coding:utf-8
import redis
from torndb import Connection

from models import Domain, Flow, Rule
import settings

rd = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT)
db = Connection("127.0.0.1", "spider", user="******", password="******")

domains = db.query("select * from domain")

for d in domains:
    domain = Domain(rd, d["domain"])
    domain.update(d)
    if "scheduled" not in domain:
        domain["scheduled"] = 0

    rule_datas = db.query("select * from rule where domain = %s", d["domain"])
    for rule_data in rule_datas:
        rule = Rule(rd, d["domain"])
        rule.update(rule_data)

    flows = db.query("select * from flow where domain = %s", d["domain"])
    for f in flows:
        flow = Flow(rd, f["flow"])
        flow.update(f)
        if "scheduled" not in flow:
            flow["scheduled"] = 0