From b88fc7fe96f321022a6ecf337e4726b614021b12 Mon Sep 17 00:00:00 2001 From: Narek Date: Tue, 21 Apr 2020 18:50:57 +0300 Subject: [PATCH 1/6] First try to implement SPARQL query with acl --- .../src/test/resources/acl-query.sparql | 23 +++++++++++++++++++ .../src/test/resources/noacl-query.sparql | 16 +++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql create mode 100644 ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql b/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql new file mode 100644 index 0000000..bc17263 --- /dev/null +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql @@ -0,0 +1,23 @@ +PREFIX rdf: +PREFIX dcterms: +PREFIX sh: +PREFIX rm: +PREFIX ppo: +PREFIX pporoles: +SELECT ?eIri0 ?targetClass0 ?title0 ?description0 ?inCreationMenu0 ?defaultIndividNs0 ?defaultFormat0 ?iconReference0 +WHERE { + ?eIri0 rdf:type sh:NodeShape; + sh:targetClass ?targetClass0. + OPTIONAL { ?eIri0 dcterms:title ?title0. } + OPTIONAL { ?eIri0 dcterms:description ?description0. } + OPTIONAL { ?eIri0 rm:inCreationMenu ?inCreationMenu0. } + OPTIONAL { ?eIri0 rm:defaultIndividNs ?defaultIndividNs0. } + OPTIONAL { ?eIri0 rm:defaultFormat ?defaultFormat0. } + OPTIONAL { ?eIri0 rm:iconReference ?iconReference0. } + FILTER(?targetClass0 = rm:Artifact) + pporoles:roleAgent ?role. + ?role ppoRoles:rolePolicy ?policies. + ?policies ppo:hasCondition ?conditions. + ?conditions ppo:classAsSubject ?targetClass0. + ?policies ppo:hasAccess acl:Read. +} \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql b/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql new file mode 100644 index 0000000..1d1efb8 --- /dev/null +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql @@ -0,0 +1,16 @@ +PREFIX rdf: +PREFIX dcterms: +PREFIX sh: +PREFIX rm: +SELECT ?eIri0 ?targetClass0 ?title0 ?description0 ?inCreationMenu0 ?defaultIndividNs0 ?defaultFormat0 ?iconReference0 +WHERE { + ?eIri0 rdf:type sh:NodeShape; + sh:targetClass ?targetClass0. + OPTIONAL { ?eIri0 dcterms:title ?title0. } + OPTIONAL { ?eIri0 dcterms:description ?description0. } + OPTIONAL { ?eIri0 rm:inCreationMenu ?inCreationMenu0. } + OPTIONAL { ?eIri0 rm:defaultIndividNs ?defaultIndividNs0. } + OPTIONAL { ?eIri0 rm:defaultFormat ?defaultFormat0. } + OPTIONAL { ?eIri0 rm:iconReference ?iconReference0. } + FILTER(?targetClass0 = rm:Artifact) +} \ No newline at end of file From 62f20fbaa476e3e53bc55ed42a62926d6e996d3d Mon Sep 17 00:00:00 2001 From: Narek Date: Tue, 21 Apr 2020 18:56:15 +0300 Subject: [PATCH 2/6] added new lines:\ --- ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql | 2 +- ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql b/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql index bc17263..5629e97 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/acl-query.sparql @@ -20,4 +20,4 @@ WHERE { ?policies ppo:hasCondition ?conditions. ?conditions ppo:classAsSubject ?targetClass0. ?policies ppo:hasAccess acl:Read. -} \ No newline at end of file +} diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql b/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql index 1d1efb8..06c3fd7 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/noacl-query.sparql @@ -13,4 +13,4 @@ WHERE { OPTIONAL { ?eIri0 rm:defaultFormat ?defaultFormat0. } OPTIONAL { ?eIri0 rm:iconReference ?iconReference0. } FILTER(?targetClass0 = rm:Artifact) -} \ No newline at end of file +} From 4825065660378bd84a3110aa8b35b82cd39fdde1 Mon Sep 17 00:00:00 2001 From: Narek Date: Sun, 3 May 2020 15:45:58 +0300 Subject: [PATCH 3/6] Added methods to ppManager for adding user to group, refactored all repository --- ru.agentlab.rdf4j.ppo/pom.xml | 7 + .../ru.agentlab.rdf4j.ppo.iml | 77 ++ .../rdf4j/ppo/policies/PPManagerImpl.java | 203 ++-- .../ppo/policies/model/PPAccessAllowed.java | 6 +- .../rdf4j/ppo/policies/model/PPComponent.java | 17 +- .../ppo/policies/model/PrivacyPreference.java | 2 +- .../model/PrivacyPreferenceFactory.java | 271 +++--- .../policies/model/PrivacyPreferenceImpl.java | 197 ++-- .../model/accesscontrol/PPAccessControl.java | 22 +- .../accesscontrol/PPAccessControlFactory.java | 18 +- .../accesscontrol/PPAccessControlImpl.java | 30 +- .../model/accessspace/PPAccessSpaceAgent.java | 23 +- .../accessspace/PPAccessSpaceFactory.java | 24 +- .../model/accessspace/PPAccessSpaceQuery.java | 8 +- .../condition/PPConditionClassAsObject.java | 58 +- .../condition/PPConditionClassAsSubject.java | 8 +- .../model/condition/PPConditionComplex.java | 40 +- .../model/condition/PPConditionFactory.java | 50 +- .../condition/PPConditionHasLiteral.java | 28 +- .../condition/PPConditionHasProperty.java | 28 +- .../PPConditionResourceAsObject.java | 32 +- .../PPConditionResourceAsSubject.java | 33 +- .../model/condition/PPConditionSingle.java | 2 +- .../restriction/PPRestrictionContext.java | 32 +- .../restriction/PPRestrictionFactory.java | 28 +- .../restriction/PPRestrictionResource.java | 40 +- .../restriction/PPRestrictionStatement.java | 20 +- .../ppo/triplestore/AccessControlSail.java | 4 +- .../triplestore/AccessControlSailImpl.java | 156 +-- .../AccessControlSailRepository.java | 69 +- .../ppo/triplestore/FakeTripleStore.java | 4 +- .../InterceptingRepositoryConnection.java | 18 +- ...terceptingRepositoryConnectionWrapper.java | 916 +++++++++--------- .../triplestore/TripleFilterInterceptor.java | 165 ++-- .../rdf4j/ppo/triplestore/TripleStore.java | 37 +- .../ppo/triplestore/TripleStoreAction.java | 6 +- .../agentlab/rdf4j/ppo/AbstractUnitTests.java | 88 ++ .../ru/agentlab/rdf4j/ppo/FilteringTests.java | 166 +--- .../agentlab/rdf4j/ppo/RightsEditingTest.java | 60 ++ .../src/test/resources/access-management.ttl | 198 ++-- .../src/test/resources/users.ttl | 155 +-- 41 files changed, 1739 insertions(+), 1607 deletions(-) create mode 100644 ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml create mode 100644 ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/AbstractUnitTests.java create mode 100644 ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java diff --git a/ru.agentlab.rdf4j.ppo/pom.xml b/ru.agentlab.rdf4j.ppo/pom.xml index 274f978..8f7babf 100644 --- a/ru.agentlab.rdf4j.ppo/pom.xml +++ b/ru.agentlab.rdf4j.ppo/pom.xml @@ -16,6 +16,13 @@ bundle + + + org.projectlombok + lombok + 1.18.12 + provided + org.hamcrest java-hamcrest diff --git a/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml b/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml new file mode 100644 index 0000000..bdca304 --- /dev/null +++ b/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java index 886156f..dec948e 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java @@ -1,17 +1,13 @@ package ru.agentlab.rdf4j.ppo.policies; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - +import lombok.Getter; +import lombok.Setter; +import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.IRI; - import org.eclipse.rdf4j.model.Namespace; +import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; @@ -19,102 +15,105 @@ import org.eclipse.rdf4j.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - +import ru.agentlab.rdf4j.ppo.policies.model.PPAccessAllowed; import ru.agentlab.rdf4j.ppo.policies.model.PrivacyPreference; import ru.agentlab.rdf4j.ppo.policies.model.PrivacyPreferenceFactory; +import ru.agentlab.rdf4j.ppo.policies.model.accesscontrol.PPAccessControl; +import ru.agentlab.rdf4j.ppo.policies.model.accesscontrol.PPAccessControlFactory; + +import java.util.ArrayList; +import java.util.List; -public class PPManagerImpl implements PPManager{ - private static Logger log = LoggerFactory.getLogger(PPManagerImpl.class); - - protected String policiesContext; - protected List ppList; - protected boolean isWhitelisting = true; // switch to false for blacklisting - public static String prefixes = ""; - public static final String CUR_USER = "?cur_user"; - - public PPManagerImpl() { - ppList = new ArrayList(); - } - - @Override - public void setWhitelisting(boolean isWhitelisting) { - this.isWhitelisting = isWhitelisting; - } - - @Override - public boolean isWhitelisting() { - return isWhitelisting; - } - - @Override - public void setPoliciesContext(String policiesContext) { - this.policiesContext = policiesContext; - } - - @Override - public String getPoliciesContext() { - return this.policiesContext; - } - - @Override - public void loadPrivacyPreferences(Repository repo) throws IOException { - try { - RepositoryConnection connection = repo.getConnection(); - /* - * store prefixes - */ - List prefixList = null; - - try { - prefixList = connection.getNamespaces().asList(); - } catch (RepositoryException e) { - e.printStackTrace(); - } - - for(Namespace p : prefixList){ - prefixes += "PREFIX "; - prefixes += p.getPrefix(); - prefixes += ": <"; - prefixes += p.getName(); - prefixes += "> "; - } - - /* - * create ppList - */ - TupleQueryResult statements = connection.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?s FROM <" + policiesContext + "> WHERE {?s } ").evaluate(); - - try { - while(statements.hasNext()) { - BindingSet bindingSet = statements.next(); - Value valueOfS = bindingSet.getValue("s"); - - IRI ppIRI = connection.getValueFactory().createIRI(valueOfS.stringValue()); - - ppList.add(PrivacyPreferenceFactory.createPrivacyPreference(ppIRI, connection, policiesContext)); - } - log.info("{} privacy preferences have been succesfully mapped", getPrivacyPreferences().size()); - } catch (Exception e) { - e.printStackTrace(); - } - - finally { - Collections.sort(ppList, Collections.reverseOrder()); // sort by priority - } - - } catch (RepositoryException e) { - log.error("Error loading policies", e); - throw new IllegalStateException(e); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - } catch (MalformedQueryException e) { - e.printStackTrace(); - } - } - - @Override - public List getPrivacyPreferences () { - return ppList; - } +@Getter +@Setter +public class PPManagerImpl implements PPManager { + private static Logger log = LoggerFactory.getLogger(PPManagerImpl.class); + + protected String policiesContext; + protected List ppList; + protected boolean isWhitelisting = true; // switch to false for blacklisting + public static String prefixes = ""; + public static final String CUR_USER = "?cur_user"; + + public PPManagerImpl() { + ppList = new ArrayList<>(); + } + + @Override + public void loadPrivacyPreferences(Repository repo) { + try { + RepositoryConnection connection = repo.getConnection(); + /* + * store prefixes + */ + List prefixList; + + prefixList = Iterations.asList(connection.getNamespaces()); + + for (Namespace p : prefixList) { + prefixes += "PREFIX "; + prefixes += p.getPrefix(); + prefixes += ": <"; + prefixes += p.getName(); + prefixes += "> "; + } + + /* + * create ppList + */ + TupleQueryResult statements = connection.prepareTupleQuery(QueryLanguage.SPARQL, + "SELECT ?s FROM <" + policiesContext + "> " + + "WHERE {?s " + + "} ") + .evaluate(); + + while (statements.hasNext()) { + BindingSet bindingSet = statements.next(); + Value valueOfS = bindingSet.getValue("s"); + + IRI ppIRI = connection.getValueFactory().createIRI(valueOfS.stringValue()); + + ppList.add(PrivacyPreferenceFactory.createPrivacyPreference(ppIRI, connection, policiesContext)); + } + log.info("{} privacy preferences have been succesfully mapped", getPrivacyPreferences().size()); + + } catch (RepositoryException e) { + log.error("Error loading policies", e); + throw new IllegalStateException(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void setUserExpertGroupOne(RepositoryConnection connection, IRI webid) { + IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertGroup1"); + editUserRole(connection, webid, adminIri); + } + + public void setUserExpertUsersTwo(RepositoryConnection connection, IRI webid) { + IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertUsers2"); + editUserRole(connection, webid, adminIri); + } + + public void setUserAdminRights(RepositoryConnection connection, IRI webid) { + IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#adminUsers"); + editUserRole(connection, webid, adminIri); + } + + private void editUserRole(RepositoryConnection connection, IRI webid, IRI userRole) { + String memberOf = "http://xmlns.com/foaf/0.1/member"; + IRI predicateForRole = connection.getValueFactory().createIRI(memberOf); + Statement statement = connection.getValueFactory().createStatement( + userRole, + predicateForRole, + webid); + connection.add(statement); + connection.commit(); + } + + @Override + public List getPrivacyPreferences() { + return ppList; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPAccessAllowed.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPAccessAllowed.java index e00e435..96bc7c0 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPAccessAllowed.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPAccessAllowed.java @@ -1,12 +1,10 @@ package ru.agentlab.rdf4j.ppo.policies.model; /** - * * @author Franz Brandstätter - * + *

* States a pp can have according to verification - * */ public enum PPAccessAllowed { - ALLOWED, DENIED, NOT_HANDLED; + ALLOWED, DENIED, NOT_HANDLED; } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPComponent.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPComponent.java index 56872b9..fe8a349 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPComponent.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PPComponent.java @@ -4,12 +4,13 @@ import org.eclipse.rdf4j.model.IRI; public interface PPComponent { - /** - * checks whether the statement is handled by the - * current PrivacyPreference - * @param webid ID of the current user - * @param statement Statement which has to be checked - * @return true if the current PP handles the statement, false otherwise - */ - boolean handlesAccess(IRI webid, Statement statement); + /** + * checks whether the statement is handled by the + * current PrivacyPreference + * + * @param webid ID of the current user + * @param statement Statement which has to be checked + * @return true if the current PP handles the statement, false otherwise + */ + boolean handlesAccess(IRI webid, Statement statement); } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreference.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreference.java index 78930e1..813ef25 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreference.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreference.java @@ -8,7 +8,7 @@ public interface PrivacyPreference extends Comparable { * gets the priority of the PP * @return the priority */ - public float getPriority(); + float getPriority(); /** * Verifies whether the current PP allows read-access for the submitted * statement and webid diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceFactory.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceFactory.java index cf57dc6..653d6e0 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceFactory.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceFactory.java @@ -1,16 +1,15 @@ package ru.agentlab.rdf4j.ppo.policies.model; -import java.util.ArrayList; -import java.util.List; - +import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.BNode; -import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.RepositoryResult; - +import org.locationtech.jts.util.Assert; import ru.agentlab.rdf4j.ppo.policies.model.accesscontrol.PPAccessControl; import ru.agentlab.rdf4j.ppo.policies.model.accesscontrol.PPAccessControlFactory; import ru.agentlab.rdf4j.ppo.policies.model.accessspace.PPAccessSpace; @@ -20,146 +19,138 @@ import ru.agentlab.rdf4j.ppo.policies.model.condition.PPConditionSingle; import ru.agentlab.rdf4j.ppo.policies.model.restriction.PPRestriction; import ru.agentlab.rdf4j.ppo.policies.model.restriction.PPRestrictionFactory; -import ru.agentlab.rdf4j.ppo.triplestore.TripleStore; +import ru.agentlab.rdf4j.ppo.triplestore.FakeTripleStore; + +import java.util.ArrayList; +import java.util.List; /** - * * Gets the statements of the current policyPreference and * map them to a PrivacyPreference - * */ public class PrivacyPreferenceFactory { - /** - * create a new PrivacyPreference based on an IRI - * @param pp IRI of the privacyPreference which has to be mapped - * @param connection the active repository-connection - * @return new PrivacyPreference - * @throws Exception Syntax Error - */ - public static PrivacyPreference createPrivacyPreference(IRI pp, RepositoryConnection connection, String policiesContext) throws Exception { - - IRI context = connection.getValueFactory().createIRI(policiesContext); - - List restrictions = new ArrayList(); - List accessControls = new ArrayList(); - List accessSpaces = new ArrayList(); - PPCondition condition = null; - float priority = 0f; - - /** - * iterate over all statements of the current policy and process them - */ - try { - RepositoryResult statements = connection.getStatements(pp, null, null, false, context); - - while (statements.hasNext()) { - Statement st = statements.next(); - - if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToResource") || - st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToContext")) { - restrictions.add(PPRestrictionFactory.createRestriction(st.getPredicate(), (IRI)st.getObject())); - } - - else if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToStatement")) { - List statementElements = new ArrayList(); - - try { - RepositoryResult stStatements = connection.getStatements((BNode)st.getObject(), null, null, false, context); - - while (stStatements.hasNext()) { - Statement s = stStatements.next(); - if(s.getPredicate().stringValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject")) - statementElements.add(0, s.getObject()); - else if(s.getPredicate().stringValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate")) - statementElements.add(1, s.getObject()); - else if(s.getPredicate().stringValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#object")) - statementElements.add(2, s.getObject()); - } - - if(statementElements.size() == 3) { - Statement statement = connection.getValueFactory().createStatement((IRI)statementElements.get(0), - (IRI)statementElements.get(1), - statementElements.get(2)); - restrictions.add(PPRestrictionFactory.createRestriction(statement)); - - } - else - throw new Exception("SyntaxError appliesToStatement - subject, predicate and object expected in " + pp.stringValue()); - - } catch (RepositoryException e) { - e.printStackTrace(); - } - } - - else if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasAccess") || - st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasNoAccess")) { - accessControls.add(PPAccessControlFactory.createAccessControl(st.getPredicate(), (IRI)st.getObject())); - } - - else if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasCondition")) { - try { - RepositoryResult conditionStatements = connection.getStatements((BNode)st.getObject(), - null, null, false, context); - - List conditionList = new ArrayList(); - - while (conditionStatements.hasNext()) { - Statement conditionStatement = conditionStatements.next(); - - conditionList.add((PPConditionSingle) PPConditionFactory.createCondition(conditionStatement.getPredicate(), - conditionStatement.getObject(), - connection)); - } - - if(conditionList.size() == 1) - condition = conditionList.get(0); - - else if(conditionList.size() > 1) { - condition = PPConditionFactory.createCondition(conditionList); - } - - } catch (RepositoryException e) { - e.printStackTrace(); - } - } - - else if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasAccessSpace")) { - - try { - RepositoryResult accessSpaceStatements = connection.getStatements((BNode)st.getObject(), - null, null, false, context); - - while (accessSpaceStatements.hasNext()) { - Statement accessSpaceStatement = accessSpaceStatements.next(); - accessSpaces.add(PPAccessSpaceFactory.createAccessSpace(accessSpaceStatement.getPredicate(), - accessSpaceStatement.getObject(), - connection)); - } - - } catch (RepositoryException e) { - e.printStackTrace(); - } - } - - else if(st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasPriority")) { - RepositoryResult hasPriorityStatements = connection.getStatements((BNode)st.getObject(),null,null,false,context); - - //should there be more priorities defined, the first one is used - Statement hasPriorityStatement = hasPriorityStatements.next(); - if(hasPriorityStatement.getPredicate().stringValue().equals("http://purl.org/ontology/wo/weightingontology.html#weight_value")) - priority = Float.parseFloat(hasPriorityStatement.getObject().stringValue()); - else - throw new Exception("SyntaxError predicate of priority in " + pp.stringValue()); - } - } - } catch (RepositoryException e) { - e.printStackTrace(); - } - - if (accessControls.isEmpty()) - throw new Exception("AccessControl missing in " + pp); - - return new PrivacyPreferenceImpl(accessControls, accessSpaces, condition, restrictions, priority); - } + /** + * create a new PrivacyPreference based on an IRI + * + * @param pp IRI of the privacyPreference which has to be mapped + * @param connection the active repository-connection + * @return new PrivacyPreference + * @throws Exception Syntax Error + */ + public static PrivacyPreference createPrivacyPreference(IRI pp, RepositoryConnection connection, String policiesContext) throws Exception { + + IRI context = connection.getValueFactory().createIRI(policiesContext); + + List restrictions = new ArrayList<>(); + List accessControls = new ArrayList<>(); + List accessSpaces = new ArrayList<>(); + PPCondition condition = null; + float priority = 0f; + + /** + * iterate over all statements of the current policy and process them + */ + try { + RepositoryResult statements = connection.getStatements(pp, null, null, false, context); + + while (statements.hasNext()) { + Statement st = statements.next(); + + if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToResource") || + st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToContext")) { + restrictions.add(PPRestrictionFactory.createRestriction(st.getPredicate(), (IRI) st.getObject())); + } else if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#appliesToStatement")) { + List statementElements = new ArrayList<>(); + + RepositoryResult stStatements = connection.getStatements((BNode) st.getObject(), null, null, false, context); + + while (stStatements.hasNext()) { + Statement s = stStatements.next(); + switch (s.getPredicate().stringValue()) { + case "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject": + statementElements.add(0, s.getObject()); + break; + case "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": + statementElements.add(1, s.getObject()); + break; + case "http://www.w3.org/1999/02/22-rdf-syntax-ns#object": + statementElements.add(2, s.getObject()); + break; + default: + throw new IllegalStateException("Unexpected value: " + s.getPredicate().stringValue()); + } + } + + if (statementElements.size() == 3) { + Statement statement = connection.getValueFactory().createStatement((IRI) statementElements.get(0), + (IRI) statementElements.get(1), + statementElements.get(2)); + restrictions.add(PPRestrictionFactory.createRestriction(statement)); + + } else + throw new Exception("SyntaxError appliesToStatement - subject, predicate and object expected in " + pp.stringValue()); + + } else { + if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasAccess") || + st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasNoAccess")) { + accessControls.add(PPAccessControlFactory.createAccessControl(st.getPredicate(), (IRI) st.getObject())); + } else { + if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasCondition")) { + RepositoryResult conditionStatements = connection.getStatements((BNode) st.getObject(), + null, null, false, context); + + List conditionList = new ArrayList<>(); + + while (conditionStatements.hasNext()) { + Statement conditionStatement = conditionStatements.next(); + + conditionList.add((PPConditionSingle) PPConditionFactory.createCondition(conditionStatement.getPredicate(), + conditionStatement.getObject(), + connection)); + } + + if (conditionList.size() == 1) + condition = conditionList.get(0); + + else if (conditionList.size() > 1) { + condition = PPConditionFactory.createCondition(conditionList); + } + } else { + if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasAccessSpace")) { + RepositoryResult accessSpaceStatements = connection.getStatements((BNode) st.getObject(), + null, null, false, context); + + while (accessSpaceStatements.hasNext()) { + Statement accessSpaceStatement = accessSpaceStatements.next(); + accessSpaces.add(PPAccessSpaceFactory.createAccessSpace(accessSpaceStatement.getPredicate(), + accessSpaceStatement.getObject(), + connection)); + } + } else { + if (st.getPredicate().stringValue().equals("http://vocab.deri.ie/ppo#hasPriority")) { + RepositoryResult hasPriorityStatements = connection.getStatements((BNode) st.getObject(), null, null, false, context); + + //should there be more priorities defined, the first one is used + Statement hasPriorityStatement = hasPriorityStatements.next(); + if (hasPriorityStatement.getPredicate().stringValue().equals("http://purl.org/ontology/wo/weightingontology.html#weight_value")) + priority = Float.parseFloat(hasPriorityStatement.getObject().stringValue()); + else + throw new Exception("SyntaxError predicate of priority in " + pp.stringValue()); + } + } + } + } + } + } + } catch (RepositoryException e) { + e.printStackTrace(); + } + + if (accessControls.isEmpty()) + throw new Exception("AccessControl missing in " + pp); + + return new PrivacyPreferenceImpl(accessControls, accessSpaces, condition, restrictions, priority); + } + } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceImpl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceImpl.java index 6d69aab..23d0025 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceImpl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/PrivacyPreferenceImpl.java @@ -11,105 +11,100 @@ import ru.agentlab.rdf4j.ppo.policies.model.restriction.PPRestriction; public class PrivacyPreferenceImpl implements PrivacyPreference { - - private List accessControls; - private List accessSpaces; - private PPCondition condition; - private List restrictions; - private float priority; - - public PrivacyPreferenceImpl(List accessControls, - List accessSpaces, - PPCondition condition, - List restrictions, - float priority) { - - this.accessControls = accessControls; - this.accessSpaces = accessSpaces; - this.condition = condition; - this.restrictions = restrictions; - this.priority = priority; - } - - @Override - public float getPriority() { - return priority; - } - - @Override - public PPAccessAllowed allowsRead(IRI webid, Statement statement) { - return allowsAccess(webid,statement, "http://www.w3.org/ns/auth/acl#Read"); - } - - @Override - public PPAccessAllowed allowsCreate(IRI webid, Statement statement) { - return allowsAccess(webid,statement,"http://vocab.deri.ie/ppo#Create"); - } - - @Override - public PPAccessAllowed allowsDelete(IRI webid, Statement statement) { - return allowsAccess(webid,statement,"http://vocab.deri.ie/ppo#Delete"); - } - - @Override - public PPAccessAllowed allowsUpdate(IRI webid, Statement statement) { - return allowsAccess(webid,statement,"http://vocab.deri.ie/ppo#Update"); - } - - @Override - public PPAccessAllowed allowsAccess(IRI webid, Statement statement, String right) { - - boolean ppIsHandlingAccess = true; - boolean userHasAccessRight = true; - // if there is a restriction or condition, then it's not applying for all triples - // and therefore the restrictions and conditions have to be verified - if(!restrictions.isEmpty() || condition != null) { - ppIsHandlingAccess = false; - - for(PPRestriction restriction : restrictions) { - - ppIsHandlingAccess = restriction.handlesAccess(webid, statement); - - if(ppIsHandlingAccess) - break; - } - - if((ppIsHandlingAccess || restrictions.isEmpty()) && condition != null) - ppIsHandlingAccess = condition.handlesAccess(webid, statement); - - if(!ppIsHandlingAccess) - return PPAccessAllowed.NOT_HANDLED; - } - - //if no accessSpace is defined, pp applies for all users - if(!accessSpaces.isEmpty()) { - userHasAccessRight = false; - - for(PPAccessSpace accessSpace : accessSpaces) { - userHasAccessRight = accessSpace.handlesAccess(webid, statement); - if(userHasAccessRight) - break; - } - - if(!userHasAccessRight) - return PPAccessAllowed.NOT_HANDLED; - } - - for(PPAccessControl accessControl : accessControls) { - if(accessControl.getAccessType().stringValue().equals(right)) - return accessControl.grantAccess() ? PPAccessAllowed.ALLOWED : PPAccessAllowed.DENIED; - } - - return PPAccessAllowed.NOT_HANDLED; - } - - @Override - public int compareTo(PrivacyPreference o) { - if(this.getPriority() < o.getPriority()) - return -1; - else if(this.getPriority() == o.getPriority()) - return 0; - else - return 1; - } + + private List accessControls; + private List accessSpaces; + private PPCondition condition; + private List restrictions; + private float priority; + + public PrivacyPreferenceImpl(List accessControls, + List accessSpaces, + PPCondition condition, + List restrictions, + float priority) { + + this.accessControls = accessControls; + this.accessSpaces = accessSpaces; + this.condition = condition; + this.restrictions = restrictions; + this.priority = priority; + } + + @Override + public float getPriority() { + return priority; + } + + @Override + public PPAccessAllowed allowsRead(IRI webid, Statement statement) { + return allowsAccess(webid, statement, "http://www.w3.org/ns/auth/acl#Read"); + } + + @Override + public PPAccessAllowed allowsCreate(IRI webid, Statement statement) { + return allowsAccess(webid, statement, "http://vocab.deri.ie/ppo#Create"); + } + + @Override + public PPAccessAllowed allowsDelete(IRI webid, Statement statement) { + return allowsAccess(webid, statement, "http://vocab.deri.ie/ppo#Delete"); + } + + @Override + public PPAccessAllowed allowsUpdate(IRI webid, Statement statement) { + return allowsAccess(webid, statement, "http://vocab.deri.ie/ppo#Update"); + } + + @Override + public PPAccessAllowed allowsAccess(IRI webid, Statement statement, String right) { + + boolean ppIsHandlingAccess; + boolean userHasAccessRight; + // if there is a restriction or condition, then it's not applying for all triples + // and therefore the restrictions and conditions have to be verified + if (!restrictions.isEmpty() || condition != null) { + ppIsHandlingAccess = false; + + for (PPRestriction restriction : restrictions) { + + ppIsHandlingAccess = restriction.handlesAccess(webid, statement); + + if (ppIsHandlingAccess) + break; + } + + if ((ppIsHandlingAccess || restrictions.isEmpty()) && condition != null) + ppIsHandlingAccess = condition.handlesAccess(webid, statement); + + if (!ppIsHandlingAccess) + return PPAccessAllowed.NOT_HANDLED; + } + + //if no accessSpace is defined, pp applies for all users + if (!accessSpaces.isEmpty()) { + userHasAccessRight = false; + + for (PPAccessSpace accessSpace : accessSpaces) { + userHasAccessRight = accessSpace.handlesAccess(webid, statement); + if (userHasAccessRight) + break; + } + + if (!userHasAccessRight) + return PPAccessAllowed.NOT_HANDLED; + } + + for (PPAccessControl accessControl : accessControls) { + if (accessControl.getAccessType().stringValue().equals(right)) + return accessControl.grantAccess() ? PPAccessAllowed.ALLOWED : PPAccessAllowed.DENIED; + } + + return PPAccessAllowed.NOT_HANDLED; + } + + @Override + public int compareTo(PrivacyPreference o) { + return Float.compare(this.getPriority(), o.getPriority()); + } } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControl.java index bf6aab0..7ccc0fc 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControl.java @@ -3,15 +3,17 @@ import org.eclipse.rdf4j.model.IRI; public interface PPAccessControl { - /** - * gets the type of accessControl - * @return create,read,update or delete - */ - IRI getAccessType(); + /** + * gets the type of accessControl + * + * @return create, read, update or delete + */ + IRI getAccessType(); - /** - * gets whether access is granted or denied - * @return true if granted, false otherwise - */ - boolean grantAccess(); + /** + * gets whether access is granted or denied + * + * @return true if granted, false otherwise + */ + boolean grantAccess(); } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlFactory.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlFactory.java index 19da0a0..e0c0e24 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlFactory.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlFactory.java @@ -4,14 +4,12 @@ public class PPAccessControlFactory { - public static PPAccessControl createAccessControl(IRI predicate, IRI object) { - - if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccess")) { - return new PPAccessControlImpl(object, true); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasNoAccess")) { - return new PPAccessControlImpl(object, false); - } - else return null; - } + public static PPAccessControl createAccessControl(IRI predicate, IRI object) { + + if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccess")) { + return new PPAccessControlImpl(object, true); + } else if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasNoAccess")) { + return new PPAccessControlImpl(object, false); + } else return null; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlImpl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlImpl.java index e184021..5a85504 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlImpl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accesscontrol/PPAccessControlImpl.java @@ -2,23 +2,23 @@ import org.eclipse.rdf4j.model.IRI; -public class PPAccessControlImpl implements PPAccessControl{ +public class PPAccessControlImpl implements PPAccessControl { - private IRI accessType; - private boolean grantAccess; + private IRI accessType; + private boolean grantAccess; - public PPAccessControlImpl(IRI accessType, boolean grantAccess) { - this.accessType = accessType; - this.grantAccess = grantAccess; - } + public PPAccessControlImpl(IRI accessType, boolean grantAccess) { + this.accessType = accessType; + this.grantAccess = grantAccess; + } - @Override - public IRI getAccessType() { - return accessType; - } + @Override + public IRI getAccessType() { + return accessType; + } - @Override - public boolean grantAccess() { - return grantAccess; - } + @Override + public boolean grantAccess() { + return grantAccess; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceAgent.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceAgent.java index 744dd0a..2f9c608 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceAgent.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceAgent.java @@ -5,17 +5,14 @@ public class PPAccessSpaceAgent implements PPAccessSpace { - private IRI hasAccessAgent; - - public PPAccessSpaceAgent(IRI hasAccessAgent) { - this.hasAccessAgent = hasAccessAgent; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - if(webid.equals(hasAccessAgent)) - return true; - else - return false; - } + private IRI hasAccessAgent; + + public PPAccessSpaceAgent(IRI hasAccessAgent) { + this.hasAccessAgent = hasAccessAgent; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + return webid.equals(hasAccessAgent); + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceFactory.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceFactory.java index 90c826e..c1d167c 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceFactory.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceFactory.java @@ -6,15 +6,17 @@ public class PPAccessSpaceFactory { - public static PPAccessSpace createAccessSpace(IRI predicate,Value object, RepositoryConnection connection) { - - if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccessQuery")) { - return new PPAccessSpaceQuery(object.stringValue(), connection); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccessAgent")) { - return new PPAccessSpaceAgent((IRI) object); - } - - return null; - } + private PPAccessSpaceFactory() { + } + + public static PPAccessSpace createAccessSpace(IRI predicate, Value object, RepositoryConnection connection) { + + if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccessQuery")) { + return new PPAccessSpaceQuery(object.stringValue(), connection); + } else if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasAccessAgent")) { + return new PPAccessSpaceAgent((IRI) object); + } + + return null; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceQuery.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceQuery.java index 2aa7527..b03c1a1 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceQuery.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/accessspace/PPAccessSpaceQuery.java @@ -29,14 +29,10 @@ public boolean handlesAccess(IRI webid, Statement statement) { handlesAccess = connection.prepareBooleanQuery(QueryLanguage.SPARQL, PPManagerImpl.prefixes + tempHasAccessQuery).evaluate(); - } catch (RepositoryException e) { - e.printStackTrace(); - } catch (MalformedQueryException e) { - e.printStackTrace(); - } catch (QueryEvaluationException e) { + } catch (RepositoryException | MalformedQueryException | QueryEvaluationException e) { e.printStackTrace(); } - + return handlesAccess; } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsObject.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsObject.java index 0ef9281..74d100b 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsObject.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsObject.java @@ -12,35 +12,31 @@ public class PPConditionClassAsObject implements PPConditionSingle { - private Value classAsObject; - private RepositoryConnection connection; - - public PPConditionClassAsObject(Value classAsObject, RepositoryConnection connection) { - this.classAsObject = classAsObject; - this.connection = connection; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - - //object must not be Literal as it should be a class - if(statement.getObject().getClass().equals(MemLiteral.class)) - return false; - - boolean handlesAccess = false; - IRI type = connection.getValueFactory().createIRI(""); - String query = "ASK {<" + statement.getObject().stringValue() + "> " + type + " <" + classAsObject + ">}"; - - try { - handlesAccess = connection.prepareBooleanQuery(QueryLanguage.SPARQL, query).evaluate(); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - } catch (RepositoryException e) { - e.printStackTrace(); - } catch (MalformedQueryException e) { - e.printStackTrace(); - } - - return handlesAccess; - } + private Value classAsObject; + private RepositoryConnection connection; + + public PPConditionClassAsObject(Value classAsObject, RepositoryConnection connection) { + this.classAsObject = classAsObject; + this.connection = connection; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + + //object must not be Literal as it should be a class + if (statement.getObject().getClass().equals(MemLiteral.class)) + return false; + + boolean handlesAccess = false; + IRI type = connection.getValueFactory().createIRI(""); + String query = "ASK {<" + statement.getObject().stringValue() + "> " + type + " <" + classAsObject + ">}"; + + try { + handlesAccess = connection.prepareBooleanQuery(QueryLanguage.SPARQL, query).evaluate(); + } catch (QueryEvaluationException | MalformedQueryException | RepositoryException e) { + e.printStackTrace(); + } + + return handlesAccess; + } } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsSubject.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsSubject.java index 21cdd0c..ff75d79 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsSubject.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionClassAsSubject.java @@ -28,14 +28,10 @@ public boolean handlesAccess(IRI webid, Statement statement) { try { handlesAccess = connection.prepareBooleanQuery(QueryLanguage.SPARQL, query).evaluate(); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - } catch (RepositoryException e) { - e.printStackTrace(); - } catch (MalformedQueryException e) { + } catch (QueryEvaluationException | MalformedQueryException | RepositoryException e) { e.printStackTrace(); } - + return handlesAccess; } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionComplex.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionComplex.java index 6cf7d51..44413db 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionComplex.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionComplex.java @@ -5,25 +5,25 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.IRI; -public class PPConditionComplex implements PPCondition{ - List conditions; - - public PPConditionComplex(List conditions) { - this.conditions = conditions; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - boolean handlesAccess = true; - - if(conditions.isEmpty()) - return false; - - for(PPConditionSingle condition : conditions) { - if(handlesAccess) - handlesAccess = condition.handlesAccess(webid, statement); - } - return handlesAccess; - } +public class PPConditionComplex implements PPCondition { + List conditions; + + public PPConditionComplex(List conditions) { + this.conditions = conditions; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + boolean handlesAccess = true; + + if (conditions.isEmpty()) + return false; + + for (PPConditionSingle condition : conditions) { + if (handlesAccess) + handlesAccess = condition.handlesAccess(webid, statement); + } + return handlesAccess; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionFactory.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionFactory.java index 77cea27..c3bc71d 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionFactory.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionFactory.java @@ -2,36 +2,36 @@ import java.util.List; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.repository.RepositoryConnection; +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class PPConditionFactory { - public static PPCondition createCondition(IRI predicate,Value object, RepositoryConnection connection) { + public static PPCondition createCondition(IRI predicate, Value object, RepositoryConnection connection) { - if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasProperty")) { - return new PPConditionHasProperty(object); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#hasLiteral")) { - return new PPConditionHasLiteral(object); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#classAsObject")) { - return new PPConditionClassAsObject(object, connection); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#classAsSubject")) { - return new PPConditionClassAsSubject(object, connection); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#resourceAsObject")) { - return new PPConditionResourceAsObject(object); - } - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#resourceAsSubject")) { - return new PPConditionResourceAsSubject(object); - } - else return null; - } - - public static PPCondition createCondition(List conditions) throws Exception { - return new PPConditionComplex(conditions); - } + switch (predicate.stringValue()) { + case "http://vocab.deri.ie/ppo#hasProperty": + return new PPConditionHasProperty(object); + case "http://vocab.deri.ie/ppo#hasLiteral": + return new PPConditionHasLiteral(object); + case "http://vocab.deri.ie/ppo#classAsObject": + return new PPConditionClassAsObject(object, connection); + case "http://vocab.deri.ie/ppo#classAsSubject": + return new PPConditionClassAsSubject(object, connection); + case "http://vocab.deri.ie/ppo#resourceAsObject": + return new PPConditionResourceAsObject(object); + case "http://vocab.deri.ie/ppo#resourceAsSubject": + return new PPConditionResourceAsSubject(object); + default: + return null; + } + } + + public static PPCondition createCondition(List conditions) { + return new PPConditionComplex(conditions); + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasLiteral.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasLiteral.java index e2d5737..0681443 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasLiteral.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasLiteral.java @@ -5,19 +5,19 @@ import org.eclipse.rdf4j.model.Value; public class PPConditionHasLiteral implements PPConditionSingle { - - private Value hasLiteral; - - public PPConditionHasLiteral(Value hasLiteral) { - this.hasLiteral = hasLiteral; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - if (statement.getObject() != null) - return statement.getObject().equals(hasLiteral); - else - return false; - } + + private Value hasLiteral; + + public PPConditionHasLiteral(Value hasLiteral) { + this.hasLiteral = hasLiteral; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + if (statement.getObject() != null) + return statement.getObject().equals(hasLiteral); + else + return false; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasProperty.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasProperty.java index b0a22b5..0f593a9 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasProperty.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionHasProperty.java @@ -4,20 +4,20 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; -public class PPConditionHasProperty implements PPConditionSingle{ +public class PPConditionHasProperty implements PPConditionSingle { - private Value hasProperty; - - public PPConditionHasProperty(Value hasProperty) { - this.hasProperty = hasProperty; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - if (statement.getPredicate() != null) - return statement.getPredicate().equals(hasProperty); - else - return false; - } + private Value hasProperty; + + public PPConditionHasProperty(Value hasProperty) { + this.hasProperty = hasProperty; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + if (statement.getPredicate() != null) + return statement.getPredicate().equals(hasProperty); + else + return false; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsObject.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsObject.java index be87a6e..c852ac2 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsObject.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsObject.java @@ -8,21 +8,21 @@ public class PPConditionResourceAsObject implements PPConditionSingle { - private Value resourceAsObject; - - public PPConditionResourceAsObject(Value resourceAsObject) { - this.resourceAsObject = resourceAsObject; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - if (statement.getObject() != null) - if(resourceAsObject.stringValue().equals(PPManagerImpl.CUR_USER)) - return statement.getObject().equals(webid); - else - return statement.getObject().equals(resourceAsObject); - else - return false; - } + private Value resourceAsObject; + + public PPConditionResourceAsObject(Value resourceAsObject) { + this.resourceAsObject = resourceAsObject; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + if (statement.getObject() != null) + if (resourceAsObject.stringValue().equals(PPManagerImpl.CUR_USER)) + return statement.getObject().equals(webid); + else + return statement.getObject().equals(resourceAsObject); + else + return false; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsSubject.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsSubject.java index 3907bd1..b3154c4 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsSubject.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionResourceAsSubject.java @@ -8,22 +8,21 @@ public class PPConditionResourceAsSubject implements PPConditionSingle { - private Value resourceAsSubject; - - public PPConditionResourceAsSubject(Value resourceAsSubject) { - this.resourceAsSubject = resourceAsSubject; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - if (statement.getSubject() != null) { - if(resourceAsSubject.stringValue().equals(PPManagerImpl.CUR_USER)) - return statement.getSubject().equals(webid); - else - return statement.getSubject().equals(resourceAsSubject); - } - else - return false; - } + private Value resourceAsSubject; + + public PPConditionResourceAsSubject(Value resourceAsSubject) { + this.resourceAsSubject = resourceAsSubject; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + if (statement.getSubject() != null) { + if (resourceAsSubject.stringValue().equals(PPManagerImpl.CUR_USER)) + return statement.getSubject().equals(webid); + else + return statement.getSubject().equals(resourceAsSubject); + } + return false; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionSingle.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionSingle.java index a76967b..7909ece 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionSingle.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/condition/PPConditionSingle.java @@ -1,5 +1,5 @@ package ru.agentlab.rdf4j.ppo.policies.model.condition; -public interface PPConditionSingle extends PPCondition{ +public interface PPConditionSingle extends PPCondition { } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionContext.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionContext.java index e497ff8..e473a33 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionContext.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionContext.java @@ -5,21 +5,21 @@ public class PPRestrictionContext implements PPRestriction { - private IRI appliesToContext; - - public PPRestrictionContext(IRI appliesToContext) { - this.appliesToContext = appliesToContext; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - IRI context = (IRI)statement.getContext(); - - if(context != null) - return context.equals(appliesToContext); - else - return false; - - } + private IRI appliesToContext; + + public PPRestrictionContext(IRI appliesToContext) { + this.appliesToContext = appliesToContext; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + IRI context = (IRI) statement.getContext(); + + if (context != null) + return context.equals(appliesToContext); + else + return false; + + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionFactory.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionFactory.java index f07c738..771cb21 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionFactory.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionFactory.java @@ -4,21 +4,17 @@ import org.eclipse.rdf4j.model.IRI; public class PPRestrictionFactory { - public static PPRestriction createRestriction(Statement statement) { - - return new PPRestrictionStatement(statement); - } + public static PPRestriction createRestriction(Statement statement) { - public static PPRestriction createRestriction(IRI predicate, IRI object) { - if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#appliesToResource")) { - return new PPRestrictionResource(object); - } - - else if(predicate.stringValue().equals("http://vocab.deri.ie/ppo#appliesToContext")) { - return new PPRestrictionContext(object); - } - - else - return null; - } + return new PPRestrictionStatement(statement); + } + + public static PPRestriction createRestriction(IRI predicate, IRI object) { + if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#appliesToResource")) { + return new PPRestrictionResource(object); + } else if (predicate.stringValue().equals("http://vocab.deri.ie/ppo#appliesToContext")) { + return new PPRestrictionContext(object); + } + return null; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionResource.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionResource.java index 94f1bab..51547dd 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionResource.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionResource.java @@ -3,24 +3,24 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.IRI; -public class PPRestrictionResource implements PPRestriction{ - - private IRI appliesToResource; - - public PPRestrictionResource (IRI appliesToResource) { - this.appliesToResource = appliesToResource; - } - - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - boolean handlesAccess = false; - - if(statement.getSubject() != null) - handlesAccess = statement.getSubject().equals(appliesToResource); - - if(statement.getObject() != null && !handlesAccess) - handlesAccess = statement.getObject().equals(appliesToResource); - - return handlesAccess; - } +public class PPRestrictionResource implements PPRestriction { + + private IRI appliesToResource; + + public PPRestrictionResource(IRI appliesToResource) { + this.appliesToResource = appliesToResource; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + boolean handlesAccess = false; + + if (statement.getSubject() != null) + handlesAccess = statement.getSubject().equals(appliesToResource); + + if (statement.getObject() != null && !handlesAccess) + handlesAccess = statement.getObject().equals(appliesToResource); + + return handlesAccess; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionStatement.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionStatement.java index cea924a..93bd5bb 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionStatement.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/model/restriction/PPRestrictionStatement.java @@ -4,16 +4,16 @@ import org.eclipse.rdf4j.model.IRI; public class PPRestrictionStatement implements PPRestriction { - - private Statement appliesToStatement; - - PPRestrictionStatement (Statement statement) { - appliesToStatement = statement; - } - @Override - public boolean handlesAccess(IRI webid, Statement statement) { - return statement.equals(appliesToStatement); - } + private Statement appliesToStatement; + + PPRestrictionStatement(Statement statement) { + appliesToStatement = statement; + } + + @Override + public boolean handlesAccess(IRI webid, Statement statement) { + return statement.equals(appliesToStatement); + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSail.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSail.java index 5ec4b11..f92c723 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSail.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSail.java @@ -9,8 +9,8 @@ public interface AccessControlSail extends StackableSail { - SailConnection getConnection(IRI webid) throws SailException; + SailConnection getConnection(IRI webid) throws SailException; - public PPManager getPPManager(); + PPManager getPPManager(); } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailImpl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailImpl.java index 58ddd5b..7b8ed2c 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailImpl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailImpl.java @@ -16,83 +16,83 @@ public class AccessControlSailImpl extends AbstractSail implements AccessControlSail { - private Sail base; - private PPManager ppManager; - - public AccessControlSailImpl(Sail parent, Repository repo, PPManager ppManager) { - this.base = parent; - this.ppManager = ppManager; - try { - ppManager.loadPrivacyPreferences(repo); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public PPManager getPPManager() { - return ppManager; - } - - @Override - public SailConnection getConnection() throws SailException { - return base.getConnection(); - } - - @Override - public SailConnection getConnection(IRI webid) throws SailException { - return getConnectionInternal(); - } - - @Override - protected SailConnection getConnectionInternal() throws SailException { - return this.base.getConnection(); - } - - @Override - public File getDataDir() { - return this.base.getDataDir(); - } - - @Override - public ValueFactory getValueFactory() { - return this.base.getValueFactory(); - } - - @Override - public void initialize() throws SailException { - this.base.initialize(); - } - - @Override - public boolean isWritable() throws SailException { - return this.base.isWritable(); - } - - @Override - public void setDataDir(File dataDir) { - this.base.setDataDir(dataDir); - } - - @Override - public void shutDown() throws SailException { - this.base.shutDown(); - } - - - @Override - protected void shutDownInternal() throws SailException { - - } - - @Override - public Sail getBaseSail() { - return base; - } - - @Override - public void setBaseSail(Sail base) { - this.base = base; - - } + private Sail base; + private PPManager ppManager; + + public AccessControlSailImpl(Sail parent, Repository repo, PPManager ppManager) { + this.base = parent; + this.ppManager = ppManager; + try { + ppManager.loadPrivacyPreferences(repo); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public PPManager getPPManager() { + return ppManager; + } + + @Override + public SailConnection getConnection() { + return base.getConnection(); + } + + @Override + public SailConnection getConnection(IRI webid) { + return getConnectionInternal(); + } + + @Override + protected SailConnection getConnectionInternal() { + return this.base.getConnection(); + } + + @Override + public File getDataDir() { + return this.base.getDataDir(); + } + + @Override + public ValueFactory getValueFactory() { + return this.base.getValueFactory(); + } + + @Override + public void initialize() { + this.base.init(); + } + + @Override + public boolean isWritable() { + return this.base.isWritable(); + } + + @Override + public void setDataDir(File dataDir) { + this.base.setDataDir(dataDir); + } + + @Override + public void shutDown() { + this.base.shutDown(); + } + + + @Override + protected void shutDownInternal() { + + } + + @Override + public Sail getBaseSail() { + return base; + } + + @Override + public void setBaseSail(Sail base) { + this.base = base; + + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailRepository.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailRepository.java index d901ba8..8b3c882 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailRepository.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/AccessControlSailRepository.java @@ -9,38 +9,39 @@ public class AccessControlSailRepository extends SailRepository { - private PPManager ppManager; - - public AccessControlSailRepository(AccessControlSail sail) { - super(sail); - ppManager = sail.getPPManager(); - } - - /** - * gets a filtered connection based on the webid - * @param webid an IRI which authenticates the requesting user - * @throws RepositoryException - * @throws SailException - * @return filtered connection based on the webid - */ - public InterceptingRepositoryConnection getConnection(IRI webid) { - - InterceptingRepositoryConnectionWrapper connection = null; - try { - connection = new InterceptingRepositoryConnectionWrapper(this, super.getConnection()); - - try { - connection.begin(); - connection.addRepositoryConnectionInterceptor(new TripleFilterInterceptor(webid, ppManager)); - } finally { - - connection.commit(); - } - - } catch (RepositoryException e) { - e.printStackTrace(); - } - - return connection; - } + private PPManager ppManager; + + public AccessControlSailRepository(AccessControlSail sail) { + super(sail); + ppManager = sail.getPPManager(); + } + + /** + * gets a filtered connection based on the webid + * + * @param webid an IRI which authenticates the requesting user + * @return filtered connection based on the webid + * @throws RepositoryException + * @throws SailException + */ + public InterceptingRepositoryConnection getConnection(IRI webid) { + + InterceptingRepositoryConnectionWrapper connection = null; + try { + connection = new InterceptingRepositoryConnectionWrapper(this, super.getConnection()); + + try { + connection.begin(); + connection.addRepositoryConnectionInterceptor(new TripleFilterInterceptor(webid, ppManager)); + } finally { + + connection.commit(); + } + + } catch (RepositoryException e) { + e.printStackTrace(); + } + + return connection; + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/FakeTripleStore.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/FakeTripleStore.java index 50768dd..b2d7623 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/FakeTripleStore.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/FakeTripleStore.java @@ -45,7 +45,7 @@ public FakeTripleStore(PPManager ppManager, String superUser, String anonymous) this.anonymousIri = unfilteredConnection.getValueFactory().createIRI(anonymous); log.info("Initialize store with {} triples", unfilteredConnection.size() - unfilteredConnection.size(unfilteredConnection.getValueFactory().createIRI(ppManager.getPoliciesContext()))); } catch(RepositoryException e) { - log.error("Error initializy the fake triple store: {}", e.getMessage()); + log.error("Error initialize the fake triple store: {}", e.getMessage()); } } @@ -107,7 +107,7 @@ public void loadData(String file) { public void loadPolicies(String file) { try { loadFile(unfilteredConnection, file, RDFFormat.TURTLE, ppManager.getPoliciesContext()); - log.info("Load {} ploicies triples", unfilteredConnection.size(unfilteredConnection.getValueFactory().createIRI(ppManager.getPoliciesContext()))); + log.info("Load {} policies triples", unfilteredConnection.size(unfilteredConnection.getValueFactory().createIRI(ppManager.getPoliciesContext()))); } catch (Exception e) { log.error("Error reading policies file: {}", e.getMessage()); e.printStackTrace(); diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnection.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnection.java index b234180..c3747bc 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnection.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnection.java @@ -4,18 +4,18 @@ import org.eclipse.rdf4j.repository.RepositoryException; /** - * * @author Franz Brandstätter */ public interface InterceptingRepositoryConnection extends org.eclipse.rdf4j.repository.event.InterceptingRepositoryConnection { - - /** - * add update-support to the connection - * @param reference statement that has to be updated - * @param st statement to replace reference - * @throws RepositoryException - */ - public void update(Statement reference, Statement st) throws RepositoryException; + + /** + * add update-support to the connection + * + * @param reference statement that has to be updated + * @param st statement to replace reference + * @throws RepositoryException + */ + public void update(Statement reference, Statement st) throws RepositoryException; } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnectionWrapper.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnectionWrapper.java index 99ba97d..b03df73 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnectionWrapper.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/InterceptingRepositoryConnectionWrapper.java @@ -47,464 +47,460 @@ * @see InterceptingRepositoryWrapper */ public class InterceptingRepositoryConnectionWrapper extends org.eclipse.rdf4j.repository.base.RepositoryConnectionWrapper - implements InterceptingRepositoryConnection { - - /*-----------* - * Variables * - *-----------*/ - - private boolean activated; - - private Set interceptors = new CopyOnWriteArraySet<>(); - - /*--------------* - * Construcotrs * - *--------------*/ - - public InterceptingRepositoryConnectionWrapper(Repository repository, RepositoryConnection connection) { - super(repository, connection); - } - - /*---------* - * Methods * - *---------*/ - - /** - * Registers a RepositoryConnectionInterceptor that will receive notifications of operations that are - * performed on this connection. - */ - @Override - public void addRepositoryConnectionInterceptor(RepositoryConnectionInterceptor interceptor) { - interceptors.add(interceptor); - activated = true; - } - - /** - * Removes a registered RepositoryConnectionInterceptor from this connection. - */ - @Override - public void removeRepositoryConnectionInterceptor(RepositoryConnectionInterceptor interceptor) { - interceptors.remove(interceptor); - activated = !interceptors.isEmpty(); - } - - @Override - protected boolean isDelegatingAdd() { - return !activated; - } - - @Override - protected boolean isDelegatingRemove() { - return !activated; - } - - @Override - public void addWithoutCommit(Resource subject, IRI predicate, Value object, Resource... contexts) - throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.add(getDelegate(), subject, predicate, object, contexts); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().add(subject, predicate, object, contexts); - } - } - - @Override - public void clear(Resource... contexts) throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.clear(getDelegate(), contexts); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().clear(contexts); - } - } - - @Override - public void begin() throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.begin(getDelegate()); - if (denied) { - break; - } - } - } - if (!denied) { - super.begin(); - } - } - - @Override - public void close() throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.close(getDelegate()); - if (denied) { - break; - } - } - } - if (!denied) { - super.close(); - } - } - - @Override - public void commit() throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.commit(getDelegate()); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().commit(); - } - } - - @Override - public void removeWithoutCommit(Resource subject, IRI predicate, Value object, Resource... contexts) - throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.remove(getDelegate(), subject, predicate, object, contexts); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().remove(subject, predicate, object, contexts); - - } - } - - @Override - public void removeNamespace(String prefix) throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.removeNamespace(getDelegate(), prefix); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().removeNamespace(prefix); - } - } - - @Override - public void clearNamespaces() throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.clearNamespaces(getDelegate()); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().clearNamespaces(); - } - } - - @Override - public void rollback() throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.rollback(getDelegate()); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().rollback(); - } - } - - @Override - @Deprecated - public void setAutoCommit(boolean autoCommit) throws RepositoryException { - boolean denied = false; - boolean wasAutoCommit = isAutoCommit(); - if (activated && wasAutoCommit != autoCommit) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.setAutoCommit(getDelegate(), autoCommit); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().setAutoCommit(autoCommit); - - } - } - - @Override - public void setNamespace(String prefix, String name) throws RepositoryException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.setNamespace(getDelegate(), prefix, name); - if (denied) { - break; - } - } - } - if (!denied) { - getDelegate().setNamespace(prefix, name); - } - } - - @Override - public Update prepareUpdate(final QueryLanguage ql, final String update, final String baseURI) - throws MalformedQueryException, RepositoryException { - if (activated) { - return new Update() { - - private final RepositoryConnection conn = getDelegate(); - - private final Update delegate = conn.prepareUpdate(ql, update, baseURI); - - @Override - public void execute() throws UpdateExecutionException { - boolean denied = false; - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - denied = interceptor.execute(conn, ql, update, baseURI, delegate); - if (denied) { - break; - } - } - } - if (!denied) { - delegate.execute(); - } - } - - @Override - public void setBinding(String name, Value value) { - delegate.setBinding(name, value); - } - - @Override - public void removeBinding(String name) { - delegate.removeBinding(name); - } - - @Override - public void clearBindings() { - delegate.clearBindings(); - } - - @Override - public BindingSet getBindings() { - return delegate.getBindings(); - } - - @Override - public void setDataset(Dataset dataset) { - delegate.setDataset(dataset); - } - - @Override - public Dataset getDataset() { - return delegate.getDataset(); - } - - @Override - public void setIncludeInferred(boolean includeInferred) { - delegate.setIncludeInferred(includeInferred); - } - - @Override - public boolean getIncludeInferred() { - return delegate.getIncludeInferred(); - } - - @Override - public void setMaxExecutionTime(int maxExecTime) { - delegate.setMaxExecutionTime(maxExecTime); - } - - @Override - public int getMaxExecutionTime() { - return delegate.getMaxExecutionTime(); - } - }; - } else { - return getDelegate().prepareUpdate(ql, update, baseURI); - } - } - - /** - * Extensions - */ - - @Override - protected boolean isDelegatingRead() throws RepositoryException { - return !activated; - } - - @Override - public RepositoryResult getStatements(Resource subj, IRI pred, - Value obj, boolean includeInferred, Resource... contexts) - throws RepositoryException { - - RepositoryResult unfilteredStatements = getDelegate().getStatements(subj, pred, obj, includeInferred, contexts); - - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - if (interceptor.getClass().equals(TripleFilterInterceptor.class)) { - TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; - - MemStatementList list = new MemStatementList(); - - try { - while (unfilteredStatements.hasNext()) { - Statement st = unfilteredStatements.next(); - - if (filterInterceptor.verifyReadStatement(st) == true) { - list.add((MemStatement) st); - } - } - } finally { - unfilteredStatements.close(); - } - - MemValueFactory memFactory = new MemValueFactory(); - CloseableIteration iter; - - MemResource[] memContexts; - if (contexts.length == 0) { - memContexts = new MemResource[0]; - } else if (contexts.length == 1 && contexts[0] != null) { - MemResource memContext = memFactory.getMemResource(contexts[0]); - if (memContext == null) { - // non-existent context - iter = new EmptyIteration<>(); - } - - memContexts = new MemResource[] { memContext }; - } else { - Set contextSet = new LinkedHashSet<>(2 * contexts.length); - - for (Resource context : contexts) { - MemResource memContext = memFactory.getMemResource(context); - if (context == null || memContext != null) { - contextSet.add(memContext); - } - } - - if (contextSet.isEmpty()) { - // no known contexts specified - iter = new EmptyIteration<>(); - } - - memContexts = contextSet.toArray(new MemResource[contextSet.size()]); - } - - iter = new MemStatementIterator(list, - memFactory.getMemResource(subj), - memFactory.getMemURI(pred), - memFactory.getMemValue(obj), - !includeInferred, - Integer.MAX_VALUE-1, - memContexts); - - return new RepositoryResult(iter); - } - } - } - - return unfilteredStatements; - } - - @Override - public void remove(Resource subject, IRI predicate, Value object, - Resource... contexts) throws RepositoryException { - - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; - - if(contexts.length > 0) - for(Resource c : contexts){ - Statement st = getValueFactory().createStatement(subject, predicate, object, c); - - if(filterInterceptor.verifyDeleteStatement(st)) - getDelegate().remove(st, contexts); - } - else { - - Statement st = getValueFactory().createStatement(subject, predicate, object); - if(filterInterceptor.verifyDeleteStatement(st)) - getDelegate().remove(st, contexts); - } - } - } - } - - @Override - public void update(Statement reference, Statement st) throws RepositoryException { - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; - - if(filterInterceptor.verifyUpdateStatement(reference, st)) { - getDelegate().remove(reference); - getDelegate().add(st); - } - } - } - } - - @Override - public void add(Resource subject, IRI predicate, Value object, - Resource... contexts) throws RepositoryException { - - if (activated) { - for (RepositoryConnectionInterceptor interceptor : interceptors) { - TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; - - if(contexts.length > 0) - for(Resource c : contexts) { - Statement st = getValueFactory().createStatement(subject, predicate, object, c); - - if(filterInterceptor.verifyCreateStatement(st)) - getDelegate().add(st, contexts); - } - else { - Statement st = getValueFactory().createStatement(subject, predicate, object); - - if(filterInterceptor.verifyCreateStatement(st)) - getDelegate().add(st, contexts); - } - } - } - } + implements InterceptingRepositoryConnection { + + /*-----------* + * Variables * + *-----------*/ + + private boolean activated; + + private Set interceptors = new CopyOnWriteArraySet<>(); + + /*--------------* + * Construcotrs * + *--------------*/ + + public InterceptingRepositoryConnectionWrapper(Repository repository, RepositoryConnection connection) { + super(repository, connection); + } + + /*---------* + * Methods * + *---------*/ + + /** + * Registers a RepositoryConnectionInterceptor that will receive notifications of operations that are + * performed on this connection. + */ + @Override + public void addRepositoryConnectionInterceptor(RepositoryConnectionInterceptor interceptor) { + interceptors.add(interceptor); + activated = true; + } + + /** + * Removes a registered RepositoryConnectionInterceptor from this connection. + */ + @Override + public void removeRepositoryConnectionInterceptor(RepositoryConnectionInterceptor interceptor) { + interceptors.remove(interceptor); + activated = !interceptors.isEmpty(); + } + + @Override + protected boolean isDelegatingAdd() { + return !activated; + } + + @Override + protected boolean isDelegatingRemove() { + return !activated; + } + + @Override + public void addWithoutCommit(Resource subject, IRI predicate, Value object, Resource... contexts) { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.add(getDelegate(), subject, predicate, object, contexts); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().add(subject, predicate, object, contexts); + } + } + + @Override + public void clear(Resource... contexts) { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.clear(getDelegate(), contexts); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().clear(contexts); + } + } + + @Override + public void begin() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.begin(getDelegate()); + if (denied) { + break; + } + } + } + if (!denied) { + super.begin(); + } + } + + @Override + public void close() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.close(getDelegate()); + if (denied) { + break; + } + } + } + if (!denied) { + super.close(); + } + } + + @Override + public void commit() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.commit(getDelegate()); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().commit(); + } + } + + @Override + public void removeWithoutCommit(Resource subject, IRI predicate, Value object, Resource... contexts) { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.remove(getDelegate(), subject, predicate, object, contexts); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().remove(subject, predicate, object, contexts); + + } + } + + @Override + public void removeNamespace(String prefix) { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.removeNamespace(getDelegate(), prefix); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().removeNamespace(prefix); + } + } + + @Override + public void clearNamespaces() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.clearNamespaces(getDelegate()); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().clearNamespaces(); + } + } + + @Override + public void rollback() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.rollback(getDelegate()); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().rollback(); + } + } + + @Override + @Deprecated + public void setAutoCommit(boolean autoCommit) { + boolean denied = false; + boolean wasAutoCommit = isAutoCommit(); + if (activated && wasAutoCommit != autoCommit) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.setAutoCommit(getDelegate(), autoCommit); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().setAutoCommit(autoCommit); + } + } + + @Override + public void setNamespace(String prefix, String name) { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.setNamespace(getDelegate(), prefix, name); + if (denied) { + break; + } + } + } + if (!denied) { + getDelegate().setNamespace(prefix, name); + } + } + + @Override + public Update prepareUpdate(final QueryLanguage ql, final String update, final String baseURI) { + if (activated) { + return new Update() { + + private final RepositoryConnection conn = getDelegate(); + + private final Update delegate = conn.prepareUpdate(ql, update, baseURI); + + @Override + public void execute() { + boolean denied = false; + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + denied = interceptor.execute(conn, ql, update, baseURI, delegate); + if (denied) { + break; + } + } + } + if (!denied) { + delegate.execute(); + } + } + + @Override + public void setBinding(String name, Value value) { + delegate.setBinding(name, value); + } + + @Override + public void removeBinding(String name) { + delegate.removeBinding(name); + } + + @Override + public void clearBindings() { + delegate.clearBindings(); + } + + @Override + public BindingSet getBindings() { + return delegate.getBindings(); + } + + @Override + public void setDataset(Dataset dataset) { + delegate.setDataset(dataset); + } + + @Override + public Dataset getDataset() { + return delegate.getDataset(); + } + + @Override + public void setIncludeInferred(boolean includeInferred) { + delegate.setIncludeInferred(includeInferred); + } + + @Override + public boolean getIncludeInferred() { + return delegate.getIncludeInferred(); + } + + @Override + public void setMaxExecutionTime(int maxExecTime) { + delegate.setMaxExecutionTime(maxExecTime); + } + + @Override + public int getMaxExecutionTime() { + return delegate.getMaxExecutionTime(); + } + }; + } else { + return getDelegate().prepareUpdate(ql, update, baseURI); + } + } + + /** + * Extensions + */ + + @Override + protected boolean isDelegatingRead() { + return !activated; + } + + @Override + public RepositoryResult getStatements(Resource subj, IRI pred, + Value obj, boolean includeInferred, Resource... contexts) + throws RepositoryException { + + RepositoryResult unfilteredStatements = getDelegate().getStatements(subj, pred, obj, includeInferred, contexts); + + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + if (interceptor.getClass().equals(TripleFilterInterceptor.class)) { + TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; + + MemStatementList list = new MemStatementList(); + + try { + while (unfilteredStatements.hasNext()) { + Statement st = unfilteredStatements.next(); + + if (filterInterceptor.verifyReadStatement(st)) { + list.add((MemStatement) st); + } + } + } finally { + unfilteredStatements.close(); + } + + MemValueFactory memFactory = new MemValueFactory(); + CloseableIteration iter; + + MemResource[] memContexts; + if (contexts.length == 0) { + memContexts = new MemResource[0]; + } else if (contexts.length == 1 && contexts[0] != null) { + MemResource memContext = memFactory.getMemResource(contexts[0]); + if (memContext == null) { + // non-existent context + iter = new EmptyIteration<>(); + } + + memContexts = new MemResource[]{memContext}; + } else { + Set contextSet = new LinkedHashSet<>(2 * contexts.length); + + for (Resource context : contexts) { + MemResource memContext = memFactory.getMemResource(context); + if (context == null || memContext != null) { + contextSet.add(memContext); + } + } + + if (contextSet.isEmpty()) { + // no known contexts specified + iter = new EmptyIteration<>(); + } + + memContexts = contextSet.toArray(new MemResource[contextSet.size()]); + } + + iter = new MemStatementIterator<>(list, + memFactory.getMemResource(subj), + memFactory.getMemURI(pred), + memFactory.getMemValue(obj), + !includeInferred, + Integer.MAX_VALUE - 1, + memContexts); + + return new RepositoryResult<>(iter); + } + } + } + + return unfilteredStatements; + } + + @Override + public void remove(Resource subject, IRI predicate, Value object, + Resource... contexts) { + + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; + + if (contexts.length > 0) + for (Resource c : contexts) { + Statement st = getValueFactory().createStatement(subject, predicate, object, c); + + if (filterInterceptor.verifyDeleteStatement(st)) + getDelegate().remove(st, contexts); + } + else { + + Statement st = getValueFactory().createStatement(subject, predicate, object); + if (filterInterceptor.verifyDeleteStatement(st)) + getDelegate().remove(st, contexts); + } + } + } + } + + @Override + public void update(Statement reference, Statement st) { + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; + + if (filterInterceptor.verifyUpdateStatement(reference, st)) { + getDelegate().remove(reference); + getDelegate().add(st); + } + } + } + } + + @Override + public void add(Resource subject, IRI predicate, Value object, + Resource... contexts) { + + if (activated) { + for (RepositoryConnectionInterceptor interceptor : interceptors) { + TripleFilterInterceptor filterInterceptor = (TripleFilterInterceptor) interceptor; + + if (contexts.length > 0) + for (Resource c : contexts) { + Statement st = getValueFactory().createStatement(subject, predicate, object, c); + + if (filterInterceptor.verifyCreateStatement(st)) + getDelegate().add(st, contexts); + } + else { + Statement st = getValueFactory().createStatement(subject, predicate, object); + + if (filterInterceptor.verifyCreateStatement(st)) + getDelegate().add(st, contexts); + } + } + } + } } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleFilterInterceptor.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleFilterInterceptor.java index 7c7866d..2c6d0c9 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleFilterInterceptor.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleFilterInterceptor.java @@ -12,97 +12,102 @@ public class TripleFilterInterceptor extends RepositoryConnectionInterceptorAdapter { - private IRI webid; - private PPManager ppManager; + private IRI webid; + private PPManager ppManager; - public TripleFilterInterceptor(IRI webid, PPManager ppManager) { + public TripleFilterInterceptor(IRI webid, PPManager ppManager) { this.webid = webid; this.ppManager = ppManager; } - /** - * verifies the submitted statement for read-access - * @param st statement to be verified - * @return true if read-access is granted, false otherwise - */ - public boolean verifyReadStatement(Statement st) { - return verifyStatement(st, TripleStoreAction.READ); - } + /** + * verifies the submitted statement for read-access + * + * @param st statement to be verified + * @return true if read-access is granted, false otherwise + */ + public boolean verifyReadStatement(Statement st) { + return verifyStatement(st, TripleStoreAction.READ); + } - /** - * verifies the submitted statement for create-access - * @param st statement to be verified - * @return true if create-access is granted, false otherwise - */ - public boolean verifyCreateStatement(Statement st) { - return verifyStatement(st,TripleStoreAction.CREATE); - } + /** + * verifies the submitted statement for create-access + * + * @param st statement to be verified + * @return true if create-access is granted, false otherwise + */ + public boolean verifyCreateStatement(Statement st) { + return verifyStatement(st, TripleStoreAction.CREATE); + } - /** - * verifies the submitted statement for delete-access - * @param st statement to be verified - * @return true if delete-access is granted, false otherwise - */ - public boolean verifyDeleteStatement(Statement st) { - return verifyStatement(st,TripleStoreAction.DELETE); - } + /** + * verifies the submitted statement for delete-access + * + * @param st statement to be verified + * @return true if delete-access is granted, false otherwise + */ + public boolean verifyDeleteStatement(Statement st) { + return verifyStatement(st, TripleStoreAction.DELETE); + } - /** - * verifies the submitted statement for update-access - * @param st statement to be verified - * @return true if update-access is granted, false otherwise - */ - public boolean verifyUpdateStatement(Statement reference, Statement st) { - boolean refMayUpdate = verifyStatement(reference, TripleStoreAction.UPDATE); + /** + * verifies the submitted statement for update-access + * + * @param st statement to be verified + * @return true if update-access is granted, false otherwise + */ + public boolean verifyUpdateStatement(Statement reference, Statement st) { + boolean refMayUpdate = verifyStatement(reference, TripleStoreAction.UPDATE); - if(refMayUpdate && reference.getSubject().equals(st.getSubject()) && - reference.getPredicate().equals(st.getPredicate())) - if(reference.getContext() == null & st.getContext() == null || reference.getContext().equals(st.getContext())) - return true; - else - return false; - else - return false; - } + if (refMayUpdate && reference.getSubject().equals(st.getSubject()) && + reference.getPredicate().equals(st.getPredicate())) + if (reference.getContext() == null & st.getContext() == null || reference.getContext().equals(st.getContext())) + return true; + else + return false; + else + return false; + } - /** - * verifies the submitted statement for access - * @param st statement to be verified - * @param action action type to be verified - * @return true if access for the action is granted, false otherwise - */ - public boolean verifyStatement(Statement st, TripleStoreAction action) { - List ppList = ppManager.getPrivacyPreferences(); + /** + * verifies the submitted statement for access + * + * @param st statement to be verified + * @param action action type to be verified + * @return true if access for the action is granted, false otherwise + */ + public boolean verifyStatement(Statement st, TripleStoreAction action) { + List ppList = ppManager.getPrivacyPreferences(); - for (PrivacyPreference preference : ppList) { - PPAccessAllowed ppAccess = PPAccessAllowed.NOT_HANDLED; + for (PrivacyPreference preference : ppList) { + PPAccessAllowed ppAccess = PPAccessAllowed.NOT_HANDLED; - switch (action) { - case READ: - ppAccess = preference.allowsRead(webid, st); - break; - case CREATE: - ppAccess = preference.allowsCreate(webid, st); - break; - case DELETE: - ppAccess = preference.allowsDelete(webid, st); - break; - case UPDATE: - ppAccess = preference.allowsUpdate(webid, st); - break; - } + switch (action) { + case READ: + ppAccess = preference.allowsRead(webid, st); + break; + case CREATE: + ppAccess = preference.allowsCreate(webid, st); + break; + case DELETE: + ppAccess = preference.allowsDelete(webid, st); + break; + case UPDATE: + ppAccess = preference.allowsUpdate(webid, st); + break; + } - if(ppAccess != PPAccessAllowed.NOT_HANDLED) { - switch(ppAccess) { - case ALLOWED: - return true; - case DENIED: - return false; - default: - break; - } - } - } - return !ppManager.isWhitelisting(); - } + if (ppAccess != PPAccessAllowed.NOT_HANDLED) { + switch (ppAccess) { + case ALLOWED: + return true; + case DENIED: + return false; + default: + break; + } + } + } + return !ppManager.isWhitelisting(); + } } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStore.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStore.java index 825a6bb..0c7fa34 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStore.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStore.java @@ -4,24 +4,27 @@ import org.eclipse.rdf4j.repository.RepositoryException; public interface TripleStore { - /** - * Filtered connection for current user - * @param webid url for current user - * @return returns connection containing statements for current user - */ - InterceptingRepositoryConnection getConnection(IRI webid); + /** + * Filtered connection for current user + * + * @param webid url for current user + * @return returns connection containing statements for current user + */ + InterceptingRepositoryConnection getConnection(IRI webid); - /** - * Filtered connection for anonymous - * @return returns connection containing statements for anonymous - */ - InterceptingRepositoryConnection getConnection(); + /** + * Filtered connection for anonymous + * + * @return returns connection containing statements for anonymous + */ + InterceptingRepositoryConnection getConnection(); - /** - * Filtered connection for superuser - * @return returns connection containing statements for superuser - */ - InterceptingRepositoryConnection getSuperUserConnection(); + /** + * Filtered connection for superuser + * + * @return returns connection containing statements for superuser + */ + InterceptingRepositoryConnection getSuperUserConnection(); - long size() throws RepositoryException; + long size() throws RepositoryException; } diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStoreAction.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStoreAction.java index 8b00d79..ba7d5d5 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStoreAction.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/triplestore/TripleStoreAction.java @@ -1,12 +1,10 @@ package ru.agentlab.rdf4j.ppo.triplestore; /** - * * @author Franz Brandstätter - * + *

* types of actions the PPs can handle - * */ public enum TripleStoreAction { - READ, CREATE, DELETE, UPDATE; + READ, CREATE, DELETE, UPDATE; } diff --git a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/AbstractUnitTests.java b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/AbstractUnitTests.java new file mode 100644 index 0000000..15da137 --- /dev/null +++ b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/AbstractUnitTests.java @@ -0,0 +1,88 @@ +package ru.agentlab.rdf4j.ppo; + +import org.eclipse.rdf4j.common.iteration.Iterations; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.eclipse.rdf4j.repository.RepositoryException; +import org.eclipse.rdf4j.repository.event.InterceptingRepositoryConnection; +import org.junit.Assert; +import org.junit.Before; +import ru.agentlab.rdf4j.ppo.policies.PPManager; +import ru.agentlab.rdf4j.ppo.policies.PPManagerImpl; +import ru.agentlab.rdf4j.ppo.triplestore.FakeTripleStore; + +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractUnitTests { + + protected PPManager ppManager; + protected FakeTripleStore triplestore; + + protected String policiesContext = "http://cpgu.kbpm.ru/ns/rm/policies"; + protected String superUser = "http://cpgu.kbpm.ru/ns/rm/users#superuser"; + protected String agentUser = "http://cpgu.kbpm.ru/ns/rm/users#exampleAgent"; + protected String anonymous = "http://cpgu.kbpm.ru/ns/rm/users#anonymous"; + protected String member = "http://xmlns.com/foaf/0.1/member"; + + InterceptingRepositoryConnection filteredConnection; + RepositoryConnection unfilteredConnection; + + @Before + public void setup() { + ppManager = new PPManagerImpl(); + ppManager.setPoliciesContext(policiesContext); + + triplestore = new FakeTripleStore(ppManager, superUser, anonymous); + triplestore.loadData("al-rm-vocab.ttl"); + triplestore.loadData("rm-user-types.ttl"); + triplestore.loadData("users.ttl"); + triplestore.loadData("cpgu.ttl"); + triplestore.loadData("sample.ttl"); + triplestore.loadPolicies("access-management.ttl"); + triplestore.init(); + + IRI webid = triplestore.getAnonymousIri(); + filteredConnection = triplestore.getConnection(webid); + + unfilteredConnection = triplestore.getUnfilteredConnection(); + } + + /** + * match unfiltered response with filtered response + */ + protected void shouldHaveReadAccess(IRI webid, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) { + List expected = Iterations.asList(unfilteredConnection.getStatements(subj, pred, obj, includeInferred, contexts)); + List actual = Iterations.asList(getFilteredConnection(webid).getStatements(subj, pred, obj, includeInferred, contexts)); + + if (expected.isEmpty()) + Assert.fail("statement does not exist"); + + Assert.assertEquals(expected, actual); + } + + /** + * match filtered response with empty list + */ + protected void shouldNotHaveReadAccess(IRI webid, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) { + List expected = Iterations.asList(unfilteredConnection.getStatements(subj, pred, obj, includeInferred, contexts)); + List actual = Iterations.asList(getFilteredConnection(webid).getStatements(subj, pred, obj, includeInferred, contexts)); + + if (expected.isEmpty()) + Assert.fail("statement does not exist"); + + Assert.assertEquals("should not return statements", new ArrayList(), actual); + } + + protected RepositoryConnection getFilteredConnection(IRI webid) throws RepositoryException { + return triplestore.getConnection(webid); + } + + protected RepositoryConnection getFilteredConnection(String webid) throws RepositoryException { + return triplestore.getConnection(webid); + } + +} diff --git a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/FilteringTests.java b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/FilteringTests.java index 5a751b1..e2c169f 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/FilteringTests.java +++ b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/FilteringTests.java @@ -1,132 +1,50 @@ package ru.agentlab.rdf4j.ppo; -import static org.eclipse.rdf4j.query.QueryLanguage.SPARQL; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.Update; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.event.InterceptingRepositoryConnection; -import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import ru.agentlab.rdf4j.ppo.policies.PPManager; -import ru.agentlab.rdf4j.ppo.policies.PPManagerImpl; -import ru.agentlab.rdf4j.ppo.triplestore.FakeTripleStore; - -public class FilteringTests { - protected PPManager ppManager; - protected FakeTripleStore triplestore; - - protected String policiesContext = "http://cpgu.kbpm.ru/ns/rm/policies"; - protected String superUser = "http://cpgu.kbpm.ru/ns/rm/users#superuser"; - protected String anonymous = "http://cpgu.kbpm.ru/ns/rm/users#anonymous"; - - InterceptingRepositoryConnection filteredConnection; - RepositoryConnection unfilteredConnection; - - @Before - public void setup() throws IOException { - ppManager = new PPManagerImpl(); - ppManager.setPoliciesContext(policiesContext); - - triplestore = new FakeTripleStore(ppManager, superUser, anonymous); - triplestore.loadData("al-rm-vocab.ttl"); - triplestore.loadData("rm-user-types.ttl"); - triplestore.loadData("users.ttl"); - triplestore.loadData("cpgu.ttl"); - triplestore.loadData("sample.ttl"); - triplestore.loadPolicies("access-management.ttl"); - triplestore.init(); - - IRI webid = triplestore.getAnonymousIri(); - filteredConnection = triplestore.getConnection(webid); - - unfilteredConnection = triplestore.getUnfilteredConnection(); - } - - @Test - public void superUserShouldHaveAccess() { - IRI webid = triplestore.getSuperUserIri();//unfilteredConnection.getValueFactory().createIRI("http://example.org/emma"); - IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); - IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); - Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); - - shouldHaveReadAccess(webid, subj, pred, obj, false); - System.out.println("Huuuu"); - } - - @Test - public void anonumousShouldNotHaveAccess() { - IRI webid = triplestore.getAnonymousIri();//unfilteredConnection.getValueFactory().createIRI("http://example.org/randomUser"); - IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); - IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); - Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); - - shouldNotHaveReadAccess(webid, subj, pred, obj, false); - } - - @Test - public void blackWhitelisting() { - IRI webid = unfilteredConnection.getValueFactory().createIRI("http://example.org/randomUser"); - IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); - IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); - Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); - - shouldNotHaveReadAccess(webid, subj, pred, obj, false); - ppManager.setWhitelisting(false); - shouldHaveReadAccess(webid, subj, pred, obj, false); - ppManager.setWhitelisting(true); - } - - /*@Test - public void superUserShouldHaveUpdateAccess() { - RepositoryConnection conn = getFilteredConnection("http://example.org/randomUser"); - Update update = conn.prepareUpdate(SPARQL, "DELETE DATA { <> <> <> }", "cpgu:///"); - update.execute(); - conn.close(); - }*/ - - /** - * match unfiltered response with filtered response - */ - private void shouldHaveReadAccess(IRI webid, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) { - List expected = Iterations.asList(unfilteredConnection.getStatements(subj, pred, obj, includeInferred, contexts)); - List actual = Iterations.asList(getFilteredConnection(webid).getStatements(subj, pred, obj, includeInferred, contexts)); - - if (expected.isEmpty()) - Assert.fail("statement does not exist"); - - Assert.assertEquals(expected, actual); - } - - /** - * match filtered response with empty list - */ - protected void shouldNotHaveReadAccess(IRI webid, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) { - List expected = Iterations.asList(unfilteredConnection.getStatements(subj, pred, obj, includeInferred, contexts)); - List actual = Iterations.asList(getFilteredConnection(webid).getStatements(subj, pred, obj, includeInferred, contexts)); - - if (expected.isEmpty()) - Assert.fail("statement does not exist"); - - Assert.assertEquals("should not return statements", new ArrayList(), actual); - } - - protected RepositoryConnection getFilteredConnection(IRI webid) throws RepositoryException { - return triplestore.getConnection(webid); - } +public class FilteringTests extends AbstractUnitTests { + + @Test + public void superUserShouldHaveAccess() { + IRI webid = triplestore.getSuperUserIri();//unfilteredConnection.getValueFactory().createIRI("http://example.org/emma"); + IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); + IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); + Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); + + shouldHaveReadAccess(webid, subj, pred, obj, false); + } + + @Test + public void anonymousShouldNotHaveAccess() { + IRI webid = triplestore.getAnonymousIri();//unfilteredConnection.getValueFactory().createIRI("http://example.org/randomUser"); + IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); + IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); + Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); + + shouldNotHaveReadAccess(webid, subj, pred, obj, false); + } + + @Test + public void blackWhitelisting() { + IRI webid = unfilteredConnection.getValueFactory().createIRI("http://example.org/randomUser"); + IRI subj = unfilteredConnection.getValueFactory().createIRI("file:///urn-s2-iisvvt-infosystems-classifier-45950.xml"); + IRI pred = unfilteredConnection.getValueFactory().createIRI("http://purl.org/dc/terms/title"); + Value obj = unfilteredConnection.getValueFactory().createLiteral("ТН ВЭД ТС"); + + shouldNotHaveReadAccess(webid, subj, pred, obj, false); + ppManager.setWhitelisting(false); + shouldHaveReadAccess(webid, subj, pred, obj, false); + ppManager.setWhitelisting(true); + } + +// @Test +// public void superUserShouldHaveUpdateAccess() { +// RepositoryConnection conn = getFilteredConnection("http://example.org/randomUser"); +// Update update = conn.prepareUpdate(SPARQL, "DELETE DATA { <> <> <> }", "cpgu:///"); +// update.execute(); +// conn.close(); +// } - protected RepositoryConnection getFilteredConnection(String webid) throws RepositoryException { - return triplestore.getConnection(webid); - } } \ No newline at end of file diff --git a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java new file mode 100644 index 0000000..3323b86 --- /dev/null +++ b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java @@ -0,0 +1,60 @@ +package ru.agentlab.rdf4j.ppo; + +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.repository.RepositoryResult; +import org.junit.Test; +import ru.agentlab.rdf4j.ppo.policies.PPManagerImpl; + +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +public class RightsEditingTest extends AbstractUnitTests { + + @Test + public void addUserToAdminGroup() { + IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); + IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); + IRI adminGroup = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#adminUsers"); + + PPManagerImpl ppManagerImpl = new PPManagerImpl(); + ppManagerImpl.setUserAdminRights(unfilteredConnection, exampleAgent); + + Statement expected = unfilteredConnection.getValueFactory().createStatement(adminGroup, predicateForRole, exampleAgent); + + RepositoryResult resultSet = unfilteredConnection.getStatements(adminGroup, predicateForRole, null); + assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + } + + @Test + public void addUserToExpertGroupOne() { + IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); + IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); + IRI expertGroupOne = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertGroup1"); + + PPManagerImpl ppManagerImpl = new PPManagerImpl(); + ppManagerImpl.setUserExpertGroupOne(unfilteredConnection, exampleAgent); + + Statement expected = unfilteredConnection.getValueFactory().createStatement(expertGroupOne, predicateForRole, exampleAgent); + + RepositoryResult resultSet = unfilteredConnection.getStatements(expertGroupOne, predicateForRole, null); + assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + } + + @Test + public void addUserToExpertUsersTwo() { + IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); + IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); + IRI expertUsersTwo = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertUsers2"); + + PPManagerImpl ppManagerImpl = new PPManagerImpl(); + ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent); + + Statement expected = unfilteredConnection.getValueFactory().createStatement(expertUsersTwo, predicateForRole, exampleAgent); + + RepositoryResult resultSet = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); + assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + } + +} diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/access-management.ttl b/ru.agentlab.rdf4j.ppo/src/test/resources/access-management.ttl index 33ec256..c09ddd0 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/resources/access-management.ttl +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/access-management.ttl @@ -1,23 +1,20 @@ -@prefix rdf: . -@prefix rdfs: . -@prefix acl: . -@prefix ppo: . +@prefix rdf: . +@prefix rdfs: . +@prefix acl: . +@prefix ppo: . -@prefix ppo: . +@prefix ppo: . @prefix pporoles: . -@prefix users: . -@prefix cpgu: . +@prefix users: . +@prefix cpgu: . @prefix policies: . -cpgu:showVeventLinksAlice a ppo:PrivacyPreference ; - ppo:hasCondition [ - ppo:classAsSubject cpgu:Группировка ; - ] ; - ppo:hasAccessSpace [ - ppo:hasAccessAgent users:doshkalo ; - ] ; - ppo:hasAccess acl:Read . +cpgu:showVeventLinksAlice + a ppo:PrivacyPreference ; + ppo:hasCondition [ ppo:classAsSubject cpgu:Группировка ; ] ; + ppo:hasAccessSpace [ ppo:hasAccessAgent users:doshkalo ; ] ; + ppo:hasAccess acl:Read . # Pure WebAC variant # Alexey Ivanov can read and edit all the classifiers and groupings @@ -47,114 +44,113 @@ cpgu:showVeventLinksAlice a ppo:PrivacyPreference ; # Роль Администратор с политикой полного доступа к данным, которая назначена # двум агентам с определенными логинами + policies:adminRole - a pporoles:PolicyRoleShape ; - dcterms:title "Администратор" ; - dcterms:description "Роль администратора системы"^^xsd:string ; - dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:creator users:amivanoff ; - dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - pporoles:roleAgent users:amivanoff ; - pporoles:roleAgent users:adminUsers ; - pporoles:rolePolicy policies:fullAccessSuperuser . + a pporoles:PolicyRoleShape ; + dcterms:title "Администратор" ; + dcterms:description "Роль администратора системы"^^xsd:string ; + dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:creator users:amivanoff ; + dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + pporoles:roleAgent users:amivanoff ; + pporoles:roleAgent users:adminUsers ; + pporoles:rolePolicy policies:fullAccessSuperuser . # Роль ПереводчикКлассификатора с политиками изменения классификатора # и чтения любых данных, которая назначена двум агентам с логинами + policies:classifierTranslatorRole - a pporoles:PolicyRoleShape ; - dcterms:title "Переводчик классификатора" ; - dcterms:description "Переводчики классификатора"^^xsd:string ; - dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:creator users:amivanoff ; - dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - pporoles:roleAgent users:dimonia ; - pporoles:rolePolicy policies:editClassifierPref ; - pporoles:rolePolicy policies:readAllPref . + a pporoles:PolicyRoleShape ; + dcterms:title "Переводчик классификатора" ; + dcterms:description "Переводчики классификатора"^^xsd:string ; + dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:creator users:amivanoff ; + dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + pporoles:roleAgent users:dimonia ; + pporoles:rolePolicy policies:editClassifierPref ; + pporoles:rolePolicy policies:readAllPref . # Роль Эксперт1, на которую назначены политики изменения классификатора # и чтения любых данных. Роль присвоена группе expertGroup1 + policies:expertRole1 - a pporoles:PolicyRoleShape ; - dcterms:title "Эксперт 1" ; - dcterms:description "Эксперт 1"^^xsd:string ; - dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:creator users:amivanoff ; - dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - pporoles:roleAgent users:expertGroup1 ; - pporoles:rolePolicy policies:editClassifierPref ; - pporoles:rolePolicy policies:readAllPref . + a pporoles:PolicyRoleShape ; + dcterms:title "Эксперт 1" ; + dcterms:description "Эксперт 1"^^xsd:string ; + dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:creator users:amivanoff ; + dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + pporoles:roleAgent users:expertGroup1 ; + pporoles:rolePolicy policies:editClassifierPref ; + pporoles:rolePolicy policies:readAllPref . policies:expertRole2 - a pporoles:PolicyRoleShape ; - dcterms:title "Эксперт 2" ; - dcterms:description "Эксперт 2"^^xsd:string ; - dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - dcterms:creator users:amivanoff ; - dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; - pporoles:roleAgent users:expertUsers2 ; - pporoles:rolePolicy policies:editClassifierPref ; - pporoles:rolePolicy policies:readAllPref . + a pporoles:PolicyRoleShape ; + dcterms:title "Эксперт 2" ; + dcterms:description "Эксперт 2"^^xsd:string ; + dcterms:created "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + dcterms:creator users:amivanoff ; + dcterms:modified "2019-08-09T13:21:08.720Z"^^xsd:dateTime ; + pporoles:roleAgent users:expertUsers2 ; + pporoles:rolePolicy policies:editClassifierPref ; + pporoles:rolePolicy policies:readAllPref . # Агенту с логином superuser разрешены все действия с данными репозитория # (минуя механизм ролей) -policies:fullAccessPref a ppo:PrivacyPreference ; - ppo:hasAccessSpace [ - ppo:hasAccessAgent users:superuser - ] ; - ppo:hasAccess ppo:Delete ; - ppo:hasAccess ppo:Create ; - ppo:hasAccess ppo:Update ; - ppo:hasAccess acl:Read . + +policies:fullAccessPref + a ppo:PrivacyPreference ; + ppo:hasAccessSpace [ ppo:hasAccessAgent users:superuser ] ; + ppo:hasAccess ppo:Delete ; + ppo:hasAccess ppo:Create ; + ppo:hasAccess ppo:Update ; + ppo:hasAccess acl:Read . # Агенту с логином anonymous запрещены все действия с данными репозитория -policies:hideAddDataFromAnon a ppo:PrivacyPreference ; - ppo:hasAccessSpace [ - ppo:hasAccessAgent users:anonymous ; - ] ; - ppo:hasNoAccess ppo:Delete ; - ppo:hasNoAccess ppo:Create ; - ppo:hasNoAccess ppo:Update ; - ppo:hasNoAccess acl:Read . + +policies:hideAddDataFromAnon + a ppo:PrivacyPreference ; + ppo:hasAccessSpace [ ppo:hasAccessAgent users:anonymous ; ] ; + ppo:hasNoAccess ppo:Delete ; + ppo:hasNoAccess ppo:Create ; + ppo:hasNoAccess ppo:Update ; + ppo:hasNoAccess acl:Read . # Агенту с ролью classifierTranslatorRole разрешено изменение и добавление триплов, # в которых субъект -- это объект классов Группировка или Classifier -policies:editClassifierPref a ppo:PrivacyPreference ; - ppo:hasCondition [ - ppo:classAsSubject cpgu:Группировка ; - ppo:classAsSubject cpgu:Classifier ; - ] ; - ppo:hasAccessSpace [ - ppo:hasAccessQuery "ASK { policies:classifierTranslatorRole pporoles:roleAgent ?cur_user }" - ] ; - ppo:hasAccess acl:Write . + +policies:editClassifierPref + a ppo:PrivacyPreference ; + ppo:hasCondition [ ppo:classAsSubject cpgu:Группировка ; + ppo:classAsSubject cpgu:Classifier ; ] ; + ppo:hasAccessSpace [ ppo:hasAccessQuery "ASK { policies:classifierTranslatorRole pporoles:roleAgent ?cur_user }" ] ; + ppo:hasAccess acl:Write . # Агенту с ролью translatorRole разрешено изменение и добавление триплов, # в которых субъект -- это объект классов из перечня -policies:readAllPref a ppo:PrivacyPreference ; - ppo:hasCondition [ - ppo:classAsSubject cpgu:Portal ; - ppo:classAsSubject cpgu:File ; - ppo:classAsSubject cpgu:Orgunit ; - ppo:classAsSubject cpgu:Person ; - ppo:classAsSubject cpgu:Classifier ; - ppo:classAsSubject cpgu:ClassifierElement ; - ppo:classAsSubject cpgu:Группировка ; - ppo:classAsSubject cpgu:Form ; - ppo:classAsSubject cpgu:FormField ; - ppo:classAsSubject cpgu:WebService ; - ppo:classAsSubject cpgu:WebServiceOperation ; - ppo:classAsSubject cpgu:WebServiceInputParameter ; - ppo:classAsSubject cpgu:WebServiceOutputParameter ; - ppo:classAsSubject cpgu:Document ; - ppo:classAsSubject cpgu:Law ; - ppo:classAsSubject cpgu:LawPurpose ; - ] ; - ppo:hasAccessSpace [ - ppo:hasAccessQuery "ASK { policies:translatorRole pporoles:roleAgent ?cur_user }" - ] ; - ppo:hasAccess acl:Read . + +policies:readAllPref + a ppo:PrivacyPreference ; + ppo:hasCondition [ ppo:classAsSubject cpgu:Portal ; + ppo:classAsSubject cpgu:File ; + ppo:classAsSubject cpgu:Orgunit ; + ppo:classAsSubject cpgu:Person ; + ppo:classAsSubject cpgu:Classifier ; + ppo:classAsSubject cpgu:ClassifierElement ; + ppo:classAsSubject cpgu:Группировка ; + ppo:classAsSubject cpgu:Form ; + ppo:classAsSubject cpgu:FormField ; + ppo:classAsSubject cpgu:WebService ; + ppo:classAsSubject cpgu:WebServiceOperation ; + ppo:classAsSubject cpgu:WebServiceInputParameter ; + ppo:classAsSubject cpgu:WebServiceOutputParameter ; + ppo:classAsSubject cpgu:Document ; + ppo:classAsSubject cpgu:Law ; + ppo:classAsSubject cpgu:LawPurpose ; ] ; + ppo:hasAccessSpace [ ppo:hasAccessQuery "ASK { policies:translatorRole pporoles:roleAgent ?cur_user }" ] ; + ppo:hasAccess acl:Read . # Pure WebAC variant # Alexey Ivanov can read and edit all the classifiers and groupings diff --git a/ru.agentlab.rdf4j.ppo/src/test/resources/users.ttl b/ru.agentlab.rdf4j.ppo/src/test/resources/users.ttl index 159ca70..3dc21df 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/resources/users.ttl +++ b/ru.agentlab.rdf4j.ppo/src/test/resources/users.ttl @@ -1,81 +1,98 @@ -@prefix rdf: . -@prefix xsd: . -@prefix dcterms: . -@prefix foaf: . -@prefix schema: . +@prefix rdf: . +@prefix xsd: . +@prefix dcterms: . +@prefix foaf: . +@prefix schema: . @prefix pporoles: . -@prefix users: . +@prefix users: . # in context http://cpgu.kbpm.ru/ns/rm/users# -users:amivanoff a pporoles:User ; - schema:affiliation users:mipt ; - foaf:name "Алексей Иванов" ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:amivanoff + a pporoles:User ; + schema:affiliation users:mipt ; + foaf:name "Алексей Иванов" ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:dimonia a pporoles:User ; - schema:affiliation users:mipt ; - foaf:name "Дмитрий Шишкин" ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:dimonia + a pporoles:User ; + schema:affiliation users:mipt ; + foaf:name "Дмитрий Шишкин" ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:doshkalo a pporoles:User ; - schema:affiliation users:mipt ; - foaf:name "Дмитрий Ошкало" ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:doshkalo + a pporoles:User ; + schema:affiliation users:mipt ; + foaf:name "Дмитрий Ошкало" ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:strenin a pporoles:User ; - schema:affiliation users:mipt ; - foaf:name "Сергей Тренин" ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:strenin + a pporoles:User ; + schema:affiliation users:mipt ; + foaf:name "Сергей Тренин" ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:expertGroup1 a pporoles:UserGroup ; - foaf:name "Эксперты 1" ; - foaf:member users:amivanoff ; - foaf:member users:dimonia ; - foaf:member users:doshkalo ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:exampleAgent + a pporoles:User ; + schema:affiliation users:mipt ; + foaf:name "Агент 1" ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:expertUsers2 a pporoles:UserGroup ; - foaf:name "Эксперты 2" ; - foaf:member users:amivanoff ; - foaf:member users:strenin ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:expertGroup1 + a pporoles:UserGroup ; + foaf:name "Эксперты 1" ; + foaf:member users:amivanoff ; + foaf:member users:dimonia ; + foaf:member users:doshkalo ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:adminUsers a pporoles:UserGroup ; - foaf:name "Администраторы" ; - foaf:member users:amivanoff ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:expertUsers2 + a pporoles:UserGroup ; + foaf:name "Эксперты 2" ; + foaf:member users:amivanoff ; + foaf:member users:strenin ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . -users:mipt a foaf:Organization ; - foaf:name "МФТИ" ; - foaf:homepage ; - foaf:member users:amivanoff ; - foaf:member users:dimonia ; - foaf:member users:doshkalo ; - foaf:member users:strenin ; - dcterms:creator users:amivanoff ; - dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; - dcterms:modifiedBy users:amivanoff ; - dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . +users:adminUsers + a pporoles:UserGroup ; + foaf:name "Администраторы" ; + foaf:member users:amivanoff ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . + +users:mipt + a foaf:Organization ; + foaf:name "МФТИ" ; + foaf:homepage ; + foaf:member users:amivanoff ; + foaf:member users:dimonia ; + foaf:member users:doshkalo ; + foaf:member users:strenin ; + dcterms:creator users:amivanoff ; + dcterms:created "2014-02-10T10:12:16.000Z"^^xsd:dateTime ; + dcterms:modifiedBy users:amivanoff ; + dcterms:modified "2014-02-10T10:12:16.000Z"^^xsd:dateTime . From c3b98040b9497180f895f696ade9a08a92e6ade2 Mon Sep 17 00:00:00 2001 From: Narek Olkinyan <34583166+Enfaseel@users.noreply.github.com> Date: Sun, 3 May 2020 15:53:14 +0300 Subject: [PATCH 4/6] Delete ru.agentlab.rdf4j.ppo.iml --- .../ru.agentlab.rdf4j.ppo.iml | 77 ------------------- 1 file changed, 77 deletions(-) delete mode 100644 ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml diff --git a/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml b/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml deleted file mode 100644 index bdca304..0000000 --- a/ru.agentlab.rdf4j.ppo/ru.agentlab.rdf4j.ppo.iml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From afa31eee79e9ef21948f0e9e149050cc707db499 Mon Sep 17 00:00:00 2001 From: Narek Date: Sun, 3 May 2020 16:09:36 +0300 Subject: [PATCH 5/6] added removing support --- .../rdf4j/ppo/policies/PPManagerImpl.java | 20 +++++--- .../agentlab/rdf4j/ppo/RightsEditingTest.java | 50 +++++++++++-------- 2 files changed, 40 insertions(+), 30 deletions(-) diff --git a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java index dec948e..03748b8 100644 --- a/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java +++ b/ru.agentlab.rdf4j.ppo/src/main/java/ru/agentlab/rdf4j/ppo/policies/PPManagerImpl.java @@ -85,29 +85,33 @@ public void loadPrivacyPreferences(Repository repo) { } } - public void setUserExpertGroupOne(RepositoryConnection connection, IRI webid) { + public void setUserExpertGroupOne(RepositoryConnection connection, IRI webid, boolean presence) { IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertGroup1"); - editUserRole(connection, webid, adminIri); + editUserRole(connection, webid, adminIri, presence); } - public void setUserExpertUsersTwo(RepositoryConnection connection, IRI webid) { + public void setUserExpertUsersTwo(RepositoryConnection connection, IRI webid, boolean presence) { IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertUsers2"); - editUserRole(connection, webid, adminIri); + editUserRole(connection, webid, adminIri, presence); } - public void setUserAdminRights(RepositoryConnection connection, IRI webid) { + public void setUserAdminGroup(RepositoryConnection connection, IRI webid, boolean presence) { IRI adminIri = connection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#adminUsers"); - editUserRole(connection, webid, adminIri); + editUserRole(connection, webid, adminIri, presence); } - private void editUserRole(RepositoryConnection connection, IRI webid, IRI userRole) { + private void editUserRole(RepositoryConnection connection, IRI webid, IRI userRole, boolean presence) { String memberOf = "http://xmlns.com/foaf/0.1/member"; IRI predicateForRole = connection.getValueFactory().createIRI(memberOf); Statement statement = connection.getValueFactory().createStatement( userRole, predicateForRole, webid); - connection.add(statement); + if (presence) { + connection.add(statement); + } else { + connection.remove(statement); + } connection.commit(); } diff --git a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java index 3323b86..206a88c 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java +++ b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java @@ -8,53 +8,59 @@ import java.util.stream.Collectors; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class RightsEditingTest extends AbstractUnitTests { @Test - public void addUserToAdminGroup() { + public void addUserToAdminGroupAndRemoveThen() { IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); IRI adminGroup = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#adminUsers"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); - ppManagerImpl.setUserAdminRights(unfilteredConnection, exampleAgent); - - Statement expected = unfilteredConnection.getValueFactory().createStatement(adminGroup, predicateForRole, exampleAgent); - - RepositoryResult resultSet = unfilteredConnection.getStatements(adminGroup, predicateForRole, null); - assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + ppManagerImpl.setUserAdminGroup(unfilteredConnection, exampleAgent, true); + Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(adminGroup, predicateForRole, exampleAgent); + RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(adminGroup, predicateForRole, null); + assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); + + ppManagerImpl.setUserAdminGroup(unfilteredConnection, exampleAgent, false); + RepositoryResult resultSetAfterRemoving = unfilteredConnection.getStatements(adminGroup, predicateForRole, null); + assertFalse(resultSetAfterRemoving.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); } @Test - public void addUserToExpertGroupOne() { + public void addUserToExpertGroupOneAndRemoveThen() { IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); IRI expertGroupOne = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertGroup1"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); - ppManagerImpl.setUserExpertGroupOne(unfilteredConnection, exampleAgent); - - Statement expected = unfilteredConnection.getValueFactory().createStatement(expertGroupOne, predicateForRole, exampleAgent); - - RepositoryResult resultSet = unfilteredConnection.getStatements(expertGroupOne, predicateForRole, null); - assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + ppManagerImpl.setUserExpertGroupOne(unfilteredConnection, exampleAgent, true); + Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(expertGroupOne, predicateForRole, exampleAgent); + RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(expertGroupOne, predicateForRole, null); + assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); + + ppManagerImpl.setUserExpertGroupOne(unfilteredConnection, exampleAgent, false); + RepositoryResult resultSetAfterRemoving = unfilteredConnection.getStatements(expertGroupOne, predicateForRole, null); + assertFalse(resultSetAfterRemoving.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); } @Test - public void addUserToExpertUsersTwo() { + public void addUserToExpertUsersTwoAndRemoveThen() { IRI exampleAgent = unfilteredConnection.getValueFactory().createIRI(agentUser); IRI predicateForRole = unfilteredConnection.getValueFactory().createIRI(member); IRI expertUsersTwo = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertUsers2"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); - ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent); - - Statement expected = unfilteredConnection.getValueFactory().createStatement(expertUsersTwo, predicateForRole, exampleAgent); - - RepositoryResult resultSet = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); - assertTrue(resultSet.stream().collect(Collectors.toList()).contains(expected)); + ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent, true); + Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(expertUsersTwo, predicateForRole, exampleAgent); + RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); + assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); + + ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent, false); + RepositoryResult resultSetAfterRemoving = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); + assertFalse(resultSetAfterRemoving.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); } - } From df860d28c3f55c4d5f108776ccc8cd8f619681d3 Mon Sep 17 00:00:00 2001 From: Narek Date: Sun, 3 May 2020 16:15:06 +0300 Subject: [PATCH 6/6] added size assert --- .../ru/agentlab/rdf4j/ppo/RightsEditingTest.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java index 206a88c..fb3af46 100644 --- a/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java +++ b/ru.agentlab.rdf4j.ppo/src/test/java/ru/agentlab/rdf4j/ppo/RightsEditingTest.java @@ -8,8 +8,7 @@ import java.util.stream.Collectors; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class RightsEditingTest extends AbstractUnitTests { @@ -20,7 +19,10 @@ public void addUserToAdminGroupAndRemoveThen() { IRI adminGroup = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#adminUsers"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); + long sizeBefore = unfilteredConnection.size(); ppManagerImpl.setUserAdminGroup(unfilteredConnection, exampleAgent, true); + long sizeAfter = unfilteredConnection.size(); + assertEquals(sizeBefore + 1, sizeAfter); Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(adminGroup, predicateForRole, exampleAgent); RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(adminGroup, predicateForRole, null); assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); @@ -37,7 +39,10 @@ public void addUserToExpertGroupOneAndRemoveThen() { IRI expertGroupOne = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertGroup1"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); + long sizeBefore = unfilteredConnection.size(); ppManagerImpl.setUserExpertGroupOne(unfilteredConnection, exampleAgent, true); + long sizeAfter = unfilteredConnection.size(); + assertEquals(sizeBefore + 1, sizeAfter); Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(expertGroupOne, predicateForRole, exampleAgent); RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(expertGroupOne, predicateForRole, null); assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); @@ -54,11 +59,15 @@ public void addUserToExpertUsersTwoAndRemoveThen() { IRI expertUsersTwo = unfilteredConnection.getValueFactory().createIRI("http://cpgu.kbpm.ru/ns/rm/users#expertUsers2"); PPManagerImpl ppManagerImpl = new PPManagerImpl(); + long sizeBefore = unfilteredConnection.size(); ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent, true); + long sizeAfter = unfilteredConnection.size(); + assertEquals(sizeBefore + 1, sizeAfter); Statement expectedAfterAdding = unfilteredConnection.getValueFactory().createStatement(expertUsersTwo, predicateForRole, exampleAgent); RepositoryResult resultSetAfterAdding = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); assertTrue(resultSetAfterAdding.stream().collect(Collectors.toList()).contains(expectedAfterAdding)); + ppManagerImpl.setUserExpertUsersTwo(unfilteredConnection, exampleAgent, false); RepositoryResult resultSetAfterRemoving = unfilteredConnection.getStatements(expertUsersTwo, predicateForRole, null); assertFalse(resultSetAfterRemoving.stream().collect(Collectors.toList()).contains(expectedAfterAdding));