Search in sources :

Example 6 with WonNodeInfo

use of won.protocol.service.WonNodeInfo in project webofneeds by researchstudio-sat.

the class UriConsistencyCheckingWonMessageProcessor method process.

@Override
public WonMessage process(WonMessage message) {
    StopWatch sw = new StopWatch();
    if (message == null) {
        throw new WonMessageProcessingException("No WonMessage object found in exchange");
    }
    sw.start("validMessageURI");
    if (!WonMessageUtils.isValidMessageUri(message.getMessageURIRequired())) {
        throw new WonMessageNotWellFormedException("Not a valid message URI: " + message.getMessageURI());
    }
    sw.stop();
    sw.start("envelopePropertyCheck");
    EnvelopePropertyCheckResult result = message.checkEnvelopeProperties();
    if (!result.isValid()) {
        throw new WonMessageNotWellFormedException(result.getMessage());
    }
    sw.stop();
    sw.start("getNodeInfo");
    Optional<URI> senderNode = messageRoutingInfoService.senderNode(message);
    Optional<URI> recipientNode = messageRoutingInfoService.recipientNode(message);
    if (!senderNode.isPresent() && !message.getMessageTypeRequired().isHintMessage()) {
        throw new WonMessageProcessingException("Cannot determine sender node for " + message.toShortStringForDebug());
    }
    if (!recipientNode.isPresent()) {
        throw new WonMessageProcessingException("Cannot determine recipient node for " + message.toShortStringForDebug());
    }
    WonNodeInfo senderNodeInfo = null;
    WonNodeInfo recipientNodeInfo = null;
    if (senderNode.isPresent() && !message.getMessageType().isHintMessage()) {
        // do not check the sender node for a hint
        // TODO: change this behaviour as soon as a matcher uses a WoN node
        senderNodeInfo = wonNodeInformationService.getWonNodeInformation(senderNode.get());
    }
    if (recipientNode != null) {
        recipientNodeInfo = wonNodeInformationService.getWonNodeInformation(recipientNode.get());
    }
    if (senderNodeInfo == null && !message.getMessageType().isHintMessage()) {
        throw new WonMessageProcessingException("Could not load sender WonNodeInfo (won node " + senderNode.get() + ")");
    }
    if (recipientNodeInfo == null) {
        throw new WonMessageProcessingException("Could not load recipient WonNodeInfo (won node " + recipientNode.get() + ")");
    }
    sw.stop();
    if (!message.getMessageType().isHintMessage()) {
        sw.start("senderAtomUriCheck");
        checkAtomUri(message.getSenderAtomURI(), senderNodeInfo);
        sw.stop();
        sw.start("senderSocketUriCheck");
        checkSocketUri(message.getSenderSocketURI(), senderNodeInfo);
        sw.stop();
        // there is no way atom or connection uri can be on the recipient node and the
        // recipient node is different from the sender node
        sw.start("atomUriCheck");
        checkAtomUri(message.getAtomURI(), senderNodeInfo);
        sw.stop();
        sw.start("connectionUriCheck");
        checkConnectionUri(message.getConnectionURI(), senderNodeInfo);
        // Check that atom URI for create_atom message corresponds to local pattern
        sw.stop();
        sw.start("createMsgAtomUriCheck");
        checkCreateMsgAtomURI(message, senderNodeInfo);
        sw.stop();
    }
    sw.start("recipientAtomUriCheck");
    checkAtomUri(message.getRecipientAtomURI(), recipientNodeInfo);
    sw.stop();
    sw.start("recipientSocketUriCheck");
    checkSocketUri(message.getRecipientSocketURI(), recipientNodeInfo);
    sw.stop();
    sw.start("signerCheck");
    WonMessageDirection statedDirection = message.getEnvelopeType();
    if (statedDirection.isFromSystem()) {
        if (!Objects.equals(message.getSenderNodeURIRequired(), message.getSignerURIRequired())) {
            RDFDataMgr.write(System.out, message.getCompleteDataset(), Lang.TRIG);
            throw new WonMessageNotWellFormedException("WonMessage " + message.toShortStringForDebug() + " is FROM_SYSTEM but not signed by its node");
        }
    }
    sw.stop();
    if (logger.isDebugEnabled()) {
        logger.debug(LogMarkers.TIMING, "URI Consistency check timing for message {}:\n{}", message.getMessageURIRequired(), sw.prettyPrint());
    }
    return message;
}
Also used : WonMessageProcessingException(won.protocol.exception.WonMessageProcessingException) EnvelopePropertyCheckResult(won.protocol.message.WonMessage.EnvelopePropertyCheckResult) WonNodeInfo(won.protocol.service.WonNodeInfo) WonMessageNotWellFormedException(won.protocol.exception.WonMessageNotWellFormedException) URI(java.net.URI) WonMessageDirection(won.protocol.message.WonMessageDirection) StopWatch(org.springframework.util.StopWatch)

