コード例 #1
0
def get_conf(request, layer_id):
    layer = Layer.objects.get(id=int(layer_id))
    datastore = Datastore.objects.get(id=layer.datastore_id)
    workspace = Workspace.objects.get(id=datastore.workspace_id)
    gs = geographic_servers.get_instance().get_server_by_id(
        workspace.server.id)
    index = utils.get_next_index(layer)
    (ds_type, resource) = gs.getResourceInfo(workspace.name, datastore,
                                             layer.name, "json")

    layer_url = core_utils.get_wms_url(workspace)
    layer_wfs_url = core_utils.get_wfs_url(workspace)

    preview_url = workspace.server.frontend_url + '/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=preview_polygon'

    conf = {
        'layer_id': layer_id,
        'layer_url': layer_url,
        'layer_wfs_url': layer_wfs_url,
        'layer_name': workspace.name + ':' + layer.name,
        'style_name': workspace.name + '_' + layer.name + '_' + str(index),
        'libraries': Library.objects.all(),
        'supported_crs': json.dumps(core_utils.get_supported_crs()),
        'extent':
        json.dumps(resource.get('coverage').get('nativeBoundingBox')),
        'extent_epsg': resource.get('coverage').get('grid').get('crs'),
        'preview_url': preview_url
    }

    return conf
コード例 #2
0
ファイル: views.py プロジェクト: fpenarru/gvsig-online
 def post(self, request, *args, **kwargs):
     form = PostgisLayerUploadForm(request.POST, request.FILES, user=request.user)
     if form.is_valid():
         try:
             gs = geographic_servers.get_instance().get_server_by_id(form.cleaned_data['datastore'].workspace.server.id)
             if gs.exportShpToPostgis(form.cleaned_data):
                 request.session.message = _('Export process done successfully')
                 return redirect("/gvsigonline/filemanager/?path=" + request.POST.get('directory_path'))
         
         except rest_geoserver.RequestError as e:
             message = e.server_message
             request.session['message'] = str(message)
             if e.status_code == -1:
                 name = form.data['name']
                 datastore_id = form.data['datastore']
                 datastore = Datastore.objects.get(id=datastore_id)
                 params = json.loads(datastore.connection_params)
                 host = params['host']
                 port = params['port']
                 dbname = params['database']
                 user = params['user']
                 passwd = params['passwd']
                 schema = params.get('schema', 'public')
                 i = Introspect(database=dbname, host=host, port=port, user=user, password=passwd)
                 i.delete_table(schema, name)
             return redirect("/gvsigonline/filemanager/export_to_database/?path=" + request.POST.get('file_path'))
             
         except Exception as exc:
             request.session['message'] = _('Server error') +  ":" + str(exc)
             return redirect("/gvsigonline/filemanager/export_to_database/?path=" + request.POST.get('file_path'))
     else:
         request.session['message'] = _('You must fill in all fields')
         return redirect("/gvsigonline/filemanager/export_to_database/?path=" + request.POST.get('file_path'))
コード例 #3
0
def linechart_update(request, layer_id, chart_id):
    if request.method == 'POST':
        layer = Layer.objects.get(id=int(layer_id))
        chart = Chart.objects.get(id=int(chart_id))

        title = request.POST.get('title')
        description = request.POST.get('description')
        chart_conf = request.POST.get('chart_conf')

        chart.title = title
        chart.description = description
        chart.conf = chart_conf

        chart.save()

        return HttpResponse(json.dumps({'success': True}, indent=4),
                            content_type='application/json')

    else:
        layer = Layer.objects.get(id=int(layer_id))
        chart = Chart.objects.get(id=int(chart_id))

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

        (ds_type, resource) = gs.getResourceInfo(workspace.name, datastore,
                                                 layer.name, "json")
        fields = utils.get_fields(resource)
        numeric_fields = utils.get_numeric_fields(fields)
        alpha_numeric_fields = utils.get_alphanumeric_fields(fields)
        geom_fields = utils.get_geometry_fields(fields)

        conf = json.loads(chart.conf)

        y_axis_begin_at_zero = False
        if 'y_axis_begin_at_zero' in conf:
            y_axis_begin_at_zero = conf['y_axis_begin_at_zero']

        return render(
            request, 'linechart_update.html', {
                'layer_id': layer_id,
                'chart_id': chart_id,
                'fields': json.dumps(fields),
                'numeric_fields': json.dumps(numeric_fields),
                'alpha_numeric_fields': json.dumps(alpha_numeric_fields),
                'geom_fields': json.dumps(geom_fields),
                'title': chart.title,
                'description': chart.description,
                'dataset_type': conf['dataset_type'],
                'x_axis_title': conf['x_axis_title'],
                'y_axis_title': conf['y_axis_title'],
                'y_axis_begin_at_zero': y_axis_begin_at_zero,
                'geographic_names_column': conf['geographic_names_column'],
                'geometries_column': conf['geometries_column'],
                'selected_columns': json.dumps(conf['columns'])
            })
