Search in sources :

Example 1 with WonMessageNotWellFormedException

use of won.protocol.exception.WonMessageNotWellFormedException in project webofneeds by researchstudio-sat.

the class WellformednessCheckingWonMessageProcessor method checkMessage.

public void checkMessage(final WonMessage message) {
    Dataset dataset = message.getCompleteDataset();
    StringBuilder errorMessage = new StringBuilder("Message is not valid, failed at check ");
    boolean valid;
    try {
        dataset.getLock().enterCriticalSection(true);
        valid = validator.validate(dataset, errorMessage);
    } finally {
        dataset.getLock().leaveCriticalSection();
    }
    if (!valid) {
        logger.info(errorMessage.toString() + ". More info on loglevel 'debug'", message.getMessageURI());
        if (logger.isDebugEnabled()) {
            logger.debug("Offending message:\n" + RdfUtils.writeDatasetToString(dataset, Lang.TRIG));
        }
        throw new WonMessageNotWellFormedException(errorMessage.toString());
    }
}
Also used : Dataset(org.apache.jena.query.Dataset) WonMessageNotWellFormedException(won.protocol.exception.WonMessageNotWellFormedException)

Example 2 with WonMessageNotWellFormedException

use of won.protocol.exception.WonMessageNotWellFormedException 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 3 with WonMessageNotWellFormedException

use of won.protocol.exception.WonMessageNotWellFormedException in project webofneeds by researchstudio-sat.

the class WonMessage method findHeadMessage.

private static URI findHeadMessage(Map<URI, WonMessage> messages) {
    if (messages.size() == 1) {
        return messages.keySet().stream().findFirst().get();
    }
    Set<URI> candidates = messages.keySet().stream().collect(Collectors.toSet());
    for (Entry<URI, WonMessage> entry : messages.entrySet()) {
        WonMessage msg = entry.getValue();
        URI msgUri = entry.getKey();
        if (msg.getMessageTypeRequired().isResponseMessage()) {
            URI respondingTo = msg.getRespondingToMessageURIRequired();
            if (candidates.contains(respondingTo)) {
                candidates.remove(msgUri);
            }
        }
        candidates.removeAll(msg.getForwardedMessageURIs());
    }
    if (candidates.size() != 1) {
        throw new WonMessageNotWellFormedException("message dataset must contain one head message");
    }
    return candidates.stream().findFirst().get();
}
Also used : URI(java.net.URI) WonMessageNotWellFormedException(won.protocol.exception.WonMessageNotWellFormedException)

Example 4 with WonMessageNotWellFormedException

use of won.protocol.exception.WonMessageNotWellFormedException in project webofneeds by researchstudio-sat.

the class WonMessageRoutesTest method configureMockEndpoint.

