Search in sources :

Example 6 with NoSuchAtomException

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

the class LinkedDataWebController method readConnectionsOfAtom.

/**
 * Get the RDF for the connections of the specified atom.
 *
 * @param request
 * @param identifier
 * @param deep If true, connection data is added to the model (not only
 * connection URIs). Default: false.
 * @param page taken into account only if client supports paging; in that case
 * the specified page is returned
 * @param resumeBefore taken into account only if client supports paging; in
 * that case the page with connections URIs that precede the connection having
 * resumeBefore is returned
 * @param resumeAfter taken into account only if client supports paging; in that
 * case the page with connections URIs that follow the connection having
 * resumeAfter are returned
 * @param type only connection events of the given type are considered when
 * ordering returned connections. Default: all event types.
 * @param timestamp only connection events that where created before the given
 * time are considered when ordering returned connections. Default: current
 * time.
 * @return
 */
@RequestMapping(value = "${uri.path.data}/atom/{identifier}/c", method = RequestMethod.GET, produces = { "application/ld+json", "application/trig", "application/n-quads" })
public ResponseEntity<Dataset> readConnectionsOfAtom(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "identifier") String identifier, @RequestParam(value = "socket", required = false) String socket, @RequestParam(value = "targetSocket", required = false) String targetSocket, @RequestParam(value = "deep", defaultValue = "false") boolean deep, @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 = "timeof", required = false) String timestamp, @RequestParam(value = "state", required = false) String state) {
    logger.debug("readConnectionsOfAtom() called");
    // TODO: pass aclevaluator and operationRequest down to linkeddataservice as an
    // additional filter
    URI atomUri = uriService.createAtomURIForId(identifier);
    Dataset rdfDataset;
    HttpHeaders headers = new HttpHeaders();
    Integer preferedSize = getPreferredSize(request);
    URI connectionsURI = URI.create(atomUri.toString() + "/c");
    try {
        ConnectionState connectionState = getConnectionState(state);
        WonMessageType eventsType = getMessageType(type);
        DateParameter dateParam = new DateParameter(timestamp);
        String passableQuery = getPassableQueryMap("type", type, "timeof", dateParam.getTimestamp(), "deep", Boolean.toString(deep));
        // paging, return everything:
        if (socket != null && targetSocket != null) {
            rdfDataset = linkedDataService.listConnection(URI.create(socket), URI.create(targetSocket), deep);
        } else if (preferedSize == null) {
            // does not support date and type filtering for clients that do not support
            // paging
            rdfDataset = linkedDataService.listConnections(atomUri, deep, true, connectionState).getContent();
        // if no page or resume parameter is specified, display the latest connections:
        } else if (page == null && resumeBefore == null && resumeAfter == null) {
            AtomInformationService.PagedResource<Dataset, Connection> resource = linkedDataService.listConnections(1, atomUri, preferedSize, eventsType, dateParam.getDate(), deep, true, connectionState);
            rdfDataset = resource.getContent();
            addPagedConnectionResourceInSequenceHeader(headers, connectionsURI, resource, passableQuery);
        } else if (page != null) {
            AtomInformationService.PagedResource<Dataset, Connection> resource = linkedDataService.listConnections(page, atomUri, preferedSize, eventsType, dateParam.getDate(), deep, true, connectionState);
            rdfDataset = resource.getContent();
            addPagedConnectionResourceInSequenceHeader(headers, connectionsURI, resource, page, passableQuery);
        } else {
            // before the specified event id:
            if (resumeBefore != null) {
                URI resumeConnURI;
                try {
                    resumeConnURI = new URI(resumeBefore);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("resumeBefore must be a full, valid connection URI");
                }
                AtomInformationService.PagedResource<Dataset, Connection> resource = linkedDataService.listConnectionsAfter(atomUri, resumeConnURI, preferedSize, eventsType, dateParam.getDate(), deep, true, connectionState);
                rdfDataset = resource.getContent();
                addPagedConnectionResourceInSequenceHeader(headers, connectionsURI, resource, passableQuery);
            // resume after parameter specified - display the connections with activities
            // after the specified event id:
            } else {
                // if (resumeAfter != null)
                URI resumeConnURI;
                try {
                    resumeConnURI = new URI(resumeAfter);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("resumeAfter must be a full, valid connection URI");
                }
                AtomInformationService.PagedResource<Dataset, Connection> resource = linkedDataService.listConnectionsBefore(atomUri, resumeConnURI, preferedSize, eventsType, dateParam.getDate(), deep, true, connectionState);
                rdfDataset = resource.getContent();
                addPagedConnectionResourceInSequenceHeader(headers, connectionsURI, resource, passableQuery);
            }
        }
        WonAclEvalContext ec = WonAclRequestHelper.getWonAclEvaluationContext(request);
        // check if the dataset contains any connections
        if (ec.isModeFilter() && !RdfUtils.toStatementStream(rdfDataset).anyMatch(p -> p.getPredicate().equals(RDFS.member))) {
            // the dataset may be empty because no connections are allowed
            // we don't have a position for all connections in the ACL, so we say: if the
            // user
            // is allowed to see the top level, we show the empty container, otherwise deny
            OperationRequest or = ec.getOperationRequest();
            or.setReqPosition(POSITION_ROOT);
            AclEvalResult result = ec.decideAndRemember(or);
            if (ACCESS_DENIED.equals(result.getDecision())) {
                int statusCode = HttpStatus.FORBIDDEN.value();
                Optional<AclEvalResult> accResult = WonAclRequestHelper.getWonAclEvaluationContext(request).getCombinedResults();
                if (accResult.isPresent()) {
                    WonAclRequestHelper.setAuthInfoAsResponseHeader(response, accResult.get());
                    statusCode = WonAclRequestHelper.getHttpStatusCodeForAclEvaluationResult(accResult.get());
                }
                HttpStatus status = HttpStatus.valueOf(statusCode);
                logger.debug("sending status {}", status);
                // append the required headers
                addMutableResourceHeaders(headers);
                addLocationHeaderIfNecessary(headers, URI.create(request.getRequestURI()), connectionsURI);
                return new ResponseEntity<>(null, headers, status);
            }
        }
        // append the required headers
        addMutableResourceHeaders(headers);
        addLocationHeaderIfNecessary(headers, URI.create(request.getRequestURI()), connectionsURI);
        addCORSHeader(headers);
        return new ResponseEntity<>(rdfDataset, headers, HttpStatus.OK);
    } catch (ParseException e) {
        logger.warn("could not parse timestamp into Date:{}", timestamp);
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } catch (NoSuchAtomException e) {
        logger.warn("did not find atom {}", e.getUnknownAtomURI());
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } catch (NoSuchConnectionException e) {
        logger.warn("did not find connection that should be connected to atom. connection:{}", e.getUnknownConnectionURI());
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) NoSuchAtomException(won.protocol.exception.NoSuchAtomException) URISyntaxException(java.net.URISyntaxException) AclEvalResult(won.auth.model.AclEvalResult) URI(java.net.URI) WonAclEvalContext(won.node.springsecurity.acl.WonAclEvalContext) AtomInformationService(won.node.service.persistence.AtomInformationService) HttpStatus(org.springframework.http.HttpStatus) NoSuchConnectionException(won.protocol.exception.NoSuchConnectionException) Dataset(org.apache.jena.query.Dataset) WonMessageType(won.protocol.message.WonMessageType) Connection(won.protocol.model.Connection) OperationRequest(won.auth.model.OperationRequest) ResponseEntity(org.springframework.http.ResponseEntity) ConnectionState(won.protocol.model.ConnectionState) ParseException(java.text.ParseException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with NoSuchAtomException

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

the class LinkedDataWebController method readAtomDeep.

/**
 * This request URL should be protected by WebID filter because the result
 * contains events data - which is data with restricted access. See
 * filterChainProxy in node-context.xml.
 *
 * @param request
 * @param identifier
 * @return
 */
@RequestMapping(value = "${uri.path.data}/atom/{identifier}/deep", method = RequestMethod.GET, produces = { "application/ld+json", "application/trig", "application/n-quads" })
public ResponseEntity<Dataset> readAtomDeep(HttpServletRequest request, @PathVariable(value = "identifier") String identifier, @RequestParam(value = "layer-size", required = false) Integer layerSize) {
    logger.debug("readAtom() called");
    URI atomUri = URI.create(this.atomResourceURIPrefix + "/" + identifier);
    try {
        Dataset dataset = linkedDataService.getAtomDataset(atomUri, true, layerSize, WonAclRequestHelper.getWonAclEvaluationContext(request));
        // TODO: atom information does change over time. The immutable atom information
        // should never expire, the mutable should
        HttpHeaders headers = new HttpHeaders();
        addCORSHeader(headers);
        return new ResponseEntity<>(dataset, headers, HttpStatus.OK);
    } catch (NoSuchAtomException | NoSuchConnectionException | NoSuchMessageException e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) NoSuchMessageException(org.springframework.context.NoSuchMessageException) NoSuchConnectionException(won.protocol.exception.NoSuchConnectionException) Dataset(org.apache.jena.query.Dataset) NoSuchAtomException(won.protocol.exception.NoSuchAtomException) URI(java.net.URI) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with NoSuchAtomException

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

the class DeleteAtomMessageFromOwnerProcessor method process.

public void process(final Exchange exchange) throws Exception {
    Message message = exchange.getIn();
    WonMessage wonMessage = (WonMessage) message.getHeader(WonCamelConstants.MESSAGE_HEADER);
    Optional<Atom> atom = atomService.getAtom(wonMessage.getAtomURI());
    if (!atom.isPresent()) {
        throw new NoSuchAtomException(wonMessage.getAtomURI());
    }
    if (atom.get().getState() == AtomState.DELETED) {
        throw new IllegalMessageForAtomStateException(atom.get().getAtomURI(), "DELETE", atom.get().getState());
    }
// the rest of the delete tasks are done in the reaction processor
}
Also used : Message(org.apache.camel.Message) WonMessage(won.protocol.message.WonMessage) NoSuchAtomException(won.protocol.exception.NoSuchAtomException) WonMessage(won.protocol.message.WonMessage) Atom(won.protocol.model.Atom) IllegalMessageForAtomStateException(won.protocol.exception.IllegalMessageForAtomStateException)

Example 9 with NoSuchAtomException

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

the class MatcherCLI method run.

@Override
public void run(String... args) throws Exception {
    String atom1 = "http://localhost:8080/won/resource/atom/1";
    String atom2 = "http://localhost:8080/won/resource/atom/2";
    String org = "http://localhost:8080/matcher";
    double score = 1;
    for (int i = 0; i < args.length; i++) {
        switch(args[i]) {
            case "-h":
                System.out.println("USAGE: java MatcherCLI [-n1 atom1] [-n2 atom2] [-o originator] [-s score] [-h]");
                System.exit(0);
            case "-n1":
                atom1 = args[++i];
                break;
            case "-n2":
                atom2 = args[++i];
                break;
            case "-o":
                org = args[++i];
                break;
            case "-s":
                score = Double.parseDouble(args[++i]);
                break;
        }
    }
    try {
        // TODO: Add rdf content
        client.hint(new URI(atom1), new URI(atom2), score, new URI(org), null, createWonMessage(URI.create(atom1), URI.create(atom2), score, URI.create(org)));
    } catch (URISyntaxException e) {
        logger.error("Exception caught:", e);
    } catch (IllegalMessageForAtomStateException e) {
        logger.error("Exception caught:", e);
    } catch (NoSuchAtomException e) {
        logger.error("Exception caught:", e);
    } catch (Exception e) {
        // To change body of catch statement use File | Settings | File Templates.
        e.printStackTrace();
    }
}
Also used : NoSuchAtomException(won.protocol.exception.NoSuchAtomException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) WonMessageBuilderException(won.protocol.exception.WonMessageBuilderException) URISyntaxException(java.net.URISyntaxException) IllegalMessageForAtomStateException(won.protocol.exception.IllegalMessageForAtomStateException) NoSuchAtomException(won.protocol.exception.NoSuchAtomException) IllegalMessageForAtomStateException(won.protocol.exception.IllegalMessageForAtomStateException)

Example 10 with NoSuchAtomException

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

the class LinkedDataWebController method showConnectionURIListPage.

// webmvc controller method
@RequestMapping("${uri.path.page}/atom/{identifier}/c")
public String showConnectionURIListPage(@PathVariable String identifier, @RequestParam(value = "p", required = false) Integer page, @RequestParam(value = "deep", defaultValue = "false") boolean deep, @RequestParam(value = "resumebefore", required = false) String resumeBefore, @RequestParam(value = "resumeafter", required = false) String resumeAfter, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "timeof", required = false) String timestamp, @RequestParam(value = "state", required = false) String state, HttpServletRequest request, Model model, HttpServletResponse response) {
    URI atomURI = uriService.createAtomURIForId(identifier);
    try {
        // TODO: post-filter returned connections
        ConnectionState connectionState = getConnectionState(state);
        DateParameter dateParam = new DateParameter(timestamp);
        WonMessageType eventsType = getMessageType(type);
        Dataset rdfDataset;
        if (page != null) {
            rdfDataset = linkedDataService.listConnections(page, atomURI, null, eventsType, dateParam.getDate(), deep, true, connectionState).getContent();
        } else if (resumeBefore != null) {
            URI connURI;
            try {
                connURI = new URI(resumeBefore);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("resumeBefore must be a full, valid connection URI");
            }
            rdfDataset = linkedDataService.listConnectionsAfter(atomURI, connURI, null, eventsType, dateParam.getDate(), deep, true, connectionState).getContent();
        } else if (resumeAfter != null) {
            URI connURI;
            try {
                connURI = new URI(resumeAfter);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("resumeAfter must be a full, valid connection URI");
            }
            rdfDataset = linkedDataService.listConnectionsBefore(atomURI, connURI, null, eventsType, dateParam.getDate(), deep, true, connectionState).getContent();
        } else {
            // all the connections of the atom; does not support type and date filtering for
            // clients that do not support
            // paging
            rdfDataset = linkedDataService.listConnections(atomURI, deep, true, connectionState).getContent();
        }
        model.addAttribute("rdfDataset", rdfDataset);
        model.addAttribute("resourceURI", uriService.toResourceURIIfPossible(URI.create(request.getRequestURI())).toString());
        model.addAttribute("dataURI", uriService.toDataURIIfPossible(URI.create(request.getRequestURI())).toString());
        return "rdfDatasetView";
    } catch (ParseException e) {
        model.addAttribute("error", "could not parse timestamp parameter");
        return "notFoundView";
    } catch (NoSuchAtomException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return "notFoundView";
    } catch (NoSuchConnectionException e) {
        logger.warn("did not find connection that should be connected to atom. connection:{}", e.getUnknownConnectionURI());
        // TODO: should display an error view
        return "notFoundView";
    }
}
Also used : NoSuchConnectionException(won.protocol.exception.NoSuchConnectionException) Dataset(org.apache.jena.query.Dataset) NoSuchAtomException(won.protocol.exception.NoSuchAtomException) WonMessageType(won.protocol.message.WonMessageType) ConnectionState(won.protocol.model.ConnectionState) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) URI(java.net.URI) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

NoSuchAtomException (won.protocol.exception.NoSuchAtomException)10 URI (java.net.URI)8 Dataset (org.apache.jena.query.Dataset)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 NoSuchConnectionException (won.protocol.exception.NoSuchConnectionException)4 URISyntaxException (java.net.URISyntaxException)3 AclEvalResult (won.auth.model.AclEvalResult)3 ParseException (java.text.ParseException)2 Instant (java.time.Instant)2 Date (java.util.Date)2 NoSuchMessageException (org.springframework.context.NoSuchMessageException)2 HttpHeaders (org.springframework.http.HttpHeaders)2 ResponseEntity (org.springframework.http.ResponseEntity)2 Transactional (org.springframework.transaction.annotation.Transactional)2 OperationRequest (won.auth.model.OperationRequest)2 WonAclEvalContext (won.node.springsecurity.acl.WonAclEvalContext)2 IllegalMessageForAtomStateException (won.protocol.exception.IllegalMessageForAtomStateException)2 WonMessageType (won.protocol.message.WonMessageType)2 ConnectionState (won.protocol.model.ConnectionState)2 UnreadMessageInfoForAtom (won.protocol.model.unread.UnreadMessageInfoForAtom)2