Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(get): extend get command to get more information (DEV-139) (#137)
* get all languages for properties and resources

* refactoring

* convert maxlength value to int

* add project's group(s) to ontology

* add project's user(s) to ontology

* reformat code

* remove code smells

* remove unnecessary main methods

* fix route call

* Add comments to properties
  • Loading branch information
irinaschubert committed Jan 3, 2022
1 parent a300b60 commit 9ce6722
Show file tree
Hide file tree
Showing 13 changed files with 265 additions and 249 deletions.
2 changes: 1 addition & 1 deletion knora/dsp_tools.py
Expand Up @@ -168,7 +168,7 @@ def program(user_args: list[str]) -> None:
verbose=args.verbose,
dump=args.dump if args.dump else False)
elif args.action == 'get':
get_ontology(projident=args.project,
get_ontology(project_identifier=args.project,
outfile=args.datamodelfile,
server=args.server,
user=args.user,
Expand Down
82 changes: 30 additions & 52 deletions knora/dsplib/models/group.py
Expand Up @@ -4,7 +4,7 @@

from pystrict import strict

from knora.dsplib.models.langstring import LangString, LangStringParam, Languages
from knora.dsplib.models.langstring import LangString, Languages
from .connection import Connection
from .helpers import Actions, BaseError
from .model import Model
Expand Down Expand Up @@ -69,6 +69,8 @@ class Group(Model):
PROJECT_MEMBER_GROUP: str = "http://www.knora.org/ontology/knora-admin#ProjectMember"
PROJECT_ADMIN_GROUP: str = "http://www.knora.org/ontology/knora-admin#ProjectAdmin"
PROJECT_SYSTEMADMIN_GROUP: str = "http://www.knora.org/ontology/knora-admin#SystemAdmin"
ROUTE: str = "/admin/groups"
ROUTE_SLASH: str = ROUTE + "/"

_id: str
_name: str
Expand Down Expand Up @@ -212,36 +214,57 @@ def toJsonObj(self, action: Actions):
def create(self):
jsonobj = self.toJsonObj(Actions.Create)
jsondata = json.dumps(jsonobj)
result = self._con.post('/admin/groups', jsondata)
result = self._con.post(Group.ROUTE, jsondata)
return Group.fromJsonObj(self._con, result['group'])

def read(self):
result = self._con.get('/admin/groups/' + quote_plus(self._id))
result = self._con.get(Group.ROUTE_SLASH + quote_plus(self._id))
return Group.fromJsonObj(self._con, result['group'])

def update(self):
jsonobj = self.toJsonObj(Actions.Update)
if jsonobj:
jsondata = json.dumps(jsonobj)
result = self._con.put('/admin/groups/' + quote_plus(self._id), jsondata)
result = self._con.put(Group.ROUTE_SLASH + quote_plus(self._id), jsondata)
updated_group = Group.fromJsonObj(self._con, result['group'])
if self._status is not None and 'status' in self._changed:
jsondata = json.dumps({'status': self._status})
result = self._con.put('/admin/groups/' + quote_plus(self._id) + '/status', jsondata)
result = self._con.put(Group.ROUTE_SLASH + quote_plus(self._id) + '/status', jsondata)
updated_group = Group.fromJsonObj(self._con, result['group'])
return updated_group

def delete(self):
result = self._con.delete('/admin/groups/' + quote_plus(self._id))
result = self._con.delete(Group.ROUTE_SLASH + quote_plus(self._id))
return Group.fromJsonObj(self._con, result['group'])

@staticmethod
def getAllGroups(con: Connection) -> List['Group']:
result = con.get('/admin/groups')
result = con.get(Group.ROUTE)
if 'groups' not in result:
raise BaseError("Request got no groups!")
return list(map(lambda a: Group.fromJsonObj(con, a), result['groups']))

@staticmethod
def getAllGroupsForProject(con: Connection, proj_shortcode: str) -> List['Group']:
result = con.get(Group.ROUTE)
if 'groups' not in result:
raise BaseError("Request got no groups!")
all_groups = result["groups"]
project_groups = []
for group in all_groups:
if group["project"]["id"] == "http://rdfh.ch/projects/" + proj_shortcode:
project_groups.append(group)
return list(map(lambda a: Group.fromJsonObj(con, a), project_groups))

def createDefinitionFileObj(self):
group = {
"name": self.name,
"descriptions": self.descriptions.createDefinitionFileObj(),
"selfjoin": self.selfjoin,
"status": self.status
}
return group

def print(self):
print('Group Info:')
print(' Id: {}'.format(self._id))
Expand All @@ -255,48 +278,3 @@ def print(self):
print(' Project: {}'.format(self._project))
print(' Selfjoin: {}'.format(self._selfjoin))
print(' Status: {}'.format(self._status))


if __name__ == '__main__':
con = Connection('http://0.0.0.0:3333')
con.login('root@example.com', 'test')

groups = Group.getAllGroups(con)
for group in groups:
group.print()

new_group = Group(con=con,
name="GROUP TEST",
descriptions=LangString({Languages.EN: 'Test group description'}),
project="http://rdfh.ch/projects/00FF",
status=True,
selfjoin=False).create()
new_group.print()

new_group.name = "GROUP TEST - modified"
new_group = new_group.update()
new_group.print()
new_group.descriptions = LangString({Languages.DE: 'Beschreibung einer Gruppe'})
new_group = new_group.update()
new_group.print()

new_group.selfjoin = True
new_group = new_group.update()
new_group.print()

new_group.status = False
new_group = new_group.update()
new_group.print()

new_group.name = '-- GROUP TEST --'
new_group.descriptions = LangString({Languages.DE: 'Neue Beschreibung einer Gruppe'})
new_group.status = True
new_group = new_group.update()
new_group.print()

new_group.delete()

print('=========================')
groups = Group.getAllGroups(con)
for group in groups:
group.print()
2 changes: 1 addition & 1 deletion knora/dsplib/models/langstring.py
Expand Up @@ -269,7 +269,7 @@ def langstrs(self):
return self._langstrs

def createDefinitionFileObj(self) -> Union[str, Dict[str, str]]:
if self._simplestring is not None:
if self._simplestring:
return self._simplestring
langstring = {}
for p in self.items():
Expand Down
19 changes: 11 additions & 8 deletions knora/dsplib/models/listnode.py
Expand Up @@ -131,6 +131,9 @@ class ListNode(Model):
"""

ROUTE = "/admin/lists"
ROUTE_SLASH = ROUTE + "/"

_id: Optional[str]
_project: Optional[str]
_label: Optional[LangString]
Expand Down Expand Up @@ -457,10 +460,10 @@ def create(self) -> 'ListNode':
jsonobj = self.toJsonObj(Actions.Create)
jsondata = json.dumps(jsonobj, cls=SetEncoder)
if self._parent:
result = self._con.post('/admin/lists/' + quote_plus(self._parent), jsondata)
result = self._con.post(ListNode.ROUTE_SLASH + quote_plus(self._parent), jsondata)
return ListNode.fromJsonObj(self._con, result['nodeinfo'])
else:
result = self._con.post('/admin/lists', jsondata)
result = self._con.post(ListNode.ROUTE, jsondata)
return ListNode.fromJsonObj(self._con, result['list']['listinfo'])

def read(self) -> Any:
Expand All @@ -470,7 +473,7 @@ def read(self) -> Any:
:return: JSON-object from DSP-API
"""

result = self._con.get('/admin/lists/nodes/' + quote_plus(self._id))
result = self._con.get(ListNode.ROUTE_SLASH + 'nodes/' + quote_plus(self._id))
if result.get('nodeinfo'):
return self.fromJsonObj(self._con, result['nodeinfo'])
elif result.get('listinfo'):
Expand All @@ -488,7 +491,7 @@ def update(self) -> Union[Any, None]:
jsonobj = self.toJsonObj(Actions.Update, self.id)
if jsonobj:
jsondata = json.dumps(jsonobj, cls=SetEncoder)
result = self._con.put('/admin/lists/' + quote_plus(self.id), jsondata)
result = self._con.put(ListNode.ROUTE_SLASH + quote_plus(self.id), jsondata)
pprint(result)
return ListNode.fromJsonObj(self._con, result['listinfo'])
else:
Expand All @@ -501,7 +504,7 @@ def delete(self) -> None:
:return: DSP-API response
"""
raise BaseError("NOT YET IMPLEMENTED")
result = self._con.delete('/admin/lists/' + quote_plus(self._id))
result = self._con.delete(ListNode.ROUTE_SLASH + quote_plus(self._id))
return result
# return Project.fromJsonObj(self.con, result['project'])

Expand All @@ -513,7 +516,7 @@ def getAllNodes(self) -> 'ListNode':
:return: Root node of list with recursive ListNodes ("children"-attributes)
"""

result = self._con.get('/admin/lists/' + quote_plus(self._id))
result = self._con.get(ListNode.ROUTE_SLASH + quote_plus(self._id))
if 'list' not in result:
raise BaseError("Request got no list!")
if 'listinfo' not in result['list']:
Expand All @@ -536,9 +539,9 @@ def getAllLists(con: Connection, project_iri: Optional[str] = None) -> List['Lis
:return: list of ListNodes
"""
if project_iri is None:
result = con.get('/admin/lists')
result = con.get(ListNode.ROUTE)
else:
result = con.get('/admin/lists?projectIri=' + quote_plus(project_iri))
result = con.get(ListNode.ROUTE + '?projectIri=' + quote_plus(project_iri))
if 'lists' not in result:
raise BaseError("Request got no lists!")
return list(map(lambda a: ListNode.fromJsonObj(con, a), result['lists']))
Expand Down
42 changes: 22 additions & 20 deletions knora/dsplib/models/ontology.py
Expand Up @@ -27,11 +27,9 @@ def default(self, obj):
"""
This model implements the handling of ontologies. It is to note that ResourceClasses, PropertyClasses
as well as the assignment of PropertyCLasses to the ResourceClasses (with a given cardinality)
is handeld in "cooperation" with the propertyclass.py (PropertyClass) and resourceclass.py (ResourceClass
is handled in "cooperation" with the propertyclass.py (PropertyClass) and resourceclass.py (ResourceClass
and HasProperty) modules.
_Note_: All modifications to an ontology
CREATE:
* Instantiate a new object of the Ontology class with all required parameters
* Call the ``create``-method on the instance to create the ontology withing the backend
Expand All @@ -51,12 +49,16 @@ def default(self, obj):
* Instantiate a new objects with ``id``(IRI of group) given, or use any instance that has the id set,
that is, that You've read before
* Call the ``delete``-method on the instance
"""


@strict
class Ontology(Model):

ROUTE: str = '/v2/ontologies'
METADATA: str = '/metadata/'
ALL_LANGUAGES: str = '?allLanguages=true'

_id: str
_project: str
_name: str
Expand Down Expand Up @@ -383,58 +385,58 @@ def toJsonObj(self, action: Actions) -> Any:
def create(self, dumpjson: Optional[str] = None) -> 'Ontology':
jsonobj = self.toJsonObj(Actions.Create)
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4)
result = self._con.post('/v2/ontologies', jsondata)
result = self._con.post(Ontology.ROUTE, jsondata)
return Ontology.fromJsonObj(self._con, result)

def update(self) -> 'Ontology':
jsonobj = self.toJsonObj(Actions.Update)
jsondata = json.dumps(jsonobj, cls=SetEncoder, indent=4)
result = self._con.put('/v2/ontologies/metadata', jsondata, 'application/ld+json')
result = self._con.put(Ontology.ROUTE + '/metadata', jsondata, 'application/ld+json')
return Ontology.fromJsonObj(self._con, result)

def read(self) -> 'Ontology':
result = self._con.get('/v2/ontologies/allentities/' + quote_plus(self._id) + '?allLanguages=true')
result = self._con.get(Ontology.ROUTE + '/allentities/' + quote_plus(self._id) + Ontology.ALL_LANGUAGES)
return Ontology.fromJsonObj(self._con, result)

def delete(self) -> Optional[str]:
result = self._con.delete('/v2/ontologies/' + quote_plus(self._id),
result = self._con.delete(Ontology.ROUTE + '/' + quote_plus(self._id),
params={'lastModificationDate': str(self._lastModificationDate)})
return result.get('knora-api:result')

@staticmethod
def getAllOntologies(con: Connection) -> List['Ontology']:
result = con.get('/v2/ontologies/metadata/')
result = con.get(Ontology.ROUTE + Ontology.METADATA)
return Ontology.allOntologiesFromJsonObj(con, result)

@staticmethod
def getProjectOntologies(con: Connection, project_id: str) -> List['Ontology']:
if project_id is None:
raise BaseError('Project ID must be defined!')
result = con.get('/v2/ontologies/metadata/' + quote_plus(project_id) + '?allLanguages=true')
result = con.get(Ontology.ROUTE + Ontology.METADATA + quote_plus(project_id) + Ontology.ALL_LANGUAGES)
return Ontology.allOntologiesFromJsonObj(con, result)

@staticmethod
def getOntologyFromServer(con: Connection, shortcode: str, name: str) -> 'Ontology':
result = con.get("/ontology/" + shortcode + "/" + name + "/v2")
result = con.get("/ontology/" + shortcode + "/" + name + "/v2" + Ontology.ALL_LANGUAGES)
return Ontology.fromJsonObj(con, result)

def createDefinitionFileObj(self):
ontology = {
"name": self._name,
"label": self._label,
"name": self.name,
"label": self.label,
"properties": [],
"resources": []
}
if self._comment is not None:
ontology["comment"] = self._comment
for prop in self._property_classes:
if self.comment:
ontology["comment"] = self.comment
for prop in self.property_classes:
if "knora-api:hasLinkToValue" in prop.superproperties:
self._skiplist.append(self._name + ":" + prop.name)
self.skiplist.append(self.name + ":" + prop.name)
continue
ontology["properties"].append(prop.createDefinitionFileObj(self.context, self._name))
ontology["properties"].append(prop.createDefinitionFileObj(self.context, self.name))

for res in self._resource_classes:
ontology["resources"].append(res.createDefinitionFileObj(self.context, self._name, self._skiplist))
for res in self.resource_classes:
ontology["resources"].append(res.createDefinitionFileObj(self.context, self.name, self._skiplist))

return ontology

Expand Down

0 comments on commit 9ce6722

Please sign in to comment.