You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2018/10/26 20:35:16 UTC

[incubator-plc4x] branch master updated (4ad765e -> 1716a22)

This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git.


    from 4ad765e  [plc4j-opm] fixed build, fixed some issues and added some tests.
     new 1c51cfd  [plc4j-opm] added fqn of entity to fields on request
     new c947721  [plc4j-opm] added sanity checks for getter having no parameters.
     new 3a187b3  [plc4j-opm] fixed is-getter calls.
     new 2bfb4ec  [plc4j-opm] renamed single letter parameters
     new 33af28e  [plc4j-opm] rearrange exception blocks (sonar issue :/)
     new 1716a22  [plc4j-opm] make timeout configurable

The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 plc4j/utils/opm/pom.xml                            |   4 +
 .../apache/plc4x/java/opm/PlcEntityManager.java    | 223 +++++++++++----------
 .../plc4x/java/opm/PlcEntityManagerTest.java       |  49 +++--
 .../opm/src/test}/resources/logback.xml            |   4 +-
 4 files changed, 155 insertions(+), 125 deletions(-)
 copy plc4j/{protocols/benchmarks/src/main => utils/opm/src/test}/resources/logback.xml (95%)


[incubator-plc4x] 04/06: [plc4j-opm] renamed single letter parameters

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit 2bfb4ecffa89c4509e708aa4cf80664570a9d188
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:15:09 2018 +0200

    [plc4j-opm] renamed single letter parameters
---
 .../apache/plc4x/java/opm/PlcEntityManager.java    | 52 +++++++++++-----------
 1 file changed, 26 insertions(+), 26 deletions(-)

diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index 206a25e..1678359 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -205,58 +205,58 @@ public class PlcEntityManager {
      * If the field is no getter, then all fields are refreshed by calling {@link #refetchAllFields(Object)}
      * and then, the method is invoked.
      *
-     * @param o    Object to intercept
-     * @param m    Method that was intercepted
-     * @param c    Callable to call the method after fetching the values
-     * @param that Reference to the proxy object
+     * @param proxy    Object to intercept
+     * @param method   Method that was intercepted
+     * @param callable Callable to call the method after fetching the values
+     * @param entity   Reference to the PlcEntity
      * @return possible result of the original methods invocation
      * @throws OPMException Problems with plc / proxying
      */
+    @SuppressWarnings("unused")
     @RuntimeType
-    // TODO: avoid using single letter params.
-    public Object intercept(@This Object o, @Origin Method m, @SuperCall Callable<?> c, @Super Object that) throws OPMException {
-        LOGGER.trace("Invoked method {} on connected PlcEntity {}", m.getName(), that);
+    public Object intercept(@This Object proxy, @Origin Method method, @SuperCall Callable<?> callable, @Super Object entity) throws OPMException {
+        LOGGER.trace("Invoked method {} on connected PlcEntity {}", method.getName(), entity);
 
-        if (m.getName().startsWith("get")) {
-            if (m.getParameterCount() > 0) {
+        if (method.getName().startsWith("get")) {
+            if (method.getParameterCount() > 0) {
                 throw new OPMException("Only getter with no arguments are supported");
             }
             // Fetch single value
             LOGGER.trace("Invoked method {} is getter, trying to find annotated field and return requested value",
-                m.getName());
-            return fetchValueForGetter(that, m);
+                method.getName());
+            return fetchValueForGetter(entity, method);
         }
 
-        if (m.getName().startsWith("is") && (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class)) {
-            if (m.getParameterCount() > 0) {
+        if (method.getName().startsWith("is") && (method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class)) {
+            if (method.getParameterCount() > 0) {
                 throw new OPMException("Only getter with no arguments are supported");
             }
             // Fetch single value
             LOGGER.trace("Invoked method {} is boolean flag method, trying to find annotated field and return requested value",
-                m.getName());
-            return fetchValueForIsGetter(that, m);
+                method.getName());
+            return fetchValueForIsGetter(entity, method);
         }
 
         // Fetch all values, than invoke method
         try {
-            LOGGER.trace("Invoked method is no getter, refetch all fields and invoke method {} then", m.getName());
-            refetchAllFields(o);
-            return c.call();
+            LOGGER.trace("Invoked method is no getter, refetch all fields and invoke method {} then", method.getName());
+            refetchAllFields(proxy);
+            return callable.call();
         } catch (Exception e) {
-            throw new OPMException("Unbale to forward invokation " + m.getName() + " on connected PlcEntity", e);
+            throw new OPMException("Unable to forward invocation " + method.getName() + " on connected PlcEntity", e);
         }
     }
 
     /**
      * Renews all values of all Fields that are annotated with {@link PlcEntity}.
      *
-     * @param o Object to refresh he fields on.
-     * @throws OPMException
+     * @param proxy Object to refresh the fields on.
+     * @throws OPMException on various errors.
      */
-    private void refetchAllFields(Object o) throws OPMException {
+    private void refetchAllFields(Object proxy) 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<?> superclass = o.getClass().getSuperclass();
-        PlcEntity plcEntity = superclass.getAnnotation(PlcEntity.class);
+        Class<?> entityClass = proxy.getClass().getSuperclass();
+        PlcEntity plcEntity = entityClass.getAnnotation(PlcEntity.class);
         if (plcEntity == null) {
             throw new OPMException("Non PlcEntity supplied");
         }
@@ -266,7 +266,7 @@ public class PlcEntityManager {
             // Build the query
             PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
 
-            Arrays.stream(superclass.getDeclaredFields())
+            Arrays.stream(entityClass.getDeclaredFields())
                 .filter(field -> field.isAnnotationPresent(PlcField.class))
                 .forEach(field ->
                     requestBuilder.addItem(
@@ -284,7 +284,7 @@ public class PlcEntityManager {
                 LOGGER.trace("Value for field " + fieldName + " is " + response.getObject(fieldName));
                 String clazzFieldName = StringUtils.substringAfterLast(fieldName, ".");
                 try {
-                    setField(o.getClass().getSuperclass(), o, response, clazzFieldName, fieldName);
+                    setField(entityClass, proxy, response, clazzFieldName, fieldName);
                 } catch (NoSuchFieldException | IllegalAccessException e) {
                     throw new PlcRuntimeException(e);
                 }


[incubator-plc4x] 01/06: [plc4j-opm] added fqn of entity to fields on request

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit 1c51cfda5e6e8a2d3aed2140fdfdcf21feacc5b5
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:02:31 2018 +0200

    [plc4j-opm] added fqn of entity to fields on request
---
 .../apache/plc4x/java/opm/PlcEntityManager.java    | 113 +++++++++++----------
 .../plc4x/java/opm/PlcEntityManagerTest.java       |  44 ++++----
 plc4j/utils/opm/src/test/resources/logback.xml     |  36 +++++++
 3 files changed, 119 insertions(+), 74 deletions(-)

diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index 59e6300..f42461f 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -23,6 +23,7 @@ import net.bytebuddy.ByteBuddy;
 import net.bytebuddy.implementation.MethodDelegation;
 import net.bytebuddy.implementation.bind.annotation.*;
 import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.plc4x.java.PlcDriverManager;
 import org.apache.plc4x.java.api.PlcConnection;
 import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
@@ -41,6 +42,7 @@ import java.math.BigInteger;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
+import java.util.Arrays;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
@@ -105,18 +107,14 @@ public class PlcEntityManager {
 
             PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
 
-            // Do the necessary queries for all fields
-            // HashMap<ReadRequestItem<?>, Field> requestItems = new HashMap<>();
-            for (Field field : clazz.getDeclaredFields()) {
-                PlcField fieldAnnotation = field.getAnnotation(PlcField.class);
-                if (fieldAnnotation == null) {
-                    // Ignore that field
-                    continue;
-                }
-                // Create the suitable Request
-                String query = fieldAnnotation.value();
-                requestBuilder.addItem(field.getName(), query);
-            }
+            Arrays.stream(clazz.getDeclaredFields())
+                .filter(field -> field.isAnnotationPresent(PlcField.class))
+                .forEach(field ->
+                    requestBuilder.addItem(
+                        field.getDeclaringClass().getName() + "." + field.getName(),
+                        field.getAnnotation(PlcField.class).value()
+                    )
+                );
 
             // Build the request
             PlcReadRequest request;
@@ -142,7 +140,8 @@ public class PlcEntityManager {
 
             // Fill all requested fields
             for (String fieldName : response.getFieldNames()) {
-                setField(clazz, instance, response, fieldName);
+                String targetFieldName = StringUtils.substringAfterLast(fieldName, ".");
+                setField(clazz, instance, response, targetFieldName, fieldName);
             }
             return instance;
         } catch (PlcConnectionException e) {
@@ -249,31 +248,37 @@ public class PlcEntityManager {
      * @throws OPMException
      */
     private void refetchAllFields(Object o) 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<?> superclass = o.getClass().getSuperclass();
         PlcEntity plcEntity = superclass.getAnnotation(PlcEntity.class);
+        if (plcEntity == null) {
+            throw new OPMException("Non PlcEntity supplied");
+        }
 
         try (PlcConnection connection = driverManager.getConnection(plcEntity.value())) {
             // Catch the exception, if no reader present (see below)
             // Build the query
-            PlcReadRequest.Builder builder = connection.readRequestBuilder();
-            for (Field field : superclass.getDeclaredFields()) {
-                // Check if the field has an annotation
-                PlcField plcField = field.getDeclaredAnnotation(PlcField.class);
-                if (plcField != null) {
-                    LOGGER.trace("Adding field " + field.getName() + " to request as " + plcField.value());
-                    builder.addItem(field.getName(), plcField.value());
-                }
+            PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
 
-            }
-            PlcReadRequest request = builder.build();
+            Arrays.stream(superclass.getDeclaredFields())
+                .filter(field -> field.isAnnotationPresent(PlcField.class))
+                .forEach(field ->
+                    requestBuilder.addItem(
+                        field.getDeclaringClass().getName() + "." + field.getName(),
+                        field.getAnnotation(PlcField.class).value()
+                    )
+                );
+
+            PlcReadRequest request = requestBuilder.build();
 
             PlcReadResponse response = getPlcReadResponse(request);
 
             // Fill all requested fields
             for (String fieldName : response.getFieldNames()) {
                 LOGGER.trace("Value for field " + fieldName + " is " + response.getObject(fieldName));
+                String clazzFieldName = StringUtils.substringAfterLast(fieldName, ".");
                 try {
-                    setField(o.getClass().getSuperclass(), o, response, fieldName);
+                    setField(o.getClass().getSuperclass(), o, response, clazzFieldName, fieldName);
                 } catch (NoSuchFieldException | IllegalAccessException e) {
                     throw new PlcRuntimeException(e);
                 }
@@ -320,63 +325,61 @@ public class PlcEntityManager {
      * This is one by looking for a field in the class and a response item
      * which is equal to the given fieldName parameter.
      *
-     * @param o         Object to set the value on
-     * @param response  Response to fetch the response from
-     * @param fieldName Name of the field in the object and the response
+     * @param o               Object to set the value on
+     * @param response        Response to fetch the response from
+     * @param targetFieldName Name of the field in the object
+     * @param sourceFieldName Name of the field in the response
      * @throws NoSuchFieldException
      * @throws IllegalAccessException
      */
-    private void setField(Class<?> clazz, Object o, PlcReadResponse response, String fieldName) throws NoSuchFieldException, IllegalAccessException {
-        Field field = clazz.getDeclaredField(fieldName);
+    private void setField(Class<?> clazz, Object o, PlcReadResponse response, String targetFieldName, String sourceFieldName) throws NoSuchFieldException, IllegalAccessException {
+        LOGGER.debug("setField on clazz: {}, Object: {}, response: {}, targetFieldName: {}, sourceFieldName:{} ", clazz, o, response, targetFieldName, sourceFieldName);
+        Field field = clazz.getDeclaredField(targetFieldName);
         field.setAccessible(true);
         try {
-            field.set(o, getTyped(field.getType(), response, fieldName));
+            field.set(o, getTyped(field.getType(), response, sourceFieldName));
         } catch (ClassCastException e) {
             // TODO should we simply fail here?
-            LOGGER.warn("Unable to assign return value {} to field {} with type {}", response.getObject(fieldName), fieldName, field.getType(), e);
+            LOGGER.warn("Unable to assign return value {} to field {} with type {}", response.getObject(sourceFieldName), targetFieldName, field.getType(), e);
         }
     }
 
-    private Object getTyped(Class<?> clazz, PlcReadResponse response, String fieldName) {
-        Object responseObject = response.getObject(fieldName);
-        if (responseObject == null) {
-            // TODO: shall we better throw an exception or is object never null?
-            return null;
-        }
+    private Object getTyped(Class<?> clazz, PlcReadResponse response, String sourceFieldName) {
+        LOGGER.debug("getTyped clazz: {}, response: {}, fieldName: {}", clazz, response, sourceFieldName);
         if (clazz.isPrimitive()) {
             if (clazz == boolean.class) {
-                return response.getBoolean(fieldName);
+                return response.getBoolean(sourceFieldName);
             } else if (clazz == byte.class) {
-                return response.getByte(fieldName);
+                return response.getByte(sourceFieldName);
             } else if (clazz == short.class) {
-                return response.getShort(fieldName);
+                return response.getShort(sourceFieldName);
             } else if (clazz == int.class) {
-                return response.getInteger(fieldName);
+                return response.getInteger(sourceFieldName);
             } else if (clazz == long.class) {
-                return response.getLong(fieldName);
+                return response.getLong(sourceFieldName);
             }
         }
 
         if (clazz == Boolean.class) {
-            return response.getBoolean(fieldName);
+            return response.getBoolean(sourceFieldName);
         } else if (clazz == Byte.class) {
-            return response.getByte(fieldName);
+            return response.getByte(sourceFieldName);
         } else if (clazz == Short.class) {
-            return response.getShort(fieldName);
+            return response.getShort(sourceFieldName);
         } else if (clazz == Integer.class) {
-            return response.getInteger(fieldName);
+            return response.getInteger(sourceFieldName);
         } else if (clazz == Long.class) {
-            return response.getLong(fieldName);
+            return response.getLong(sourceFieldName);
         } else if (clazz == BigInteger.class) {
-            return response.getBigInteger(fieldName);
+            return response.getBigInteger(sourceFieldName);
         } else if (clazz == Float.class) {
-            return response.getFloat(fieldName);
+            return response.getFloat(sourceFieldName);
         } else if (clazz == Double.class) {
-            return response.getDouble(fieldName);
+            return response.getDouble(sourceFieldName);
         } else if (clazz == BigDecimal.class) {
-            return response.getBigDecimal(fieldName);
+            return response.getBigDecimal(sourceFieldName);
         } else if (clazz == String.class) {
-            return response.getString(fieldName);
+            return response.getString(sourceFieldName);
         } else if (clazz == LocalTime.class) {
             // TODO: where are the methods for this?
             throw new UnsupportedOperationException("no supported yet for " + clazz);
@@ -387,11 +390,13 @@ public class PlcEntityManager {
             // TODO: where are the methods for this?
             throw new UnsupportedOperationException("no supported yet for " + clazz);
         } else if (clazz == byte[].class) {
-            return ArrayUtils.toPrimitive(response.getByteArray(fieldName));
+            return ArrayUtils.toPrimitive(response.getByteArray(sourceFieldName));
         } else if (clazz == Byte[].class) {
-            return response.getByteArray(fieldName);
+            return response.getByteArray(sourceFieldName);
         }
 
+        // Fallback
+        Object responseObject = response.getObject(sourceFieldName);
         if (clazz.isAssignableFrom(responseObject.getClass())) {
             return responseObject;
         }
diff --git a/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java b/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
index dea046e..d161e62 100644
--- a/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
+++ b/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
@@ -39,6 +39,7 @@ import org.mockito.Mockito;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.CompletableFuture;
 import java.util.function.Function;
 import java.util.stream.Collectors;
@@ -68,8 +69,9 @@ public class PlcEntityManagerTest {
     @Test
     public void read() throws OPMException, PlcConnectionException {
         Map<String, BaseDefaultFieldItem> results = new HashMap<>();
-        results.put("counter", new DefaultIntegerFieldItem(1));
-        results.put("counter2", new DefaultIntegerFieldItem(1));
+        String prefix = MyEntity.class.getName() + ".";
+        results.put(prefix + "counter", new DefaultIntegerFieldItem(1));
+        results.put(prefix + "counter2", new DefaultLongFieldItem(1l));
         PlcEntityManager manager = getPlcEntityManager(results);
 
         MyEntity myEntity = manager.read(MyEntity.class);
@@ -81,13 +83,14 @@ public class PlcEntityManagerTest {
     @Test
     public void readComplexObject() throws PlcConnectionException, OPMException {
         Map<String, BaseDefaultFieldItem> map = new HashMap<>();
-        map.put("boolVar", new DefaultBooleanFieldItem(true));
-        map.put("byteVar", new DefaultByteFieldItem((byte) 1));
-        map.put("shortVar", new DefaultShortFieldItem((short) 1));
-        map.put("intVar", new DefaultIntegerFieldItem(1));
-        map.put("longVar", new DefaultLongFieldItem(1l));
-        map.put("boxedLongVar", new DefaultLongFieldItem(1L));
-        map.put("stringVar", new DefaultStringFieldItem("Hallo"));
+        String prefix = ConnectedEntity.class.getName() + ".";
+        map.put(prefix + "boolVar", new DefaultBooleanFieldItem(true));
+        map.put(prefix + "byteVar", new DefaultByteFieldItem((byte) 1));
+        map.put(prefix + "shortVar", new DefaultShortFieldItem((short) 1));
+        map.put(prefix + "intVar", new DefaultIntegerFieldItem(1));
+        map.put(prefix + "longVar", new DefaultLongFieldItem(1l));
+        map.put(prefix + "boxedLongVar", new DefaultLongFieldItem(1L));
+        map.put(prefix + "stringVar", new DefaultStringFieldItem("Hallo"));
         PlcEntityManager manager = getPlcEntityManager(map);
 
         ConnectedEntity connect = manager.read(ConnectedEntity.class);
@@ -101,15 +104,16 @@ public class PlcEntityManagerTest {
     }
 
     @Test
-    public void connec_callComplexMethodt() throws PlcConnectionException, OPMException {
+    public void connect_callComplexMethod() throws PlcConnectionException, OPMException {
         Map<String, BaseDefaultFieldItem> map = new HashMap<>();
-        map.put("boolVar", new DefaultBooleanFieldItem(true));
-        map.put("byteVar", new DefaultByteFieldItem((byte) 1));
-        map.put("shortVar", new DefaultShortFieldItem((short) 1));
-        map.put("intVar", new DefaultIntegerFieldItem(1));
-        map.put("longVar", new DefaultLongFieldItem(1l));
-        map.put("boxedLongVar", new DefaultLongFieldItem(1L));
-        map.put("stringVar", new DefaultStringFieldItem("Hallo"));
+        String prefix = ConnectedEntity.class.getName() + ".";
+        map.put(prefix + "boolVar", new DefaultBooleanFieldItem(true));
+        map.put(prefix + "byteVar", new DefaultByteFieldItem((byte) 1));
+        map.put(prefix + "shortVar", new DefaultShortFieldItem((short) 1));
+        map.put(prefix + "intVar", new DefaultIntegerFieldItem(1));
+        map.put(prefix + "longVar", new DefaultLongFieldItem(1l));
+        map.put(prefix + "boxedLongVar", new DefaultLongFieldItem(1L));
+        map.put(prefix + "stringVar", new DefaultStringFieldItem("Hallo"));
         PlcEntityManager manager = getPlcEntityManager(map);
 
         ConnectedEntity connect = manager.connect(ConnectedEntity.class);
@@ -165,11 +169,11 @@ public class PlcEntityManagerTest {
             Map<String, Pair<PlcResponseCode, BaseDefaultFieldItem>> map = readRequest.getFieldNames().stream()
                 .collect(Collectors.toMap(
                     Function.identity(),
-                    s -> Pair.of(PlcResponseCode.OK, responses.get(s))
+                    s -> Pair.of(PlcResponseCode.OK, Objects.requireNonNull(responses.get(s), s + " not found"))
                 ));
-            return CompletableFuture.completedFuture(new DefaultPlcReadResponse(((InternalPlcReadRequest) readRequest), map));
+            return CompletableFuture.completedFuture(new DefaultPlcReadResponse((InternalPlcReadRequest) readRequest, map));
         };
-        when(connection.readRequestBuilder()).thenReturn(new DefaultPlcReadRequest.Builder(reader, getFieldHandler()));
+        when(connection.readRequestBuilder()).then(invocation -> new DefaultPlcReadRequest.Builder(reader, getFieldHandler()));
 
         return new PlcEntityManager(mock);
     }
diff --git a/plc4j/utils/opm/src/test/resources/logback.xml b/plc4j/utils/opm/src/test/resources/logback.xml
new file mode 100644
index 0000000..8b49981
--- /dev/null
+++ b/plc4j/utils/opm/src/test/resources/logback.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied.  See the License for the
+  specific language governing permissions and limitations
+  under the License.
+  -->
+<configuration xmlns="http://ch.qos.logback/xml/ns/logback"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback https://raw.githubusercontent.com/enricopulatzo/logback-XSD/master/src/main/xsd/logback.xsd">
+
+  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+    <!-- encoders are assigned the type
+         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
+    <encoder>
+      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
+    </encoder>
+  </appender>
+
+  <root level="debug">
+    <appender-ref ref="STDOUT"/>
+  </root>
+
+</configuration>
\ No newline at end of file


[incubator-plc4x] 06/06: [plc4j-opm] make timeout configurable

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit 1716a22e8aa3dd3b7a57dbdd64becf4043b75db6
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:30:52 2018 +0200

    [plc4j-opm] make timeout configurable
---
 plc4j/utils/opm/pom.xml                            |  4 +++
 .../apache/plc4x/java/opm/PlcEntityManager.java    | 37 +++++++++++-----------
 2 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/plc4j/utils/opm/pom.xml b/plc4j/utils/opm/pom.xml
index 7c289b3..500820c 100644
--- a/plc4j/utils/opm/pom.xml
+++ b/plc4j/utils/opm/pom.xml
@@ -57,6 +57,10 @@
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-configuration2</artifactId>
+    </dependency>
 
     <!--Testing-->
     <dependency>
diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index e2f8a43..0a51049 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -22,6 +22,8 @@ package org.apache.plc4x.java.opm;
 import net.bytebuddy.ByteBuddy;
 import net.bytebuddy.implementation.MethodDelegation;
 import net.bytebuddy.implementation.bind.annotation.*;
+import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.SystemConfiguration;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.plc4x.java.PlcDriverManager;
@@ -85,6 +87,9 @@ public class PlcEntityManager {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(PlcEntityManager.class);
 
+    private static final Configuration CONF = new SystemConfiguration();
+    private static final long READ_TIMEOUT = CONF.getLong("org.apache.plc4x.java.opm.entity_manager.read_timeout", 1_000);
+
     private final PlcDriverManager driverManager;
 
     public PlcEntityManager() {
@@ -119,8 +124,7 @@ public class PlcEntityManager {
             PlcReadRequest request = requestBuilder.build();
 
             // Perform the request
-            // TODO: make configurable.
-            PlcReadResponse response = request.execute().get(1_000, TimeUnit.MILLISECONDS);
+            PlcReadResponse response = getPlcReadResponse(request);
 
             // Construct the Object
             T instance = clazz.getConstructor().newInstance();
@@ -131,19 +135,14 @@ public class PlcEntityManager {
                 setField(clazz, instance, response, targetFieldName, fieldName);
             }
             return instance;
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new OPMException("Unable to fetch request", e);
-        } catch (ExecutionException e) {
-            throw new OPMException("Unable to fetch request", e);
-        } catch (TimeoutException e) {
-            throw new OPMException("Timeout during fetching values", e);
         } catch (PlcInvalidFieldException e) {
             throw new OPMException("Unable to parse one field request", e);
         } catch (PlcConnectionException e) {
             throw new OPMException("Unable to get connection with url '" + source + "'", e);
-        } catch (Exception e) {
+        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) {
             throw new OPMException("Unable to fetch PlcEntity " + clazz.getName(), e);
+        } catch (Exception e) {
+            throw new OPMException("Unknown Error", e);
         }
     }
 
@@ -285,8 +284,10 @@ public class PlcEntityManager {
                     throw new PlcRuntimeException(e);
                 }
             }
-        } catch (Exception e) {
+        } catch (PlcConnectionException e) {
             throw new OPMException("Problem during processing", e);
+        } catch (Exception e) {
+            throw new OPMException("Unknown Error", e);
         }
     }
 
@@ -320,8 +321,7 @@ public class PlcEntityManager {
                 .addItem(m.getName(), annotation.value())
                 .build();
 
-            PlcReadResponse response;
-            response = getPlcReadResponse(request);
+            PlcReadResponse response = getPlcReadResponse(request);
 
             return getTyped(m.getReturnType(), response, m.getName());
         } catch (ClassCastException e) {
@@ -419,19 +419,20 @@ public class PlcEntityManager {
     /**
      * Fetch the request and do appropriate error handling
      *
-     * @param request
-     * @return
-     * @throws OPMException
+     * @param request the request to get the exception from
+     * @return the response from the exception.
+     * @throws OPMException on {@link InterruptedException} or {@link ExecutionException} or {@link TimeoutException}
      */
     private PlcReadResponse getPlcReadResponse(PlcReadRequest request) throws OPMException {
         try {
-            // TODO: add configurable timeout
-            return request.execute().get();
+            return request.execute().get(READ_TIMEOUT, TimeUnit.MILLISECONDS);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();
             throw new OPMException("Exception during execution", e);
         } catch (ExecutionException e) {
             throw new OPMException("Exception during execution", e);
+        } catch (TimeoutException e) {
+            throw new OPMException("Timeout during fetching values", e);
         }
     }
 


[incubator-plc4x] 02/06: [plc4j-opm] added sanity checks for getter having no parameters.

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit c947721355042ca76d634e3ac9b14fef26bcd1af
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:02:56 2018 +0200

    [plc4j-opm] added sanity checks for getter having no parameters.
---
 .../src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java   | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index f42461f..aa51f7b 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -218,6 +218,9 @@ public class PlcEntityManager {
         LOGGER.trace("Invoked method {} on connected PlcEntity {}", m.getName(), that);
 
         if (m.getName().startsWith("get")) {
+            if (m.getParameterCount() > 0) {
+                throw new OPMException("Only getter with no arguments are supported");
+            }
             // Fetch single value
             LOGGER.trace("Invoked method {} is getter, trying to find annotated field and return requested value",
                 m.getName());
@@ -225,6 +228,9 @@ public class PlcEntityManager {
         }
 
         if (m.getName().startsWith("is") && (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class)) {
+            if (m.getParameterCount() > 0) {
+                throw new OPMException("Only getter with no arguments are supported");
+            }
             // Fetch single value
             LOGGER.trace("Invoked method {} is boolean flag method, trying to find annotated field and return requested value",
                 m.getName());


[incubator-plc4x] 03/06: [plc4j-opm] fixed is-getter calls.

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit 3a187b3c6e3c4f2b55b816afa72bb78250eca013
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:09:14 2018 +0200

    [plc4j-opm] fixed is-getter calls.
---
 .../java/org/apache/plc4x/java/opm/PlcEntityManager.java  | 15 ++++++++++++---
 .../org/apache/plc4x/java/opm/PlcEntityManagerTest.java   |  5 +++++
 2 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index aa51f7b..206a25e 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -234,7 +234,7 @@ public class PlcEntityManager {
             // Fetch single value
             LOGGER.trace("Invoked method {} is boolean flag method, trying to find annotated field and return requested value",
                 m.getName());
-            return fetchValueForGetter(that, m);
+            return fetchValueForIsGetter(that, m);
         }
 
         // Fetch all values, than invoke method
@@ -294,9 +294,18 @@ public class PlcEntityManager {
         }
     }
 
-    // TODO: why isn't o used?
+
+    private Object fetchValueForIsGetter(Object o, Method m) throws OPMException {
+        return fetchValueForGetter(o, m, 2);
+    }
+
     private Object fetchValueForGetter(Object o, Method m) throws OPMException {
-        String s = m.getName().substring(3);
+        return fetchValueForGetter(o, m, 3);
+    }
+
+    // TODO: why isn't o used?
+    private Object fetchValueForGetter(Object o, Method m, int prefixLength) throws OPMException {
+        String s = m.getName().substring(prefixLength);
         // First char to lower
         String variable = s.substring(0, 1).toLowerCase().concat(s.substring(1));
         LOGGER.trace("Looking for field with name {} after invokation of getter {}", variable, m.getName());
diff --git a/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java b/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
index d161e62..ec0dc6c 100644
--- a/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
+++ b/plc4j/utils/opm/src/test/java/org/apache/plc4x/java/opm/PlcEntityManagerTest.java
@@ -131,6 +131,7 @@ public class PlcEntityManagerTest {
         Map<String, BaseDefaultFieldItem> map = new HashMap<>();
         map.put("getIntVar", new DefaultIntegerFieldItem(1));
         map.put("getStringVar", new DefaultStringFieldItem("Hello"));
+        map.put("isBoolVar", new DefaultBooleanFieldItem(true));
         PlcEntityManager manager = getPlcEntityManager(map);
 
         ConnectedEntity connect = manager.connect(ConnectedEntity.class);
@@ -140,6 +141,7 @@ public class PlcEntityManagerTest {
         // Call getter
         assertEquals(1, connect.getIntVar());
         assertEquals("Hello", connect.getStringVar());
+        assertEquals(true, connect.isBoolVar());
     }
 
     private PlcEntityManager getPlcEntityManager(final Map<String, BaseDefaultFieldItem> responses) throws PlcConnectionException {
@@ -320,6 +322,9 @@ public class PlcEntityManagerTest {
             // Default
         }
 
+        public boolean isBoolVar() {
+            return boolVar;
+        }
 
         public byte getByteVar() {
             return byteVar;


[incubator-plc4x] 05/06: [plc4j-opm] rearrange exception blocks (sonar issue :/)

Posted by sr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git

commit 33af28e7d0eac200ec2560cc730131b58f164ee0
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Oct 26 22:19:54 2018 +0200

    [plc4j-opm] rearrange exception blocks (sonar issue :/)
---
 .../apache/plc4x/java/opm/PlcEntityManager.java    | 28 ++++++++++------------
 1 file changed, 12 insertions(+), 16 deletions(-)

diff --git a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
index 1678359..e2f8a43 100644
--- a/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
+++ b/plc4j/utils/opm/src/main/java/org/apache/plc4x/java/opm/PlcEntityManager.java
@@ -100,7 +100,6 @@ public class PlcEntityManager {
         String source = annotation.value();
 
         try (PlcConnection connection = driverManager.getConnection(source)) {
-
             if (!connection.getMetadata().canRead()) {
                 throw new OPMException("Unable to get Reader for connection with url '" + source + "'");
             }
@@ -117,23 +116,11 @@ public class PlcEntityManager {
                 );
 
             // Build the request
-            PlcReadRequest request;
-            try {
-                request = requestBuilder.build();
-            } catch (PlcInvalidFieldException e) {
-                throw new OPMException("Unable to parse one field request", e);
-            }
+            PlcReadRequest request = requestBuilder.build();
 
             // Perform the request
-            PlcReadResponse response;
-            try {
-                // TODO: make configurable.
-                response = request.execute().get(1_000, TimeUnit.MILLISECONDS);
-            } catch (InterruptedException | ExecutionException e) {
-                throw new OPMException("Request fetching not able", e);
-            } catch (TimeoutException e) {
-                throw new OPMException("Timeout during fetching values", e);
-            }
+            // TODO: make configurable.
+            PlcReadResponse response = request.execute().get(1_000, TimeUnit.MILLISECONDS);
 
             // Construct the Object
             T instance = clazz.getConstructor().newInstance();
@@ -144,6 +131,15 @@ public class PlcEntityManager {
                 setField(clazz, instance, response, targetFieldName, fieldName);
             }
             return instance;
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new OPMException("Unable to fetch request", e);
+        } catch (ExecutionException e) {
+            throw new OPMException("Unable to fetch request", e);
+        } catch (TimeoutException e) {
+            throw new OPMException("Timeout during fetching values", e);
+        } catch (PlcInvalidFieldException e) {
+            throw new OPMException("Unable to parse one field request", e);
         } catch (PlcConnectionException e) {
             throw new OPMException("Unable to get connection with url '" + source + "'", e);
         } catch (Exception e) {