Search in sources :

Example 11 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class WonMessageIntoCamelProcessor method process.

@Override
public void process(final Exchange exchange) throws Exception {
    logger.debug("processing won message");
    Map headers = exchange.getIn().getHeaders();
    // if the wonMessage header is there, don't change it - that way we can re-route internal messages
    WonMessage wonMessage = (WonMessage) headers.get(WonCamelConstants.MESSAGE_HEADER);
    if (wonMessage == null) {
        try {
            wonMessage = WonMessageDecoder.decode(Lang.TRIG, exchange.getIn().getBody().toString());
        } catch (Exception e) {
            // stop the exchange in this case - maybe at some point we can return a failure response but
            // currently, we would have to look into the message for doing that, and looking into
            // the message is not possible if we cannot decode it.
            logger.info("could not decode message as TriG, ignoring it (the offending message is logged at loglevel 'DEBUG')", e);
            if (logger.isDebugEnabled()) {
                logger.debug("offending message: {}", exchange.getIn().getBody().toString());
            }
            exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
            throw new WonMessageProcessingException("Could not decode message", e);
        }
    }
    if (wonMessage == null) {
        throw new WonMessageProcessingException("No WonMessage found in header '" + WonCamelConstants.MESSAGE_HEADER + "' or in the body");
    }
    exchange.getIn().setHeader(WonCamelConstants.MESSAGE_TYPE_HEADER, URI.create(wonMessage.getMessageType().getResource().getURI()));
    exchange.getIn().setHeader(WonCamelConstants.MESSAGE_HEADER, wonMessage);
    exchange.getIn().setBody(null);
}
Also used : WonMessageProcessingException(won.protocol.message.processor.exception.WonMessageProcessingException) WonMessage(won.protocol.message.WonMessage) Map(java.util.Map) WonMessageProcessingException(won.protocol.message.processor.exception.WonMessageProcessingException)

Example 12 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class WonMessageSignerVerifierTest method signAndVerifySignedMessageNode.

@Test
public void signAndVerifySignedMessageNode() throws Exception {
    // create signed dataset
    Dataset testDataset = TestSigningUtils.prepareTestDataset(RESOURCE_NODE_FILE_NOSIG);
    WonMessage testMsg = new WonMessage(testDataset);
    // sign
    testMsg = WonMessageSignerVerifier.sign(nodeKey, pubKeysMap.get(TestSigningUtils.nodeCertUri), TestSigningUtils.nodeCertUri, testMsg);
    // pretend msg was serialized and deserialized in between
    // pretend it was serialized and deserialized
    String datasetString = RdfUtils.writeDatasetToString(testMsg.getCompleteDataset(), Lang.TRIG);
    testMsg = new WonMessage(RdfUtils.readDatasetFromString(datasetString, Lang.TRIG));
    // verify
    SignatureVerificationState result = WonMessageSignerVerifier.verify(pubKeysMap, testMsg);
    Assert.assertTrue(result.getMessage(), result.isVerificationPassed());
    Assert.assertEquals(3, result.getSignatureGraphNames().size());
    Assert.assertEquals(NEED_CORE_DATA_URI, result.getSignedGraphName(NEED_CORE_DATA_SIG_URI));
    Assert.assertEquals(EVENT_ENV1_URI, result.getSignedGraphName(EVENT_ENV1_SIG_URI));
    Assert.assertEquals(EVENT_ENV2_URI, result.getSignedGraphName(EVENT_ENV2_SIG_URI));
    // write for debugging
    TestSigningUtils.writeToTempFile(testMsg.getCompleteDataset());
}
Also used : Dataset(org.apache.jena.query.Dataset) WonMessage(won.protocol.message.WonMessage) SignatureVerificationState(won.cryptography.rdfsign.SignatureVerificationState) Test(org.junit.Test)

Example 13 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class SignatureAddingWonMessageProcessor method processWithKey.

private WonMessage processWithKey(final WonMessage wonMessage, final String privateKeyUri, final PrivateKey privateKey, final PublicKey publicKey) throws Exception {
    WonMessage signed = WonMessageSignerVerifier.sign(privateKey, publicKey, privateKeyUri, wonMessage);
    logger.debug("SIGNED with key " + privateKeyUri + ":\n" + WonMessageEncoder.encode(signed, Lang.TRIG));
    return signed;
}
Also used : WonMessage(won.protocol.message.WonMessage)

Example 14 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class FacetTypeSlipComputer method evaluate.

