Search in sources :

Example 6 with QueryResponse

use of it.unibo.arces.wot.sepa.commons.response.QueryResponse in project SEPA by arces-wot.

the class SPARQL11SEProtocol method parseSPARQL11SEResponse.

protected Response parseSPARQL11SEResponse(String response, SPARQL11SEPrimitive op) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    if (response == null)
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response is null");
    JsonObject json = null;
    try {
        json = new JsonParser().parse(response).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Unknown response: " + response);
    }
    // Error response
    if (json.get("code") != null)
        if (json.get("code").getAsInt() >= 400)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());
    if (op == SPARQL11SEPrimitive.SECUREQUERY)
        return new QueryResponse(json);
    if (op == SPARQL11SEPrimitive.SECUREUPDATE)
        return new UpdateResponse(response);
    if (op == SPARQL11SEPrimitive.REGISTER) {
        if (json.get("client_id") != null && json.get("client_secret") != null) {
            try {
                properties.setCredentials(json.get("client_id").getAsString(), json.get("client_secret").getAsString());
            } catch (SEPASecurityException | SEPAPropertiesException e) {
                return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to save credentials");
            }
            return new RegistrationResponse(json.get("client_id").getAsString(), json.get("client_secret").getAsString(), json.get("signature"));
        }
        return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Credentials not found in registration response");
    }
    if (op == SPARQL11SEPrimitive.REQUESTTOKEN) {
        if (json.get("access_token") != null && json.get("expires_in") != null && json.get("token_type") != null) {
            int seconds = json.get("expires_in").getAsInt();
            Date expires = new Date();
            expires.setTime(expires.getTime() + (1000 * seconds));
            try {
                properties.setJWT(json.get("access_token").getAsString(), expires, json.get("token_type").getAsString());
            } catch (SEPASecurityException | SEPAPropertiesException e) {
                return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to save JWT");
            }
            return new JWTResponse(json.get("access_token").getAsString(), json.get("token_type").getAsString(), json.get("expires_in").getAsLong());
        } else if (json.get("code") != null && json.get("body") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());
        else if (json.get("code") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), "");
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response not recognized: " + json.toString());
    }
    return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response unknown: " + response);
}
Also used : SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) JsonObject(com.google.gson.JsonObject) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JsonParseException(com.google.gson.JsonParseException) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 7 with QueryResponse

use of it.unibo.arces.wot.sepa.commons.response.QueryResponse in project SEPA by arces-wot.

the class SPARQL11Protocol method query.

/**
 * Implements a SPARQL 1.1 query operation
 * (https://www.w3.org/TR/sparql11-protocol/)
 *
 * <pre>
 * query via GET
 * - HTTP Method: GET
 * - Query String Parameters: <b>query</b> (exactly 1). default-graph-uri (0 or more). named-graph-uri (0 or more)
 * - Request Content Type: None
 * - Request Message Body: None
 *
 * query via URL-encoded POST
 * - HTTP Method: POST
 * - Query String Parameters: None
 * - Request Content Type: <b>application/x-www-form-urlencoded</b>
 * - Request Message Body: URL-encoded, ampersand-separated query parameters. <b>query</b> (exactly 1). default-graph-uri (0 or more). named-graph-uri (0 or more)
 *
 * query via POST directly
 * - HTTP Method: POST
 * - Query String parameters: default-graph-uri (0 or more). named-graph-uri (0 or more)
 * - Request Content Type: <b>application/sparql-query</b>
 * - Request Message Body: Unencoded SPARQL update request string
 *
 * QUERY 2.1.5 Accepted Response Formats
 *
 * Protocol clients should use HTTP content negotiation [RFC2616] to request
 * response formats that the client can consume. See below for more on
 * potential response formats.
 *
 * 2.1.6 Success Responses
 *
 * The SPARQL Protocol uses the response status codes defined in HTTP to
 * indicate the success or failure of an operation. Consult the HTTP
 * specification [RFC2616] for detailed definitions of each status code.
 * While a protocol service should use a 2XX HTTP response code for a
 * successful query, it may choose instead to use a 3XX response code as per
 * HTTP.
 *
 * The response body of a successful query operation with a 2XX response is
 * either:
 *
 * a SPARQL Results Document in XML, JSON, or CSV/TSV format (for SPARQL
 * Query forms SELECT and ASK); or, an RDF graph [RDF-CONCEPTS] serialized,
 * for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph
 * serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). The
 * content type of the response to a successful query operation must be the
 * media type defined for the format of the response body.
 *
 * 2.1.7 Failure Responses
 *
 * The HTTP response codes applicable to an unsuccessful query operation
 * include:
 *
 * 400 if the SPARQL query supplied in the request is not a legal sequence
 * of characters in the language defined by the SPARQL grammar; or, 500 if
 * the service fails to execute the query. SPARQL Protocol services may also
 * return a 500 response code if they refuse to execute a query. This
 * response does not indicate whether the server may or may not process a
 * subsequent, identical request or requests. The response body of a failed
 * query request is implementation defined. Implementations may use HTTP
 * content negotiation to provide human-readable or machine-processable (or
 * both) information about the failed query request.
 *
 * A protocol service may use other 4XX or 5XX HTTP response codes for other
 * failure conditions, as per HTTP.
 *
 * </pre>
 */
