Search in sources :

Example 36 with SEPASecurityException

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

the class StressUsingPAC method subscribeAndUpdateRaceDetection.

@RepeatedTest(ConfigurationProvider.REPEATED_TEST)
public // @Timeout(10)
void subscribeAndUpdateRaceDetection() throws InterruptedException, SEPASecurityException, IOException, SEPAPropertiesException, SEPAProtocolException, SEPABindingsException {
    Thread pub = new Thread() {

        public void run() {
            for (int i = 0; i < 500; i++) {
                try {
                    randomProducer.update(provider.TIMEOUT, provider.NRETRY);
                } catch (SEPASecurityException | SEPAPropertiesException | SEPABindingsException | SEPAProtocolException e) {
                    assertFalse(true, "Failed on update: " + i + " " + e.getMessage());
                }
            }
        }
    };
    Thread sub = new Thread() {

        public void run() {
            for (int i = 0; i < 500; i++) {
                try {
                    consumerRandom1 = new ConsumerTestUnit(provider, "RANDOM1");
                    consumerRandom1.syncSubscribe(provider.TIMEOUT, provider.NRETRY);
                    consumerRandom1.close();
                    consumerAll = new ConsumerTestUnit(provider, "ALL");
                    consumerAll.syncSubscribe(provider.TIMEOUT, provider.NRETRY);
                    consumerAll.close();
                } catch (SEPASecurityException | SEPAPropertiesException | SEPABindingsException | SEPAProtocolException | IOException | InterruptedException e) {
                    assertFalse(true, "Failed on subscribe: " + i + " " + e.getMessage());
                }
            }
        }
    };
    pub.start();
    sub.start();
    synchronized (pub) {
        pub.wait();
    }
    synchronized (sub) {
        sub.wait();
    }
}
Also used : ConsumerTestUnit(it.unibo.arces.wot.sepa.ConsumerTestUnit) SEPABindingsException(it.unibo.arces.wot.sepa.commons.exceptions.SEPABindingsException) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IOException(java.io.IOException) RepeatedTest(org.junit.jupiter.api.RepeatedTest)

Example 37 with SEPASecurityException

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

the class ConfigurationProvider method buildSecurityManager.

private ClientSecurityManager buildSecurityManager() throws SEPASecurityException, SEPAPropertiesException {
    ClientSecurityManager sm = null;
    if (appProfile.isSecure()) {
        sm = new ClientSecurityManager(appProfile.getAuthenticationProperties());
        if (!appProfile.getAuthenticationProperties().isClientRegistered()) {
            Response ret = sm.registerClient(getClientId(), appProfile.getAuthenticationProperties().getUsername(), appProfile.getAuthenticationProperties().getInitialAccessToken());
            if (ret.isError())
                throw new SEPASecurityException(getClientId() + " registration failed");
        }
        sm.refreshToken();
        appProfile.getAuthenticationProperties().storeProperties();
    }
    return sm;
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) ClientSecurityManager(it.unibo.arces.wot.sepa.commons.security.ClientSecurityManager)

Example 38 with SEPASecurityException

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

the class AggregatorTestUnit method onResults.

@Override
public void onResults(ARBindingsResults results) {
    synchronized (this) {
        notificationReceived = true;
        notify();
    }
    try {
        Response ret = update();
        if (ret.isError())
            logger.error(ret);
    } catch (SEPASecurityException | SEPAProtocolException | SEPAPropertiesException | SEPABindingsException e) {
        logger.error(e);
    }
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) SEPABindingsException(it.unibo.arces.wot.sepa.commons.exceptions.SEPABindingsException) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)

Example 39 with SEPASecurityException

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

the class SPARQL11Protocol method executeRequest.

/*
	 * http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.
	 * html#d5e279
	 * 
	 * 1.5. Exception handling
	 * 
	 * HTTP protocol processors can throw two types of exceptions:
	 * 
	 * 1) java.io.IOException in case of an I/O failure such as socket timeout or an
	 * socket reset 2) HttpException that signals an HTTP failure such as a
	 * violation of the HTTP protocol.
	 * 
	 * Usually I/O errors are considered non-fatal and recoverable, whereas HTTP
	 * protocol errors are considered fatal and cannot be automatically recovered
	 * from. Please note that HttpClient implementations re-throw HttpExceptions as
	 * ClientProtocolException, which is a subclass of java.io.IOException. This
	 * enables the users of HttpClient to handle both I/O errors and protocol
	 * violations from a single catch clause.
	 */
