Search in sources :

Example 1 with SEPASparqlParsingException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException in project SEPA by arces-wot.

the class Gate method parseRequest.

/**
 * SPARQL 1.1 Subscribe language
 *
 * <pre>
 *	{"subscribe":{
 *		"sparql":"SPARQL Query 1.1",
 *		"authorization": "Bearer JWT", (optional)
 *		"alias":"an alias for the subscription", (optional)
 *		"default-graph-uri": "graphURI", (optional)
 *		"named-graph-uri": "graphURI" (optional)
 *	}}
 *
 *	{"unsubscribe":{
 *		"spuid":"SPUID",
 *		"authorization": "Bearer JWT" (optional)
 *	}}
 * </pre>
 *
 * @throws SEPAProtocolException
 */
protected final InternalRequest parseRequest(String request, ClientAuthorization auth) throws JsonParseException, JsonSyntaxException, IllegalStateException, ClassCastException, SEPAProtocolException, SEPASparqlParsingException {
    JsonObject req;
    ErrorResponse error;
    try {
        req = new JsonParser().parse(request).getAsJsonObject();
    } catch (JsonParseException e) {
        error = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "JsonParseException", "JsonParseException: " + request);
        return new InternalDiscardRequest(request, error, auth);
    }
    if (req.has("subscribe")) {
        String sparql = null;
        String alias = null;
        Set<String> defaultGraphUri = new HashSet<String>();
        Set<String> namedGraphUri = new HashSet<String>();
        try {
            sparql = req.get("subscribe").getAsJsonObject().get("sparql").getAsString();
        } catch (Exception e) {
            error = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "Exception", "sparql member not found: " + request);
            return new InternalDiscardRequest(request, error, auth);
        }
        try {
            alias = req.get("subscribe").getAsJsonObject().get("alias").getAsString();
        } catch (Exception e) {
        }
        try {
            JsonArray array = req.get("subscribe").getAsJsonObject().get("default-graph-uri").getAsJsonArray();
            for (JsonElement element : array) defaultGraphUri.add(element.getAsString());
        } catch (Exception e) {
        }
        try {
            JsonArray array = req.get("subscribe").getAsJsonObject().get("named-graph-uri").getAsJsonArray();
            for (JsonElement element : array) namedGraphUri.add(element.getAsString());
        } catch (Exception e) {
        }
        return new InternalSubscribeRequest(sparql, alias, defaultGraphUri, namedGraphUri, this, auth);
    } else if (req.has("unsubscribe")) {
        String spuid;
        try {
            spuid = req.get("unsubscribe").getAsJsonObject().get("spuid").getAsString();
        } catch (Exception e) {
            error = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "Exception", "spuid member not found: " + request);
            return new InternalDiscardRequest(request, error, auth);
        }
        return new InternalUnsubscribeRequest(gid, spuid, auth);
    }
    error = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "unsupported", "Bad request: " + request);
    return new InternalDiscardRequest(request, error, auth);
}
Also used : JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException) JsonParseException(com.google.gson.JsonParseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser) HashSet(java.util.HashSet)

Example 2 with SEPASparqlParsingException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException in project SEPA by arces-wot.

the class WebsocketServer method onMessage.

@Override
public void onMessage(WebSocket conn, String message) {
    GateBeans.onMessage();
    // Check path
    if (!conn.getResourceDescriptor().equals(path)) {
        logger.warn("@onMessage bad resource descriptor: " + conn.getResourceDescriptor() + " Use: " + path);
        ErrorResponse response = new ErrorResponse(HttpStatus.SC_NOT_FOUND, "wrong_path", "Bad resource descriptor: " + conn.getResourceDescriptor() + " Use: " + path);
        try {
            conn.send(response.toString());
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return;
    }
    synchronized (gates) {
        try {
            if (gates.get(conn) != null)
                gates.get(conn).onMessage(message);
            else {
                logger.error("Gate NOT FOUND: " + conn);
            }
        } catch (SEPAProtocolException | SEPASecurityException | SEPASparqlParsingException e) {
            logger.error(e);
            ErrorResponse response = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "parsing failed", e.getMessage());
            try {
                conn.send(response.toString());
            } catch (Exception e1) {
                logger.warn(e1.getMessage());
            }
        }
    }
}
Also used : SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) BindException(java.net.BindException) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) UnknownHostException(java.net.UnknownHostException) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 3 with SEPASparqlParsingException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException in project SEPA by arces-wot.

the class Processor method processUpdate.

