Search in sources :

Example 26 with AtomModelWrapper

use of won.protocol.util.AtomModelWrapper in project webofneeds by researchstudio-sat.

the class ExecuteReplaceCommandAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    if (!(event instanceof ReplaceCommandEvent)) {
        return;
    }
    ReplaceCommandEvent replaceCommandEvent = (ReplaceCommandEvent) event;
    Dataset atomDataset = replaceCommandEvent.getAtomDataset();
    if (atomDataset == null) {
        logger.warn("ReplaceCommandEvent did not contain an atom model, aborting atom creation");
        getEventListenerContext().getEventBus().publish(new ReplaceAbortedEvent(null, replaceCommandEvent, "CreateAtomCommandEvent did not contain an atom model, aborting atom creation"));
        return;
    }
    Resource atomResource = WonRdfUtils.AtomUtils.getAtomResource(atomDataset);
    if (!atomResource.isURIResource()) {
        throw new IllegalArgumentException("atom resource in dataset is not an URI");
    }
    URI atomURI = URI.create(atomResource.getURI());
    RdfUtils.replaceBaseURI(atomDataset, atomResource.getURI(), true);
    RdfUtils.replaceBaseResource(atomDataset, atomResource, true);
    // AtomModelWrapper atomModelWrapper = new AtomModelWrapper(atomDataset);
    // URI wonNodeURI =
    // getEventListenerContext().getWonNodeInformationService().getWonNodeUri(atomURI);
    final URI wonNodeUri = getEventListenerContext().getWonNodeInformationService().getWonNodeUri(atomURI);
    logger.debug("replacing atom content on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(atomDataset), 150));
    RdfUtils.renameResourceWithPrefix(atomDataset, atomResource.getURI(), atomURI.toString());
    WonMessage replaceMessage = createWonMessage(atomURI, wonNodeUri, atomDataset);
    replaceMessage = getEventListenerContext().getWonMessageSender().prepareMessage(replaceMessage);
    EventListener successCallback = event12 -> {
        logger.debug("atom content replacement successful for atom URI {}", atomURI);
        getEventListenerContext().getEventBus().publish(new ReplaceCommandSuccessEvent(atomURI, replaceCommandEvent));
    };
    EventListener failureCallback = event1 -> {
        String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event1).getFailureMessage());
        logger.debug("atom content replacement failed for atom URI {}, original message URI {}: {}", new Object[] { atomURI, ((FailureResponseEvent) event1).getOriginalMessageURI(), textMessage });
        getEventListenerContext().getEventBus().publish(new ReplaceCommandFailureEvent(atomURI, replaceCommandEvent, textMessage));
    };
    EventBotActionUtils.makeAndSubscribeResponseListener(replaceMessage, successCallback, failureCallback, getEventListenerContext());
    logger.debug("registered listeners for response to message URI {}", replaceMessage.getMessageURI());
    getEventListenerContext().getWonMessageSender().sendMessage(replaceMessage);
    logger.debug("atom content replacement message sent with message URI {}", replaceMessage.getMessageURI());
}
Also used : Logger(org.slf4j.Logger) WonMessageBuilderException(won.protocol.exception.WonMessageBuilderException) ReplaceAbortedEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceAbortedEvent) MethodHandles(java.lang.invoke.MethodHandles) LoggerFactory(org.slf4j.LoggerFactory) ReplaceCommandEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandEvent) ReplaceCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandFailureEvent) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) EventBotActionUtils(won.bot.framework.eventbot.action.EventBotActionUtils) ReplaceCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandSuccessEvent) StringUtils(org.apache.commons.lang3.StringUtils) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) WonMessage(won.protocol.message.WonMessage) WonRdfUtils(won.protocol.util.WonRdfUtils) WonMessageBuilder(won.protocol.message.builder.WonMessageBuilder) AtomModelWrapper(won.protocol.util.AtomModelWrapper) Event(won.bot.framework.eventbot.event.Event) RdfUtils(won.protocol.util.RdfUtils) Resource(org.apache.jena.rdf.model.Resource) EventListener(won.bot.framework.eventbot.listener.EventListener) URI(java.net.URI) Dataset(org.apache.jena.query.Dataset) EventListenerContext(won.bot.framework.eventbot.EventListenerContext) Dataset(org.apache.jena.query.Dataset) Resource(org.apache.jena.rdf.model.Resource) ReplaceAbortedEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceAbortedEvent) URI(java.net.URI) ReplaceCommandEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandEvent) ReplaceCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandSuccessEvent) WonMessage(won.protocol.message.WonMessage) ReplaceCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.replace.ReplaceCommandFailureEvent) EventListener(won.bot.framework.eventbot.listener.EventListener) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent)

Example 27 with AtomModelWrapper

use of won.protocol.util.AtomModelWrapper in project webofneeds by researchstudio-sat.

the class AnalyzeBehaviour method getUniqueGoalId.

