use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse 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);
}
use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse 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());
}
use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.
the class Producer method update.
public Response update(Bindings forcedBindings) {
if (sparqlUpdate == null || protocolClient == null) {
logger.fatal("Producer not initialized");
return new ErrorResponse(-1, 400, "Producer not initialized");
}
String sparql = prefixes() + replaceBindings(sparqlUpdate, forcedBindings);
logger.debug("<UPDATE> " + SPARQL_ID + " ==> " + sparql);
return protocolClient.update(new UpdateRequest(sparql));
}
Aggregations