Search in sources :

Example 16 with Descriptor

use of org.infinispan.protostream.descriptors.Descriptor in project protostream by infinispan.

the class ProtobufParserTest method testTagHandler.

@Test
public void testTagHandler() throws Exception {
    ImmutableSerializationContext ctx = createContext();
    User user = new User();
    user.setId(1);
    user.setName("John");
    user.setSurname("Batman");
    user.setGender(User.Gender.MALE);
    user.setAccountIds(new HashSet<>(Arrays.asList(1, 3)));
    user.setAddresses(Arrays.asList(new Address("Old Street", "XYZ42", -12), new Address("Bond Street", "W23", 2)));
    byte[] userBytes = ProtobufUtil.toWrappedByteArray(ctx, user);
    Descriptor wrapperDescriptor = ctx.getMessageDescriptor(WrappedMessage.PROTOBUF_TYPE_NAME);
    TagHandler messageHandler = new TagHandler() {

        @Override
        public void onStart(GenericDescriptor descriptor) {
            log.debugf("\tonStart %s", descriptor);
        }

        @Override
        public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) {
            log.debugf("\tonTag %d %s %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null, tagValue);
        }

        @Override
        public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
            log.debugf("\tonStartNested %d %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null);
        }

        @Override
        public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
            log.debugf("\tonEndNested %d %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null);
        }

        @Override
        public void onEnd() {
            log.debug("\tonEnd");
        }
    };
    TagHandler wrapperHandler = new TagHandler() {

        private Integer typeId;

        private String typeName;

        private byte[] wrappedMessage;

        private Integer wrappedEnum;

        private GenericDescriptor getDescriptor() {
            return typeId != null ? ctx.getDescriptorByTypeId(typeId) : ctx.getDescriptorByName(typeName);
        }

        @Override
        public void onStart(GenericDescriptor descriptor) {
            log.debugf("onStart %s", descriptor);
        }

        @Override
        public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) {
            log.debugf("onTag %d %s %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null, tagValue);
            if (fieldDescriptor == null) {
                // ignore unknown fields
                return;
            }
            switch(fieldNumber) {
                case WrappedMessage.WRAPPED_TYPE_ID:
                    typeId = (Integer) tagValue;
                    break;
                case WrappedMessage.WRAPPED_TYPE_NAME:
                    typeName = (String) tagValue;
                    break;
                case WrappedMessage.WRAPPED_MESSAGE:
                    wrappedMessage = (byte[]) tagValue;
                    break;
                case WrappedMessage.WRAPPED_ENUM:
                    wrappedEnum = (Integer) tagValue;
                    break;
                case WrappedMessage.WRAPPED_DOUBLE:
                case WrappedMessage.WRAPPED_FLOAT:
                case WrappedMessage.WRAPPED_INT64:
                case WrappedMessage.WRAPPED_UINT64:
                case WrappedMessage.WRAPPED_INT32:
                case WrappedMessage.WRAPPED_FIXED64:
                case WrappedMessage.WRAPPED_FIXED32:
                case WrappedMessage.WRAPPED_BOOL:
                case WrappedMessage.WRAPPED_STRING:
                case WrappedMessage.WRAPPED_BYTES:
                case WrappedMessage.WRAPPED_UINT32:
                case WrappedMessage.WRAPPED_SFIXED32:
                case WrappedMessage.WRAPPED_SFIXED64:
                case WrappedMessage.WRAPPED_SINT32:
                case WrappedMessage.WRAPPED_SINT64:
                    messageHandler.onStart(null);
                    messageHandler.onTag(fieldNumber, fieldDescriptor, tagValue);
                    messageHandler.onEnd();
                    break;
            }
        }

        @Override
        public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
            log.debugf("onStartNested %d %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null);
        }

        @Override
        public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) {
            log.debugf("onEndNested %d %s", fieldNumber, fieldDescriptor != null ? fieldDescriptor.getFullName() : null);
        }

        @Override
        public void onEnd() {
            if (wrappedEnum != null) {
                EnumDescriptor enumDescriptor = (EnumDescriptor) getDescriptor();
                String enumConstantName = enumDescriptor.findValueByNumber(wrappedEnum).getName();
                FieldDescriptor fd = wrapperDescriptor.findFieldByNumber(WrappedMessage.WRAPPED_ENUM);
                messageHandler.onStart(enumDescriptor);
                messageHandler.onTag(WrappedMessage.WRAPPED_ENUM, fd, enumConstantName);
                messageHandler.onEnd();
            } else if (wrappedMessage != null) {
                try {
                    Descriptor messageDescriptor = (Descriptor) getDescriptor();
                    ProtobufParser.INSTANCE.parse(messageHandler, messageDescriptor, wrappedMessage);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            log.debug("onEnd");
        }
    };
    ProtobufParser.INSTANCE.parse(wrapperHandler, wrapperDescriptor, userBytes);
}
Also used : User(org.infinispan.protostream.domain.User) Address(org.infinispan.protostream.domain.Address) GenericDescriptor(org.infinispan.protostream.descriptors.GenericDescriptor) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) IOException(java.io.IOException) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) GenericDescriptor(org.infinispan.protostream.descriptors.GenericDescriptor) Descriptor(org.infinispan.protostream.descriptors.Descriptor) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) Test(org.junit.Test) AbstractProtoStreamTest(org.infinispan.protostream.test.AbstractProtoStreamTest)

Example 17 with Descriptor

use of org.infinispan.protostream.descriptors.Descriptor in project kogito-runtimes by kiegroup.

the class AbstractMarshallerGenerator method generate.

public List<CompilationUnit> generate(FileDescriptorSource proto) throws IOException {
    List<CompilationUnit> units = new ArrayList<>();
    TemplatedGenerator generator = TemplatedGenerator.builder().withFallbackContext(JavaKogitoBuildContext.CONTEXT_NAME).withTemplateBasePath(TEMPLATE_PERSISTENCE_FOLDER).build(context, "MessageMarshaller");
    Predicate<String> typeExclusions = ExclusionTypeUtils.createTypeExclusions();
    // filter types that don't require to create a marshaller
    Predicate<Descriptor> packagePredicate = (msg) -> !msg.getFileDescriptor().getPackage().equals("kogito");
    Predicate<Descriptor> jacksonPredicate = (msg) -> !typeExclusions.test(packageFromOption(msg.getFileDescriptor(), msg) + "." + msg.getName());
    Predicate<Descriptor> predicate = packagePredicate.and(jacksonPredicate);
    CompilationUnit parsedClazzFile = generator.compilationUnitOrThrow();
    SerializationContext serializationContext = new SerializationContextImpl(Configuration.builder().build());
    FileDescriptorSource kogitoTypesDescriptor = new FileDescriptorSource().addProtoFile("kogito-types.proto", context.getClassLoader().getResourceAsStream("META-INF/kogito-types.proto"));
    serializationContext.registerProtoFiles(kogitoTypesDescriptor);
    serializationContext.registerProtoFiles(proto);
    Map<String, FileDescriptor> descriptors = serializationContext.getFileDescriptors();
    for (Entry<String, FileDescriptor> entry : descriptors.entrySet()) {
        FileDescriptor d = entry.getValue();
        List<Descriptor> messages = d.getMessageTypes().stream().filter(predicate).collect(Collectors.toList());
        for (Descriptor msg : messages) {
            CompilationUnit clazzFile = parsedClazzFile.clone();
            units.add(clazzFile);
            String javaType = packageFromOption(d, msg) + "." + msg.getName();
            clazzFile.setPackageDeclaration(d.getPackage());
            ClassOrInterfaceDeclaration clazz = clazzFile.findFirst(ClassOrInterfaceDeclaration.class, sl -> true).orElseThrow(() -> new InvalidTemplateException(generator, "No class found"));
            clazz.setName(msg.getName() + "MessageMarshaller");
            clazz.getImplementedTypes(0).setTypeArguments(NodeList.nodeList(new ClassOrInterfaceType(null, javaType)));
            MethodDeclaration getJavaClassMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("getJavaClass")).orElseThrow(() -> new InvalidTemplateException(generator, "No getJavaClass method found"));
            getJavaClassMethod.setType(new ClassOrInterfaceType(null, new SimpleName(Class.class.getName()), NodeList.nodeList(new ClassOrInterfaceType(null, javaType))));
            BlockStmt getJavaClassMethodBody = new BlockStmt();
            getJavaClassMethodBody.addStatement(new ReturnStmt(new NameExpr(javaType + ".class")));
            getJavaClassMethod.setBody(getJavaClassMethodBody);
            MethodDeclaration getTypeNameMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("getTypeName")).orElseThrow(() -> new InvalidTemplateException(generator, "No getTypeName method found"));
            BlockStmt getTypeNameMethodBody = new BlockStmt();
            getTypeNameMethodBody.addStatement(new ReturnStmt(new StringLiteralExpr(msg.getFullName())));
            getTypeNameMethod.setBody(getTypeNameMethodBody);
            MethodDeclaration readFromMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("readFrom")).orElseThrow(() -> new InvalidTemplateException(generator, "No readFrom method found"));
            readFromMethod.setType(javaType);
            readFromMethod.setBody(new BlockStmt());
            MethodDeclaration writeToMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("writeTo")).orElseThrow(() -> new InvalidTemplateException(generator, "No writeTo method found"));
            writeToMethod.getParameter(1).setType(javaType);
            writeToMethod.setBody(new BlockStmt());
            ClassOrInterfaceType classType = new ClassOrInterfaceType(null, javaType);
            // read method
            VariableDeclarationExpr instance = new VariableDeclarationExpr(new VariableDeclarator(classType, "value", new ObjectCreationExpr(null, classType, NodeList.nodeList())));
            readFromMethod.getBody().ifPresent(b -> b.addStatement(instance));
            for (FieldDescriptor field : msg.getFields()) {
                String protoStreamMethodType = protoStreamMethodType(field.getTypeName());
                Expression write = null;
                Expression read = null;
                if (protoStreamMethodType != null && !field.isRepeated()) {
                    // has a mapped type
                    read = new MethodCallExpr(new NameExpr("reader"), "read" + protoStreamMethodType).addArgument(new StringLiteralExpr(field.getName()));
                    String accessor = protoStreamMethodType.equals("Boolean") ? "is" : "get";
                    write = new MethodCallExpr(new NameExpr("writer"), "write" + protoStreamMethodType).addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), accessor + StringUtils.ucFirst(field.getName())));
                } else {
                    // custom types
                    String customTypeName = javaTypeForMessage(d, field.getTypeName(), serializationContext);
                    if (field.isRepeated()) {
                        if (null == customTypeName || customTypeName.isEmpty()) {
                            customTypeName = primaryTypeClassName(field.getTypeName());
                        }
                        String writeMethod;
                        if (isArray(javaType, field)) {
                            writeMethod = "writeArray";
                            read = new MethodCallExpr(new NameExpr("reader"), "readArray").addArgument(new StringLiteralExpr(field.getName())).addArgument(new NameExpr(customTypeName + ".class"));
                        } else {
                            writeMethod = "writeCollection";
                            read = new MethodCallExpr(new NameExpr("reader"), "readCollection").addArgument(new StringLiteralExpr(field.getName())).addArgument(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ArrayList.class.getCanonicalName()), NodeList.nodeList())).addArgument(new NameExpr(customTypeName + ".class"));
                        }
                        write = new MethodCallExpr(new NameExpr("writer"), writeMethod).addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), "get" + StringUtils.ucFirst(field.getName()))).addArgument(new NameExpr(customTypeName + ".class"));
                    } else {
                        read = new MethodCallExpr(new NameExpr("reader"), "readObject").addArgument(new StringLiteralExpr(field.getName())).addArgument(new NameExpr(customTypeName + ".class"));
                        write = new MethodCallExpr(new NameExpr("writer"), "writeObject").addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), "get" + StringUtils.ucFirst(field.getName()))).addArgument(new NameExpr(customTypeName + ".class"));
                    }
                    if (customTypeName.equals(Serializable.class.getName())) {
                        String fieldClazz = (String) field.getOptionByName(KOGITO_JAVA_CLASS_OPTION);
                        if (fieldClazz == null) {
                            throw new IllegalArgumentException(format("Serializable proto field '%s' is missing value for option %s", field.getName(), KOGITO_JAVA_CLASS_OPTION));
                        } else {
                            read = new CastExpr().setExpression(new EnclosedExpr(read)).setType(fieldClazz);
                        }
                    }
                }
                MethodCallExpr setter = new MethodCallExpr(new NameExpr("value"), "set" + StringUtils.ucFirst(field.getName())).addArgument(read);
                readFromMethod.getBody().ifPresent(b -> b.addStatement(setter));
                // write method
                writeToMethod.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!")).addStatement(write);
            }
            readFromMethod.getBody().ifPresent(b -> b.addStatement(new ReturnStmt(new NameExpr("value"))));
            clazz.getMembers().sort(new BodyDeclarationComparator());
        }
        for (EnumDescriptor msg : d.getEnumTypes()) {
            CompilationUnit compilationUnit = new CompilationUnit();
            units.add(compilationUnit);
            String javaType = packageFromOption(d, msg) + "." + msg.getName();
            ClassOrInterfaceDeclaration classDeclaration = compilationUnit.setPackageDeclaration(d.getPackage()).addClass(msg.getName() + "EnumMarshaller").setPublic(true);
            classDeclaration.addImplementedType(EnumMarshaller.class).getImplementedTypes(0).setTypeArguments(NodeList.nodeList(new ClassOrInterfaceType(null, javaType)));
            classDeclaration.addMethod("getTypeName", PUBLIC).setType(String.class).setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(msg.getFullName()))));
            classDeclaration.addMethod("getJavaClass", PUBLIC).setType(new ClassOrInterfaceType(null, new SimpleName(Class.class.getName()), NodeList.nodeList(new ClassOrInterfaceType(null, javaType)))).setBody(new BlockStmt().addStatement(new ReturnStmt(new ClassExpr(new ClassOrInterfaceType(null, javaType)))));
            BlockStmt encodeBlock = new BlockStmt().addStatement(new IfStmt(new BinaryExpr(new NullLiteralExpr(), new NameExpr(STATE_PARAM), EQUALS), new ThrowStmt(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, IllegalArgumentException.class.getName()), NodeList.nodeList(new StringLiteralExpr("Invalid value provided to enum")))), null)).addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(STATE_PARAM), "ordinal")));
            classDeclaration.addMethod("encode", PUBLIC).setType("int").addParameter(javaType, STATE_PARAM).setBody(encodeBlock);
            MethodDeclaration decode = classDeclaration.addMethod("decode", PUBLIC).setType(javaType).addParameter("int", "value");
            SwitchStmt decodeSwitch = new SwitchStmt().setSelector(new NameExpr("value"));
            msg.getValues().forEach(v -> {
                SwitchEntry dEntry = new SwitchEntry();
                dEntry.getLabels().add(new IntegerLiteralExpr(v.getNumber()));
                dEntry.addStatement(new ReturnStmt(new NameExpr(javaType + "." + v.getName())));
                decodeSwitch.getEntries().add(dEntry);
            });
            decodeSwitch.getEntries().add(new SwitchEntry().addStatement(new ThrowStmt(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, IllegalArgumentException.class.getName()), NodeList.nodeList(new StringLiteralExpr("Invalid value provided to enum"))))));
            decode.setBody(new BlockStmt().addStatement(decodeSwitch));
        }
    }
    return units;
}
Also used : TemplatedGenerator(org.kie.kogito.codegen.api.template.TemplatedGenerator) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) EQUALS(com.github.javaparser.ast.expr.BinaryExpr.Operator.EQUALS) ExclusionTypeUtils(org.kie.kogito.codegen.process.persistence.ExclusionTypeUtils) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) SerializationContextImpl(org.infinispan.protostream.impl.SerializationContextImpl) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) NodeList(com.github.javaparser.ast.NodeList) SimpleName(com.github.javaparser.ast.expr.SimpleName) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) Predicate(java.util.function.Predicate) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) KOGITO_JAVA_CLASS_OPTION(org.kie.kogito.codegen.process.persistence.proto.ProtoGenerator.KOGITO_JAVA_CLASS_OPTION) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) String.format(java.lang.String.format) Serializable(java.io.Serializable) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) ThrowStmt(com.github.javaparser.ast.stmt.ThrowStmt) List(java.util.List) Entry(java.util.Map.Entry) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) SwitchEntry(com.github.javaparser.ast.stmt.SwitchEntry) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) EnumMarshaller(org.infinispan.protostream.EnumMarshaller) Descriptor(org.infinispan.protostream.descriptors.Descriptor) BodyDeclarationComparator(org.kie.kogito.codegen.core.BodyDeclarationComparator) CastExpr(com.github.javaparser.ast.expr.CastExpr) PUBLIC(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) Option(org.infinispan.protostream.descriptors.Option) SwitchStmt(com.github.javaparser.ast.stmt.SwitchStmt) NoSuchElementException(java.util.NoSuchElementException) FileDescriptorSource(org.infinispan.protostream.FileDescriptorSource) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) InvalidTemplateException(org.kie.kogito.codegen.api.template.InvalidTemplateException) JavaKogitoBuildContext(org.kie.kogito.codegen.api.context.impl.JavaKogitoBuildContext) TemplatedGenerator(org.kie.kogito.codegen.api.template.TemplatedGenerator) IOException(java.io.IOException) NameExpr(com.github.javaparser.ast.expr.NameExpr) IfStmt(com.github.javaparser.ast.stmt.IfStmt) StringUtils(org.drools.util.StringUtils) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Configuration(org.infinispan.protostream.config.Configuration) Collections(java.util.Collections) SerializationContext(org.infinispan.protostream.SerializationContext) IntegerLiteralExpr(com.github.javaparser.ast.expr.IntegerLiteralExpr) SerializationContext(org.infinispan.protostream.SerializationContext) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) IntegerLiteralExpr(com.github.javaparser.ast.expr.IntegerLiteralExpr) Serializable(java.io.Serializable) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) SimpleName(com.github.javaparser.ast.expr.SimpleName) ArrayList(java.util.ArrayList) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) SerializationContextImpl(org.infinispan.protostream.impl.SerializationContextImpl) CastExpr(com.github.javaparser.ast.expr.CastExpr) BodyDeclarationComparator(org.kie.kogito.codegen.core.BodyDeclarationComparator) SwitchEntry(com.github.javaparser.ast.stmt.SwitchEntry) FileDescriptorSource(org.infinispan.protostream.FileDescriptorSource) CompilationUnit(com.github.javaparser.ast.CompilationUnit) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) SwitchStmt(com.github.javaparser.ast.stmt.SwitchStmt) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) InvalidTemplateException(org.kie.kogito.codegen.api.template.InvalidTemplateException) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) IfStmt(com.github.javaparser.ast.stmt.IfStmt) Expression(com.github.javaparser.ast.expr.Expression) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) Descriptor(org.infinispan.protostream.descriptors.Descriptor) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) ThrowStmt(com.github.javaparser.ast.stmt.ThrowStmt) NoSuchElementException(java.util.NoSuchElementException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 18 with Descriptor

use of org.infinispan.protostream.descriptors.Descriptor in project kogito-apps by kiegroup.

the class ProtobufService method registerProtoBufferType.

public void registerProtoBufferType(String content) throws ProtobufValidationException {
    LOGGER.debug("Registering new ProtoBuffer file with content: \n{}", content);
    content = content.replaceAll("kogito.Date", "string");
    SerializationContext ctx = createSerializationContext(kogitoDescriptors, FileDescriptorSource.fromString(DOMAIN_MODEL_PROTO_NAME, content));
    FileDescriptor desc = ctx.getFileDescriptors().get(DOMAIN_MODEL_PROTO_NAME);
    Option processIdOption = desc.getOption("kogito_id");
    if (processIdOption == null || processIdOption.getValue() == null) {
        throw new ProtobufValidationException("Missing marker for process id in proto file, please add option kogito_id=\"processid\"");
    }
    String processId = (String) processIdOption.getValue();
    Option model = desc.getOption("kogito_model");
    if (model == null || model.getValue() == null) {
        throw new ProtobufValidationException("Missing marker for main message type in proto file, please add option kogito_model=\"messagename\"");
    }
    String messageName = (String) model.getValue();
    String fullTypeName = desc.getPackage() == null ? messageName : desc.getPackage() + "." + messageName;
    Descriptor descriptor;
    try {
        descriptor = ctx.getMessageDescriptor(fullTypeName);
    } catch (IllegalArgumentException ex) {
        throw new ProtobufValidationException(format("Could not find message with name: %s in proto file, e, please review option kogito_model", fullTypeName));
    }
    validateDescriptorField(messageName, descriptor, Constants.KOGITO_DOMAIN_ATTRIBUTE);
    Map<String, EntityIndexDescriptor> entityIndexes = desc.getMessageTypes().stream().map(t -> t.<EntityIndexDescriptor>getProcessedAnnotation(INDEXED_ANNOTATION)).filter(Objects::nonNull).collect(toMap(EntityIndexDescriptor::getName, Function.identity()));
    Map<String, EntityIndexDescriptor> entityIndexedDescriptors = createEntityIndexDescriptors(desc, entityIndexes);
    try {
        schemaEvent.fire(new SchemaRegisteredEvent(new SchemaDescriptor(processId + ".proto", content, entityIndexedDescriptors, new ProcessDescriptor(processId, fullTypeName)), SCHEMA_TYPE));
    } catch (RuntimeException ex) {
        throw new ProtobufValidationException(ex.getMessage(), ex);
    }
    domainModelEvent.fire(new FileDescriptorRegisteredEvent(desc));
}
Also used : SerializationContext(org.infinispan.protostream.SerializationContext) SchemaDescriptor(org.kie.kogito.persistence.api.schema.SchemaDescriptor) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) SchemaRegisteredEvent(org.kie.kogito.persistence.api.schema.SchemaRegisteredEvent) Descriptor(org.infinispan.protostream.descriptors.Descriptor) SchemaDescriptor(org.kie.kogito.persistence.api.schema.SchemaDescriptor) EntityIndexDescriptor(org.kie.kogito.persistence.api.schema.EntityIndexDescriptor) ProcessDescriptor(org.kie.kogito.persistence.api.schema.ProcessDescriptor) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) Option(org.infinispan.protostream.descriptors.Option) ProcessDescriptor(org.kie.kogito.persistence.api.schema.ProcessDescriptor) EntityIndexDescriptor(org.kie.kogito.persistence.api.schema.EntityIndexDescriptor)

Example 19 with Descriptor

use of org.infinispan.protostream.descriptors.Descriptor in project kogito-apps by kiegroup.

the class ProtoDomainModelProducer method onFileDescriptorRegistered.

public void onFileDescriptorRegistered(@Observes FileDescriptorRegisteredEvent event) {
    FileDescriptor descriptor = event.getDescriptor();
    String rootMessage = (String) descriptor.getOption("kogito_model").getValue();
    String processId = (String) descriptor.getOption("kogito_id").getValue();
    Map<String, Descriptor> map = descriptor.getMessageTypes().stream().collect(toMap(AnnotatedDescriptorImpl::getName, desc -> desc));
    Descriptor rootDescriptor = map.remove(rootMessage);
    DomainDescriptor domain = new DomainDescriptorMapper().apply(rootDescriptor);
    List<DomainDescriptor> additionalTypes = map.values().stream().map(desc -> new DomainDescriptorMapper().apply(desc)).collect(toList());
    domainEvent.fire(new DomainModelRegisteredEvent(processId, domain, additionalTypes));
}
Also used : Event(javax.enterprise.event.Event) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Descriptor(org.infinispan.protostream.descriptors.Descriptor) Function(java.util.function.Function) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) Inject(javax.inject.Inject) AnnotatedDescriptorImpl(org.infinispan.protostream.impl.AnnotatedDescriptorImpl) AttributeDescriptor(org.kie.kogito.persistence.api.proto.AttributeDescriptor) FileDescriptorRegisteredEvent(org.kie.kogito.persistence.protobuf.FileDescriptorRegisteredEvent) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Collectors.toMap(java.util.stream.Collectors.toMap) DomainDescriptor(org.kie.kogito.persistence.api.proto.DomainDescriptor) Map(java.util.Map) Observes(javax.enterprise.event.Observes) DomainModelRegisteredEvent(org.kie.kogito.persistence.api.proto.DomainModelRegisteredEvent) ApplicationScoped(javax.enterprise.context.ApplicationScoped) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor) Descriptor(org.infinispan.protostream.descriptors.Descriptor) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) AttributeDescriptor(org.kie.kogito.persistence.api.proto.AttributeDescriptor) DomainDescriptor(org.kie.kogito.persistence.api.proto.DomainDescriptor) DomainModelRegisteredEvent(org.kie.kogito.persistence.api.proto.DomainModelRegisteredEvent) DomainDescriptor(org.kie.kogito.persistence.api.proto.DomainDescriptor) FileDescriptor(org.infinispan.protostream.descriptors.FileDescriptor)

Example 20 with Descriptor

use of org.infinispan.protostream.descriptors.Descriptor in project infinispan by infinispan.

the class ProtobufPropertyHelper method hasProperty.

@Override
public boolean hasProperty(Descriptor entityType, String[] propertyPath) {
    Descriptor messageDescriptor = entityType;
    int i = 0;
    for (String p : propertyPath) {
        i++;
        FieldDescriptor field = messageDescriptor.findFieldByName(p);
        if (field == null) {
            return false;
        }
        if (field.getJavaType() == JavaType.MESSAGE) {
            messageDescriptor = field.getMessageType();
        } else {
            break;
        }
    }
    return i == propertyPath.length;
}
Also used : EnumValueDescriptor(org.infinispan.protostream.descriptors.EnumValueDescriptor) EnumDescriptor(org.infinispan.protostream.descriptors.EnumDescriptor) Descriptor(org.infinispan.protostream.descriptors.Descriptor) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor) FieldDescriptor(org.infinispan.protostream.descriptors.FieldDescriptor)

Aggregations

Descriptor (org.infinispan.protostream.descriptors.Descriptor)28 FieldDescriptor (org.infinispan.protostream.descriptors.FieldDescriptor)24 EnumDescriptor (org.infinispan.protostream.descriptors.EnumDescriptor)19 FileDescriptor (org.infinispan.protostream.descriptors.FileDescriptor)13 GenericDescriptor (org.infinispan.protostream.descriptors.GenericDescriptor)11 List (java.util.List)9 Test (org.junit.Test)8 Map (java.util.Map)7 FileDescriptorSource (org.infinispan.protostream.FileDescriptorSource)7 Configuration (org.infinispan.protostream.config.Configuration)7 EnumValueDescriptor (org.infinispan.protostream.descriptors.EnumValueDescriptor)7 ExtendDescriptor (org.infinispan.protostream.descriptors.ExtendDescriptor)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 AnnotationElement (org.infinispan.protostream.descriptors.AnnotationElement)5 IOException (java.io.IOException)4 Objects (java.util.Objects)3 Set (java.util.Set)3 Function (java.util.function.Function)3 Predicate (java.util.function.Predicate)3