def layer_replace(request, layername, template='layers/layer_replace.html'): layer = _resolve_layer(request, layername, 'layers.change_layer',_PERMISSION_MSG_MODIFY) if request.method == 'GET': cat = Layer.objects.gs_catalog info = cat.get_resource(layer.name) is_featuretype = info.resource_type == FeatureType.resource_type return render_to_response(template, RequestContext(request, {'layer': layer, 'is_featuretype': is_featuretype})) elif request.method == 'POST': form = LayerUploadForm(request.POST, request.FILES) tempdir = None if form.is_valid(): try: tempdir, base_file = form.write_files() saved_layer = save(layer, base_file, request.user, overwrite=True, permissions=layer.get_all_level_info()) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename])})) except Exception, e: logger.info("Unexpected error during upload.") return HttpResponse(json.dumps({ "success": False, "errors": ["Unexpected error during upload: " + escape(str(e))]})) finally:
def layer_replace(request, layername, template='layers/layer_replace.html'): layer = _resolve_layer(request, layername, 'layers.change_layer',_PERMISSION_MSG_MODIFY) if request.method == 'GET': cat = Layer.objects.gs_catalog info = cat.get_resource(layer.name) is_featuretype = info.resource_type == FeatureType.resource_type return render_to_response(template, RequestContext(request, {'layer': layer, 'is_featuretype': is_featuretype})) elif request.method == 'POST': form = LayerUploadForm(request.POST, request.FILES) tempdir = None out = {} if form.is_valid(): try: tempdir, base_file = form.write_files() saved_layer = save(layer, base_file, request.user, overwrite=True, permissions=layer.get_all_level_info()) except Exception, e: out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) finally:
def layer_replace(request, layername, template='layers/layer_replace.html'): layer = _resolve_layer(request, layername, 'layers.change_layer', _PERMISSION_MSG_MODIFY) if request.method == 'GET': return render_to_response( template, RequestContext(request, { 'layer': layer, 'is_featuretype': layer.is_vector() })) elif request.method == 'POST': form = LayerUploadForm(request.POST, request.FILES) tempdir = None out = {} if form.is_valid(): try: tempdir, base_file = form.write_files() saved_layer = save(layer, base_file, request.user, overwrite=True) except Exception, e: out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) finally:
def layer_upload(request, template='layers/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None if form.is_valid(): try: tempdir, base_file = form.write_files() title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext(form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".","_")) if form.cleaned_data["templetize"] == True: if request.user.is_superuser: saved_template = save_template(name, base_file, request.user) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_simpli_upload')})) ##Verify NAME field of the shapefile infile = ogr.Open(str(base_file), 1) inlyr = infile.GetLayerByIndex(0) layer_defn = inlyr.GetLayerDefn() field_names = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())] if not 'NAME' in field_names: fieldDefn = ogr.FieldDefn('NAME', ogr.OFTString) fieldDefn.SetWidth(14) inlyr.CreateField(fieldDefn) saved_layer = save(name, base_file, request.user, overwrite = False, abstract = form.cleaned_data["abstract"], title = form.cleaned_data["layer_title"], permissions = form.cleaned_data["permissions"] ) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename])})) except Exception, e: logger.exception("Unexpected error during upload.") return HttpResponse(json.dumps({ "success": False, "errormsgs": ["Unexpected error during upload: " + escape(str(e))]})) finally:
def layer_upload(request, template='upload/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None errormsgs = [] out = {'success': False} if form.is_valid(): title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext( form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".", "_")) try: # Moved this inside the try/except block because it can raise # exceptions when unicode characters are present. # This should be followed up in upstream Django. tempdir, base_file = form.write_files() saved_layer = save( name, base_file, request.user, overwrite=False, charset=form.cleaned_data["charset"], abstract=form.cleaned_data["abstract"], title=form.cleaned_data["layer_title"], ) except Exception, e: logger.exception(e) out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) permissions = form.cleaned_data["permissions"] if permissions is not None and len(permissions.keys()) > 0: saved_layer.set_permissions(permissions) finally:
def layer_upload(request, template='layers/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None if form.is_valid(): try: tempdir, base_file = form.write_files() title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext( form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".", "_")) saved_layer = save( name, base_file, request.user, overwrite=False, abstract=form.cleaned_data["abstract"], title=form.cleaned_data["layer_title"], permissions=form.cleaned_data["permissions"]) return HttpResponse( json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename]) })) except Exception, e: logger.exception("Unexpected error during upload.") return HttpResponse( json.dumps({ "success": False, "errormsgs": ["Unexpected error during upload: " + escape(str(e))] })) finally:
def layer_upload(request, template='upload/layer_upload.html'): user = get_valid_user() ogc_server_settings.DATASTORE = request.user.profile.user.username if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None errormsgs = [] out = {'success': False} if form.is_valid(): title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext(form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".","_")) try: # Moved this inside the try/except block because it can raise # exceptions when unicode characters are present. # This should be followed up in upstream Django. tempdir, base_file = form.write_files() saved_layer = save(name, base_file, request.user, overwrite = False, charset = form.cleaned_data["charset"], abstract = form.cleaned_data["abstract"], title = form.cleaned_data["layer_title"], permissions = form.cleaned_data["permissions"], ) except Exception, e: logger.exception(e) out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) finally:
def layer_replace(request, layername, template='layers/layer_replace.html'): layer = _resolve_layer(request, layername, 'layers.change_layer', _PERMISSION_MSG_MODIFY) if request.method == 'GET': cat = Layer.objects.gs_catalog info = cat.get_resource(layer.name) is_featuretype = info.resource_type == FeatureType.resource_type return render_to_response( template, RequestContext(request, { 'layer': layer, 'is_featuretype': is_featuretype })) elif request.method == 'POST': form = LayerUploadForm(request.POST, request.FILES) tempdir = None if form.is_valid(): try: tempdir, base_file = form.write_files() saved_layer = save(layer, base_file, request.user, overwrite=True, permissions=layer.get_all_level_info()) return HttpResponse( json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename]) })) except Exception, e: logger.info("Unexpected error during upload.") return HttpResponse( json.dumps({ "success": False, "errors": ["Unexpected error during upload: " + escape(str(e))] })) finally:
def layer_upload(request, template='upload/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None errormsgs = [] out = {'success': False} if form.is_valid(): tempdir, base_file = form.write_files() title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext( form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".", "_")) try: saved_layer = save( name, base_file, request.user, overwrite=False, abstract=form.cleaned_data["abstract"], title=form.cleaned_data["layer_title"], permissions=form.cleaned_data["permissions"]) except Exception, e: out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) finally:
def layer_upload(request, template='upload/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None errormsgs = [] out = {'success': False} if form.is_valid(): tempdir, base_file = form.write_files() title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext(form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".","_")) try: saved_layer = save(name, base_file, request.user, overwrite = False, abstract = form.cleaned_data["abstract"], title = form.cleaned_data["layer_title"], permissions = form.cleaned_data["permissions"] ) except Exception, e: logger.exception(e) out['success'] = False out['errors'] = str(e) else: out['success'] = True out['url'] = reverse('layer_detail', args=[saved_layer.typename]) finally:
def test_layer_upload(self): """ Try uploading a layer and verify that the user can administrate his own layer despite not being a site administrator. """ from django.contrib.auth.models import User client = Client() client.login(username='******', password='******') #TODO: Would be nice to ensure the name is available before #running the test... norman = User.objects.get(username="******") saved_layer = save("san_andres_y_providencia_poi_by_norman", os.path.join(gisdata.VECTOR_DATA, "san_andres_y_providencia_poi.shp"), norman, overwrite=False, ) url = reverse('layer_metadata', args=[saved_layer.typename]) resp = client.get(url) self.assertEquals(resp.status_code, 200)
def test_layer_upload(self): """ Try uploading a layer and verify that the user can administrate his own layer despite not being a site administrator. """ from django.contrib.auth.models import User client = Client() client.login(username='******', password='******') #TODO: Would be nice to ensure the name is available before #running the test... norman = User.objects.get(username="******") saved_layer = save("san_andres_y_providencia_poi_by_norman", os.path.join(gisdata.VECTOR_DATA, "san_andres_y_providencia_poi.shp"), norman, overwrite=True, ) url = reverse('layer_metadata', args=[saved_layer.typename]) resp = client.get(url) self.assertEquals(resp.status_code, 200)
def layer_upload(request, template='layers/layer_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None if form.is_valid(): try: tempdir, base_file = form.write_files() title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext(form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".","_")) saved_layer = save(name, base_file, request.user, overwrite = False, abstract = form.cleaned_data["abstract"], title = form.cleaned_data["layer_title"], permissions = form.cleaned_data["permissions"] ) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename])})) except Exception, e: logger.exception("Unexpected error during upload.") return HttpResponse(json.dumps({ "success": False, "errormsgs": ["Unexpected error during upload: " + escape(str(e))]})) finally:
def testPrintProxy(self): """ Test the PrintProxyMiddleware if activated. It should respect the permissions on private layers. """ if 'geonode.middleware.PrintProxyMiddleware' in settings.MIDDLEWARE_CLASSES: # STEP 1: Import a layer from django.contrib.auth.models import User from geonode.maps.models import Map client = Client() client.login(username='******', password='******') #TODO: Would be nice to ensure the name is available before #running the test... norman = User.objects.get(username="******") saved_layer = save("san_andres_y_providencia_poi_by_norman", os.path.join(gisdata.VECTOR_DATA, "san_andres_y_providencia_poi.shp"), norman, overwrite=True, ) # Set the layer private saved_layer.set_gen_level(ANONYMOUS_USERS, saved_layer.LEVEL_NONE) url = reverse('layer_metadata', args=[saved_layer.typename]) # check is accessible while logged in resp = client.get(url) self.assertEquals(resp.status_code, 200) # check is inaccessible when not logged in client.logout() resp = client.get(url) self.assertEquals(resp.status_code, 302) # STEP 2: Create a Map with that layer map_obj = Map(owner=norman, zoom=0, center_x=0, center_y=0) map_obj.create_from_layer_list(norman, [saved_layer], 'title','') map_obj.set_default_permissions() # STEP 3: Print the map print_url = settings.OGC_SERVER['default']['LOCATION'] + 'pdf/create.json' post_payload = { 'dpi': 75, 'layers': [ { 'baseURL': settings.OGC_SERVER['default']['LOCATION'] + 'wms?SERVICE=WMS&', 'format': "image/png", 'customParams': { 'TILED': True, 'TRANSPARENT': True }, 'layers': [saved_layer.typename], 'opacity': 1, 'singleTile': False, 'type': 'WMS' } ], 'layout': 'A4 portrait', 'mapTitle': 'test', 'outputFilename': 'print', 'srs': 'EPSG:900913', 'units': 'm' } client.post(print_url, post_payload) # Test the layer is still inaccessible as non authenticated resp = client.get(url) self.assertEquals(resp.status_code, 302) else: pass
def layer_simpli_upload(request, template='layers/layer_simpli_upload.html'): if request.method == 'GET': return render_to_response(template, RequestContext(request, {})) elif request.method == 'POST': form = LayerCreateFromTemplateForm(request.POST) if form.is_valid(): template_name = request.POST['ctype'] if form.cleaned_data["remove"] == True: if request.user.is_superuser: remove_template(template_name) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_simpli_upload')})) title = form.cleaned_data["layer_title"] if title is not None and len(title) > 0: name_base = title name = slugify(name_base.replace(".","_")) saved_template = LayerTemplate.objects.get(name=template_name) base_file = PROJECT_ROOT+"/shapefile_templates/"+str(saved_template.name)+"/"+saved_template.base_file ##Verify NAME field of the shapefile infile = ogr.Open(str(base_file), 1) inlyr = infile.GetLayerByIndex(0) layer_defn = inlyr.GetLayerDefn() field_names = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())] if not 'NAME' in field_names: fieldDefn = ogr.FieldDefn('NAME', ogr.OFTString) fieldDefn.SetWidth(14) inlyr.CreateField(fieldDefn) '''# Cancelliamo il campo "ID" i = layer_defn.GetFieldIndex('id') if id != -1: pass # Teniamo il primo POI if inlyr.GetFeatureCount() == 0: layer_defn = inlyr.GetLayerDefn() point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(12.469482, 41.877741) #create a new point at given ccordinates #474695, 5429281 #12.469482, 41.877741 #y = osr.SpatialReference() #y.ImportFromEPSG(900913) #point = ogr.CreateGeometryFromWkt("POINT (474695 5429281)", reference=y) #point.AddPoint(474695, 5429281) featureIndex = 0 feature = ogr.Feature(layer_defn) feature.SetGeometry(point) feature.SetFID(featureIndex) inlyr.CreateFeature(feature) infile = None''' saved_layer = save(name, base_file, request.user, overwrite = False, abstract = form.cleaned_data['abstract'], title = form.cleaned_data['layer_title'], permissions = form.cleaned_data["permissions"] ) ''' Questa porcata serve per risolvere il bug che sussiste caricando uno shapefile vuoto. Questa funzione inserisce 'brutalmente' un record sul database. Il record è configurabile nei settings. Inserrendo il record si evita che geoserver si confonda con il ESPG. Che il dio degli ingegneri abbia pietà della mia anima... ''' initialize_default_features(saved_layer) return HttpResponse(json.dumps({ "success": True, "redirect_to": reverse('layer_metadata', args=[saved_layer.typename])})) else: errormsgs = [] for e in form.errors.values(): errormsgs.extend([escape(v) for v in e]) return HttpResponse(json.dumps({ "success": False, "errors": form.errors, "errormsgs": errormsgs}))