Search in sources :

Example 1 with WonMessageType

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

the class LinkedDataWebController method showConnectionEventsPage.

// webmvc controller method
@RequestMapping("${uri.path.page.connection}/{identifier}/events")
public String showConnectionEventsPage(@PathVariable String identifier, @RequestParam(value = "p", required = false) Integer page, @RequestParam(value = "resumebefore", required = false) String beforeId, @RequestParam(value = "resumeafter", required = false) String afterId, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "deep", required = false, defaultValue = "false") boolean deep, Model model, HttpServletResponse response) {
    try {
        URI connectionURI = uriService.createConnectionURIForId(identifier);
        String eventsURI = connectionURI.toString() + "/events";
        Dataset rdfDataset;
        WonMessageType msgType = getMessageType(type);
        if (page == null && beforeId == null && afterId == null) {
            // all events, does not support type filtering for clients that do not support
            // paging
            rdfDataset = linkedDataService.listConnectionEventURIs(connectionURI, deep);
        } else if (page != null) {
            // a page having particular page number is requested
            NeedInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIs(connectionURI, page, null, msgType, deep);
            rdfDataset = resource.getContent();
        } else if (beforeId != null) {
            // a page that precedes the item identified by the beforeId is requested
            URI referenceEvent = uriService.createEventURIForId(beforeId);
            NeedInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIsBefore(connectionURI, referenceEvent, null, msgType, deep);
            rdfDataset = resource.getContent();
        } else {
            // a page that follows the item identified by the afterId is requested
            URI referenceEvent = uriService.createEventURIForId(afterId);
            NeedInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIsAfter(connectionURI, referenceEvent, null, msgType, deep);
            rdfDataset = resource.getContent();
        }
        model.addAttribute("rdfDataset", rdfDataset);
        model.addAttribute("resourceURI", eventsURI);
        model.addAttribute("dataURI", uriService.toDataURIIfPossible(URI.create(eventsURI)).toString());
        return "rdfDatasetView";
    } catch (NoSuchConnectionException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return "notFoundView";
    }
}
Also used : NeedInformationService(won.protocol.service.NeedInformationService) NoSuchConnectionException(won.protocol.exception.NoSuchConnectionException) Dataset(org.apache.jena.query.Dataset) WonMessageType(won.protocol.message.WonMessageType) URI(java.net.URI) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with WonMessageType

use of won.protocol.message.WonMessageType 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 3 with WonMessageType

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

the class ConnectionService method grabRemoteConnectionURIFromRemoteResponse.

public void grabRemoteConnectionURIFromRemoteResponse(WonMessage responseMessage) {
    responseMessage.getMessageType().requireType(WonMessageType.SUCCESS_RESPONSE);
    WonMessageType responseToType = responseMessage.getRespondingToMessageType();
    // the remote connection uri
    URI senderURI = responseMessage.getConnectionURIRequired();
    URI senderSocketURI = responseMessage.getSenderSocketURIRequired();
    URI recipientSocketURI = responseMessage.getRecipientSocketURIRequired();
    Optional<Connection> con = connectionRepository.findOneBySocketURIAndTargetSocketURI(recipientSocketURI, senderSocketURI);
    if (con.isPresent() && senderURI != null) {
        con.get().setTargetConnectionURI(senderURI);
        if (logger.isDebugEnabled()) {
            logger.debug("Grabbed targetURI {} for connectionURI {} from success response {}", new Object[] { senderURI, con.get().getConnectionURI(), responseMessage.getMessageURI() });
        }
        connectionRepository.save(con.get());
    }
}
Also used : WonMessageType(won.protocol.message.WonMessageType) URI(java.net.URI)

Example 4 with WonMessageType

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

the class SignatureCheckingWonMessageProcessor method process.

