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();
}
}
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;
}
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);
}
}
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));
}
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());
}
}
}
Aggregations