use of org.apache.jena.rdf.model.impl.StatementImpl in project webofneeds by researchstudio-sat.
the class DynamicDatasetToDatasetBySparqlGSPOSelectFunction method apply.
@Override
public Dataset apply(Dataset dataset) {
dataset.begin(ReadWrite.READ);
Dataset result = DatasetFactory.createGeneral();
result.begin(ReadWrite.WRITE);
Query query = QueryFactory.create(sparql);
try (QueryExecution queryExecution = QueryExecutionFactory.create(query, dataset, initialBinding)) {
ResultSet resultSet = queryExecution.execSelect();
RDFNode currentProposal = null;
Model currentProposalContent = ModelFactory.createDefaultModel();
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.next();
RDFNode proposalNode = solution.get("g");
if (currentProposal == null) {
// first solution: remember uri of first proposal
currentProposal = proposalNode;
} else {
// the currentProposal URI and prepare a new empty model for the next proposal
if (!currentProposal.equals(proposalNode)) {
// we have seen all triples of currentProposal
result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
currentProposalContent = ModelFactory.createDefaultModel();
}
currentProposal = proposalNode;
}
// add current triple into currentAgreementModel
RDFNode s = solution.get("s");
RDFNode p = solution.get("p");
RDFNode o = solution.get("o");
Statement newStatement = new StatementImpl(s.asResource(), new PropertyImpl(p.asResource().getURI()), o);
currentProposalContent.add(newStatement);
}
// add the last model
if (currentProposal != null) {
result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
}
return result;
} finally {
dataset.commit();
result.commit();
}
}
use of org.apache.jena.rdf.model.impl.StatementImpl in project webofneeds by researchstudio-sat.
the class AgreementProtocolState method recalculate.
/**
* Calculates all agreements present in the specified conversation dataset.
*/
private void recalculate(Dataset conversationDataset) {
if (logger.isDebugEnabled()) {
logger.debug("starting conversation analysis for high-level protocols");
}
pendingProposals.begin(ReadWrite.WRITE);
agreements.begin(ReadWrite.WRITE);
cancelledAgreements.begin(ReadWrite.WRITE);
rejected.begin(ReadWrite.WRITE);
conversationDataset.begin(ReadWrite.READ);
this.messagesByURI = ConversationMessagesReader.readConversationMessages(conversationDataset);
Set<ConversationMessage> roots = new HashSet();
Collection<ConversationMessage> messages = messagesByURI.values();
// iterate over messages and interconnect them
messages.stream().forEach(message -> {
if (message.getCorrespondingRemoteMessageURI() != null && !message.getCorrespondingRemoteMessageURI().equals(message.getMessageURI())) {
ConversationMessage other = messagesByURI.get(message.getCorrespondingRemoteMessageURI());
throwExceptionIfOtherisMissing(message.getMessageURI(), message.getCorrespondingRemoteMessageURI(), other, "msg:hasCorrespondingRemoteMessage");
message.setCorrespondingRemoteMessageRef(other);
other.setCorrespondingRemoteMessageRef(message);
}
message.getPrevious().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "msg:hasPreviousMessage");
message.addPreviousRef(other);
other.addPreviousInverseRef(message);
});
message.getAccepts().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "agr:accepts");
message.addAcceptsRef(other);
other.addAcceptsInverseRef(message);
});
message.getProposes().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "agr:proposes");
message.addProposesRef(other);
other.addProposesInverseRef(message);
});
message.getRejects().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "agr:rejects");
message.addRejectsRef(other);
other.addRejectsInverseRef(message);
});
message.getProposesToCancel().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "agr:proposesToCancel");
message.addProposesToCancelRef(other);
other.addProposesToCancelInverseRef(message);
});
message.getRetracts().stream().filter(uri -> !uri.equals(message.getMessageURI())).forEach(uri -> {
ConversationMessage other = messagesByURI.get(uri);
throwExceptionIfOtherisMissing(message.getMessageURI(), uri, other, "mod:retracts");
message.addRetractsRef(other);
other.addRetractsInverseRef(message);
});
if (message.getIsResponseTo() != null && !message.getIsResponseTo().equals(message.getMessageURI())) {
ConversationMessage other = messagesByURI.get(message.getIsResponseTo());
throwExceptionIfOtherisMissing(message.getMessageURI(), message.getIsResponseTo(), other, "msg:isResponseTo");
message.setIsResponseToRef(other);
other.setIsResponseToInverseRef(message);
}
if (message.getIsRemoteResponseTo() != null && !message.getIsRemoteResponseTo().equals(message.getMessageURI())) {
ConversationMessage other = messagesByURI.get(message.getIsRemoteResponseTo());
throwExceptionIfOtherisMissing(message.getMessageURI(), message.getIsRemoteResponseTo(), other, "msg:isRemoteResponseTo");
message.setIsRemoteResponseToRef(other);
other.setIsRemoteResponseToInverseRef(message);
}
if (message.getPrevious().isEmpty()) {
roots.add(message);
}
});
// link messages to deliveryChains
deliveryChains = messages.stream().map(m -> {
if (logger.isDebugEnabled()) {
logger.debug("deliveryChain for message {}: {}", m.getMessageURI(), m.getDeliveryChain());
}
return m.getDeliveryChain();
}).collect(Collectors.toSet());
// find interleaved delivery chains
deliveryChains.stream().forEach(dc -> deliveryChains.stream().forEach(dc2 -> {
dc.determineRelationshipWith(dc2);
}));
// apply acknowledgment protocol to whole conversation first:
conversation = acknowledgedSelection(conversationDataset, messages);
// on top of this, apply modification and agreement protocol on a per-message basis, starting with the root(s)
// expect proposals and agreements to be empty
PriorityQueue<ConversationMessage> currentMessages = new PriorityQueue<ConversationMessage>();
currentMessages.addAll(messages);
// TODO: we need to use a priority queue for the messages, which is
// sorted by temporal ordering. Each time we process a message, we
// add the subsequent ones to the queue, the retrieve the
// oldest from the queue for the next iteration.
Set<ConversationMessage> processed = new HashSet<>();
List<ConversationMessage> processedInOrder = null;
if (logger.isDebugEnabled()) {
processedInOrder = new ArrayList<>();
}
ConversationMessage last = null;
while (!currentMessages.isEmpty()) {
ConversationMessage msg = currentMessages.poll();
if (processed.contains(msg)) {
continue;
}
processed.add(msg);
MessageEffectsBuilder effectsBuilder = new MessageEffectsBuilder(msg.getMessageURI());
if (logger.isDebugEnabled() && processedInOrder != null) {
processedInOrder.add(msg);
}
last = msg;
if (!msg.isHeadOfDeliveryChain()) {
continue;
}
if (!msg.isAgreementProtocolMessage()) {
continue;
}
if (msg.isRetractsMessage()) {
removeContentGraphs(conversation, msg);
if (logger.isDebugEnabled()) {
msg.getRetractsRefs().forEach(other -> {
logger.debug("{} retracts {}", msg.getMessageURI(), other.getMessageURI());
});
}
msg.getRetractsRefs().stream().filter(other -> msg != other).filter(other -> other.getSenderNeedURI().equals(msg.getSenderNeedURI())).filter(other -> other.isHeadOfDeliveryChain()).filter(other -> msg.isMessageOnPathToRoot(other)).forEach(other -> {
if (logger.isDebugEnabled()) {
logger.debug("{} retracts {}: valid", msg.getMessageURI(), other.getMessageURI());
}
boolean changedSomething = false;
changedSomething = removeContentGraphs(conversation, other) || changedSomething;
retractedUris.add(other.getMessageURI());
if (other.isProposesMessage()) {
changedSomething = retractProposal(other.getMessageURI()) || changedSomething;
}
if (changedSomething) {
effectsBuilder.retracts(other.getMessageURI());
}
});
}
if (msg.isRejectsMessage()) {
removeContentGraphs(conversation, msg);
if (logger.isDebugEnabled()) {
msg.getRejectsRefs().forEach(other -> {
logger.debug("{} rejects {}", msg.getMessageURI(), other.getMessageURI());
});
}
msg.getRejectsRefs().stream().filter(other -> msg != other).filter(other -> other.isProposesMessage()).filter(other -> other.isHeadOfDeliveryChain()).filter(other -> !other.getSenderNeedURI().equals(msg.getSenderNeedURI())).filter(other -> msg.isMessageOnPathToRoot(other)).filter(other -> {
// Resolution: neither statement has any effect.
return !msg.accepts(other);
}).forEach(other -> {
if (logger.isDebugEnabled()) {
logger.debug("{} rejects {}: valid", msg.getMessageURI(), other.getMessageURI());
}
boolean changedSomething = rejectProposal(other.getMessageURI());
if (changedSomething) {
effectsBuilder.rejects(other.getMessageURI());
}
});
}
if (msg.isProposesMessage()) {
if (logger.isDebugEnabled()) {
msg.getProposesRefs().forEach(other -> {
logger.debug("{} proposes {}", msg.getMessageURI(), other.getMessageURI());
});
}
Model proposalContent = ModelFactory.createDefaultModel();
msg.getProposesRefs().stream().filter(other -> msg != other).filter(other -> other.isHeadOfDeliveryChain()).filter(other -> msg.isMessageOnPathToRoot(other)).forEach(other -> {
if (logger.isDebugEnabled()) {
logger.debug("{} proposes {}: valid", msg.getMessageURI(), other.getMessageURI());
}
boolean changedSomething = propose(conversationDataset, other.getContentGraphs(), proposalContent);
if (changedSomething) {
effectsBuilder.proposes(other.getMessageURI());
}
});
pendingProposals.addNamedModel(msg.getMessageURI().toString(), proposalContent);
}
if (msg.isAcceptsMessage()) {
if (logger.isDebugEnabled()) {
msg.getAcceptsRefs().forEach(other -> {
logger.debug("{} accepts {}", msg.getMessageURI(), other.getMessageURI());
});
}
msg.getAcceptsRefs().stream().filter(other -> msg != other).filter(other -> other.isHeadOfDeliveryChain()).filter(other -> !other.getSenderNeedURI().equals(msg.getSenderNeedURI())).filter(other -> msg.isMessageOnPathToRoot(other)).filter(other -> {
// Resolution: neither statement has any effect.
return !msg.rejects(other);
}).forEach(other -> {
if (logger.isDebugEnabled()) {
logger.debug("{} accepts {}: valid", msg.getMessageURI(), other.getMessageURI());
}
boolean changedSomething = acceptProposal(other.getMessageURI());
if (changedSomething) {
effectsBuilder.accepts(other.getMessageURI(), other.getProposesToCancel().stream().collect(Collectors.toSet()));
}
});
}
if (msg.isProposesToCancelMessage()) {
if (logger.isDebugEnabled()) {
msg.getProposesToCancelRefs().forEach(other -> {
logger.debug("{} proposesToCancel {}", msg.getMessageURI(), other.getMessageURI());
});
}
final Model cancellationProposals = pendingProposals.getDefaultModel();
msg.getProposesToCancelRefs().stream().filter(other -> msg != other).filter(other -> other.isHeadOfDeliveryChain()).filter(toCancel -> msg.isMessageOnPathToRoot(toCancel)).forEach(other -> {
if (logger.isDebugEnabled()) {
logger.debug("{} proposesToCancel {}: valid", msg.getMessageURI(), other.getMessageURI());
}
cancellationProposals.add(new StatementImpl(cancellationProposals.getResource(msg.getMessageURI().toString()), WONAGR.PROPOSES_TO_CANCEL, cancellationProposals.getResource(other.getMessageURI().toString())));
pendingProposals.setDefaultModel(cancellationProposals);
effectsBuilder.proposesToCancel(other.getMessageURI());
});
}
msg.setEffects(effectsBuilder.build());
}
if (logger.isDebugEnabled()) {
logger.debug("messages in the order they were processed:");
if (processedInOrder != null) {
processedInOrder.stream().forEach(x -> logger.debug(x.toString()));
}
logger.debug("finished conversation analysis for high-level protocols");
}
pendingProposals.commit();
agreements.commit();
cancelledAgreements.commit();
rejected.commit();
conversationDataset.end();
}
use of org.apache.jena.rdf.model.impl.StatementImpl in project webofneeds by researchstudio-sat.
the class NeedModelWrapper method recursiveCopy.
private RDFNode recursiveCopy(RDFNode node, ModelModification modelModification, RDFNode toReplace, RDFNode replacement, Collection<RDFNode> visited) {
if (node.equals(toReplace))
return replacement;
if (!node.isResource())
return node;
if (visited.contains(node))
return copyNode(node.asResource());
visited.add(node);
RDFNode nodeInCopy;
if (isSplittableNode(node)) {
nodeInCopy = copyNode(node.asResource());
visited.add(nodeInCopy);
} else {
return node;
}
if (toReplace == null && replacement == null) {
toReplace = node;
replacement = nodeInCopy;
}
List<Statement> outgoingEdges = node.getModel().listStatements(node.asResource(), null, (RDFNode) null).toList();
for (Statement stmt : outgoingEdges) {
RDFNode newObject = recursiveCopy(stmt.getObject(), modelModification, toReplace, replacement, visited);
modelModification.add(new StatementImpl(nodeInCopy.asResource(), stmt.getPredicate(), newObject));
modelModification.remove(stmt);
// RDFDataMgr.write(System.out, modelModification.copyAndModify(node.getModel()), Lang.TRIG);
}
return nodeInCopy;
}
use of org.apache.jena.rdf.model.impl.StatementImpl in project webofneeds by researchstudio-sat.
the class DatasetToDatasetBySparqlGSPOSelectFunction method apply.
@Override
public Dataset apply(Dataset dataset) {
dataset.begin(ReadWrite.READ);
Dataset result = DatasetFactory.createGeneral();
result.begin(ReadWrite.WRITE);
Query query = QueryFactory.create(sparql);
try (QueryExecution queryExecution = QueryExecutionFactory.create(query, dataset)) {
ResultSet resultSet = queryExecution.execSelect();
RDFNode currentProposal = null;
Model currentProposalContent = ModelFactory.createDefaultModel();
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.next();
RDFNode proposalNode = solution.get("g");
if (currentProposal == null) {
// first solution: remember uri of first proposal
currentProposal = proposalNode;
} else {
// the currentProposal URI and prepare a new empty model for the next proposal
if (!currentProposal.equals(proposalNode)) {
// we have seen all triples of currentProposal
result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
currentProposalContent = ModelFactory.createDefaultModel();
}
currentProposal = proposalNode;
}
// add current triple into currentAgreementModel
RDFNode s = solution.get("s");
RDFNode p = solution.get("p");
RDFNode o = solution.get("o");
Statement newStatement = new StatementImpl(s.asResource(), new PropertyImpl(p.asResource().getURI()), o);
currentProposalContent.add(newStatement);
}
// add the last model
if (currentProposal != null) {
result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
}
return result;
} finally {
dataset.commit();
result.commit();
}
}
Aggregations