public synchronized Response processUpdate(InternalUpdateRequest update) {
    InternalUpdateRequest preRequest = update;
    if (spuManager.doUpdateARQuadsExtraction(update)) {
        try {
            preRequest = ARQuadsAlgorithm.extractARQuads(update, queryProcessor);
        } catch (SEPAProcessingException | SPARQL11ProtocolException | SEPASparqlParsingException e) {
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "update_processing", e.getMessage());
        }
    }
    // PRE-UPDATE processing
    spuManager.subscriptionsProcessingPreUpdate(preRequest);
    // Endpoint UPDATE
    Response ret;
    try {
        ret = updateEndpoint(preRequest);
    } catch (SEPASecurityException | IOException e) {
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "sparql11endpoint", e.getMessage());
    }
    // STOP processing?
    if (ret.isError()) {
        logger.error("*** UPDATE ENDPOINT PROCESSING FAILED *** " + ret);
        spuManager.abortSubscriptionsProcessing();
        return ret;
    }
    // POST-UPDATE processing
    spuManager.subscriptionsProcessingPostUpdate(ret);
    return ret;
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) SPARQL11ProtocolException(it.unibo.arces.wot.sepa.engine.protocol.sparql11.SPARQL11ProtocolException) IOException(java.io.IOException) InternalUpdateRequest(it.unibo.arces.wot.sepa.engine.scheduling.InternalUpdateRequest) SEPAProcessingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProcessingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 4 with SEPASparqlParsingException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException in project SEPA by arces-wot.

the class JenaSparqlParsing method getQueryGraphURIs.

public Set<String> getQueryGraphURIs(String sparql) throws SEPASparqlParsingException {
    Set<String> ret = new HashSet<>();
    if (sparql == null)
        return ret;
    Query q = null;
    logger.trace("Parsing query: " + sparql);
    try {
        q = QueryFactory.create(sparql);
    } catch (Exception e) {
        // logger.error("FAILED TO CREATE QUERY WITH JENA "+e.getMessage()+" Query "+sparql);
        // ret.add("*");
        // return ret;
        logger.error(e.getMessage());
        throw new SEPASparqlParsingException(e.getMessage());
    }
    logger.trace("Get dataset descriptiors");
    if (q.hasDatasetDescription()) {
        logger.trace("Get default graph URIs");
        for (String gr : q.getDatasetDescription().getDefaultGraphURIs()) {
            ret.add(gr);
        }
        logger.trace("Get named graph URIs");
        for (String gr : q.getDatasetDescription().getNamedGraphURIs()) {
            ret.add(gr);
        }
    }
    logger.trace("Get graph URIs");
    List<String> graphs = q.getGraphURIs();
    logger.trace("Get named graph URIs");
    List<String> namedGraphs = q.getNamedGraphURIs();
    ret.addAll(extractGraphs(q.getQueryPattern()));
    ret.addAll(graphs);
    ret.addAll(namedGraphs);
    return ret;
}
Also used : Query(org.apache.jena.query.Query) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) HashSet(java.util.HashSet)

Example 5 with SEPASparqlParsingException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException in project SEPA by arces-wot.

the class SPARQL11Handler method parse.

