Search in sources :

Example 1 with BindTransform

use of com.abubusoft.kripton.processor.bind.transform.BindTransform in project kripton by xcesco.

the class BindEntityBuilder method parse.

public static BindEntity parse(final BindModel model, TypeElement element) {
    final Elements elementUtils = BaseProcessor.elementUtils;
    final InnerCounter counterPropertyInValue = new InnerCounter();
    final Converter<String, String> typeNameConverter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
    final TypeElement beanElement = element;
    final BindEntity currentEntity = new BindEntity(beanElement.getSimpleName().toString(), beanElement, AnnotationUtility.buildAnnotationList(element, classAnnotationFilter));
    // tag typeName
    String tagName = AnnotationUtility.extractAsString(beanElement, BindType.class, AnnotationAttributeType.VALUE);
    if (StringUtils.hasText(tagName)) {
        currentEntity.xmlInfo.label = tagName;
    } else {
        currentEntity.xmlInfo.label = typeNameConverter.convert(beanElement.getSimpleName().toString());
    }
    final boolean bindAllFields = AnnotationUtility.getAnnotationAttributeAsBoolean(currentEntity, BindType.class, AnnotationAttributeType.ALL_FIELDS, Boolean.TRUE);
    PropertyUtility.buildProperties(elementUtils, currentEntity, new PropertyFactory<BindEntity, BindProperty>() {

        @Override
        public BindProperty createProperty(BindEntity entity, Element propertyElement) {
            return new BindProperty(currentEntity, propertyElement, AnnotationUtility.buildAnnotationList(propertyElement));
        }
    }, propertyAnnotationFilter, new PropertyCreatedListener<BindEntity, BindProperty>() {

        @Override
        public boolean onProperty(BindEntity entity, BindProperty property) {
            // if we are build Map, the model are not null
            boolean contextExternal = (model == null);
            // if @BindDisabled is present, exit immediately
            if (property.hasAnnotation(BindDisabled.class)) {
                if (bindAllFields) {
                    return false;
                } else {
                    throw new InvalidDefinition(String.format("In class '%s', @%s can not be used with @%s(allField=false)", property.getParent().getElement().asType().toString(), BindDisabled.class.getSimpleName(), BindType.class.getSimpleName()));
                }
            }
            boolean enabled = bindAllFields;
            ModelAnnotation annotationBind = property.getAnnotation(Bind.class);
            enabled = enabled || (annotationBind != null && AnnotationUtility.extractAsBoolean(property, annotationBind, AnnotationAttributeType.ENABLED));
            // we have to analyze in every case.
            if (!enabled && !contextExternal) {
                return false;
            }
            ModelAnnotation annotationBindXml = property.getAnnotation(BindXml.class);
            property.order = 0;
            property.mapKeyName = Bind.MAP_KEY_DEFAULT;
            property.mapValueName = Bind.MAP_VALUE_DEFAULT;
            // label for item and collection elements are the same for
            // default
            property.label = typeNameConverter.convert(property.getName());
            property.xmlInfo.labelItem = property.label;
            property.xmlInfo.wrappedCollection = false;
            property.xmlInfo.xmlType = XmlType.valueOf(XmlType.TAG.toString());
            property.xmlInfo.mapEntryType = MapEntryType.valueOf(MapEntryType.TAG.toString());
            // check if there is an adapter
            if ((property.getAnnotation(BindAdapter.class) != null)) {
                BindTransform transform = BindTransformer.lookup(TypeUtility.typeName(property.typeAdapter.dataType));
                if (!transform.isTypeAdapterSupported()) {
                    String msg = String.format("In class '%s', property '%s' uses @BindAdapter with unsupported 'dataType' '%s'", beanElement.asType().toString(), property.getName(), property.typeAdapter.dataType);
                    throw (new IncompatibleAnnotationException(msg));
                }
                if (property.getPropertyType().isPrimitive()) {
                    String msg = String.format("In class '%s', property '%s' is primitive of type '%s' and it can not be annotated with @BindAdapter", beanElement.asType().toString(), property.getName(), property.getPropertyType().getTypeName());
                    throw (new IncompatibleAnnotationException(msg));
                }
            }
            // @Bind management
            if (annotationBind != null) {
                int order = AnnotationUtility.extractAsInt(property.getElement(), Bind.class, AnnotationAttributeType.ORDER);
                property.order = order;
                String tempName = AnnotationUtility.extractAsString(property.getElement(), Bind.class, AnnotationAttributeType.VALUE);
                if (StringUtils.hasText(tempName)) {
                    // for the moment are the same
                    property.label = tempName;
                    property.xmlInfo.labelItem = property.label;
                }
                // map info
                String mapKeyName = AnnotationUtility.extractAsString(property.getElement(), Bind.class, AnnotationAttributeType.MAP_KEY_NAME);
                if (StringUtils.hasText(mapKeyName))
                    property.mapKeyName = mapKeyName;
                String mapValueName = AnnotationUtility.extractAsString(property.getElement(), Bind.class, AnnotationAttributeType.MAP_VALUE_NAME);
                if (StringUtils.hasText(mapValueName))
                    property.mapValueName = mapValueName;
            }
            // @BindXml management
            if (annotationBindXml != null) {
                String mapEntryType = AnnotationUtility.extractAsEnumerationValue(property.getElement(), BindXml.class, AnnotationAttributeType.MAP_ENTRY_TYPE);
                if (StringUtils.hasText(mapEntryType))
                    property.xmlInfo.mapEntryType = MapEntryType.valueOf(mapEntryType);
                // define element tag typeName
                String tempElementName = AnnotationUtility.extractAsString(property.getElement(), BindXml.class, AnnotationAttributeType.XML_ELEMENT_TAG);
                if (StringUtils.hasText(tempElementName)) {
                    property.xmlInfo.labelItem = tempElementName;
                    property.xmlInfo.wrappedCollection = true;
                }
                String xmlType = AnnotationUtility.extractAsEnumerationValue(property.getElement(), BindXml.class, AnnotationAttributeType.XML_TYPE);
                if (StringUtils.hasText(xmlType))
                    property.xmlInfo.xmlType = XmlType.valueOf(xmlType);
            }
            if (property.xmlInfo.xmlType == XmlType.ATTRIBUTE) {
                BindTransform transform = BindTransformer.lookup(property.getPropertyType().getTypeName());
                // check if property is a array
                if (property.isBindedArray() && !(transform instanceof ByteArrayBindTransform)) {
                    String msg = String.format("In class '%s', property '%s' is an array and it can not be mapped in a xml attribute", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                // check if property is a collection
                if (property.isBindedCollection()) {
                    String msg = String.format("In class '%s', property '%s' is a collection and it can not be mapped in a xml attribute", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                // check if property is a map
                if (property.isBindedMap()) {
                    String msg = String.format("In class '%s', property '%s' is an map and it can not be mapped in a xml attribute", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                if (transform != null && transform instanceof ObjectBindTransform) {
                    String msg = String.format("In class '%s', property '%s' is an object and it can not be mapped in a xml attribute", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
            }
            if (property.xmlInfo.xmlType == XmlType.VALUE || property.xmlInfo.xmlType == XmlType.VALUE_CDATA) {
                counterPropertyInValue.inc();
                BindTransform transform = BindTransformer.lookup(property.getPropertyType().getTypeName());
                // check if property is a array
                if (property.isBindedArray() && !(transform instanceof ByteArrayBindTransform)) {
                    String msg = String.format("In class '%s', property '%s' is an array and it can not be mapped in a xml value", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                // check if property is a collection
                if (property.isBindedCollection()) {
                    String msg = String.format("In class '%s', property '%s' is a collection and it can not be mapped in a xml value", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                // check if property is a map
                if (property.isBindedMap()) {
                    String msg = String.format("In class '%s', property '%s' is a map and it can not be mapped in a xml value", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
                if (transform != null && transform instanceof ObjectBindTransform) {
                    String msg = String.format("In class '%s', property '%s' is an object and it can not be mapped in a xml value", beanElement.asType().toString(), property.getName());
                    throw (new IncompatibleAttributesInAnnotationException(msg));
                }
            }
            if (counterPropertyInValue.value() > 1) {
                String msg = String.format("In class '%s', property '%s' and other properties are mapped in a xml value, but only one property for class can be a xml value", beanElement.asType().toString(), property.getName());
                throw (new IncompatibleAttributesInAnnotationException(msg));
            }
            property.bindedObject = BindTransformer.isBindedObject(property);
            // set inCollection to true, permits this.
            if (property.bindedObject && contextExternal) {
                property.inCollection = true;
            }
            return true;
        }
    });
    // if we don't have model, we dont save bean definition
    if (model != null) {
        model.entityAdd(currentEntity);
    }
    return currentEntity;
}
Also used : Bind(com.abubusoft.kripton.annotation.Bind) ObjectBindTransform(com.abubusoft.kripton.processor.bind.transform.ObjectBindTransform) BindAdapter(com.abubusoft.kripton.annotation.BindAdapter) BindTransform(com.abubusoft.kripton.processor.bind.transform.BindTransform) ObjectBindTransform(com.abubusoft.kripton.processor.bind.transform.ObjectBindTransform) ByteArrayBindTransform(com.abubusoft.kripton.processor.bind.transform.ByteArrayBindTransform) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ByteArrayBindTransform(com.abubusoft.kripton.processor.bind.transform.ByteArrayBindTransform) Elements(javax.lang.model.util.Elements) BindType(com.abubusoft.kripton.annotation.BindType) IncompatibleAttributesInAnnotationException(com.abubusoft.kripton.processor.exceptions.IncompatibleAttributesInAnnotationException) BindEntity(com.abubusoft.kripton.processor.bind.model.BindEntity) ModelAnnotation(com.abubusoft.kripton.processor.core.ModelAnnotation) InvalidDefinition(com.abubusoft.kripton.processor.exceptions.InvalidDefinition) BindDisabled(com.abubusoft.kripton.annotation.BindDisabled) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty) IncompatibleAnnotationException(com.abubusoft.kripton.processor.exceptions.IncompatibleAnnotationException) BindXml(com.abubusoft.kripton.annotation.BindXml)

Example 2 with BindTransform

use of com.abubusoft.kripton.processor.bind.transform.BindTransform in project kripton by xcesco.

the class ManagedPropertyPersistenceHelper method generateParamParser.

public static void generateParamParser(BindTypeContext context, String methodName, TypeName parameterTypeName, PersistType persistType) {
    methodName = SQLiteDaoDefinition.PARAM_PARSER_PREFIX + methodName;
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName).addJavadoc("for param $L parsing\n", methodName).returns(parameterTypeName);
    methodBuilder.addModifiers(context.modifiers);
    switch(persistType) {
        case STRING:
            methodBuilder.addParameter(ParameterSpec.builder(className(String.class), "input").build());
            break;
        case BYTE:
            methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(Byte.TYPE), "input").build());
            break;
    }
    methodBuilder.beginControlFlow("if (input==null)");
    methodBuilder.addStatement("return null");
    methodBuilder.endControlFlow();
    methodBuilder.addStatement("$T context=$T.jsonBind()", KriptonJsonContext.class, KriptonBinder.class);
    methodBuilder.beginControlFlow("try ($T wrapper=context.createParser(input))", JacksonWrapperParser.class);
    methodBuilder.addStatement("$T jacksonParser=wrapper.jacksonParser", JsonParser.class);
    methodBuilder.addCode("// START_OBJECT\n");
    methodBuilder.addStatement("jacksonParser.nextToken()");
    methodBuilder.addCode("// value of \"element\"\n");
    methodBuilder.addStatement("jacksonParser.nextValue()");
    String parserName = "jacksonParser";
    BindTransform bindTransform = BindTransformer.lookup(parameterTypeName);
    methodBuilder.addStatement("$T result=null", parameterTypeName);
    BindProperty property = BindProperty.builder(parameterTypeName).inCollection(false).elementName(DEFAULT_FIELD_NAME).build();
    bindTransform.generateParseOnJackson(context, methodBuilder, parserName, null, "result", property);
    methodBuilder.addStatement("return result");
    methodBuilder.nextControlFlow("catch($T e)", Exception.class);
    methodBuilder.addStatement("throw(new $T(e.getMessage()))", KriptonRuntimeException.class);
    methodBuilder.endControlFlow();
    // typeBuilder.
    context.builder.addMethod(methodBuilder.build());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) BindTransform(com.abubusoft.kripton.processor.bind.transform.BindTransform) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty)

Example 3 with BindTransform

use of com.abubusoft.kripton.processor.bind.transform.BindTransform in project kripton by xcesco.

the class ManagedPropertyPersistenceHelper method generateParamSerializer.

public static void generateParamSerializer(BindTypeContext context, String propertyName, TypeName parameterTypeName, PersistType persistType) {
    propertyName = SQLiteDaoDefinition.PARAM_SERIALIZER_PREFIX + propertyName;
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(propertyName).addJavadoc("for param $L serialization\n", propertyName).addParameter(ParameterSpec.builder(parameterTypeName, "value").build());
    methodBuilder.addModifiers(context.modifiers);
    switch(persistType) {
        case STRING:
            methodBuilder.returns(className(String.class));
            break;
        case BYTE:
            methodBuilder.returns(TypeUtility.arrayTypeName(Byte.TYPE));
            break;
    }
    methodBuilder.beginControlFlow("if (value==null)");
    methodBuilder.addStatement("return null");
    methodBuilder.endControlFlow();
    methodBuilder.addStatement("$T context=$T.jsonBind()", KriptonJsonContext.class, KriptonBinder.class);
    methodBuilder.beginControlFlow("try ($T stream=new $T(); $T wrapper=context.createSerializer(stream))", KriptonByteArrayOutputStream.class, KriptonByteArrayOutputStream.class, JacksonWrapperSerializer.class);
    methodBuilder.addStatement("$T jacksonSerializer=wrapper.jacksonGenerator", JsonGenerator.class);
    methodBuilder.addStatement("int fieldCount=0");
    BindTransform bindTransform = BindTransformer.lookup(parameterTypeName);
    String serializerName = "jacksonSerializer";
    boolean isInCollection = true;
    if (!BindTransformer.isBindedObject(parameterTypeName)) {
        methodBuilder.addStatement("$L.writeStartObject()", serializerName);
        isInCollection = false;
    }
    BindProperty property = BindProperty.builder(parameterTypeName).inCollection(isInCollection).elementName(DEFAULT_FIELD_NAME).build();
    bindTransform.generateSerializeOnJackson(context, methodBuilder, serializerName, null, "value", property);
    if (!BindTransformer.isBindedObject(parameterTypeName)) {
        methodBuilder.addStatement("$L.writeEndObject()", serializerName);
    }
    methodBuilder.addStatement("$L.flush()", serializerName);
    switch(persistType) {
        case STRING:
            methodBuilder.addStatement("return stream.toString()");
            break;
        case BYTE:
            methodBuilder.addStatement("return stream.toByteArray()");
            break;
    }
    methodBuilder.nextControlFlow("catch($T e)", Exception.class);
    methodBuilder.addStatement("throw(new $T(e.getMessage()))", KriptonRuntimeException.class);
    methodBuilder.endControlFlow();
    context.builder.addMethod(methodBuilder.build());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) BindTransform(com.abubusoft.kripton.processor.bind.transform.BindTransform) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty)

Example 4 with BindTransform

use of com.abubusoft.kripton.processor.bind.transform.BindTransform in project kripton by xcesco.

the class BindTypeBuilder method generateSerializeOnJackson.

private static void generateSerializeOnJackson(BindTypeContext context, BindEntity entity) {
    // @formatter:off
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("serializeOnJackson").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(typeName(entity.getElement()), "object").addParameter(typeName(JsonGenerator.class), "jacksonSerializer").returns(Integer.TYPE).addException(Exception.class);
    // @formatter:on
    // methodBuilder.beginControlFlow("try");
    // methodBuilder.addStatement("$T jacksonSerializer =
    // wrapper.jacksonGenerator", className(JsonGenerator.class));
    methodBuilder.addStatement("jacksonSerializer.writeStartObject()");
    methodBuilder.addStatement("int fieldCount=0");
    BindTransform bindTransform;
    methodBuilder.addCode("\n");
    // fields
    methodBuilder.addCode("// Serialized Field:\n\n");
    for (BindProperty item : entity.getCollection()) {
        bindTransform = BindTransformer.lookup(item);
        methodBuilder.addCode("// field $L (mapped with $S)\n", item.getName(), item.label);
        bindTransform.generateSerializeOnJackson(context, methodBuilder, "jacksonSerializer", item.getPropertyType().getTypeName(), "object", item);
        methodBuilder.addCode("\n");
    }
    methodBuilder.addStatement("jacksonSerializer.writeEndObject()");
    methodBuilder.addStatement("return fieldCount");
    // methodBuilder.nextControlFlow("catch($T e)",
    // typeName(Exception.class));
    // methodBuilder.addStatement("e.printStackTrace()");
    // methodBuilder.addStatement("throw (new $T(e))",
    // typeName(KriptonRuntimeException.class));
    // methodBuilder.endControlFlow();
    context.builder.addMethod(methodBuilder.build());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) BindTransform(com.abubusoft.kripton.processor.bind.transform.BindTransform) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty)

Example 5 with BindTransform

use of com.abubusoft.kripton.processor.bind.transform.BindTransform in project kripton by xcesco.

the class BindTypeBuilder method generateParserOnXmlStartElement.

private static void generateParserOnXmlStartElement(BindTypeContext context, MethodSpec.Builder methodBuilder, String instanceName, String parserName, BindEntity entity) {
    BindTransform bindTransform;
    // start and inner bean
    methodBuilder.addStatement("currentTag = xmlParser.getName().toString()");
    int count = 0;
    // count property to manage
    {
        // for each elements
        for (BindProperty property : entity.getCollection()) {
            if (property.xmlInfo.xmlType != XmlType.TAG)
                continue;
            bindTransform = BindTransformer.lookup(property);
            // here we manage only property of bean type
            if (bindTransform != null) {
                count++;
            }
        }
    }
    if (count > 0) {
        // switch for tag elements
        // @formatter:off
        methodBuilder.beginControlFlow("switch(currentTag)$>");
        // for each elements
        for (BindProperty property : entity.getCollection()) {
            if (property.xmlInfo.xmlType != XmlType.TAG)
                continue;
            bindTransform = BindTransformer.lookup(property);
            // here we manage only property of bean type
            if (bindTransform != null) {
                methodBuilder.addCode("case $S:\n$>", property.label);
                methodBuilder.addCode("// property $L (mapped on $S)\n", property.getName(), property.label);
                // methodBuilder.beginControlFlow("if
                // (!xmlParser.isEmptyElement())");
                bindTransform.generateParseOnXml(context, methodBuilder, "xmlParser", property.getPropertyType().getTypeName(), "instance", property);
                // methodBuilder.endControlFlow();
                methodBuilder.addStatement("$<break");
            }
        }
        methodBuilder.addCode("default:\n$>");
        // methodBuilder.addStatement("$L.skipElement()", parserName);
        methodBuilder.addStatement("$<break");
        methodBuilder.endControlFlow();
    } else {
        methodBuilder.addCode("// No property to manage here\n");
    }
// @formatter:on
}
Also used : BindTransform(com.abubusoft.kripton.processor.bind.transform.BindTransform) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty)

Aggregations

BindTransform (com.abubusoft.kripton.processor.bind.transform.BindTransform)13 BindProperty (com.abubusoft.kripton.processor.bind.model.BindProperty)11 MethodSpec (com.squareup.javapoet.MethodSpec)9 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 JsonParser (com.fasterxml.jackson.core.JsonParser)2 Bind (com.abubusoft.kripton.annotation.Bind)1 BindAdapter (com.abubusoft.kripton.annotation.BindAdapter)1 BindDisabled (com.abubusoft.kripton.annotation.BindDisabled)1 BindType (com.abubusoft.kripton.annotation.BindType)1 BindXml (com.abubusoft.kripton.annotation.BindXml)1 BindEntity (com.abubusoft.kripton.processor.bind.model.BindEntity)1 ByteArrayBindTransform (com.abubusoft.kripton.processor.bind.transform.ByteArrayBindTransform)1 ObjectBindTransform (com.abubusoft.kripton.processor.bind.transform.ObjectBindTransform)1 ModelAnnotation (com.abubusoft.kripton.processor.core.ModelAnnotation)1 IncompatibleAnnotationException (com.abubusoft.kripton.processor.exceptions.IncompatibleAnnotationException)1 IncompatibleAttributesInAnnotationException (com.abubusoft.kripton.processor.exceptions.IncompatibleAttributesInAnnotationException)1 InvalidDefinition (com.abubusoft.kripton.processor.exceptions.InvalidDefinition)1 Element (javax.lang.model.element.Element)1 TypeElement (javax.lang.model.element.TypeElement)1 Elements (javax.lang.model.util.Elements)1