def validateParams(params): """ Checks if all necessary params for a process process are within the given parameter set. :param params: dict :return: bool :raise: process.utils.exceptions.ParameterException """ if not 'id' in params: raise ParameterException("Missing id field in process request.") if not 'georeference' in params: raise ParameterException( "Missing process field in process request.") return True
def parseConfirmationRequestParams(request): """ Checks if the request params are complete and parse them :type request: pyramid.request :return: dict :raise: georeference.utils.exceptions.ParameterException """ requestData = parseGeoreferenceParamsFromRequest(request) requestData['userid'] = requestData['username'] # checkIsUser(request) if not 'type' in requestData: raise ParameterException("Missing type field in request.") if requestData['type'] == 'update' and 'overwrites' not in requestData: raise ParameterException("Missing overwrites field in update request.") return requestData
def createValidationResult(requestParams, gcps, gcpstargetSrs, LOGGER): """ Function creates a process image and creates a temporary wms. :type requestParams: dict :type gcps: List.<gdal.GCP> :type georefTargetSRS: int :type LOGGER: logging.LOGGER :return: str :raise: vkviewer.python.georef.georeferenceexceptions.ParameterException """ LOGGER.debug('Process georeference result ...') tmpFile = os.path.join(GEOREFERENCE_MAPFILE_FOLDER,requestParams['mapObj'].apsdateiname+"::"+str(uuid.uuid4())+".tif") destPath = None if requestParams['georeference']['algorithm'] == 'affine': destPath = rectifyImageAffine(requestParams['mapObj'].originalimage, tmpFile, [], gcps, gcpstargetSrs, LOGGER) elif requestParams['georeference']['algorithm'] == 'polynom': destPath = rectifyPolynomWithVRT(requestParams['mapObj'].originalimage, tmpFile, gcps, gcpstargetSrs, LOGGER, TMP_DIR) elif requestParams['georeference']['algorithm'] == 'tps': destPath = rectifyTpsWithVrt(requestParams['mapObj'].originalimage, tmpFile, gcps, gcpstargetSrs, LOGGER, TMP_DIR) else: raise ParameterException('Transformation algorithm - %s - is not supported yet.'%requestParams['georeference']['algorithm']) LOGGER.debug('Create temporary mapfile ...') wmsUrl = createMapfile(requestParams['mapObj'].apsdateiname, destPath, gcpstargetSrs, GEOREFERENCE_MAPFILE_TEMPLATE, GEOREFERENCE_MAPFILE_FOLDER, GEOREFERENCE_MAPFILE_DEFAULT_PARAMS) LOGGER.debug('Calculate extent ...') dataset = gdal.Open(destPath, GA_ReadOnly) extent = getBoundsFromDataset(dataset) LOGGER.debug('Deliver results.') return {'wmsUrl':wmsUrl,'layerId':requestParams['mapObj'].apsdateiname, 'extent': extent}
def parseMapObjForId(requestParams, name, dbsession): """ This functions parses a map objectid from an objectid :param requestParams: dict :param name: str :param dbsession: sqlalchemy.orm.session.Session :return: process.models.vkdb.map.Map :raise: process.utils.exceptions.ParameterException """ if name in requestParams: validateId(requestParams[name]) # @deprecated # do mapping for support of new name schema mapObj = Map.by_id(int(requestParams[name]), dbsession) if mapObj is None: raise ParameterException('Missing or wrong objectid parameter.') else: return mapObj raise ParameterException('Missing or wrong objectid parameter.')
def validateId(id): """ Checks if given id is a valide objectid in the vk2.0 domain. :param id: ? :return: bool :raise: process.utils.exceptions.ParameterException """ errorMsg = "Object identifier is not valide." try: # check if mtbid is valide if (id != None): if isinstance(int(id), int): return True else: raise ParameterException(errorMsg) except: raise ParameterException(errorMsg) return False
def georeferenceValidation(request): """ The function generates a process validation result and publish it via a WMS instance. The wms references are returned. :type request: pyramid.request :return: dict :raise: HTTPBadRequest :raise: HTTPInternalServerError """ LOGGER.info('Receive process validation request with parameters: %s'%request.json_body) try: # extract validation data LOGGER.debug('Parse request params ...') requestParams = parseGeoreferenceParamsFromRequest(request) LOGGER.debug('Parse and validate SRS params ...') georefSourceSRS = requestParams['georeference']['source'] if str(georefSourceSRS).lower() != 'pixel': raise ParameterException('Only "pixel" is yet supported as source srs.') if ':' not in str(requestParams['georeference']['target']): raise ParameterException('Missing "EPSG:...." syntax for target srs.') georefTargetSRS = stripSRIDFromEPSG(requestParams['georeference']['target']) # generate a temporary process result and publish it via wms LOGGER.debug('Parse and validate gcps params ...') if len(requestParams['georeference']['gcps']) < 2: raise ParameterException('Not enough gcps for valid georeferencing ...') gcps = parseGcps(requestParams['georeference']['gcps']) # calculate validation result return createValidationResult(requestParams, gcps, georefTargetSRS, LOGGER) except ParameterException as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPBadRequest(ERROR_MSG) except Exception as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPInternalServerError(ERROR_MSG)
def loadDbSession(database_params): logger.info('Initialize new database connection ...') sqlalchemy_enginge = 'postgresql+psycopg2://%(user)s:%(password)s@%(host)s:5432/%(db)s' % ( database_params) try: return initializeDb(sqlalchemy_enginge) except: logger.error( 'Could not initialize database. Plase check your database settings parameter.' ) raise ParameterException( 'Could not initialize database. Plase check your database settings parameter.' )
def getByObjectId(request): """ The function returns the process process information for a given objectid. Supports GET/POST requests :type request: pyramid.request :return: dict :raise: HTTPBadRequest :raise: HTTPInternalServerError """ def getObjectId(request): """ Parse the object id from the request. :type request: pyramid.request :return: int """ objectid = None if request.method == 'POST' and 'objectid' in request.json_body: objectid = request.json_body['objectid'] if request.method == 'GET' and 'objectid' in request.params: objectid = request.params['objectid'] if objectid is None: return None else: namespace, id = objectid.rsplit('-', 1) # check if it is the correct namespace if namespace == OAI_ID_PATTERN.rsplit('-', 1)[0]: return int(id) return None try: objectid = getObjectId(request) if objectid is None: raise ParameterException("Wrong or missing objectid.") LOGGER.debug('Create response for objectid - %s ...'%objectid) return generateGeoreferenceProcessForMapObj(objectid, request, LOGGER) except ParameterException as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) except Exception as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPInternalServerError(ERROR_MSG)
def getGeoreferenceResource(request): """ The function returns the process process information for a given objectid. Supports GET/POST requests :type request: pyramid.request :return: dict :raise: HTTPBadRequest :raise: HTTPInternalServerError """ def getGeoreferenceId(request): """ Parse the process id from the request. :type request: pyramid.request :return: int|None """ if request.method == 'GET' and 'georeferenceid' in request.matchdict: return int(request.matchdict['georeferenceid']) return None try: georeferenceid = getGeoreferenceId(request) if georeferenceid is None: raise ParameterException("Wrong or missing georeferenceid.") LOGGER.debug('Create response for georeferenceid - %s ...'%georeferenceid) return generateGeoreferenceProcessForSpecificGeoreferenceId(georeferenceid, request, LOGGER) except ParameterException as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPBadRequest(ERROR_MSG) except ProcessIsInvalideException as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPBadRequest('This process process is blocked for further work!') except Exception as e: LOGGER.error(e) LOGGER.error(traceback.format_exc()) raise HTTPInternalServerError(ERROR_MSG)