Example 7 with WonNodeInfo

use of won.protocol.service.WonNodeInfo in project webofneeds by researchstudio-sat.

the class WonNodeInformationServiceImpl method getWonNodeInformation.

@Override
public WonNodeInfo getWonNodeInformation(URI wonNodeURI) {
    Objects.requireNonNull(wonNodeURI);
    WonNodeInfo info = getFromCache(wonNodeURI);
    if (info != null) {
        return info;
    }
    Dataset nodeDataset = linkedDataSource.getDataForPublicResource(wonNodeURI);
    info = WonRdfUtils.WonNodeUtils.getWonNodeInfo(wonNodeURI, nodeDataset);
    if (info == null) {
        throw new IllegalStateException("Could not obtain WonNodeInformation for URI " + wonNodeURI);
    }
    wonNodeInfoCache.put(new Element(wonNodeURI, info));
    return info;
}
Also used : Dataset(org.apache.jena.query.Dataset) Element(net.sf.ehcache.Element) WonNodeInfo(won.protocol.service.WonNodeInfo)

Example 8 with WonNodeInfo

use of won.protocol.service.WonNodeInfo in project webofneeds by researchstudio-sat.

the class WonLinkedDataUtils method findWonNode.

public static Optional<WonNodeInfo> findWonNode(URI someURI, Optional<URI> requesterWebID, LinkedDataSource linkedDataSource) {
    assert linkedDataSource != null : "linkedDataSource must not be null";
    int depth = 5;
    int maxRequests = 1000;
    List<Path> propertyPaths = new ArrayList<>();
    PrefixMapping pmap = new PrefixMappingImpl();
    pmap.withDefaultMappings(PrefixMapping.Standard);
    pmap.setNsPrefix("won", WON.getURI());
    pmap.setNsPrefix("msg", WONMSG.getURI());
    pmap.setNsPrefix("rdfs", RDFS.getURI());
    propertyPaths.add(PathParser.parse("^rdfs:member / ^won:messageContainer / ^won:wonNode", pmap));
    propertyPaths.add(PathParser.parse("^won:messageContainer / ^won:wonNode", pmap));
    propertyPaths.add(PathParser.parse("^won:wonNode", pmap));
    propertyPaths.add(PathParser.parse("rdfs:member / ^won:wonNode", pmap));
    Dataset ds = linkedDataSource.getDataForResourceWithPropertyPath(someURI, requesterWebID, propertyPaths, maxRequests, depth);
    WonNodeInfo info = WonRdfUtils.WonNodeUtils.getWonNodeInfo(ds);
    return Optional.ofNullable(info);
}
Also used : Path(org.apache.jena.sparql.path.Path) PrefixMapping(org.apache.jena.shared.PrefixMapping) Dataset(org.apache.jena.query.Dataset) WonNodeInfo(won.protocol.service.WonNodeInfo) PrefixMappingImpl(org.apache.jena.shared.impl.PrefixMappingImpl)

Example 9 with WonNodeInfo

use of won.protocol.service.WonNodeInfo in project webofneeds by researchstudio-sat.

the class WonLinkedDataUtils method getNodeAtomUrisPageAfter.

/**
 * Fetch <code>pageSize</code> atoms with specified restrictions, starting after
 * the specified atom <code>resumeAfter</code>.
 *
 * @param nodeURI
 * @param modifiedAfter
 * @param createdAfter
 * @param atomState
 * @param filterBySocketTypeUri
 * @param filterByAtomTypeUri
 * @param resumeAfter the next link URI as returned by the container. Must start
 * with the node URI.
 * @param pageSize
 * @param linkedDataSource
 * @return
 */