/*
	 * {"error":"IOException","status_code":500,
	 * "error_description":"Connect to mml.arces.unibo.it:8666 [mml.arces.unibo.it/137.204.143.19] failed: Operation timed out"
	 * }
	 * 
	 * extended by java.io.IOException extended by java.net.SocketException extended
	 * by java.net.ConnectException extended by
	 * org.apache.http.conn.HttpHostConnectException
	 * 
	 */
private Response executeRequest(HttpUriRequest req, Request request) {
    CloseableHttpResponse httpResponse = null;
    HttpEntity responseEntity = null;
    int responseCode = 0;
    String responseBody = null;
    ErrorResponse errorResponse = null;
    try {
        // Execute HTTP request
        logger.trace(req.toString() + " " + request.toString() + " (timeout: " + request.getTimeout() + " ms) ");
        long start = Timings.getTime();
        httpResponse = httpClient.execute(req);
        long stop = Timings.getTime();
        if (request.getClass().equals(UpdateRequest.class))
            Timings.log("HTTP_UPDATE_TIME", start, stop);
        else
            Timings.log("HTTP_QUERY_TIME", start, stop);
        // Status code
        responseCode = httpResponse.getStatusLine().getStatusCode();
        // Body
        responseEntity = httpResponse.getEntity();
        responseBody = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
        logger.trace(String.format("Response code: %d", responseCode));
        EntityUtils.consume(responseEntity);
    } catch (Exception e) {
        errorResponse = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getClass().getName(), e.getMessage());
        // Considered as *** TIMEOUTS ***
        if (e instanceof HttpHostConnectException || e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException || e instanceof RequestAbortedException)
            errorResponse = new ErrorResponse(HttpStatus.SC_REQUEST_TIMEOUT, e.getClass().getName(), e.getMessage() + " [timeout: " + request.getTimeout() + " ms retry: " + request.getNRetry() + "]");
    } finally {
        try {
            if (httpResponse != null)
                httpResponse.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
        responseEntity = null;
    }
    if (responseCode >= 400 && errorResponse == null) {
        // http://mml.arces.unibo.it/TR/sparql11-se-protocol.html#ErrorResponses
        try {
            JsonObject ret = new JsonParser().parse(responseBody).getAsJsonObject();
            errorResponse = new ErrorResponse(ret.get("status_code").getAsInt(), ret.get("error").getAsString(), ret.get("error_description").getAsString());
        } catch (Exception e) {
            // E.g. parsing response from a "common" SPARQL endpoint
            logger.warn(e.getMessage() + " response code:" + responseCode + " response body: " + responseBody);
            if (responseBody.equals(""))
                responseBody = httpResponse.toString();
            errorResponse = new ErrorResponse(responseCode, "sparql11_endpoint", responseBody);
        }
    }
    if (errorResponse != null) {
        logger.error(errorResponse + " Token expired: " + errorResponse.isTokenExpiredError() + " Security manager: " + (sm != null) + " nRetry: " + request.getNRetry());
        // TOKEN EXPIRED
        if (errorResponse.isTokenExpiredError()) {
            try {
                logger.info("Refresh token");
                Response ret = sm.refreshToken();
                if (ret.isError())
                    return ret;
                JWTResponse token = (JWTResponse) ret;
                logger.debug(token.getAccessToken());
                req.setHeader("Authorization", token.getTokenType() + " " + token.getAccessToken());
            // request.setAuthorizationHeader(token.getTokenType()+"
            // "+token.getAccessToken());
            } catch (SEPAPropertiesException | SEPASecurityException e) {
                logger.error("Failed to refresh token. " + e.getMessage());
                return errorResponse;
            }
            return executeRequest(req, request);
        } else // TIMEOUT
        if (errorResponse.isTimeout() && request.getNRetry() > 0) {
            logger.warn(errorResponse);
            logger.warn("*** TIMEOUT RETRY " + request.getNRetry() + " ***");
            request.retry();
            return executeRequest(req, request);
        }
        return errorResponse;
    }
    return (request.getClass().equals(UpdateRequest.class) ? new UpdateResponse(responseBody) : new QueryResponse(responseBody));
}
Also used : HttpEntity(org.apache.http.HttpEntity) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) JsonObject(com.google.gson.JsonObject) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) RequestAbortedException(org.apache.http.impl.execchain.RequestAbortedException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Response(it.unibo.arces.wot.sepa.commons.response.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) SocketTimeoutException(java.net.SocketTimeoutException) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RequestAbortedException(org.apache.http.impl.execchain.RequestAbortedException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 40 with SEPASecurityException

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

the class DefaultAuthenticationService method registerClient.

public Response registerClient(String client_id, String username, String initialAccessToken, int timeout) throws SEPASecurityException {
    if (client_id == null)
        throw new SEPASecurityException("Identity is null");
    logger.log(Level.getLevel("oauth"), "REGISTER " + client_id);
    CloseableHttpResponse response = null;
    long start = Timings.getTime();
    try {
        URI uri = new URI(oauthProperties.getRegisterUrl());
        ByteArrayEntity body = new ByteArrayEntity(new RegistrationRequest(client_id).toString().getBytes("UTF-8"));
        HttpPost httpRequest = new HttpPost(uri);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("Accept", "application/json");
        httpRequest.setEntity(body);
        // Set timeout
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpRequest.setConfig(requestConfig);
        logger.log(Level.getLevel("oauth"), "Request: " + httpRequest);
        try {
            response = httpClient.execute(httpRequest);
        } catch (IOException e) {
            logger.error("HTTP EXECUTE: " + e.getMessage());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "HttpExecute", e.getMessage());
        }
        logger.log(Level.getLevel("oauth"), "Response: " + response);
        HttpEntity entity = response.getEntity();
        String jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        EntityUtils.consume(entity);
        JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
        if (json.has("error")) {
            int code = json.get("status_code").getAsInt();
            String error = json.get("error").getAsString();
            String description = json.get("error_description").getAsString();
            ErrorResponse ret = new ErrorResponse(code, error, description);
            logger.error(ret);
            return ret;
        }
        String id = json.get("credentials").getAsJsonObject().get("client_id").getAsString();
        String secret = json.get("credentials").getAsJsonObject().get("client_secret").getAsString();
        JsonElement signature = json.get("credentials").getAsJsonObject().get("signature");
        Timings.log("REGISTER", start, Timings.getTime());
        return new RegistrationResponse(id, secret, signature);
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "URISyntaxException", e.getMessage());
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "UnsupportedEncodingException", e.getMessage());
    } catch (ParseException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "ParseException", e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            Timings.log("REGISTER_ERROR", start, Timings.getTime());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JsonObject(com.google.gson.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RegistrationRequest(it.unibo.arces.wot.sepa.commons.request.RegistrationRequest) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JsonElement(com.google.gson.JsonElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ParseException(org.apache.http.ParseException) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JsonParser(com.google.gson.JsonParser)

Aggregations

SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)69 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)29 IOException (java.io.IOException)20 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)18 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)15 Response (it.unibo.arces.wot.sepa.commons.response.Response)12 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)11 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)10 JsonObject (com.google.gson.JsonObject)7 JsonParser (com.google.gson.JsonParser)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 DefaultModification (org.apache.directory.api.ldap.model.entry.DefaultModification)7 Modification (org.apache.directory.api.ldap.model.entry.Modification)7 SEPABindingsException (it.unibo.arces.wot.sepa.commons.exceptions.SEPABindingsException)5 Credentials (it.unibo.arces.wot.sepa.commons.security.Credentials)5 HttpEntity (org.apache.http.HttpEntity)5 JOSEException (com.nimbusds.jose.JOSEException)4 SignedJWT (com.nimbusds.jwt.SignedJWT)4 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)4 ParseException (java.text.ParseException)4