private static String getUniqueGoalId(Resource goal, Dataset atomDataset) {
    if (goal.getURI() != null) {
        return goal.getURI();
    } else {
        AtomModelWrapper atomWrapper = new AtomModelWrapper(atomDataset);
        Model dataModel = atomWrapper.getDataGraph(goal);
        Model shapesModel = atomWrapper.getShapesGraph(goal);
        String strGraphs = "";
        if (dataModel != null) {
            StringWriter sw = new StringWriter();
            RDFDataMgr.write(sw, dataModel, Lang.NQUADS);
            String content = sw.toString();
            String dataGraphName = atomWrapper.getDataGraphName(goal);
            strGraphs += replaceBlankNode(content, dataGraphName);
        }
        if (shapesModel != null) {
            StringWriter sw = new StringWriter();
            RDFDataMgr.write(sw, shapesModel, Lang.NQUADS);
            String content = sw.toString();
            String shapesGraphName = atomWrapper.getShapesGraphName(goal);
            strGraphs += replaceBlankNode(content, shapesGraphName);
        }
        String[] statements = strGraphs.split("\n");
        Arrays.sort(statements);
        String strStatements = Arrays.toString(statements);
        // java.security.MessageDigest -> SHA256
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(strStatements.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.getEncoder().encode(hash));
        } catch (NoSuchAlgorithmException e) {
            return strStatements;
        }
    }
}
Also used : StringWriter(java.io.StringWriter) Model(org.apache.jena.rdf.model.Model) AtomModelWrapper(won.protocol.util.AtomModelWrapper) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 28 with AtomModelWrapper

use of won.protocol.util.AtomModelWrapper in project webofneeds by researchstudio-sat.

the class AbstractModifyAtomAction method buildWonMessage.

/**
 * Builds a modify message with the given atomURI using the atomDataset as the
 * content wonNodeInformationService and nodeUri will be taken from the
 * eventListenerContext of the Action
 *
 * @param atomURI uri of the atom that should be replaced
 * @param modifiedAtomDataset updated content that should be used instead of the
 * existing one
 * @return modify WonMessage
 */
protected final WonMessage buildWonMessage(URI atomURI, Dataset modifiedAtomDataset) {
    RdfUtils.replaceBaseURI(modifiedAtomDataset, atomURI.toString(), true);
    AtomModelWrapper modifiedAtomModelWrapper = new AtomModelWrapper(modifiedAtomDataset);
    return WonMessageBuilder.replace().atom(atomURI).content().dataset(modifiedAtomModelWrapper.copyDatasetWithoutSysinfo()).build();
}
Also used : AtomModelWrapper(won.protocol.util.AtomModelWrapper)

Example 29 with AtomModelWrapper

use of won.protocol.util.AtomModelWrapper in project webofneeds by researchstudio-sat.

the class GoalInstantiationProducer method findInstantiationForGoals.

/**
 * Create a goal instantiation result from the attempt to instantiate two goals
 * of two atoms using all the atom data, the conversation data and the data and
 * shapes of the two goals. If a model can be found that conforms to the shacl
 * shapes of both atoms this model is chosen to be returned in the
 * GoalInstantiationResult. If no conforming model can be found, the model with
 * the least shacl validation results (validation errors) is used.
 *
 * @param goal1 resource referencing goal from atom1
 * @param goal2 resource referencing goal from atom2
 * @return a goal instantiation result whose input model can either conform to
 * its shacl shapes or not
 */
