Search in sources :

Example 1 with ErrorResponse

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

the class SEPAWebsocketClient method onError.

@Override
public void onError(Exception ex) {
    ErrorResponse error = new ErrorResponse(500, ex.getMessage());
    logger.debug("@onError: " + error);
    if (handler != null)
        handler.onError(error);
}
Also used : ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 2 with ErrorResponse

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

the class SPARQL11SEProtocol method executeSPARQL11SEPrimitive.

protected Response executeSPARQL11SEPrimitive(SPARQL11SEPrimitive op, Object request) {
    // Create the HTTPS request
    URI uri;
    String path = null;
    int port = 0;
    // Headers and body
    String contentType = null;
    ByteArrayEntity body = null;
    String accept = null;
    String authorization = null;
    switch(op) {
        case SUBSCRIBE:
            SubscribeRequest subscribe = (SubscribeRequest) request;
            return wsClient.subscribe(subscribe.getSPARQL());
        case UNSUBSCRIBE:
            UnsubscribeRequest unsubscribe = (UnsubscribeRequest) request;
            return wsClient.unsubscribe(unsubscribe.getSubscribeUUID());
        // }
        default:
            break;
    }
    switch(op) {
        case REGISTER:
            path = properties.getRegisterPath();
            port = properties.getHttpsPort();
            accept = "application/json";
            contentType = "application/json";
            String identity = (String) request;
            try {
                body = new ByteArrayEntity(new RegistrationRequest(identity).toString().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            break;
        case REQUESTTOKEN:
            String basic;
            try {
                basic = properties.getBasicAuthorization();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            if (basic == null)
                return new ErrorResponse(0, 401, "Basic authorization in null. Register first");
            path = properties.getTokenRequestPath();
            port = properties.getHttpsPort();
            authorization = "Basic " + basic;
            contentType = "application/json";
            accept = "application/json";
            break;
        case SECUREUPDATE:
            path = properties.getSecurePath() + properties.getUpdatePath();
            port = properties.getHttpsPort();
            accept = "text/plain";
            contentType = "application/x-www-form-urlencoded";
            try {
                authorization = "Bearer " + properties.getAccessToken();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            String encodedContent;
            try {
                encodedContent = URLEncoder.encode(((UpdateRequest) request).getSPARQL(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            body = new ByteArrayEntity(("update=" + encodedContent).getBytes());
            body.setContentType(contentType);
            break;
        case SECUREQUERY:
            path = properties.getSecurePath() + properties.getQueryPath();
            port = properties.getHttpsPort();
            accept = "application/sparql-results+json";
            contentType = "application/sparql-query";
            try {
                authorization = "Bearer " + properties.getAccessToken();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            try {
                body = new ByteArrayEntity(((QueryRequest) request).getSPARQL().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            break;
        default:
            break;
    }
    // POST request
    try {
        uri = new URI("https", null, properties.getHost(), port, path, null, null);
    } catch (URISyntaxException e1) {
        return new ErrorResponse(500, e1.getMessage());
    }
    HttpUriRequest httpRequest = new HttpPost(uri);
    if (contentType != null)
        httpRequest.setHeader("Content-Type", contentType);
    if (accept != null)
        httpRequest.setHeader("Accept", accept);
    if (authorization != null)
        httpRequest.setHeader("Authorization", authorization);
    if (body != null)
        ((HttpPost) httpRequest).setEntity(body);
    logger.debug("Request: " + httpRequest);
    // HTTP request execution
    CloseableHttpClient httpclient;
    try {
        httpclient = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017").getSSLHttpClient();
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
        return new ErrorResponse(500, e.getMessage());
    }
    CloseableHttpResponse response = null;
    String jsonResponse = null;
    try {
        long timing = System.nanoTime();
        try {
            response = httpclient.execute(httpRequest);
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
        timing = System.nanoTime() - timing;
        logger.debug("Response: " + response);
        if (op.equals(SPARQL11SEPrimitive.REGISTER))
            logger.debug("REGISTER " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.REQUESTTOKEN))
            logger.debug("TOKEN " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.SECUREQUERY))
            logger.debug("SECURE_QUERY " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.SECUREUPDATE))
            logger.debug("SECURE_UPDATE " + timing / 1000000 + " ms");
        HttpEntity entity = response.getEntity();
        try {
            jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        } catch (ParseException | IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
        try {
            EntityUtils.consume(entity);
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
    }
    // Parsing the response
    try {
        return parseSPARQL11SEResponse(jsonResponse, op);
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
        return new ErrorResponse(500, e.getMessage());
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) URI(java.net.URI) RegistrationRequest(it.unibo.arces.wot.sepa.commons.request.RegistrationRequest) KeyManagementException(java.security.KeyManagementException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SubscribeRequest(it.unibo.arces.wot.sepa.commons.request.SubscribeRequest) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UpdateRequest(it.unibo.arces.wot.sepa.commons.request.UpdateRequest) UnsubscribeRequest(it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonParseException(com.google.gson.JsonParseException) ParseException(org.apache.http.ParseException)

Example 3 with ErrorResponse

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

the class SPARQL11SEWebsocket method subscribe.

public Response subscribe(String sparql) {
    if (sparql == null)
        return new ErrorResponse(500, "SPARQL query is null");
    // Create SPARQL 1.1 Subscribe request
    JsonObject request = new JsonObject();
    request.add("subscribe", new JsonPrimitive(sparql));
    if (!connected) {
        client = new SEPAWebsocketClient(wsURI, this);
        try {
            if (!client.connectBlocking()) {
                logger.error("Not connected");
                return new ErrorResponse(500, "Not connected");
            }
        } catch (InterruptedException e) {
            logger.debug(e);
            return new ErrorResponse(500, "Not connected");
        }
    }
    // Send request and wait for response
    Response ret = client.sendAndReceive(request.toString(), TIMEOUT);
    if (ret.isSubscribeResponse())
        connected = true;
    return ret;
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 4 with ErrorResponse

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

the class Aggregator method update.

public final Response update(Bindings forcedBindings) {
    if (protocolClient == null || sparqlUpdate == null) {
        logger.fatal("Aggregator not initialized");
        return new ErrorResponse(-1, 400, "Aggregator not initialized");
    }
    String sparql = prefixes() + replaceBindings(sparqlUpdate, forcedBindings);
    logger.debug("<UPDATE> " + SPARQL_ID + " ==> " + sparql);
    return protocolClient.update(new UpdateRequest(sparql));
}
Also used : UpdateRequest(it.unibo.arces.wot.sepa.commons.request.UpdateRequest) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 5 with ErrorResponse

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

the class SPARQL11Protocol method update.

/**
 * Implements a SPARQL 1.1 update operation
 * (https://www.w3.org/TR/sparql11-protocol/)
 *
 * <pre>
 * update 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>update</b> (exactly 1). using-graph-uri (0 or more). using-named-graph-uri (0 or more)
 *
 * update via POST directly
 * - HTTP Method: POST
 * - Query String parameters: using-graph-uri (0 or more); using-named-graph-uri (0 or more)
 * - Request Content Type: <b>application/sparql-update</b>
 * - Request Message Body: Unencoded SPARQL update request string
 * </pre>
 *
 * UPDATE 2.2 update operation The response to an update request indicates
 * success or failure of the request via HTTP response status code.
 */
public Response update(UpdateRequest req, int timeout) {
    StringEntity requestEntity = null;
    CloseableHttpResponse httpResponse = null;
    HttpEntity responseEntity = null;
    int responseCode = 0;
    String responseBody = null;
    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        // Set request entity
        if (properties.getQueryMethod().equals(HTTPMethod.GET)) {
            // ***********************
            // OpenLink VIRTUOSO PATCH
            // ***********************
            // SPARQL 1.1 Update are issued as GET requests using the "query" URL parameter
            // The "default-graph-uri" parameter is REQUIRED
            String query = "query=" + URLEncoder.encode(req.getSPARQL(), "UTF-8") + "&format=" + URLEncoder.encode(properties.getUpdateAcceptHeader(), "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.getUpdatePath() + "?" + query;
            else
                url = "http://" + properties.getHost() + "/" + properties.getUpdatePath() + "?" + query;
            HttpGet queryGetRequest;
            queryGetRequest = new HttpGet(url);
            queryGetRequest.setConfig(requestConfig);
            updateRequest = queryGetRequest;
        } else {
            if (properties.getUpdateMethod().equals(HTTPMethod.URL_ENCODED_POST)) {
                requestEntity = new StringEntity("update=" + URLEncoder.encode(req.getSPARQL(), "UTF-8"));
            } else if (properties.getUpdateMethod().equals(HTTPMethod.POST)) {
                requestEntity = new StringEntity(req.getSPARQL(), Consts.UTF_8);
            }
            updatePostRequest.setEntity(requestEntity);
            updatePostRequest.setConfig(requestConfig);
            updateRequest = updatePostRequest;
        }
        // Execute HTTP request
        logger.debug("Execute SPARQL 1.1 QUERY (timeout: " + timeout + " ms) " + updatePostRequest.toString(), timeout);
        long timing = System.nanoTime();
        httpResponse = httpClient.execute(updateRequest);
        timing = System.nanoTime() - timing;
        logger.debug("UPDATE_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 UpdateResponse(req.getToken(), responseBody);
}
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) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonParser(com.google.gson.JsonParser)

Aggregations

ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)23 Response (it.unibo.arces.wot.sepa.commons.response.Response)8 JsonParser (com.google.gson.JsonParser)6 IOException (java.io.IOException)6 JsonObject (com.google.gson.JsonObject)5 JsonParseException (com.google.gson.JsonParseException)5 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)4 QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)4 HttpEntity (org.apache.http.HttpEntity)4 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)3 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)3 UpdateRequest (it.unibo.arces.wot.sepa.commons.request.UpdateRequest)3 SubscribeResponse (it.unibo.arces.wot.sepa.commons.response.SubscribeResponse)3 UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 JOSEException (com.nimbusds.jose.JOSEException)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 SignedJWT (com.nimbusds.jwt.SignedJWT)2 SubscribeRequest (it.unibo.arces.wot.sepa.commons.request.SubscribeRequest)2