Search in sources :

Example 6 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection 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;
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 7 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class ScraperTest method real_stuff.

@Test
@Disabled
void real_stuff() throws InterruptedException {
    PlcDriverManager driverManager = new PooledPlcDriverManager(pooledPlcConnectionFactory -> {
        GenericKeyedObjectPoolConfig<PlcConnection> config = new GenericKeyedObjectPoolConfig<>();
        config.setJmxEnabled(true);
        config.setMaxWaitMillis(-1);
        config.setMaxTotal(3);
        config.setMinIdlePerKey(0);
        config.setBlockWhenExhausted(true);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        return new GenericKeyedObjectPool<>(pooledPlcConnectionFactory, config);
    });
    Scraper scraper = new ScraperImpl((j, a, m) -> {
    }, driverManager, Arrays.asList(new ScrapeJobImpl("job1", 10, Collections.singletonMap("tim", CONN_STRING_TIM), Collections.singletonMap("distance", FIELD_STRING_TIM)), new ScrapeJobImpl("job2", 10, Collections.singletonMap("chris", CONN_STRING_CH), Collections.singletonMap("counter", FIELD_STRING_CH))));
    Thread.sleep(30_000_000);
}
Also used : GenericKeyedObjectPoolConfig(org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig) GenericKeyedObjectPool(org.apache.commons.pool2.impl.GenericKeyedObjectPool) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PooledPlcDriverManager(org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PooledPlcDriverManager(org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 8 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class CachedDriverManager method getConnection_.

/**
 * Private Impl.
 */
private synchronized PlcConnection getConnection_(String url) throws PlcConnectionException {
    logger.trace("Current State {}", this.state.get());
    switch(state.get()) {
        case AVAILABLE:
            logger.debug("Connection was requested and is available, thus, returning Chached Connection for usage");
            setState(ConnectionState.BORROWED);
            this.numberOfBorrows.incrementAndGet();
            this.borrowedConnection = new CachedPlcConnection(this, activeConnection);
            // Set the Borrwed Counter
            startWatchdog(this.borrowedConnection);
            return this.borrowedConnection;
        case DISCONNECTED:
            logger.debug("Connection was requested but no connection is active, trying to establish a Connection");
            // Initialize Connection
            setState(ConnectionState.CONNECTING);
            this.numberOfConnects.incrementAndGet();
            // Start Connection in Background
            CompletableFuture.runAsync(() -> {
                logger.debug("Starting to establish Connection");
                try {
                    PlcConnection connection = this.connectionFactory.create();
                    logger.debug("Connection successfully established");
                    synchronized (this) {
                        this.activeConnection = connection;
                        setState(ConnectionState.AVAILABLE);
                        // Now See if there is someone waiting in the line
                        checkQueue();
                        logger.trace("Inline queue check succeeded");
                    }
                } catch (Exception e) {
                    logger.warn("Unable to establish connection to PLC {}", url, e);
                    setState(ConnectionState.DISCONNECTED);
                }
            });
            this.numberOfRejections.incrementAndGet();
            throw new PlcConnectionException("No Connection Available, Starting Connection");
        case CONNECTING:
            // We cannot give a Connection
            logger.debug("Connection was requsted, but currently establishing one, so none available");
            this.numberOfRejections.incrementAndGet();
            throw new PlcConnectionException("No Connection Available, Currently Connecting");
        case BORROWED:
            // We cannot give a Connection
            logger.debug("Connection was requsted, but Connection currently is borrowed, so none available");
            this.numberOfRejections.incrementAndGet();
            throw new PlcConnectionException("No Connection Available, its in Use");
    }
    throw new IllegalStateException();
}
Also used : PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) NotImplementedException(org.apache.commons.lang3.NotImplementedException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 9 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection 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;
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ScraperException(org.apache.plc4x.java.scraper.exception.ScraperException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException)

Example 10 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection 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);
            }
        }
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) ExecutionException(java.util.concurrent.ExecutionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ExecutionException(java.util.concurrent.ExecutionException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) StopWatch(org.apache.commons.lang3.time.StopWatch)

Aggregations

PlcConnection (org.apache.plc4x.java.api.PlcConnection)80 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)36 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)30 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)23 Test (org.junit.jupiter.api.Test)22 PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)20 ExecutionException (java.util.concurrent.ExecutionException)18 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)12 TimeoutException (java.util.concurrent.TimeoutException)9 BigInteger (java.math.BigInteger)8 PlcSubscriptionResponse (org.apache.plc4x.java.api.messages.PlcSubscriptionResponse)8 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)8 Map (java.util.Map)7 HashMap (java.util.HashMap)6 MockConnection (org.apache.plc4x.java.mock.connection.MockConnection)6 CompletableFuture (java.util.concurrent.CompletableFuture)5 Condition (org.assertj.core.api.Condition)5 Disabled (org.junit.jupiter.api.Disabled)5 Field (java.lang.reflect.Field)4 LocalDateTime (java.time.LocalDateTime)4