public static LDPContainerPage<List<URI>> getNodeAtomUrisPageAfter(URI nodeURI, ZonedDateTime modifiedAfter, ZonedDateTime createdAfter, AtomState atomState, URI filterBySocketTypeUri, URI filterByAtomTypeUri, URI resumeAfter, int pageSize, LinkedDataSource linkedDataSource) {
    URI atomListUri = null;
    if (resumeAfter == null) {
        Dataset nodeDataset = getDataForPublicResource(nodeURI, linkedDataSource);
        WonNodeInfo wonNodeInfo = WonRdfUtils.WonNodeUtils.getWonNodeInfo(nodeURI, nodeDataset);
        atomListUri = URI.create(wonNodeInfo.getAtomListURI());
    } else {
        if (!resumeAfter.toString().startsWith(nodeURI.toString())) {
            throw new IllegalArgumentException(String.format("URI for resumeAfter is provided as '%s'but it does not start with node URI '%s'", resumeAfter, nodeURI));
        }
        atomListUri = resumeAfter;
    }
    Map<String, String> params = extractQueryParams(atomListUri.getQuery());
    HttpHeaders headers = new HttpHeaders();
    addOptionalQueryParam(params, "state", atomState);
    addOptionalQueryParam(params, "createdafter", createdAfter);
    addOptionalQueryParam(params, "modifiedafter", modifiedAfter);
    addOptionalQueryParam(params, "filterByAtomTypeUri", filterByAtomTypeUri);
    addOptionalQueryParam(params, "filterBySocketTypeUri", filterBySocketTypeUri);
    if (pageSize <= 0) {
        throw new IllegalArgumentException("The pageSize must be a positive integer");
    }
    headers.set("Prefer", String.format("return=representation; max-member-count=\"%d\"", pageSize));
    try {
        atomListUri = new URI(atomListUri.getScheme(), atomListUri.getAuthority(), atomListUri.getPath(), toQueryString(params), atomListUri.getFragment());
    } catch (URISyntaxException e) {
        logger.warn("Could not append parameters to nodeURI, proceeding request without parameters");
    }
    DatasetResponseWithStatusCodeAndHeaders result = getDataForResourceWithHeaders(atomListUri, headers, linkedDataSource);
    List<URI> uris = RdfUtils.visitFlattenedToList(result.getDataset(), model -> {
        StmtIterator it = model.listStatements(null, RDFS.member, (RDFNode) null);
        List<URI> ret = new ArrayList<>();
        while (it.hasNext()) {
            ret.add(URI.create(it.next().getObject().toString()));
        }
        return ret;
    });
    return new LDPContainerPage<List<URI>>(uris, result.getResponseHeaders());
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DatasetResponseWithStatusCodeAndHeaders(won.protocol.rest.DatasetResponseWithStatusCodeAndHeaders) Dataset(org.apache.jena.query.Dataset) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) WonNodeInfo(won.protocol.service.WonNodeInfo)

Example 10 with WonNodeInfo

use of won.protocol.service.WonNodeInfo in project webofneeds by researchstudio-sat.

the class WonNodeSparqlService method retrieveAllWonNodeInfo.

/**
 * Retrieve resource data of all known won nodes that are saved in the Sparql
 * endpoint.
 *
 * @return Set of all known won node resource data
 */
public Set<WonNodeInfo> retrieveAllWonNodeInfo() {
    Set<WonNodeInfo> wonNodeInfos = new HashSet<>();
    String queryString = "SELECT ?graphUri ?nodeUri WHERE { GRAPH ?graphUri {?nodeUri won:uriPrefixSpecification ?c} }";
    ParameterizedSparqlString pps = new ParameterizedSparqlString();
    pps.setCommandText(queryString);
    pps.setNsPrefix("won", "https://w3id.org/won/core#");
    logger.debug("Query SPARQL Endpoint: {}", sparqlEndpoint);
    logger.debug("Execute query: {}", pps.toString());
    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlEndpoint, pps.asQuery())) {
        ResultSet results = qexec.execSelect();
        while (results.hasNext()) {
            QuerySolution qs = results.nextSolution();
            RDFNode rdfNode = qs.get("graphUri");
            if (rdfNode != null) {
                String graphUri = rdfNode.asResource().getURI();
                Dataset ds = retrieveDataset(graphUri);
                WonNodeInfo nodeInfo = getWonNodeInfoFromDataset(ds);
                wonNodeInfos.add(nodeInfo);
            }
        }
        return wonNodeInfos;
    }
}
Also used : WonNodeInfo(won.protocol.service.WonNodeInfo) RDFNode(org.apache.jena.rdf.model.RDFNode) HashSet(java.util.HashSet)

Aggregations

WonNodeInfo (won.protocol.service.WonNodeInfo)11 Dataset (org.apache.jena.query.Dataset)7 URI (java.net.URI)4 DistributedPubSubMediator (akka.cluster.pubsub.DistributedPubSubMediator)2 URISyntaxException (java.net.URISyntaxException)2 HttpHeaders (org.springframework.http.HttpHeaders)2 WonNodeConnection (won.matcher.service.nodemanager.pojo.WonNodeConnection)2 DatasetResponseWithStatusCodeAndHeaders (won.protocol.rest.DatasetResponseWithStatusCodeAndHeaders)2 akka.actor (akka.actor)1 DistributedPubSub (akka.cluster.pubsub.DistributedPubSub)1 Logging (akka.event.Logging)1 LoggingAdapter (akka.event.LoggingAdapter)1 Function (akka.japi.Function)1 java.util (java.util)1 HashSet (java.util.HashSet)1 Collectors (java.util.stream.Collectors)1 Element (net.sf.ehcache.Element)1 IteratorUtils (org.apache.commons.collections.IteratorUtils)1 RDFNode (org.apache.jena.rdf.model.RDFNode)1 PrefixMapping (org.apache.jena.shared.PrefixMapping)1