コード例 #4
0
def get_conf(request, layer_id):
    layer = Layer.objects.get(id=int(layer_id))
    datastore = Datastore.objects.get(id=layer.datastore_id)
    workspace = Workspace.objects.get(id=datastore.workspace_id)
    gs = geographic_servers.get_instance().get_server_by_id(workspace.server.id)
    index = utils.get_next_index(layer)
    (ds_type, resource) = gs.getResourceInfo(workspace.name, datastore, layer.name, "json")
    fields = utils.get_fields(resource)
    if layer.conf:
        new_fields = []
        conf = None
        if layer and layer.conf:
            conf = ast.literal_eval(layer.conf)
        for field in fields:
            if conf:
                for f in conf['fields']:
                    if f['name'] == field['name']:
                        for id, language in settings.LANGUAGES:
                            field['title-'+id] = f['title-'+id]
            else:
                for id, language in settings.LANGUAGES:
                    field['title-'+id] = field['name']
            new_fields.append(field)
        fields = new_fields
        
    feature_type = utils.get_feature_type(fields)
    alphanumeric_fields = utils.get_alphanumeric_fields(fields)
       
    supported_fonts_str = gs.getSupportedFonts()
    supported_fonts = json.loads(supported_fonts_str)
    sorted_fonts = utils.sortFontsArray(supported_fonts.get("fonts"))
              
    layer_url = core_utils.get_wms_url(workspace)
    layer_wfs_url = core_utils.get_wfs_url(workspace)
    
    preview_url = ''
    if feature_type == 'PointSymbolizer':
        preview_url = workspace.server.frontend_url + '/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=preview_point'    
    elif feature_type == 'LineSymbolizer':      
        preview_url = workspace.server.frontend_url + '/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=preview_line'     
    elif feature_type == 'PolygonSymbolizer': 
        preview_url = workspace.server.frontend_url + '/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=preview_polygon'
                  
    conf = {
        'featureType': feature_type,
        'fields': alphanumeric_fields,
        'json_alphanumeric_fields': json.dumps(alphanumeric_fields),
        'fonts': sorted_fonts,
        'layer_id': layer_id,
        'layer_url': layer_url,
        'layer_wfs_url': layer_wfs_url,
        'layer_name': workspace.name + ':' + layer.name,
        'style_name': workspace.name + '_' + layer.name + '_' + str(index),
        'libraries': Library.objects.all(),
        'supported_crs': json.dumps(core_utils.get_supported_crs()),
        'preview_url': preview_url
    }    
     
    return conf
コード例 #5
0
def create_style(style_name,
                 style_title,
                 is_default,
                 sld,
                 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)
    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

    if is_preview:
        style_name = style_name + '__tmp'
        is_default = False

    style = Style(name=style_name,
                  title=style_title,
                  is_default=is_default,
                  minscale=-1,
                  maxscale=-1,
                  type='CS',
                  sld=sld)
    style.save()
    style_layer = StyleLayer(style=style, layer=layer)
    style_layer.save()

    sld_body = sld

    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
コード例 #6
0
ファイル: service.py プロジェクト: fpenarru/gvsig-online
 def layer_updated_handler(self, sender, **kwargs):
     try:
         logger.debug(u'layer_updated_handler')
         layer = kwargs['layer']
         lm = LayerMetadata.objects.get(layer=layer)
         
         gs = geographic_servers.get_instance().get_server_by_id(layer.datastore.workspace.server.id)
         (ds_type, layer_info) = gs.getResourceInfo(layer.datastore.workspace.name, layer.datastore, layer.name, "json")
         if self.xmlapi.gn_auth(self.user, self.password) and lm.metadata_uuid:
             self.xmlapi.gn_update_metadata(lm.metadata_uuid, layer, layer.abstract, layer_info, ds_type)
             self.xmlapi.gn_unauth()
     except Exception as e:
         logger.exception("layer metadata update failed")
         pass