@Override
public WonMessage process(final WonMessage message) throws WonMessageProcessingException {
    StopWatch sw = new StopWatch();
    try {
        SignatureVerificationState result;
        /*
             * If the message is a successResponse to a delete Message then we can't check
             * the signature as it is stored in the deleted Atom, so we just accept the
             * message as valid and return it.
             */
        if (message.getRespondingToMessageType() == WonMessageType.DELETE && message.getMessageType() == WonMessageType.SUCCESS_RESPONSE) {
            return message;
        }
        for (WonMessage toCheck : message.getAllMessages()) {
            try {
                // obtain public keys
                sw.start("get public keys");
                Map<String, PublicKey> keys = WonKeysReaderWriter.readKeyFromMessage(toCheck);
                WonMessageType type = toCheck.getMessageType();
                switch(type) {
                    case CREATE_ATOM:
                        if (keys.isEmpty()) {
                            throw new WonMessageProcessingException("No key found in CREATE message");
                        }
                        break;
                    case REPLACE:
                        if (keys.isEmpty()) {
                            keys.putAll(getRequiredPublicKeys(toCheck.getCompleteDataset()));
                        }
                        break;
                    default:
                        if (!keys.isEmpty()) {
                            throw new WonMessageProcessingException(String.format("An Atom key may only be embedded in CREATE or REPLACE messages! Found one in %s message %s", type, message.getMessageURIRequired()));
                        }
                        keys.putAll(getRequiredPublicKeys(toCheck.getCompleteDataset()));
                }
                sw.stop();
                // verify with those public keys
                sw.start("verify");
                result = WonMessageSignerVerifier.verify(keys, toCheck);
                sw.stop();
                if (logger.isDebugEnabled()) {
                    logger.debug("VERIFIED=" + result.isVerificationPassed() + " with keys: " + keys.values() + " for\n" + RdfUtils.writeDatasetToString(Prefixer.setPrefixes(toCheck.getCompleteDataset()), Lang.TRIG));
                }
            } catch (LinkedDataFetchingException e) {
                /*
                     * If a delete message could not be validated because the atom was already
                     * deleted, we assume that this message is just mirrored back to the owner and
                     * is to be accepteed
                     */
                if (WonMessageType.DELETE.equals(toCheck.getMessageType())) {
                    if (e.getCause() instanceof HttpClientErrorException && HttpStatus.GONE.equals(((HttpClientErrorException) e.getCause()).getStatusCode())) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Failure during processing signature check of message" + toCheck.getMessageURI() + " (messageType was DELETE, but atom is already deleted, accept message anyway)");
                        }
                        return toCheck;
                    }
                }
                // TODO SignatureProcessingException?
                throw new WonMessageProcessingException("Could not verify message " + toCheck.getMessageURI(), e);
            } catch (Exception e) {
                // TODO SignatureProcessingException?
                throw new WonMessageProcessingException("Could not verify message " + toCheck.getMessageURI(), e);
            }
            // throw exception if the verification fails:
            if (!result.isVerificationPassed()) {
                String errormessage = "Message verification failed. Message:" + toCheck.toStringForDebug(false) + ", Problem:" + result.getMessage();
                if (logger.isDebugEnabled()) {
                    logger.debug(errormessage + ". Offending message:\n" + RdfUtils.toString(Prefixer.setPrefixes(toCheck.getCompleteDataset())));
                }
                // TODO SignatureProcessingException?
                throw new WonMessageProcessingException(new SignatureException(errormessage + ". To log the offending message, set Loglevel to DEBUG for logger '" + this.getClass().getName() + "'"));
            }
        }
        return message;
    } finally {
        logger.debug(LogMarkers.TIMING, "Signature check for message {} took {} millis, details:\n {}", new Object[] { message.getMessageURIRequired(), sw.getTotalTimeMillis(), sw.prettyPrint() });
    }
}
Also used : WonMessageProcessingException(won.protocol.exception.WonMessageProcessingException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) PublicKey(java.security.PublicKey) WonMessage(won.protocol.message.WonMessage) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) WonMessageType(won.protocol.message.WonMessageType) SignatureVerificationState(won.cryptography.rdfsign.SignatureVerificationState) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) WonMessageProcessingException(won.protocol.exception.WonMessageProcessingException) SignatureException(java.security.SignatureException) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) StopWatch(org.springframework.util.StopWatch)

Example 5 with WonMessageType

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

the class LinkedDataWebController method readConnectionEvents.

