use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class PlcEntityInterceptor method refetchAllFields.
/**
* Renews all values of all Fields that are annotated with {@link PlcEntity}.
*
* @param proxy Object to refresh the fields on.
* @param driverManager Driver Manager to use
* @param registry AliasRegistry to use
* @param lastFetched
* @throws OPMException on various errors.
*/
// Nested try blocks readability is okay, move to other method makes it imho worse
@SuppressWarnings("squid:S1141")
static void refetchAllFields(Object proxy, PlcDriverManager driverManager, String address, AliasRegistry registry, Map<String, Instant> lastFetched) throws OPMException {
// Don't log o here as this would cause a second request against a plc so don't touch it, or if you log be aware of that
Class<?> entityClass = proxy.getClass().getSuperclass();
LOGGER.trace("Refetching all fields on proxy object of class {}", entityClass);
PlcEntity plcEntity = entityClass.getAnnotation(PlcEntity.class);
if (plcEntity == null) {
throw new OPMException("Non PlcEntity supplied");
}
// Check if all fields are valid
for (Field field : entityClass.getDeclaredFields()) {
if (field.isAnnotationPresent(PlcField.class)) {
OpmUtils.getOrResolveAddress(registry, field.getAnnotation(PlcField.class).value());
}
}
try (PlcConnection connection = driverManager.getConnection(address)) {
// Catch the exception, if no reader present (see below)
// Build the query
PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
Arrays.stream(entityClass.getDeclaredFields()).filter(field -> field.isAnnotationPresent(PlcField.class)).filter(field -> needsToBeSynced(lastFetched, field)).forEach(field -> requestBuilder.addItem(getFqn(field), OpmUtils.getOrResolveAddress(registry, field.getAnnotation(PlcField.class).value())));
PlcReadRequest request = requestBuilder.build();
LOGGER.trace("Request for refetch of {} was build and is {}", entityClass, request);
PlcReadResponse response = getPlcReadResponse(request);
// Fill all requested fields
for (String fieldName : response.getFieldNames()) {
// Fill into Cache
lastFetched.put(fieldName, Instant.now());
LOGGER.trace("Value for field {} is {}", fieldName, response.getObject(fieldName));
String clazzFieldName = StringUtils.substringAfterLast(fieldName, ".");
try {
setField(entityClass, proxy, response, clazzFieldName, fieldName);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new PlcRuntimeException(e);
}
}
} catch (PlcConnectionException e) {
throw new OPMException("Problem during processing", e);
} catch (Exception e) {
throw new OPMException("Unexpected error during processing", e);
}
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class PlcEntityInterceptor method setForField.
private static void setForField(Field field, Object proxy, Object value) {
try {
field.setAccessible(true);
field.set(proxy, value);
} catch (IllegalAccessException e) {
throw new PlcRuntimeException(e);
}
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class ManualS7PlcDriverMT method runSingleRequest.
private double runSingleRequest(PlcDriverManager plcDriverManager) {
long start = System.nanoTime();
try (PlcConnection connection = plcDriverManager.getConnection(CONN_STRING)) {
System.out.println("Connection: " + connection);
CompletableFuture<? extends PlcReadResponse> future = connection.readRequestBuilder().addItem("distance", FIELD_STRING).build().execute();
PlcReadResponse response = future.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
throw new PlcRuntimeException(e);
}
long end = System.nanoTime();
return (double) end - start;
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class TriggeredScraperImpl method getPlcConnection.
/**
* acquires a plc connection from connection pool
* @param plcDriverManager Driver manager handling connection and pools
* @param connectionString Connection string as defined in the regarding implementation of {@link PlcDriver}
* @param executorService ExecuterService holding a pool as threads handling requests and stuff
* @param requestTimeoutMs maximum awaiting for the the future to return a result
* @param info additional info for trace reasons
* @return the {@link PlcConnection} used for acquiring data from PLC endpoint
* @throws InterruptedException something went wrong
* @throws ExecutionException something went wrong
* @throws TimeoutException something went wrong
*/
public static PlcConnection getPlcConnection(PlcDriverManager plcDriverManager, String connectionString, ExecutorService executorService, long requestTimeoutMs, String info) throws InterruptedException, ExecutionException, TimeoutException {
if (!info.isEmpty() && LOGGER.isTraceEnabled()) {
LOGGER.trace("Additional Info from caller {}", info);
}
CompletableFuture<PlcConnection> future = CompletableFuture.supplyAsync(() -> {
try {
return plcDriverManager.getConnection(connectionString);
} catch (PlcConnectionException e) {
LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
throw new PlcRuntimeException(e);
} catch (Exception e) {
LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
throw new PlcRuntimeException(e);
}
}, executorService);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("try to get a connection to {}", connectionString);
}
PlcConnection plcConnection = null;
try {
plcConnection = future.get(requestTimeoutMs, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LOGGER.trace("Additional Info from caller {}", info, e);
throw e;
}
return plcConnection;
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class ScraperTaskImpl method run.
@Override
public void run() {
// Does a single fetch
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Start new scrape of task of job {} for connection {}", jobName, connectionAlias);
}
requestCounter.incrementAndGet();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
PlcConnection connection = null;
try {
CompletableFuture<PlcConnection> future = CompletableFuture.supplyAsync(() -> {
try {
return driverManager.getConnection(connectionString);
} catch (PlcConnectionException e) {
LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
throw new PlcRuntimeException(e);
}
}, handlerService);
connection = future.get(10 * requestTimeoutMs, TimeUnit.MILLISECONDS);
LOGGER.debug("Connection to {} established: {}", connectionString, connection);
PlcReadResponse plcReadResponse;
try {
// build read request
PlcReadRequest.Builder readRequestBuilder = connection.readRequestBuilder();
// add fields to be acquired to builder
fields.forEach((alias, qry) -> {
LOGGER.trace("Requesting: {} -> {}", alias, qry);
readRequestBuilder.addItem(alias, qry);
});
plcReadResponse = readRequestBuilder.build().execute().get(requestTimeoutMs, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
// Handle execution exception
handleException(e);
return;
}
LOGGER.debug("Performing statistics");
// Add some statistics
stopWatch.stop();
latencyStatistics.addValue(stopWatch.getNanoTime());
failedStatistics.addValue(0.0);
successCounter.incrementAndGet();
// Validate response
validateResponse(plcReadResponse);
// Handle response (Async)
CompletableFuture.runAsync(() -> resultHandler.handle(jobName, connectionAlias, transformResponseToMap(plcReadResponse)), handlerService);
} catch (Exception e) {
LOGGER.warn("Exception during scraping of Job {}, Connection-Alias {}: Error-message: {} - for stack-trace change logging to DEBUG", jobName, connectionAlias, e.getMessage());
handleException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
LOGGER.warn("Error on closing connection", e);
}
}
}
}
Aggregations