コード例 #7
0
def update_style(style_title,
                 is_default,
                 sld,
                 layer_id,
                 style_id,
                 is_preview=False):
    style = Style.objects.get(id=int(style_id))
    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)

    if is_default:
        for ls in layer_styles:
            s = Style.objects.get(id=ls.style.id)
            s.is_default = False
            s.save()
        gs.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:
            gs.setLayerStyle(layer, style.name, True)

    style.sld = sld
    style.title = style_title
    style.is_default = is_default
    style.save()

    sld_body = sld

    if is_preview:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            return True
        else:
            return False
    else:
        if gs.updateStyle(layer, style.name, sld_body):
            gs.setLayerStyle(layer, style.name, style.is_default)
            return True
        else:
            return False
コード例 #8
0
 def metadata_insert(self, layer):
     gs = geographic_servers.get_instance().get_server_by_id(layer.datastore.workspace.server.id)
     (ds_type, layer_info) = gs.getResourceInfo(layer.datastore.workspace.name, layer.datastore, layer.name, "json")
     md_record = self.create_metadata(layer, layer_info, ds_type)
     try:
         if self.xmlapi.gn_auth(self.user, self.password):
             uuid = self.xmlapi.gn_insert_metadata(md_record)
             self.xmlapi.add_thumbnail(uuid[0], layer.thumbnail.url)
             self.xmlapi.set_metadata_privileges(uuid[0])
             self.xmlapi.gn_unauth()
             return uuid
         logger.error("Error authenticating in catalog")
         return None
     
     except:
         logger.exception("Error inserting metadata")
コード例 #9
0
def get_conf(request, layer_id):
    layer = Layer.objects.get(id=int(layer_id))
    datastore = Datastore.objects.get(id=layer.datastore_id)
    workspace = Workspace.objects.get(id=datastore.workspace_id)
    gs = geographic_servers.get_instance().get_server_by_id(
        workspace.server.id)

    index = len(StyleLayer.objects.filter(layer=layer))
    styleLayers = StyleLayer.objects.filter(layer=layer)
    for style_layer in styleLayers:
        aux_name = style_layer.style.name
        aux_name = aux_name.replace(workspace.name + '_' + layer.name + '_',
                                    '')

        try:
            aux_index = int(aux_name)
            if index < aux_index + 1:
                index = aux_index + 1
        except ValueError:
            print "Error getting index"

    (ds_type, resource) = gs.getResourceInfo(workspace.name, datastore,
                                             layer.name, "json")

    layer_url = core_utils.get_wms_url(request, workspace)
    layer_wfs_url = core_utils.get_wfs_url(request, workspace)

    preview_url = workspace.server.frontend_url + '/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=preview_polygon'

    conf = {
        'layer_id': layer_id,
        'layer_url': layer_url,
        'layer_wfs_url': layer_wfs_url,
        'layer_name': workspace.name + ':' + layer.name,
        'style_name': workspace.name + '_' + layer.name + '_' + str(index),
        'libraries': Library.objects.all(),
        'supported_crs': json.dumps(core_utils.get_supported_crs()),
        'extent':
        json.dumps(resource.get('coverage').get('nativeBoundingBox')),
        'extent_epsg': resource.get('coverage').get('grid').get('crs'),
        'preview_url': preview_url
    }

    return conf
コード例 #10
0
def piechart_add(request, layer_id):
    if request.method == 'POST':
        layer = Layer.objects.get(id=int(layer_id))

        title = request.POST.get('title')
        description = request.POST.get('description')
        chart_conf = request.POST.get('chart_conf')

        chart = Chart(layer=layer,
                      type='piechart',
                      title=title,
                      description=description,
                      conf=chart_conf)
        chart.save()

        return HttpResponse(json.dumps({'success': True}, indent=4),
                            content_type='application/json')

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

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

        (ds_type, resource) = gs.getResourceInfo(workspace.name, datastore,
                                                 layer.name, "json")
        fields = utils.get_fields(resource)
        numeric_fields = utils.get_numeric_fields(fields)
        alpha_numeric_fields = utils.get_alphanumeric_fields(fields)
        geom_fields = utils.get_geometry_fields(fields)

        conf = {
            'layer_id': layer_id,
            'fields': json.dumps(fields),
            'numeric_fields': json.dumps(numeric_fields),
            'alpha_numeric_fields': json.dumps(alpha_numeric_fields),
            'geom_fields': json.dumps(geom_fields)
        }

        return render(request, 'piechart_add.html', conf)
コード例 #11
0
    def clean(self):
        cleaned_data = super(DatastoreForm, self).clean()
        workspace = cleaned_data.get("workspace")
        name = cleaned_data.get("name")
        connection_params = cleaned_data.get("connection_params")

        if name and workspace:
            gs = geographic_servers.get_instance().get_server_by_id(
                workspace.server.id)
            if gs.datastore_exists(workspace.name, name):
                self.add_error('name', _("Datastore already exists"))

        if connection_params:
            try:
                json.loads(connection_params)
            except:
                self.add_error('connection_params',
                               _("Error: Invalid JSON format"))
        return cleaned_data
コード例 #12
0
def delete_symbol(rule, library_rule):
    try:
        gs = geographic_servers.get_instance().get_default_server()
        style = Style.objects.get(id=rule.style.id)

        if gs.deleteStyle(style.name):
            style.delete()
        symbolizers = Symbolizer.objects.filter(rule_id=rule.id)
        for symbolizer in symbolizers:
            if get_ftype(symbolizer) == 'ExternalGraphic':
                file_name = rule.name + '.png'
                utils.delete_external_graphic_img(library_rule.library,
                                                  file_name)
            symbolizer.delete()
        library_rule.delete()
        rule.delete()

    except Exception as e:
        raise e
コード例 #13
0
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
    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='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 gs.createOverwrittenStyle(style.name, sld_body, True):
            return True
        else:
            return False
    else:
        if gs.createOverwrittenStyle(style.name, sld_body, True):
            if not is_preview:
                gs.setLayerStyle(layer, style.name, style.is_default)
            return True

        else:
            return False