@Override
public <T> T evaluate(final Exchange exchange, final Class<T> type) {
    WonMessage message = (WonMessage) exchange.getIn().getHeader(WonCamelConstants.MESSAGE_HEADER);
    assert message != null : "wonMessage header must not be null";
    String slip = "";
    // exchange.getIn().setHeader();
    URI messageType = (URI) exchange.getIn().getHeader(WonCamelConstants.MESSAGE_TYPE_HEADER);
    assert messageType != null : "messageType header must not be null";
    URI direction = (URI) exchange.getIn().getHeader(WonCamelConstants.DIRECTION_HEADER);
    assert direction != null : "direction header must not be null";
    URI facetType = (URI) exchange.getIn().getHeader(WonCamelConstants.FACET_TYPE_HEADER);
    // for ordinary messages, the process method is called
    // for responses, the on[Failure|Success]Response is called.
    String method = "process";
    if (WonMessageDirection.FROM_EXTERNAL.isIdentifiedBy(direction)) {
        // we are now handling the response to
        if (WonMessageType.SUCCESS_RESPONSE.isIdentifiedBy(messageType)) {
            method = "onSuccessResponse";
            direction = URI.create(WonMessageDirection.FROM_OWNER.getResource().toString());
            WonMessageType origType = message.getIsResponseToMessageType();
            if (origType == null) {
                throw new MissingMessagePropertyException(URI.create(WONMSG.IS_RESPONSE_TO_MESSAGE_TYPE.getURI().toString()));
            }
            messageType = origType.getURI();
        } else if (WonMessageType.FAILURE_RESPONSE.isIdentifiedBy(messageType)) {
            WonMessageType isResponseToType = message.getIsResponseToMessageType();
            if (WonMessageType.FAILURE_RESPONSE == isResponseToType || WonMessageType.SUCCESS_RESPONSE == isResponseToType) {
                // will specially process this.
                return null;
            }
            method = "onFailureResponse";
            direction = URI.create(WonMessageDirection.FROM_OWNER.getResource().toString());
            WonMessageType origType = message.getIsResponseToMessageType();
            if (origType == null) {
                throw new MissingMessagePropertyException(URI.create(WONMSG.IS_RESPONSE_TO_MESSAGE_TYPE.getURI().toString()));
            }
            messageType = origType.getURI();
        }
    }
    try {
        slip = "bean:" + computeFacetSlip(messageType, facetType, direction) + "?method=" + method;
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return type.cast(slip);
}
Also used : MissingMessagePropertyException(won.protocol.message.processor.exception.MissingMessagePropertyException) WonMessage(won.protocol.message.WonMessage) WonMessageType(won.protocol.message.WonMessageType) URI(java.net.URI) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 15 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class FailResponder method process.

@Override
public void process(final Exchange exchange) throws Exception {
    Exception exception = null;
    WonMessage originalMessage = null;
    try {
        originalMessage = (WonMessage) exchange.getIn().getHeader(WonCamelConstants.ORIGINAL_MESSAGE_HEADER);
        if (originalMessage == null) {
            logger.debug("Processing an exception. camel header {} was null, assuming original message in header {}", WonCamelConstants.ORIGINAL_MESSAGE_HEADER, WonCamelConstants.MESSAGE_HEADER);
            originalMessage = (WonMessage) exchange.getIn().getHeader(WonCamelConstants.MESSAGE_HEADER);
        }
        if (originalMessage == null) {
            // we didn't find the original message, so we can't send a response.
            // Log all we can so that we can start debugging the problem
            logger.warn("Could not obtain original message from camel headers {} or {} for error {}", new Object[] { WonCamelConstants.ORIGINAL_MESSAGE_HEADER, WonCamelConstants.MESSAGE_HEADER, exchange.getProperty(Exchange.EXCEPTION_CAUGHT) });
            logger.warn("original exception:", exchange.getProperty(Exchange.EXCEPTION_CAUGHT));
            return;
        }
        exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
        String errormessage = null;
        if (exception != null) {
            errormessage = exception.getClass().getSimpleName() + ": " + exception.getMessage();
        } else {
            errormessage = String.format("An error occurred while processing message %s", originalMessage.getMessageURI());
        }
        if (originalMessage.getMessageType() == WonMessageType.HINT_MESSAGE) {
            // we don't want to send a FailureResponse for a hint message as matchers
            // are not fully compatible messaging agents (needs), so sending this message will fail.
            logger.debug("suppressing failure response for HINT message", exception);
            return;
        }
        logger.info("Caught error while processing WON message {} (type:{}) : {} - sending FailureResponse (more info on log level DEBUG)", new Object[] { originalMessage.getMessageURI(), originalMessage.getMessageType(), errormessage });
        if (exception != null) {
            logger.debug("stacktrace of caught exception:", exception);
        }
        logger.debug("original message: {}", RdfUtils.toString(originalMessage.getCompleteDataset()));
        if (WonMessageType.FAILURE_RESPONSE == originalMessage.getMessageType() && WonMessageType.FAILURE_RESPONSE == originalMessage.getIsResponseToMessageType()) {
            // do not throw failures back and forth. If the original message is already a failure message
            // that indicates a problem processing a failure message, log this and stop.
            logger.info("Encountered an error processing a FailureResponse for a FailureResponse. The FailureResponse is " + "logged at log level DEBUG. Its message URI is {}", originalMessage.getMessageURI(), exception);
            StringWriter sw = new StringWriter();
            RDFDataMgr.write(sw, originalMessage.getCompleteDataset(), Lang.TRIG);
            logger.warn("FailureResponse to FailureResponse that raised the error:\n{}", sw.toString());
            return;
        }
        URI newMessageURI = this.wonNodeInformationService.generateEventURI();
        logger.debug("Sending FailureResponse {}", newMessageURI);
        Model errorMessageContent = WonRdfUtils.MessageUtils.textMessage(errormessage);
        RdfUtils.replaceBaseURI(errorMessageContent, newMessageURI.toString());
        WonMessage responseMessage = WonMessageBuilder.setPropertiesForNodeResponse(originalMessage, false, newMessageURI).addContent(errorMessageContent).build();
        if (WonMessageDirection.FROM_OWNER == originalMessage.getEnvelopeType()) {
            String ownerApplicationId = (String) exchange.getIn().getHeader(WonCamelConstants.OWNER_APPLICATION_ID);
            sendSystemMessageToOwner(responseMessage, ownerApplicationId);
        } else if (WonMessageDirection.FROM_EXTERNAL == originalMessage.getEnvelopeType()) {
            sendSystemMessage(responseMessage);
        } else {
            logger.info(String.format("cannot route failure message for direction of original message, " + "expected FROM_OWNER or FROM_EXTERNAL, but found %s. Original cause is logged on log level DEBUG.", originalMessage.getEnvelopeType()));
            logger.debug("original cause", exception);
        }
    } catch (Throwable t) {
        // something went wrong - we can't inform the sender of the message.
        // now:
        // 1. log the error we had here
        // 2. log the original error, otherwise it is swallowed completely
        logger.warn("Error in failure response handling!");
        URI originalMessageURI = null;
        try {
            originalMessageURI = originalMessage == null ? null : originalMessage.getMessageURI();
        } catch (Exception e) {
            logger.error("Error getting message URI from WonMessage");
        }
        if (exception != null && exception.getClass() != null) {
            logger.warn(String.format("Could not send FailureResponse for original Exception %s (message: %s) that occurred while processing message %s.", exception.getClass().getSimpleName(), exception.getMessage(), originalMessageURI), t);
            logger.warn("original error: ", exception);
        } else {
            logger.warn(String.format("Could not send FailureResponse to original message %s.", originalMessageURI), t);
            logger.warn("original error: ", exception);
        }
    }
}
Also used : StringWriter(java.io.StringWriter) WonMessage(won.protocol.message.WonMessage) Model(org.apache.jena.rdf.model.Model) URI(java.net.URI)

Aggregations

WonMessage (won.protocol.message.WonMessage)89 URI (java.net.URI)47 Connection (won.protocol.model.Connection)19 Test (org.junit.Test)18 Message (org.apache.camel.Message)17 Dataset (org.apache.jena.query.Dataset)17 Exchange (org.apache.camel.Exchange)13 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)13 DefaultExchange (org.apache.camel.impl.DefaultExchange)13 WonMessageProcessingException (won.protocol.message.processor.exception.WonMessageProcessingException)11 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)10 MissingMessagePropertyException (won.protocol.message.processor.exception.MissingMessagePropertyException)9 Event (won.bot.framework.eventbot.event.Event)8 FailureResponseEvent (won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent)8 EventListener (won.bot.framework.eventbot.listener.EventListener)7 Need (won.protocol.model.Need)7 WonNodeInformationService (won.protocol.service.WonNodeInformationService)7 Model (org.apache.jena.rdf.model.Model)5 WonURI (won.bot.framework.eventbot.action.impl.mail.model.WonURI)5 DefaultNeedModelWrapper (won.protocol.util.DefaultNeedModelWrapper)4