protected InternalUQRequest parse(HttpAsyncExchange exchange, ClientAuthorization auth) {
    URI uri;
    try {
        uri = new URI(exchange.getRequest().getRequestLine().getUri());
    } catch (URISyntaxException e1) {
        throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e1.getMessage());
    }
    String requestUri = exchange.getRequest().getRequestLine().getUri();
    if (exchange.getRequest().getRequestLine().getMethod().toUpperCase().equals("GET")) {
        /**
         * <a href="https://www.w3.org/TR/sparql11-protocol/"> SPARQL 1.1 Protocol</a>
         *
         * <pre>
         *
         * 					HTTP Method 	Query String Parameters 	Request 	| Content Type 	Request Message Body
         * ----------------------------------------------------------------------------------------------------------------------------------------
         * query via GET 	| GET 			|	query (exactly 1) 		|  None 	| None 			| default-graph-uri (0 or more)  named-graph-uri (0 or more)
         *
         * 2.1.4 Specifying an RDF Dataset
         *
         * A SPARQL query is executed against an RDF Dataset. The RDF Dataset for a
         * query may be specified either via the default-graph-uri and named-graph-uri
         * parameters in the SPARQL Protocol or in the SPARQL query string using the
         * FROM and FROM NAMED keywords.
         *
         * If different RDF Datasets are specified in both the protocol request and the
         * SPARQL query string, then the SPARQL service must execute the query using the
         * RDF Dataset given in the protocol request.
         *
         * Note that a service may reject a query with HTTP response code 400 if the
         * service does not allow protocol clients to specify the RDF Dataset. If an RDF
         * Dataset is not specified in either the protocol request or the SPARQL query
         * string, then implementations may execute the query against an
         * implementation-defined default RDF dataset.
         *
         * </pre>
         */
        if (!uri.getPath().equals(queryPath))
            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "GET method available for query only. Wrong path: " + uri.getPath() + " expecting: " + queryPath);
        try {
            if (requestUri.indexOf('?') == -1) {
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong request uri: ? not found in " + requestUri);
            }
            String queryParameters = requestUri.substring(requestUri.indexOf('?') + 1);
            Map<String, Set<String>> params = HttpUtilities.splitQuery(queryParameters);
            if (params.get("query") == null) {
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong request uri: 'query=' not found in " + queryParameters);
            }
            String sparql = params.get("query").iterator().next();
            Set<String> graphUri = params.get("default-graph-uri");
            Set<String> namedGraphUri = params.get("named-graph-uri");
            Header[] headers = exchange.getRequest().getHeaders("Accept");
            if (headers.length != 1)
                return new InternalQueryRequest(sparql, graphUri, namedGraphUri, auth);
            else
                return new InternalQueryRequest(sparql, graphUri, namedGraphUri, auth, headers[0].getValue());
        } catch (SEPASparqlParsingException | UnsupportedEncodingException e) {
            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
        }
    } else if (exchange.getRequest().getRequestLine().getMethod().toUpperCase().equals("POST")) {
        /**
         * <a href="https://www.w3.org/TR/sparql11-protocol/"> SPARQL 1.1 Protocol</a>
         *
         * *
         *
         * <pre>
         *                               HTTP Method   Query String Parameters           Request Content Type                Request Message Body
         *----------------------------------------------------------------------------------------------------------------------------------------
         * update via URL-encoded POST|   POST         None                              application/x-www-form-urlencoded   URL-encoded, ampersand-separated query parameters.
         *                            |                                                                                     update (exactly 1)
         *                            |                                                                                     using-graph-uri (0 or more)
         *                            |                                                                                     using-named-graph-uri (0 or more)
         *----------------------------------------------------------------------------------------------------------------------------------------
         * update via POST directly   |   POST        using-graph-uri (0 or more)        application/sparql-update           Unencoded SPARQL update request string
         *                                            using-named-graph-uri (0 or more)
         * ----------------------------------------------------------------------------------------------------------------------------------------
         * query via URL-encoded POST |   POST         None                              application/x-www-form-urlencoded   URL-encoded, ampersand-separated query parameters.
         *                            |                                                                                     query (exactly 1)
         *                            |                                                                                     default-graph-uri (0 or more)
         *                            |                                                                                     named-graph-uri (0 or more)
         *----------------------------------------------------------------------------------------------------------------------------------------
         * query via POST directly    |   POST         default-graph-uri (0 or more)
         *                            |                named-graph-uri (0 or more)       application/sparql-query            Unencoded SPARQL query string
         * </pre>
         */
        Header[] headers = exchange.getRequest().getHeaders("Content-Type");
        if (headers.length != 1) {
            logger.log(Level.getLevel("http"), "Content-Type is missing or multiple");
            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Content-Type is missing or multiple");
        }
        HttpEntity entity = ((HttpEntityEnclosingRequest) exchange.getRequest()).getEntity();
        String body;
        try {
            body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        } catch (ParseException | IOException e) {
            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
        }
        String defGraph = "default-graph-uri";
        String namedGraph = "named-graph-uri";
        String sparql = null;
        Set<String> default_graph_uri = null;
        Set<String> named_graph_uri = null;
        if (headers[0].getValue().equals("application/x-www-form-urlencoded")) {
            String decodedBody;
            try {
                decodedBody = URLDecoder.decode(body, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
            }
            try {
                Map<String, Set<String>> params = HttpUtilities.splitQuery(decodedBody);
                if (params.containsKey("query")) {
                    if (!uri.getPath().equals(queryPath))
                        throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong path: " + uri.getPath() + " was expecting: " + queryPath);
                    params = HttpUtilities.splitQuery(decodedBody);
                    sparql = params.get("query").iterator().next();
                    default_graph_uri = params.get(defGraph);
                    named_graph_uri = params.get(namedGraph);
                    headers = exchange.getRequest().getHeaders("Accept");
                    if (headers.length != 1)
                        try {
                            return new InternalQueryRequest(sparql, default_graph_uri, named_graph_uri, auth);
                        } catch (SEPASparqlParsingException e) {
                            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                        }
                    else
                        try {
                            return new InternalQueryRequest(sparql, default_graph_uri, named_graph_uri, auth, headers[0].getValue());
                        } catch (SEPASparqlParsingException e) {
                            throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                        }
                } else if (params.containsKey("update")) {
                    if (!uri.getPath().equals(updatePath))
                        throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong path: " + uri.getPath() + " was expecting: " + updatePath);
                    defGraph = "using-graph-uri";
                    namedGraph = "using-named-graph-uri";
                    params = HttpUtilities.splitQuery(decodedBody);
                    sparql = params.get("update").iterator().next();
                    default_graph_uri = params.get(defGraph);
                    named_graph_uri = params.get(namedGraph);
                    try {
                        return new InternalUpdateRequest(sparql, default_graph_uri, named_graph_uri, auth);
                    } catch (SPARQL11ProtocolException | SEPASparqlParsingException e) {
                        throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                    }
                }
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Query or update query parameter not found");
            } catch (UnsupportedEncodingException e) {
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
            }
        } else if (headers[0].getValue().equals("application/sparql-query")) {
            if (!uri.getPath().equals(queryPath))
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong path: " + uri.getPath() + " was expecting: " + queryPath);
            if (requestUri.indexOf('?') != -1) {
                String queryParameters = requestUri.substring(requestUri.indexOf('?') + 1);
                Map<String, Set<String>> params;
                try {
                    params = HttpUtilities.splitQuery(queryParameters);
                    default_graph_uri = params.get(defGraph);
                    named_graph_uri = params.get(namedGraph);
                } catch (UnsupportedEncodingException e) {
                    throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                }
            }
            sparql = body;
            headers = exchange.getRequest().getHeaders("Accept");
            if (headers.length != 1)
                try {
                    return new InternalQueryRequest(sparql, default_graph_uri, named_graph_uri, auth);
                } catch (SEPASparqlParsingException e) {
                    throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                }
            else
                try {
                    return new InternalQueryRequest(sparql, default_graph_uri, named_graph_uri, auth, headers[0].getValue());
                } catch (SEPASparqlParsingException e) {
                    throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                }
        } else if (headers[0].getValue().equals("application/sparql-update")) {
            if (!uri.getPath().equals(updatePath))
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Wrong path: " + uri.getPath() + " was expecting: " + updatePath);
            defGraph = "using-graph-uri";
            namedGraph = "using-named-graph-uri";
            if (requestUri.indexOf('?') != -1) {
                String queryParameters = requestUri.substring(requestUri.indexOf('?') + 1);
                Map<String, Set<String>> params;
                try {
                    params = HttpUtilities.splitQuery(queryParameters);
                    default_graph_uri = params.get(defGraph);
                    named_graph_uri = params.get(namedGraph);
                } catch (UnsupportedEncodingException e) {
                    throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
                }
            }
            sparql = body;
            try {
                return new InternalUpdateRequest(sparql, default_graph_uri, named_graph_uri, auth);
            } catch (SPARQL11ProtocolException | SEPASparqlParsingException e) {
                throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, e.getMessage());
            }
        }
    }
    throw new SPARQL11ProtocolException(HttpStatus.SC_BAD_REQUEST, "Unsupported HTTP method: " + exchange.getRequest().getRequestLine().getMethod().toUpperCase());
}
Also used : Set(java.util.Set) HttpEntity(org.apache.http.HttpEntity) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) InternalQueryRequest(it.unibo.arces.wot.sepa.engine.scheduling.InternalQueryRequest) Header(org.apache.http.Header) SEPASparqlParsingException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException) Map(java.util.Map) InternalUpdateRequest(it.unibo.arces.wot.sepa.engine.scheduling.InternalUpdateRequest)

Aggregations

SEPASparqlParsingException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASparqlParsingException)6 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)3 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)3 HashSet (java.util.HashSet)3 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)2 InternalUpdateRequest (it.unibo.arces.wot.sepa.engine.scheduling.InternalUpdateRequest)2 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonParseException (com.google.gson.JsonParseException)1 JsonParser (com.google.gson.JsonParser)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 SEPAProcessingException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProcessingException)1 Response (it.unibo.arces.wot.sepa.commons.response.Response)1 SPARQL11ProtocolException (it.unibo.arces.wot.sepa.engine.protocol.sparql11.SPARQL11ProtocolException)1 InternalQueryRequest (it.unibo.arces.wot.sepa.engine.scheduling.InternalQueryRequest)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 BindException (java.net.BindException)1 URI (java.net.URI)1