Commit 6ff4bfac authored by Manuel's avatar Manuel

[reputation-calculation] added database connection and repositories

parent 3f3b9aa3
......@@ -4,7 +4,7 @@ paths:
#####
/use-cases/{use_case}/contexts/{context}/trust-adapters:
get:
operationId: "routes.trust_adapter.all_for_use_case"
operationId: "routes.trust_adapter.all_for_use_case_and_context"
tags:
- "Trust Adapter"
summary: "Get all trust adapters for a use case"
......@@ -55,6 +55,49 @@ paths:
#####
# Contexts
#####
/use-cases/{use_case}/users:
get:
operationId: "routes.user.all_for_use_case"
tags:
- "User"
summary: "Get all users for a use case"
description: "Get all users for a use case"
parameters:
- name: "use_case"
in: "path"
description: "Name of the Use-Case the User belongs to"
required: true
type: "string"
responses:
"200":
description: "OK"
"404":
description: "Use-Case was not found"
"400":
description: "Wrong or missing parameters"
post:
operationId: "routes.user.add"
tags:
- "User"
summary: "Adds a new user to the system"
description: "Adds a new user to the system"
parameters:
- name: "use_case"
in: "path"
description: "Name of the Use-Case the Contexts belongs to"
required: true
type: "string"
- in: body
name: "Object"
required: true
schema:
$ref: '#/definitions/User'
responses:
"200":
description: "User was successfully added"
#####
# Contexts
#####
/use-cases/{use_case}/contexts:
get:
operationId: "routes.context.all_for_use_case"
......@@ -110,6 +153,18 @@ paths:
"200":
description: "Successful echo of request data"
definitions:
User:
type: "object"
required:
- use_case
- name
properties:
use_case:
type: string
example: "car-sharing"
name:
type: string
example: "Alice"
Context:
type: "object"
required:
......
......@@ -13,4 +13,7 @@ class Context:
@staticmethod
def from_serializable_dict(data: Dict):
return Context(data["use_case"], data["context"])
\ No newline at end of file
if "use_case" not in data.keys() or "name" not in data.keys():
raise ValueError("Missing fields!")
return Context(data["use_case"], data["name"])
\ No newline at end of file
from typing import Dict
class Context:
class TrustAdapter:
def __init__(self, use_case: str, context: str, user_source: str, volume_source: str,
conversion: float, certainty: float, cutoff: float, bias_negative: float, bias_positive: float):
self.use_case = use_case
......@@ -29,7 +29,10 @@ class Context:
@staticmethod
def from_serializable_dict(data: Dict):
return Context(
if "use_case" not in data.keys() or "context" not in data.keys() or "user_source" not in data.keys() or "volume_source" not in data.keys() or "conversion" not in data.keys() or "certainty" not in data.keys() or "cutoff" not in data.keys() or "bias_negative" not in data.keys() or "bias_positive" not in data.keys():
raise ValueError("Missing fields for TrustAdapter!")
return TrustAdapter(
data["use_case"],
data["context"],
data["user_source"],
......
from typing import Dict
class TrustTrace:
def __init__(self, use_case: str, context: str, user: str, volume: float, rating: float):
self.use_case = use_case
self.context = context
self.user = user
self.volume = volume
self.oracle_rating = rating
def to_serializable_dict(self):
return {
"use_case": self.use_case,
"context": self.user,
"user": self.volume,
"volume": self.volume,
"oracle_rating": self.oracle_rating
}
@staticmethod
def from_serializable_dict(data: Dict):
if "use_case" not in data.keys() or "context" not in data.keys() or "user" not in data.keys() or "volume" not in data.keys() or "oracle_rating" not in data.keys():
raise ValueError("Missing fields for User!")
return TrustTrace(
data["use_case"],
data["context"],
data["user"],
data["volume"],
data["oracle_rating"],
)
from typing import Dict
class User:
def __init__(self, use_case:str, name:str):
self.use_case = use_case
self.name = name
def to_serializable_dict(self):
return {
"use_case": self.use_case,
"name": self.name
}
@staticmethod
def from_serializable_dict(data: Dict):
if "use_case" not in data.keys() or "name" not in data.keys():
raise ValueError("Missing fields for User!")
return User(data["use_case"], data["name"])
\ No newline at end of file
# global imports (dont't worry, red is normal)
import network_constants as netconst
from database.MongoRepositoryBase import MongoRepositoryBase
from database.entities.context import Context
from typing import List, Dict
class ContextRepository(MongoRepositoryBase):
'''This is a repository for MongoDb.'''
def __init__(self):
super().__init__(netconst.REPUTATION_CALCULATION_DB_HOSTNAME,
netconst.REPUTATION_CALCULATION_DB_PORT,
'rest-gateway-db')
self._collection = 'context'
def add(self, context: Context):
super().insert_entry(self._collection, context.to_serializable_dict())
def all(self) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False})
return list(result)
def all_for_use_case(self, use_case: str) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False}, selection={"use_case": use_case})
return list(result)
\ No newline at end of file
# global imports (dont't worry, red is normal)
import network_constants as netconst
from database.MongoRepositoryBase import MongoRepositoryBase
from database.entities.trust_adapter import TrustAdapter
from typing import List, Dict
class TrustAdapterRepository(MongoRepositoryBase):
'''This is a repository for MongoDb.'''
def __init__(self):
super().__init__(netconst.REPUTATION_CALCULATION_DB_HOSTNAME,
netconst.REPUTATION_CALCULATION_DB_PORT,
'rest-gateway-db')
self._collection = 'trust_adapter'
def add(self, adapter: TrustAdapter):
super().insert_entry(self._collection, adapter.to_serializable_dict())
def all(self) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False})
return list(result)
def one_for_use_case_and_context(self, use_case: str, context: str) -> List[Dict]:
result = super().get_entries(
self._collection,
projection={'_id': False},
selection={"use_case": use_case, "context": context}
)
rows = list(result)
if len(rows) == 0:
return None
return rows[0]
\ No newline at end of file
# global imports (dont't worry, red is normal)
import network_constants as netconst
from database.MongoRepositoryBase import MongoRepositoryBase
from database.entities.trust_trace import TrustTrace
from typing import List, Dict
class TrustTraceRepository(MongoRepositoryBase):
'''This is a repository for MongoDb.'''
def __init__(self):
super().__init__(netconst.REPUTATION_CALCULATION_DB_HOSTNAME,
netconst.REPUTATION_CALCULATION_DB_PORT,
'rest-gateway-db')
self._collection = 'trust_trace'
def add(self, trace: TrustTrace):
super().insert_entry(self._collection, trace.to_serializable_dict())
def all(self) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False})
return list(result)
def all_for_use_case_and_context(self, use_case: str, context: str) -> List[Dict]:
result = super().get_entries(
self._collection,
projection={'_id': False},
selection={"use_case": use_case, "context": context}
)
return list(result)
\ No newline at end of file
# global imports (dont't worry, red is normal)
import network_constants as netconst
from database.MongoRepositoryBase import MongoRepositoryBase
from database.entities.user import User
from typing import List, Dict
class UserRepository(MongoRepositoryBase):
'''This is a repository for MongoDb.'''
def __init__(self):
super().__init__(netconst.REPUTATION_CALCULATION_DB_HOSTNAME,
netconst.REPUTATION_CALCULATION_DB_PORT,
'rest-gateway-db')
self._collection = 'user'
def add(self, user: User):
super().insert_entry(self._collection, user.to_serializable_dict())
def all(self) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False})
return list(result)
def all_for_use_case(self, use_case: str) -> List[Dict]:
result = super().get_entries(self._collection, projection={'_id': False}, selection={"use_case": use_case})
return list(result)
\ No newline at end of file
from database.entities.context import Context
from database.repositories.context_repository import ContextRepository
from flask import request, Response
context_repository: ContextRepository = ContextRepository()
def add(use_case: str):
return "nice"
data = request.json
context_new = None
try:
context_new = Context.from_serializable_dict(data)
except ValueError:
return Response(status=400, response="Missing fields in request")
if context_new.use_case != use_case:
return Response(status = 400, response="Use-Cases in body and url do not match!")
context_repository.add(context_new)
return context_new.to_serializable_dict()
def all_for_use_case(use_case: str):
return f"uc: {use_case}"
return context_repository.all_for_use_case(use_case)
from database.repositories.context_repository import ContextRepository
from database.entities.context import Context
from database.entities.trust_adapter import TrustAdapter
from database.repositories.context_repository import ContextRepository
from database.repositories.trust_adapter_repository import TrustAdapterRepository
from flask import request, Response
from typing import List
context_repository: ContextRepository = ContextRepository()
trust_adapter_repository: TrustAdapterRepository = TrustAdapterRepository()
def add(use_case: str, context: str):
return "nice"
_ensure_context_exists_for_use_case(use_case, context)
data = request.json
adapter_reference = trust_adapter_repository.one_for_use_case_and_context(use_case, context)
if adapter_reference != None:
return Response(status=400, response="There already exists a TrustAdapter.")
adapter_new = None
try:
adapter_new = TrustAdapter.from_serializable_dict(data)
except ValueError:
return Response(status=400, response="Missing fields in request")
if adapter_new.context != context:
return Response(status=400, response="Context in body and url do not match!")
if adapter_new.use_case != use_case:
return Response(status=400, response="Use-Cases in body and url do not match!")
trust_adapter_repository.add(adapter_new)
return adapter_new.to_serializable_dict()
def all_for_use_case_and_context(use_case: str, context: str):
_ensure_context_exists_for_use_case(use_case, context)
return trust_adapter_repository.one_for_use_case_and_context(use_case, context)
def _ensure_context_exists_for_use_case(use_case: str, context: str) -> Context:
contexts: List[Context] = context_repository.all_for_use_case(use_case)
target_context = None
for c in contexts:
if c["name"] == context:
target_context = c
break
if target_context == None:
return Response(status=404, response=f"Context {context} not found!")
def all_for_use_case(use_case: str, context: str):
return f"uc: {use_case}"
return Context.from_serializable_dict(target_context)
\ No newline at end of file
from database.entities.user import User
from database.repositories.user_repository import UserRepository
from flask import request, Response
user_repository: UserRepository = UserRepository()
def add(use_case: str):
data = request.json
user_new = None
try:
user_new = User.from_serializable_dict(data)
except ValueError:
return Response(status=400, response="Missing fields in request")
if user_new.use_case != use_case:
return Response(status = 400, response="Use-Cases in body and url do not match!")
user_repository.add(user_new)
return user_new.to_serializable_dict()
def all_for_use_case(use_case: str):
return user_repository.all_for_use_case(use_case)
......@@ -85,3 +85,16 @@ else:
BUSINESS_LOGIC_DB_PORT = 30421
#endregion Participation Hub
## Reputation-Calculation
if server:
REPUTATION_CALCULATION_HOSTNAME = 'reputation-calculation'
REPUTATION_CALCULATION_DB_HOSTNAME = f'{BUSINESS_LOGIC_HOSTNAME}-db'
REPUTATION_CALCULATION_REST_PORT = 80
REPUTATION_CALCULATION_DB_PORT = 27017
else:
REPUTATION_CALCULATION_HOSTNAME = 'articonf1.itec.aau.at'
REPUTATION_CALCULATION_DB_HOSTNAME = 'articonf1.itec.aau.at'
REPUTATION_CALCULATION_REST_PORT = 30107
REPUTATION_CALCULATION_DB_PORT = 30109
#endregion Reputation-Calculation
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment