prankstrisse commented on code in PR #11499:
URL: https://github.com/apache/nifi/pull/11499#discussion_r4094472126


##########
nifi-extension-bundles/nifi-protobuf-bundle/nifi-protobuf-services/src/main/java/org/apache/nifi/services/protobuf/converter/ProtobufDataSerializer.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.services.protobuf.converter;
+
+import com.google.protobuf.CodedOutputStream;
+import com.squareup.wire.schema.EnumConstant;
+import com.squareup.wire.schema.EnumType;
+import com.squareup.wire.schema.Field;
+import com.squareup.wire.schema.MessageType;
+import com.squareup.wire.schema.OneOf;
+import com.squareup.wire.schema.ProtoType;
+import com.squareup.wire.schema.Schema;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.util.DataTypeUtils;
+import org.apache.nifi.services.protobuf.FieldType;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Serializes a NiFi {@link Record} into Protocol Buffers binary payload using 
a Square Wire
+ * {@link Schema}. This is the write-side inverse of {@code 
ProtobufDataConverter}: it walks the
+ * declared fields of the target message type and encodes each present Record 
value to a
+ * {@link CodedOutputStream} following the Protocol Buffers wire format.
+ * <p>
+ * This class has no dependency on the NiFi framework and can be exercised 
directly with plain
+ * unit tests.
+ */
+public class ProtobufDataSerializer {
+
+    private static final int WIRETYPE_VARINT = 0;
+    private static final int WIRETYPE_FIXED64 = 1;
+    private static final int WIRETYPE_LENGTH_DELIMITED = 2;
+    private static final int WIRETYPE_FIXED32 = 5;
+
+    private static final int MAP_KEY_TAG = 1;
+    private static final int MAP_VALUE_TAG = 2;
+
+    private final Schema schema;
+    private final String rootMessageType;
+
+    public ProtobufDataSerializer(final Schema schema, final String 
rootMessageType) {
+        this.schema = schema;
+        this.rootMessageType = rootMessageType;
+    }
+
+    /**
+     * Serializes the provided Record into Protocol Buffers binary format for 
the configured root
+     * message type.
+     *
+     * @param record the record to serialize
+     * @return the serialized protobuf payload
+     * @throws IOException if the record cannot be encoded
+     */
+    public byte[] serialize(final Record record) throws IOException {
+        final MessageType messageType = (MessageType) 
schema.getType(rootMessageType);
+        Objects.requireNonNull(messageType, String.format("Message with name 
[%s] not found in the provided proto files", rootMessageType));
+
+        return serializeMessage(messageType, record);
+    }
+
+    private byte[] serializeMessage(final MessageType messageType, final 
Record record) throws IOException {
+        final ByteArrayOutputStream output = new ByteArrayOutputStream();
+        final CodedOutputStream codedOutput = 
CodedOutputStream.newInstance(output);
+
+        for (final Field field : messageType.getDeclaredFields()) {
+            writeField(codedOutput, field, record.getValue(field.getName()));
+        }
+        for (final Field field : messageType.getExtensionFields()) {
+            writeField(codedOutput, field, record.getValue(field.getName()));
+        }
+        for (final OneOf oneOf : messageType.getOneOfs()) {
+            for (final Field field : oneOf.getFields()) {
+                writeField(codedOutput, field, 
record.getValue(field.getName()));
+            }
+        }
+
+        codedOutput.flush();
+        return output.toByteArray();
+    }
+
+    private void writeField(final CodedOutputStream output, final Field field, 
final Object value) throws IOException {
+        if (value == null) {
+            return;
+        }
+
+        final int tag = field.getTag();
+        final ProtoType protoType = field.getType();
+
+        if (protoType.isMap()) {
+            writeMap(output, tag, protoType, value);
+        } else if (field.isRepeated()) {
+            writeRepeated(output, tag, protoType, value);
+        } else {
+            writeSingleValue(output, tag, protoType, value);
+        }
+    }
+
+    private void writeRepeated(final CodedOutputStream output, final int tag, 
final ProtoType protoType, final Object value) throws IOException {
+        final Object[] values = toArray(value);
+
+        if (isPackable(protoType)) {
+            // proto3 packs repeated scalar and enum fields into a single 
length-delimited entry
+            final ByteArrayOutputStream packedBytes = new 
ByteArrayOutputStream();
+            final CodedOutputStream packedOutput = 
CodedOutputStream.newInstance(packedBytes);
+            for (final Object element : values) {
+                writeScalarOrEnumValueNoTag(packedOutput, protoType, element);
+            }
+            packedOutput.flush();
+
+            output.writeTag(tag, WIRETYPE_LENGTH_DELIMITED);
+            final byte[] packed = packedBytes.toByteArray();
+            output.writeUInt32NoTag(packed.length);
+            output.writeRawBytes(packed);
+        } else {
+            // repeated messages, strings and bytes are written as separate 
length-delimited entries
+            for (final Object element : values) {
+                writeSingleValue(output, tag, protoType, element);
+            }
+        }
+    }
+
+    private void writeSingleValue(final CodedOutputStream output, final int 
tag, final ProtoType protoType, final Object value) throws IOException {
+        if (protoType.isScalar()) {
+            final FieldType fieldType = 
FieldType.findValue(protoType.getSimpleName());
+            output.writeTag(tag, wireTypeFor(fieldType));
+            writeScalarValueNoTag(output, fieldType, value);
+            return;
+        }
+
+        if (schema.getType(protoType) instanceof EnumType) {
+            output.writeTag(tag, WIRETYPE_VARINT);
+            output.writeEnumNoTag(enumTag(protoType, value));
+            return;
+        }
+
+        // nested message
+        final MessageType messageType = (MessageType) 
schema.getType(protoType);
+        Objects.requireNonNull(messageType, String.format("Message type with 
name [%s] not found in the provided proto files", protoType));
+        final byte[] nested = serializeMessage(messageType, toRecord(value, 
protoType));
+        output.writeTag(tag, WIRETYPE_LENGTH_DELIMITED);
+        output.writeUInt32NoTag(nested.length);
+        output.writeRawBytes(nested);
+    }
+
+    private void writeMap(final CodedOutputStream output, final int tag, final 
ProtoType protoType, final Object value) throws IOException {
+        if (!(value instanceof final Map<?, ?> map)) {
+            throw new IOException(String.format("Expected a Map value for map 
field but received [%s]", value.getClass()));
+        }
+
+        final ProtoType keyType = protoType.getKeyType();
+        final ProtoType valueType = protoType.getValueType();
+
+        for (final Map.Entry<?, ?> entry : map.entrySet()) {
+            final ByteArrayOutputStream entryBytes = new 
ByteArrayOutputStream();
+            final CodedOutputStream entryOutput = 
CodedOutputStream.newInstance(entryBytes);
+
+            writeSingleValue(entryOutput, MAP_KEY_TAG, keyType, 
entry.getKey());

Review Comment:
   Yes, fixed. I also changed unknown enum values to throw IOException instead 
of IllegalStateException, so that the errors are reported in the same way in 
all places



##########
nifi-extension-bundles/nifi-protobuf-bundle/nifi-protobuf-services/src/main/java/org/apache/nifi/services/protobuf/StandardProtobufWriter.java:
##########
@@ -0,0 +1,356 @@
+/*
+ * 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.services.protobuf;
+
+import com.squareup.wire.schema.Schema;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnEnabled;
+import org.apache.nifi.components.AllowableValue;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.components.PropertyValue;
+import org.apache.nifi.context.PropertyContext;
+import org.apache.nifi.controller.AbstractControllerService;
+import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.controller.ControllerServiceInitializationContext;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.schema.access.SchemaNotFoundException;
+import org.apache.nifi.schemaregistry.services.MessageIndexWriter;
+import org.apache.nifi.schemaregistry.services.MessageName;
+import org.apache.nifi.schemaregistry.services.MessageNameResolver;
+import org.apache.nifi.schemaregistry.services.SchemaDefinition;
+import org.apache.nifi.schemaregistry.services.SchemaReferenceWriter;
+import org.apache.nifi.schemaregistry.services.SchemaRegistry;
+import org.apache.nifi.schemaregistry.services.StandardMessageNameFactory;
+import org.apache.nifi.schemaregistry.services.StandardSchemaDefinition;
+import org.apache.nifi.serialization.RecordSetWriter;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.serialization.SchemaRegistryService;
+import org.apache.nifi.serialization.SimpleRecordSchema;
+import org.apache.nifi.serialization.record.RecordSchema;
+import org.apache.nifi.serialization.record.SchemaIdentifier;
+import org.apache.nifi.services.protobuf.schema.ProtoSchemaParser;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+
+import static 
org.apache.nifi.expression.ExpressionLanguageScope.FLOWFILE_ATTRIBUTES;
+import static 
org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY;
+import static 
org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_BRANCH_NAME;
+import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_NAME;

Review Comment:
   Yes, done



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to