Search in sources :

Example 1 with UpdateResponse

use of it.unibo.arces.wot.sepa.commons.response.UpdateResponse 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)

Example 2 with UpdateResponse

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

the class Processor method run.

@Override
public void run() {
    while (true) {
        // WAIT NEW REQUEST
        ScheduledRequest scheduledRequest;
        try {
            scheduledRequest = queue.waitRequest();
        } catch (InterruptedException e1) {
            return;
        }
        Request request = scheduledRequest.getRequest();
        if (request.isUpdateRequest()) {
            logger.info("Update request #" + request.getToken());
            logger.debug(request);
            // Process update request
            Response ret = updateProcessor.process((UpdateRequest) request, ProcessorBeans.getUpdateTimeout());
            // // Notify update result
            // setChanged();
            // notifyObservers(ret);
            queue.addResponse(ret);
            if (ret.isUpdateResponse()) {
                // updateProcessing = true;
                spuManager.process((UpdateResponse) ret);
                try {
                    updateProcessingQueue.waitUpdateEOP();
                } catch (InterruptedException e1) {
                    return;
                }
            // while (updateProcessing) {
            // // Wait for SPUs processing end
            // synchronized (updateProcessor) {
            // try {
            // updateProcessor.wait();
            // } catch (InterruptedException e) {
            // return;
            // }
            // }
            // }
            }
        } else if (request.isQueryRequest()) {
            logger.info("Query request #" + request.getToken());
            logger.debug(request);
            Thread queryProcessing = new Thread() {

                public void run() {
                    Response ret = queryProcessor.process((QueryRequest) request, ProcessorBeans.getQueryTimeout());
                    // setChanged();
                    // notifyObservers(ret);
                    queue.addResponse(ret);
                }
            };
            queryProcessing.setName("SEPA Query Processing Thread-" + request.getToken());
            queryProcessing.start();
        } else if (request.isSubscribeRequest()) {
            logger.info("Subscribe request #" + request.getToken());
            logger.debug(request);
            Response ret = spuManager.subscribe((SubscribeRequest) request, (EventHandler) scheduledRequest.getHandler());
            // setChanged();
            // notifyObservers(ret);
            queue.addResponse(ret);
        } else if (request.isUnsubscribeRequest()) {
            logger.info("Unsubscribe request #" + request.getToken());
            logger.debug(request);
            Response ret = spuManager.unsubscribe((UnsubscribeRequest) request);
            // setChanged();
            // notifyObservers(ret);
            queue.addResponse(ret);
        }
    // 
    // UpdateRequest request;
    // while ((request = updateRequestQueue.poll()) != null) {
    // logger.debug("New request: " + request);
    // 
    // // Process update request
    // Response ret = updateProcessor.process(request,
    // ProcessorBeans.getUpdateTimeout());
    // 
    // // Notify update result
    // setChanged();
    // notifyObservers(ret);
    // 
    // if (ret.isUpdateResponse()) {
    // updateProcessing = true;
    // 
    // spuManager.process((UpdateResponse) ret);
    // 
    // while (updateProcessing) {
    // // Wait for SPUs processing end
    // synchronized (updateProcessor) {
    // try {
    // updateProcessor.wait();
    // } catch (InterruptedException e) {
    // return;
    // }
    // }
    // }
    // }
    // }
    // 
    // synchronized (updateRequestQueue) {
    // try {
    // updateRequestQueue.wait();
    // } catch (InterruptedException e) {
    // logger.error(e.getMessage());
    // return;
    // }
    // }
    }
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) ScheduledRequest(it.unibo.arces.wot.sepa.engine.scheduling.ScheduledRequest) QueryRequest(it.unibo.arces.wot.sepa.commons.request.QueryRequest) UnsubscribeRequest(it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest) Request(it.unibo.arces.wot.sepa.commons.request.Request) UpdateRequest(it.unibo.arces.wot.sepa.commons.request.UpdateRequest) QueryRequest(it.unibo.arces.wot.sepa.commons.request.QueryRequest) SubscribeRequest(it.unibo.arces.wot.sepa.commons.request.SubscribeRequest) UnsubscribeRequest(it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest) ScheduledRequest(it.unibo.arces.wot.sepa.engine.scheduling.ScheduledRequest)

Example 3 with UpdateResponse

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

the class SPUNaive method processInternal.