@Before
public void configureMockEndpoint() throws Exception {
    camelContext.setTracing(true);
    ModelCamelContext context = (ModelCamelContext) camelContext;
    AdviceWith.adviceWith(context.getRouteDefinition("activemq:queue:" + FROM_NODE_QUEUENAME), context, new AdviceWithRouteBuilder() {

        @Override
        public void configure() throws Exception {
            replaceFromWith("direct:fromNodeMock");
        }
    });
    AdviceWith.adviceWith(context.getRouteDefinition("activemq:queue:" + FROM_OWNER_QUEUENAME), context, new AdviceWithRouteBuilder() {

        @Override
        public void configure() throws Exception {
            replaceFromWith("direct:fromOwnerMock");
        }
    });
    AdviceWith.adviceWith(context.getRouteDefinition("activemq:queue:" + FROM_MATCHER_QUEUENAME), context, new AdviceWithRouteBuilder() {

        @Override
        public void configure() throws Exception {
            replaceFromWith("direct:fromMatcherMock");
        }
    });
    // for some reason, we have to add the advice to each route
    // don't try to do it by iterating over routes etc. Doesn't work.
    AdviceWith.adviceWith(context.getRouteDefinition("direct:sendToOwner"), context, adviceForOwnerProtocolOut());
    AdviceWith.adviceWith(context.getRouteDefinition("direct:reactToMessage"), context, adviceForMatcherProtocolOut());
    // 
    // MockEndpoint intercepting messages to owners
    toOwnerMockEndpoint.reset();
    toOwnerMockEndpoint.setResultWaitTime(5000);
    toOwnerMockEndpoint.setReporter(exchange -> {
        Optional<String> ownerAppId = WonCamelHelper.getOwnerApplicationId(exchange);
        String ownerAppString = ownerAppId.isPresent() ? " [" + ownerAppId.get() + "]" : "";
        logMessageRdf(makeMessageBox("message NODE => OWNER" + ownerAppString), WonMessage.of(RdfUtils.readDatasetFromString((String) exchange.getIn().getBody(), WonCamelConstants.RDF_LANGUAGE_FOR_MESSAGE)));
    });
    // 
    // MockEndpoint intercepting messages to registered matchers
    // camelContext.addRoutes(new RouteBuilder() {
    // @Override
    // public void configure() throws Exception {
    // from("direct:toMatcherMock").to("mock:seda:MatcherProtocolOut");
    // }
    // });
    toMatcherMockEndpoint.reset();
    toMatcherMockEndpoint.setResultWaitTime(5000);
    toMatcherMockEndpoint.setReporter(exchange -> {
        try {
            Optional<String> ownerAppId = WonCamelHelper.getOwnerApplicationId(exchange);
            Optional<String> wonMessageString = Optional.ofNullable((String) exchange.getIn().getBody());
            if (wonMessageString.isPresent() && wonMessageString.get().trim().length() > 0) {
                logMessageRdf(makeMessageBox("message NODE => MATCHER"), WonMessage.of(RdfUtils.readDatasetFromString(wonMessageString.get(), WonCamelConstants.RDF_LANGUAGE_FOR_MESSAGE)));
            } else {
                logger.debug(makeMessageBox("message NODE => MATCHER (no WonMessage)"));
            }
        } catch (WonMessageNotWellFormedException e) {
            logger.info("swallowed WonMessageNotWellFormedException - this can happen");
        }
    });
    Mockito.when(wonNodeInformationService.generateAtomURI(any(URI.class))).then(x -> newAtomURI());
    Mockito.when(wonNodeInformationService.generateConnectionURI(any(URI.class))).then(invocation -> newConnectionURI((URI) invocation.getArguments()[0]));
    Mockito.when(wonNodeInformationService.generateAtomURI()).then(x -> newAtomURI());
    Mockito.when(wonNodeInformationService.getWonNodeInformation(URI_NODE_1)).then(x -> new WonNodeInfoBuilder().setAtomURIPrefix(URI_NODE_1 + "/atom").setWonNodeURI(URI_NODE_1.toString()).setConnectionURIPrefix(URI_NODE_1 + "/connection").build());
    Mockito.when(uriService.isAtomURI(any(URI.class))).thenReturn(true);
    Mockito.when(uriService.getAtomResourceURIPrefix()).then(x -> URI_NODE_1.toString() + "/atom");
    Mockito.when(uriService.getResourceURIPrefix()).then(x -> URI_NODE_1.toString());
    Mockito.when(uriService.createSysInfoGraphURIForAtomURI(any(URI.class))).thenCallRealMethod();
    // Mockito.when(linkedDataSource.getDataForResource(any(URI.class),
    // any(URI.class)))
    // .thenThrow(new UnsupportedOperationException("cannot do linkeddata lookups
    // during tests"));
    // Mockito.when(linkedDataSource.getDataForResource(any(URI.class)))
    // .thenThrow(new UnsupportedOperationException("cannot do linkeddata lookups
    // during tests"));
    Mockito.when(linkedDataSource.getDataForPublicResource(eq(URI_NODE_1))).then(x -> linkedDataService.getNodeDataset());
    mockForMessageFromNode1ToNode1();
}
Also used : CheapInsecureRandomString(won.protocol.util.CheapInsecureRandomString) WonMessageNotWellFormedException(won.protocol.exception.WonMessageNotWellFormedException) URI(java.net.URI) WonMessageNotWellFormedException(won.protocol.exception.WonMessageNotWellFormedException) IOException(java.io.IOException) ModelCamelContext(org.apache.camel.model.ModelCamelContext) AdviceWithRouteBuilder(org.apache.camel.builder.AdviceWithRouteBuilder) WonNodeInfoBuilder(won.protocol.service.WonNodeInfoBuilder) Before(org.junit.Before)

Aggregations

WonMessageNotWellFormedException (won.protocol.exception.WonMessageNotWellFormedException)4 URI (java.net.URI)3 IOException (java.io.IOException)1 AdviceWithRouteBuilder (org.apache.camel.builder.AdviceWithRouteBuilder)1 ModelCamelContext (org.apache.camel.model.ModelCamelContext)1 Dataset (org.apache.jena.query.Dataset)1 Before (org.junit.Before)1 StopWatch (org.springframework.util.StopWatch)1 WonMessageProcessingException (won.protocol.exception.WonMessageProcessingException)1 EnvelopePropertyCheckResult (won.protocol.message.WonMessage.EnvelopePropertyCheckResult)1 WonMessageDirection (won.protocol.message.WonMessageDirection)1 WonNodeInfo (won.protocol.service.WonNodeInfo)1 WonNodeInfoBuilder (won.protocol.service.WonNodeInfoBuilder)1 CheapInsecureRandomString (won.protocol.util.CheapInsecureRandomString)1