コード例 #14
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
コード例 #15
0
ファイル: views.py プロジェクト: kirui-max/gvsig-online
def user_add(request):
    ad_suffix = GVSIGOL_LDAP['AD']
    if not ad_suffix:
        show_pass_form = True
    else:
        show_pass_form = False

    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            assigned_groups = []

            is_staff = False
            if 'is_staff' in form.data:
                is_staff = True

            is_superuser = False
            if 'is_superuser' in form.data:
                is_superuser = True
                is_staff = True

            assigned_groups = []
            for key in form.data:
                if 'group-' in key:
                    assigned_groups.append(int(key.split('-')[1]))

            try:
                gs = geographic_servers.get_instance().get_default_server()
                server_object = Server.objects.get(id=int(gs.id))

                if form.data['password1'] == form.data['password2']:
                    user = User(username=form.data['username'].lower(),
                                first_name=u''.join(
                                    form.data['first_name']).encode('utf-8'),
                                last_name=u''.join(
                                    form.data['last_name']).encode('utf-8'),
                                email=form.data['email'].lower(),
                                is_superuser=is_superuser,
                                is_staff=is_staff)
                    user.set_password(form.data['password1'])
                    user.save()

                    #admin_group = UserGroup.objects.get(name__exact='admin')
                    aux = UserGroup.objects.filter(name="admin")
                    if aux.count() > 1:
                        print "WARNING: table gvsigol_auth_usergroup inconsistent !!!!!!!!!!!"

                    admin_group = aux[0]

                    if user.is_superuser:
                        auth_services.get_services().ldap_add_user(
                            user, form.data['password1'], True)
                        auth_services.get_services().ldap_add_group_member(
                            user, admin_group)
                        usergroup_user = UserGroupUser(user=user,
                                                       user_group=admin_group)
                        usergroup_user.save()

                    else:
                        auth_services.get_services().ldap_add_user(
                            user, form.data['password1'], False)
                        #auth_services.get_services().ldap_add_group_member(user, admin_group)

                    for ag in assigned_groups:
                        user_group = UserGroup.objects.get(id=ag)
                        usergroup_user = UserGroupUser(user=user,
                                                       user_group=user_group)
                        usergroup_user.save()
                        auth_services.get_services().ldap_add_group_member(
                            user, user_group)

                    #User backend
                    if is_superuser or is_staff:
                        ugroup = UserGroup(
                            name='ug_' + form.data['username'].lower(),
                            description=_(u'User group for') + ': ' +
                            form.data['username'].lower())
                        ugroup.save()

                        ugroup_user = UserGroupUser(user=user,
                                                    user_group=ugroup)
                        ugroup_user.save()

                        auth_services.get_services().ldap_add_group(ugroup)
                        auth_services.get_services().add_data_directory(ugroup)
                        auth_services.get_services().ldap_add_group_member(
                            user, ugroup)

                        url = server_object.frontend_url + '/'
                        ws_name = 'ws_' + form.data['username'].lower()

                        if gs.createWorkspace(ws_name, url + ws_name):
                            # save it on DB if successfully created
                            newWs = Workspace(
                                server=server_object,
                                name=ws_name,
                                description='',
                                uri=url + ws_name,
                                wms_endpoint=url + ws_name + '/wms',
                                wfs_endpoint=url + ws_name + '/wfs',
                                wcs_endpoint=url + ws_name + '/wcs',
                                wmts_endpoint=url + 'gwc/service/wmts',
                                cache_endpoint=url + 'gwc/service/wms',
                                created_by=user.username,
                                is_public=False)
                            newWs.save()

                            ds_name = 'ds_' + form.data['username'].lower()
                            services_utils.create_datastore(
                                request, user.username, ds_name, newWs)

                            gs.reload_nodes()

                    try:
                        auth_utils.sendMail(user, form.data['password1'])
                    except Exception as ex:
                        print str(ex)
                        pass

                    return redirect('user_list')

            except Exception as e:
                print "ERROR: Problem creating user " + str(e)
                errors = []
                errors.append(
                    {'message': "ERROR: Problem creating user " + str(e)})
                groups = auth_utils.get_all_groups()
                return render(
                    request, 'user_add.html', {
                        'form': form,
                        'groups': groups,
                        'errors': errors,
                        'show_pass_form': show_pass_form
                    })

        else:
            groups = auth_utils.get_all_groups()
            return render(request, 'user_add.html', {
                'form': form,
                'groups': groups,
                'show_pass_form': show_pass_form
            })

    else:

        form = UserCreateForm()
        groups = auth_utils.get_all_groups()
        return render(request, 'user_add.html', {
            'form': form,
            'groups': groups,
            'show_pass_form': show_pass_form
        })
コード例 #16
0
def update_symbol(request, json_rule, rule, library_rule):
    try:
        gs = geographic_servers.get_instance().get_default_server()

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

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

        rule.title = title
        rule.save()
        symbol_type = None
        eg_file = None

        if 'eg-file' in request.FILES:
            file_name = json_rule.get('file_name').split('/')[-1]
            eg_file = request.FILES['eg-file']

        for s in Symbolizer.objects.filter(rule=rule):
            if get_ftype(s) == 'ExternalGraphicSymbolizer':
                symbol_type = get_ftype(s)
                if eg_file is not None:
                    utils.delete_external_graphic_img(library_rule.library,
                                                      file_name)
            s.delete()

        for sym in json_rule.get('symbolizers'):

            json_sym = json.loads(sym.get('json'))
            if json_sym.get('type') == 'ExternalGraphicSymbolizer':
                library_path = utils.check_library_path(library_rule.library)
                file_name = name + '.png'
                if eg_file is not None:
                    if utils.save_external_graphic(library_path, eg_file,
                                                   file_name):
                        online_resource = utils.get_online_resource(
                            library_rule.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 json_sym.get('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 json_sym.get('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 json_sym.get('type') == 'MarkSymbolizer':
                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()

        style = Style.objects.get(id=rule.style.id)

        if gs.deleteStyle(style.name):
            sld_body = sld_builder.build_library_symbol(rule)
            if not gs.createStyle(style.name, sld_body):
                return False

        return True

    except Exception as e:
        raise e
コード例 #17
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
コード例 #18
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)