private GoalInstantiationResult findInstantiationForGoals(Resource goal1, Resource goal2) {
    AtomModelWrapper atomWrapper1 = new AtomModelWrapper(atom1);
    Model shapesModel1 = atomWrapper1.getShapesGraph(goal1);
    Model dataModel1 = atomWrapper1.getDataGraph(goal1);
    AtomModelWrapper atomWrapper2 = new AtomModelWrapper(atom2);
    Model shapesModel2 = atomWrapper2.getShapesGraph(goal2);
    Model dataModel2 = atomWrapper2.getDataGraph(goal2);
    if (shapesModel1 == null || shapesModel2 == null) {
        throw new IllegalArgumentException("shapes model for goal not found");
    }
    // create the combined model with atom content, conversation data and the data
    // of the two goals
    Model combinedModelWithGoalData = ModelFactory.createDefaultModel();
    combinedModelWithGoalData.add(combinedModelWithoutGoals);
    if (dataModel1 != null) {
        combinedModelWithGoalData.add(dataModel1);
    }
    if (dataModel2 != null) {
        combinedModelWithGoalData.add(dataModel2);
    }
    // validate the two goal shapes against the combined data model
    // and extract specific data for each goal using the shacl results
    Model extractedModel1 = GoalUtils.extractGoalData(combinedModelWithGoalData, shapesModel1);
    Model extractedModel2 = GoalUtils.extractGoalData(combinedModelWithGoalData, shapesModel2);
    Model combinedShapesModel = ModelFactory.createDefaultModel();
    combinedShapesModel.add(shapesModel1);
    combinedShapesModel.add(shapesModel2);
    int minValidationResults = Integer.MAX_VALUE;
    GoalInstantiationResult bestGoalInstantiationResult = null;
    // blend the two extracted graphs
    GraphBlendingIterator blendingIterator = new GraphBlendingIterator(extractedModel1, extractedModel2, variableUriPrefix, blendingUriPrefix);
    while (blendingIterator.hasNext()) {
        Model blendedModel = blendingIterator.next();
        // check if the blended model conforms to the combined shacl shapes of both
        // atoms
        Resource report = ValidationUtil.validateModel(blendedModel, combinedShapesModel, false);
        ShaclReportWrapper shaclReportWrapper = new ShaclReportWrapper(report);
        if (shaclReportWrapper.isConform()) {
            // if we found a blended model that is conform to the shacl shapes lets try to
            // condense it
            // as far as possible to get the minimum model that is still conform to the
            // shapes
            Function<Model, Boolean> modelTestingFunction = param -> GoalUtils.validateModelShaclConformity(param, combinedShapesModel);
            Model condensedModel = RdfUtils.condenseModelByIterativeTesting(blendedModel, modelTestingFunction);
            bestGoalInstantiationResult = new GoalInstantiationResult(condensedModel, combinedShapesModel);
        } else {
            // found so far
            if (shaclReportWrapper.getValidationResults().size() < minValidationResults) {
                minValidationResults = shaclReportWrapper.getValidationResults().size();
                bestGoalInstantiationResult = new GoalInstantiationResult(blendedModel, combinedShapesModel);
            }
        }
    }
    return bestGoalInstantiationResult;
}
Also used : AtomGraphType(won.protocol.model.AtomGraphType) Collection(java.util.Collection) UpdateProcessor(org.apache.jena.update.UpdateProcessor) ShaclReportWrapper(won.utils.shacl.ShaclReportWrapper) Function(java.util.function.Function) UpdateExecutionFactory(org.apache.jena.update.UpdateExecutionFactory) Model(org.apache.jena.rdf.model.Model) AtomModelWrapper(won.protocol.util.AtomModelWrapper) UpdateFactory(org.apache.jena.update.UpdateFactory) RdfUtils(won.protocol.util.RdfUtils) DatasetFactory(org.apache.jena.query.DatasetFactory) Resource(org.apache.jena.rdf.model.Resource) ValidationUtil(org.topbraid.shacl.validation.ValidationUtil) ModelFactory(org.apache.jena.rdf.model.ModelFactory) LinkedList(java.util.LinkedList) UpdateRequest(org.apache.jena.update.UpdateRequest) Dataset(org.apache.jena.query.Dataset) Model(org.apache.jena.rdf.model.Model) Resource(org.apache.jena.rdf.model.Resource) AtomModelWrapper(won.protocol.util.AtomModelWrapper) ShaclReportWrapper(won.utils.shacl.ShaclReportWrapper)

Example 30 with AtomModelWrapper

use of won.protocol.util.AtomModelWrapper in project webofneeds by researchstudio-sat.

the class GoalInstantiationProducer method createAllGoalInstantiationResults.

/**
 * create all possible goal instantiations between two atoms. Including the
 * separate goals of each atom as well.
 *
 * @return
 */
public Collection<GoalInstantiationResult> createAllGoalInstantiationResults() {
    AtomModelWrapper atomWrapper1 = new AtomModelWrapper(atom1);
    AtomModelWrapper atomWrapper2 = new AtomModelWrapper(atom2);
    Collection<GoalInstantiationResult> results = new LinkedList<>();
    boolean addedGoal2s = false;
    for (Resource goal1 : atomWrapper1.getGoals()) {
        results.add(findInstantiationForGoal(goal1));
        for (Resource goal2 : atomWrapper2.getGoals()) {
            GoalInstantiationResult instantiationResult = findInstantiationForGoals(goal1, goal2);
            results.add(instantiationResult);
            if (!addedGoal2s) {
                results.add(findInstantiationForGoal(goal2));
            }
        }
        addedGoal2s = true;
    }
    if (!addedGoal2s) {
        for (Resource goal2 : atomWrapper2.getGoals()) {
            results.add(findInstantiationForGoal(goal2));
        }
    }
    return results;
}
Also used : Resource(org.apache.jena.rdf.model.Resource) AtomModelWrapper(won.protocol.util.AtomModelWrapper) LinkedList(java.util.LinkedList)

Aggregations

AtomModelWrapper (won.protocol.util.AtomModelWrapper)37 Dataset (org.apache.jena.query.Dataset)19 Resource (org.apache.jena.rdf.model.Resource)15 URI (java.net.URI)9 Model (org.apache.jena.rdf.model.Model)8 WonMessage (won.protocol.message.WonMessage)6 RdfUtils (won.protocol.util.RdfUtils)6 IOException (java.io.IOException)5 MethodHandles (java.lang.invoke.MethodHandles)5 LinkedList (java.util.LinkedList)5 Test (org.junit.Test)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 GoalInstantiationProducer (won.utils.goals.GoalInstantiationProducer)5 GoalInstantiationResult (won.utils.goals.GoalInstantiationResult)5 DistributedPubSubMediator (akka.cluster.pubsub.DistributedPubSubMediator)4 java.util (java.util)4 Collectors (java.util.stream.Collectors)4 StringUtils (org.apache.commons.lang3.StringUtils)4 ActorRef (akka.actor.ActorRef)3