@RequestMapping(value = "${uri.path.data}/atom/{atomId}/c/{identifier}/msg", method = RequestMethod.GET, produces = { "application/ld+json", "application/trig", "application/n-quads" })
public ResponseEntity<Dataset> readConnectionEvents(HttpServletRequest request, @PathVariable String atomId, @PathVariable(value = "identifier") String identifier, @RequestParam(value = "p", required = false) Integer page, @RequestParam(value = "resumebefore", required = false) String resumeBefore, @RequestParam(value = "resumeafter", required = false) String resumeAfter, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "deep", required = false, defaultValue = "false") boolean deep) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    logger.debug("readConnection() called");
    Dataset rdfDataset;
    HttpHeaders headers = new HttpHeaders();
    Integer preferedSize = getPreferredSize(request);
    URI connectionUri = uriService.createConnectionURIForId(atomId, identifier);
    URI connectionEventsURI = URI.create(connectionUri.toString() + "/" + "msg");
    WonMessageType msgType = getMessageType(type);
    try {
        String passableMap = getPassableQueryMap("type", type);
        if (preferedSize == null) {
            // client doesn't not support paging - return all members; does not support type
            // filtering for clients that do
            // not support paging
            rdfDataset = linkedDataService.listConnectionEventURIs(connectionUri, deep);
        } else if (resumeBefore == null && resumeAfter == null) {
            // if page == null -> return page with latest events
            AtomInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIs(connectionUri, page != null ? page : 1, preferedSize, msgType, // FIXME:
            deep);
            // does not
            // respect
            // preferredSize
            // if deep is
            // used
            rdfDataset = resource.getContent();
            if (page == null) {
                addPagedResourceInSequenceHeader(headers, connectionEventsURI, resource, passableMap);
            } else {
                addPagedResourceInSequenceHeader(headers, connectionEventsURI, resource, page, passableMap);
            }
        } else if (resumeBefore != null) {
            // a page that precedes the item identified by the resumeBefore is requested
            URI referenceEvent;
            try {
                referenceEvent = new URI(resumeBefore);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("resumeBefore must be a full, valid message URI");
            }
            AtomInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIsAfter(connectionUri, referenceEvent, preferedSize, msgType, deep);
            rdfDataset = resource.getContent();
            addPagedResourceInSequenceHeader(headers, connectionEventsURI, resource, passableMap);
        } else {
            // a page that follows the item identified by the resumeAfter is requested
            URI referenceEvent;
            try {
                referenceEvent = new URI(resumeAfter);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("resumeAfter must be a full, valid message URI");
            }
            AtomInformationService.PagedResource<Dataset, URI> resource = linkedDataService.listConnectionEventURIsBefore(connectionUri, referenceEvent, preferedSize, msgType, deep);
            rdfDataset = resource.getContent();
            addPagedResourceInSequenceHeader(headers, connectionEventsURI, resource, passableMap);
        }
    } catch (NoSuchConnectionException e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    // TODO: events list information does change over time, unless the connection is
    // closed and cannot be reopened.
    // The events list of immutable connection information should never expire, the
    // mutable should
    addLocationHeaderIfNecessary(headers, URI.create(request.getRequestURI()), URI.create(this.connectionResourceURIPrefix));
    addMutableResourceHeaders(headers);
    addCORSHeader(headers);
    stopWatch.stop();
    logger.debug("readConnectionEvents took " + stopWatch.getLastTaskTimeMillis() + " millis");
    return new ResponseEntity<>(rdfDataset, headers, HttpStatus.OK);
}
Also used : AtomInformationService(won.node.service.persistence.AtomInformationService) HttpHeaders(org.springframework.http.HttpHeaders) NoSuchConnectionException(won.protocol.exception.NoSuchConnectionException) Dataset(org.apache.jena.query.Dataset) WonMessageType(won.protocol.message.WonMessageType) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StopWatch(org.springframework.util.StopWatch) ResponseEntity(org.springframework.http.ResponseEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WonMessageType (won.protocol.message.WonMessageType)20 URI (java.net.URI)12 WonMessage (won.protocol.message.WonMessage)9 Dataset (org.apache.jena.query.Dataset)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 NoSuchConnectionException (won.protocol.exception.NoSuchConnectionException)6 URISyntaxException (java.net.URISyntaxException)4 ParseException (java.text.ParseException)3 HttpHeaders (org.springframework.http.HttpHeaders)3 ResponseEntity (org.springframework.http.ResponseEntity)3 AtomInformationService (won.node.service.persistence.AtomInformationService)3 Connection (won.protocol.model.Connection)3 StopWatch (org.springframework.util.StopWatch)2 NoSuchAtomException (won.protocol.exception.NoSuchAtomException)2 WonMessageProcessingException (won.protocol.exception.WonMessageProcessingException)2 ConnectionState (won.protocol.model.ConnectionState)2 NeedInformationService (won.protocol.service.NeedInformationService)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1