@Override
public Response processInternal(UpdateResponse update, int timeout) {
    logger.debug("* PROCESSING *" + request);
    Response ret;
    try {
        // Query the SPARQL processing service
        ret = queryProcessor.process(request, timeout);
        if (ret.getClass().equals(ErrorResponse.class)) {
            logger.error(ret);
            return ret;
        }
        // Current and previous bindings
        BindingsResults results = ((QueryResponse) ret).getBindingsResults();
        BindingsResults currentBindings = new BindingsResults(results);
        // Initialize the results with the current bindings
        BindingsResults added = new BindingsResults(results.getVariables(), null);
        BindingsResults removed = new BindingsResults(results.getVariables(), null);
        // Create empty bindings if null
        if (lastBindings == null)
            lastBindings = new BindingsResults(null, null);
        logger.debug("Current bindings: " + currentBindings);
        logger.debug("Last bindings: " + lastBindings);
        // Find removed bindings
        long start = System.nanoTime();
        for (Bindings solution : lastBindings.getBindings()) {
            if (!results.contains(solution) && !solution.isEmpty())
                removed.add(solution);
            else
                results.remove(solution);
        }
        long stop = System.nanoTime();
        logger.debug("Removed bindings: " + removed + " found in " + (stop - start) + " ns");
        // Find added bindings
        start = System.nanoTime();
        for (Bindings solution : results.getBindings()) {
            if (!lastBindings.contains(solution) && !solution.isEmpty())
                added.add(solution);
        }
        stop = System.nanoTime();
        logger.debug("Added bindings: " + added + " found in " + (stop - start) + " ns");
        // Update the last bindings with the current ones
        lastBindings = currentBindings;
        // Send notification (or end processing indication)
        if (!added.isEmpty() || !removed.isEmpty())
            ret = new Notification(getUUID(), new ARBindingsResults(added, removed), sequence++);
    } catch (Exception e) {
        ret = new ErrorResponse(500, e.getMessage());
    }
    return ret;
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) ARBindingsResults(it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults) BindingsResults(it.unibo.arces.wot.sepa.commons.sparql.BindingsResults) ARBindingsResults(it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) Bindings(it.unibo.arces.wot.sepa.commons.sparql.Bindings) Notification(it.unibo.arces.wot.sepa.commons.response.Notification) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 4 with UpdateResponse

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

the class SPU method run.

@Override
public void run() {
    while (running) {
        // Poll the request from the queue
        UpdateResponse updateResponse;
        while ((updateResponse = updateQueue.poll()) != null && running) {
            // Processing update
            logger.debug("* PROCESSING *");
            // Asynchronous processing and waiting for result
            notify = processInternal(updateResponse, SPUManagerBeans.getSPUProcessingTimeout());
            // Notify event handler
            if (handler != null) {
                if (notify.isNotification())
                    try {
                        handler.notifyEvent((Notification) notify);
                    } catch (IOException e) {
                        logger.error("Failed to notify " + notify);
                    }
                else
                    logger.debug("Not a notification: " + notify);
            } else
                logger.error("Handler is null");
            // Notify SPU manager
            logger.debug("Notify SPU manager. Running: " + running);
            synchronized (queue) {
                queue.remove(this);
                logger.debug("SPUs left: " + queue.size());
                queue.notify();
            }
        }
        // Wait next request...
        if (running)
            synchronized (updateQueue) {
                try {
                    updateQueue.wait();
                } catch (InterruptedException e) {
                    return;
                }
            }
    }
}
Also used : UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) IOException(java.io.IOException) Notification(it.unibo.arces.wot.sepa.commons.response.Notification)

Example 5 with UpdateResponse

use of it.unibo.arces.wot.sepa.commons.response.UpdateResponse 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)

Aggregations

UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)5 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)3 JsonParseException (com.google.gson.JsonParseException)2 JsonParser (com.google.gson.JsonParser)2 Notification (it.unibo.arces.wot.sepa.commons.response.Notification)2 QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)2 Response (it.unibo.arces.wot.sepa.commons.response.Response)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 Request (it.unibo.arces.wot.sepa.commons.request.Request)1 SubscribeRequest (it.unibo.arces.wot.sepa.commons.request.SubscribeRequest)1 UnsubscribeRequest (it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest)1 UpdateRequest (it.unibo.arces.wot.sepa.commons.request.UpdateRequest)1 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)1 RegistrationResponse (it.unibo.arces.wot.sepa.commons.response.RegistrationResponse)1 ARBindingsResults (it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults)1