tpalfy commented on a change in pull request #3796: WIP: NIFI-6752 Add ASN.1 
RecordReader
URL: https://github.com/apache/nifi/pull/3796#discussion_r337129818
 
 

 ##########
 File path: 
nifi-nar-bundles/nifi-asn1-bundle/nifi-asn1-services/src/main/java/org/apache/nifi/jasn1/JASN1RecordReader.java
 ##########
 @@ -0,0 +1,238 @@
+/*
+ * 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.
+ */
+package org.apache.nifi.jasn1;
+
+import com.beanit.jasn1.ber.types.BerBoolean;
+import com.beanit.jasn1.ber.types.BerInteger;
+import com.beanit.jasn1.ber.types.BerOctetString;
+import com.beanit.jasn1.ber.types.BerType;
+import com.beanit.jasn1.ber.types.string.BerUTF8String;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.serialization.MalformedRecordException;
+import org.apache.nifi.serialization.RecordReader;
+import org.apache.nifi.serialization.record.DataType;
+import org.apache.nifi.serialization.record.MapRecord;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordField;
+import org.apache.nifi.serialization.record.RecordFieldType;
+import org.apache.nifi.serialization.record.RecordSchema;
+import org.apache.nifi.serialization.record.type.ArrayDataType;
+import org.apache.nifi.util.StringUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Supplier;
+
+import static org.apache.nifi.jasn1.JASN1Utils.getSeqOfElementType;
+import static org.apache.nifi.jasn1.JASN1Utils.getSeqOfField;
+import static org.apache.nifi.jasn1.JASN1Utils.invokeGetter;
+import static org.apache.nifi.jasn1.JASN1Utils.toGetterMethod;
+
+public class JASN1RecordReader implements RecordReader {
+
+    private final Class<? extends BerType> rootClass;
+    private final Class<? extends BerType> recordModelClass;
+    private final Class<? extends RecordModelIteratorProvider> 
iteratorProviderClass;
+    private final String recordField;
+    private final Field seqOfField;
+    private final RecordSchemaProvider schemaProvider;
+    private final ClassLoader classLoader;
+    private final InputStream inputStream;
+    private final ComponentLog logger;
+
+    private Iterator<BerType> recordModelIterator;
+
+    private <T> T withClassLoader(Supplier<T> supplier) {
+        final ClassLoader originalContextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            if (classLoader != null) {
+                Thread.currentThread().setContextClassLoader(classLoader);
+            }
+
+            return supplier.get();
+        } finally {
+            if (classLoader != null && originalContextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(originalContextClassLoader);
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public JASN1RecordReader(String rootClassName, String recordField,
+                             RecordSchemaProvider schemaProvider, ClassLoader 
classLoader,
+                             String iteratorProviderClassName,
+                             InputStream inputStream, ComponentLog logger) {
+
+        this.schemaProvider = schemaProvider;
+        this.classLoader = classLoader;
+        this.inputStream = inputStream;
+        this.logger = logger;
+
+        this.recordField = recordField;
+        this.rootClass = withClassLoader(() -> {
+            try {
+                return (Class<? extends BerType>) 
classLoader.loadClass(rootClassName);
+            } catch (ClassNotFoundException e) {
+                throw new RuntimeException("The root class " + rootClassName + 
" was not found.", e);
+            }
+        });
+
+        this.iteratorProviderClass = withClassLoader(() -> {
+            if (StringUtils.isEmpty(iteratorProviderClassName)) {
+                return StandardRecordModelIteratorProvider.class;
+            }
+
+            try {
+                return (Class<? extends RecordModelIteratorProvider>) 
classLoader.loadClass(iteratorProviderClassName);
+            } catch (ClassNotFoundException e) {
+                throw new RuntimeException("The iterator provider class " + 
iteratorProviderClassName + " was not found.", e);
+            }
+        });
+
+        if (StringUtils.isEmpty(recordField)) {
+            recordModelClass = rootClass;
+            seqOfField = null;
+        } else {
+            try {
+                final Method recordModelGetter = 
rootClass.getMethod(toGetterMethod(recordField));
+                final Class<?> readPointType = 
recordModelGetter.getReturnType();
+                seqOfField = getSeqOfField(readPointType);
+                if (seqOfField != null) {
+                    recordModelClass = getSeqOfElementType(seqOfField);
+                } else {
+                    recordModelClass = (Class<? extends BerType>) 
readPointType;
+                }
+            } catch (ReflectiveOperationException e) {
+                throw new RuntimeException("Failed to get record model class 
due to " + e, e);
+            }
+        }
+
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public Record nextRecord(boolean coerceTypes, boolean dropUnknownFields) 
throws IOException, MalformedRecordException {
+
+        return withClassLoader(() -> {
+            if (recordModelIterator == null) {
+
+                final RecordModelIteratorProvider recordModelIteratorProvider;
+                try {
+                    recordModelIteratorProvider = 
iteratorProviderClass.newInstance();
+                } catch (ReflectiveOperationException e) {
+                    throw new RuntimeException("Failed to instantiate " + 
iteratorProviderClass.getCanonicalName(), e);
+                }
+
+                recordModelIterator = 
recordModelIteratorProvider.iterator(inputStream, logger, rootClass, 
recordField, seqOfField);
+            }
+
+            if (recordModelIterator.hasNext()) {
+                return convertBerRecord(recordModelIterator.next());
+            } else {
+                return null;
+            }
+
+        });
+    }
+
+    @SuppressWarnings("unchecked")
+    private Object convertBerValue(String name, DataType dataType, BerType 
instance, Object value) {
+        if (value == null) {
+            return null;
+
+        } else if (value instanceof BerBoolean) {
+            return ((BerBoolean) value).value;
+
+        } else if (value instanceof BerInteger) {
+            final BerInteger berInteger = ((BerInteger) value);
+
+            if (RecordFieldType.INT.equals(dataType.getFieldType())) {
+                return berInteger.value.intValue();
+            }
+
+            return ((BerInteger) value).value;
+
+        } else if (value instanceof BerUTF8String) {
+            return value.toString();
+
+        } else if (value instanceof BerOctetString) {
+            return ((BerOctetString) value).value;
+
+        } else if (value instanceof BerType) {
+
+            if (RecordFieldType.ARRAY.equals(dataType.getFieldType())) {
+                // If the field is declared with a direct SEQUENCE OF, then 
this value is a Parent$Children innerclass,
+                // in such a case, use the parent instance to get the 
seqOfContainer.
+                // Otherwise, the value is a separated class holding only 
seqOf field.
+                final BerType seqOfContainer = 
instance.getClass().equals(value.getClass().getEnclosingClass())
+                    ? (BerType) invokeGetter(instance, toGetterMethod(name))
 
 Review comment:
   This `invokeGetter(instance, toGetterMethod(name))` will always be the same 
as `value`.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to