public Response query(QueryRequest req, int timeout) {
    StringEntity requestEntity = null;
    CloseableHttpResponse httpResponse = null;
    HttpEntity responseEntity = null;
    int responseCode = 0;
    String responseBody = null;
    long timing = 0;
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
    try {
        if (properties.getQueryMethod().equals(HTTPMethod.GET)) {
            String query = "query=" + URLEncoder.encode(req.getSPARQL(), "UTF-8") + "&format=" + URLEncoder.encode(properties.getQueryAcceptHeader(), "UTF-8");
            if (properties.getDefaultGraphURI() != null) {
                query += "&default-graph-uri=" + URLEncoder.encode(properties.getDefaultGraphURI(), "UTF-8");
            }
            String url;
            if (properties.getHttpPort() != -1)
                url = "http://" + properties.getHost() + ":" + properties.getHttpPort() + "/" + properties.getQueryPath() + "?" + query;
            else
                url = "http://" + properties.getHost() + "/" + properties.getQueryPath() + "?" + query;
            HttpGet queryGetRequest;
            queryGetRequest = new HttpGet(url);
            queryGetRequest.setConfig(requestConfig);
            queryRequest = queryGetRequest;
        } else {
            // Set request entity
            if (properties.getQueryMethod().equals(HTTPMethod.URL_ENCODED_POST)) {
                requestEntity = new StringEntity("query=" + URLEncoder.encode(req.getSPARQL(), "UTF-8"));
            } else if (properties.getQueryMethod().equals(HTTPMethod.POST)) {
                requestEntity = new StringEntity(req.getSPARQL(), Consts.UTF_8);
            }
            queryPostRequest.setEntity(requestEntity);
            queryPostRequest.setConfig(requestConfig);
            queryRequest = queryPostRequest;
        }
        // Execute HTTP request
        logger.debug("Execute SPARQL 1.1 QUERY (timeout: " + timeout + " ms) " + queryRequest.toString(), timeout);
        timing = System.nanoTime();
        httpResponse = httpClient.execute(queryRequest);
        timing = System.nanoTime() - timing;
        logger.debug("QUERY_TIME (" + timing / 1000000 + " ms)");
        // Status code
        responseCode = httpResponse.getStatusLine().getStatusCode();
        // Body
        responseEntity = httpResponse.getEntity();
        responseBody = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
        EntityUtils.consume(responseEntity);
    } catch (IOException e) {
        return new ErrorResponse(req.getToken(), HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        try {
            if (httpResponse != null)
                httpResponse.close();
        } catch (IOException e) {
            return new ErrorResponse(req.getToken(), HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
        requestEntity = null;
        responseEntity = null;
    }
    if (responseCode >= 400) {
        try {
            return new ErrorResponse(req.getToken(), new JsonParser().parse(responseBody).getAsJsonObject());
        } catch (JsonParseException e) {
            return new ErrorResponse(req.getToken(), responseCode, responseBody);
        }
    }
    return new QueryResponse(req.getToken(), new JsonParser().parse(responseBody).getAsJsonObject());
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) StringEntity(org.apache.http.entity.StringEntity) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonParser(com.google.gson.JsonParser)

Aggregations

QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)7 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)6 Response (it.unibo.arces.wot.sepa.commons.response.Response)5 Bindings (it.unibo.arces.wot.sepa.commons.sparql.Bindings)4 UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)3 ARBindingsResults (it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults)3 BindingsResults (it.unibo.arces.wot.sepa.commons.sparql.BindingsResults)3 JsonParseException (com.google.gson.JsonParseException)2 JsonParser (com.google.gson.JsonParser)2 SubscribeResponse (it.unibo.arces.wot.sepa.commons.response.SubscribeResponse)2 IOException (java.io.IOException)2 JsonObject (com.google.gson.JsonObject)1 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)1 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)1 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)1 QueryRequest (it.unibo.arces.wot.sepa.commons.request.QueryRequest)1 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)1 Notification (it.unibo.arces.wot.sepa.commons.response.Notification)1 RegistrationResponse (it.unibo.arces.wot.sepa.commons.response.RegistrationResponse)1 RDFTermLiteral (it.unibo.arces.wot.sepa.commons.sparql.RDFTermLiteral)1