Search in sources :

Example 21 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project flow by vaadin.

the class ComponentGenerator method createEventListenerEventClass.

private JavaClassSource createEventListenerEventClass(JavaClassSource javaClass, ComponentEventData event, String javaEventName, String propertyNameCamelCase, Map<String, MethodSource<JavaClassSource>> propertyToGetterMap) {
    boolean isPropertyChange = propertyNameCamelCase != null;
    String eventClassName = StringUtils.capitalize(javaEventName);
    String eventClassString = String.format("public static class %sEvent<%s extends %s<%s>> extends ComponentEvent<%s> {}", eventClassName, GENERIC_TYPE, javaClass.getName(), GENERIC_TYPE, GENERIC_TYPE);
    JavaClassSource eventClass = Roaster.parse(JavaClassSource.class, eventClassString);
    MethodSource<JavaClassSource> eventConstructor = eventClass.addMethod().setConstructor(true).setPublic().setBody("super(source, fromClient);");
    eventConstructor.addParameter(GENERIC_TYPE, "source");
    eventConstructor.addParameter("boolean", "fromClient");
    if (isPropertyChange) {
        addFieldAndGetterToPropertyChangeEvent(propertyNameCamelCase, propertyToGetterMap, eventClass, eventConstructor);
    } else {
        addEventDataParameters(javaClass, event, eventClassName, eventClass, eventConstructor);
        eventClass.addAnnotation(DomEvent.class).setStringValue(event.getName());
        javaClass.addImport(DomEvent.class);
    }
    javaClass.addImport(ComponentEvent.class);
    javaClass.addImport(ComponentEventListener.class);
    return eventClass;
}
Also used : JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) DomEvent(com.vaadin.flow.component.DomEvent)

Example 22 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project flow by vaadin.

the class ComponentGenerator method generateSetterFor.

private void generateSetterFor(JavaClassSource javaClass, ComponentMetadata metadata, ComponentPropertyData property) {
    String propertyJavaName = getJavaNameForProperty(metadata, property.getName());
    boolean isValue = "value".equals(propertyJavaName);
    if (containsObjectType(property)) {
        // the getter already created the nested pojo, so here we just need
        // to get the name
        String nestedClassName = ComponentGeneratorUtils.generateValidJavaClassName(propertyJavaName + "-property");
        MethodSource<JavaClassSource> method = javaClass.addMethod().setName(ComponentGeneratorUtils.generateMethodNameForProperty("set", propertyJavaName));
        setMethodVisibility(method, property.getObjectType());
        method.addParameter(nestedClassName, "property");
        method.setBody(String.format("getElement().setPropertyJson(\"%s\", property.toJson());", property.getName()));
        if (StringUtils.isNotEmpty(property.getDescription())) {
            addMarkdownJavaDoc(property.getDescription(), method.getJavaDoc());
        }
        method.getJavaDoc().addTagValue(JAVADOC_PARAM, "property the property to set");
        if (fluentMethod) {
            addFluentReturnToMethod(method);
        }
        if (isValue && shouldImplementHasValue(metadata)) {
            method.addAnnotation(Override.class);
            preventSettingTheSameValue(javaClass, "property", method);
        }
    } else {
        for (ComponentBasicType basicType : property.getType()) {
            MethodSource<JavaClassSource> method = javaClass.addMethod().setName(ComponentGeneratorUtils.generateMethodNameForProperty("set", propertyJavaName));
            setMethodVisibility(method, basicType);
            Class<?> setterType = ComponentGeneratorUtils.toJavaType(basicType);
            String parameterName = ComponentGeneratorUtils.formatStringToValidJavaIdentifier(propertyJavaName);
            ComponentGeneratorUtils.addMethodParameter(javaClass, method, setterType, parameterName);
            boolean nullable = !isValue || !shouldImplementHasValue(metadata) || String.class != setterType;
            method.setBody(ComponentGeneratorUtils.generateElementApiSetterForType(basicType, property.getName(), parameterName, nullable));
            if (StringUtils.isNotEmpty(property.getDescription())) {
                addMarkdownJavaDoc(property.getDescription(), method.getJavaDoc());
            }
            method.getJavaDoc().addTagValue(JAVADOC_PARAM, String.format("%s the %s value to set", parameterName, setterType.getSimpleName()));
            if (fluentMethod) {
                addFluentReturnToMethod(method);
            }
            if (isValue && shouldImplementHasValue(metadata)) {
                method.addAnnotation(Override.class);
                preventSettingTheSameValue(javaClass, parameterName, method);
                if (setterType.isPrimitive()) {
                    implementHasValueSetterWithPrimitiveType(javaClass, property, method, setterType, parameterName);
                } else if (!nullable) {
                    method.setBody(String.format("Objects.requireNonNull(%s, \"%s cannot be null\");", parameterName, parameterName) + method.getBody());
                }
            }
        }
    }
}
Also used : JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ComponentBasicType(com.vaadin.generator.metadata.ComponentBasicType)

Example 23 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project flow by vaadin.

the class ComponentGenerator method generateMethodParameters.

/**
 * Adds the parameters and javadocs to the given method and generates nested
 * classes for complex object parameters if needed.
 *
 * @param javaClass
 *            the main class file
 * @param method
 *            the method to add parameters to
 * @param function
 *            the function data
 * @param typeVariant
 *            the list of types to use for each added parameter
 * @param nestedClassesMap
 *            map for memorizing already generated nested classes
 * @return a string of the parameters of the function, or an empty string if
 *         no parameters
 */
private String generateMethodParameters(JavaClassSource javaClass, MethodSource<JavaClassSource> method, ComponentFunctionData function, List<ComponentType> typeVariant, Map<ComponentObjectType, JavaClassSource> nestedClassesMap) {
    int paramIndex = 0;
    StringBuilder sb = new StringBuilder();
    for (ComponentType paramType : typeVariant) {
        String paramName = function.getParameters().get(paramIndex).getName();
        String paramDescription = function.getParameters().get(paramIndex).getDescription();
        String formattedName = StringUtils.uncapitalize(ComponentGeneratorUtils.formatStringToValidJavaIdentifier(function.getParameters().get(paramIndex).getName()));
        paramIndex++;
        if (paramType.isBasicType()) {
            ComponentBasicType bt = (ComponentBasicType) paramType;
            ComponentGeneratorUtils.addMethodParameter(javaClass, method, ComponentGeneratorUtils.toJavaType(bt), formattedName);
            sb.append(", ").append(formattedName);
        } else {
            ComponentObjectType ot = (ComponentObjectType) paramType;
            String nameHint = function.getName() + "-" + paramName;
            JavaClassSource nestedClass = nestedClassesMap.computeIfAbsent(ot, objectType -> generateNestedPojo(javaClass, objectType, nameHint, String.format("Class that encapsulates the data to be sent to the {@link %s#%s(%s)} method.", javaClass.getName(), method.getName(), ComponentGeneratorUtils.generateValidJavaClassName(nameHint))));
            sb.append(", ").append(formattedName).append(".toJson()");
            method.getJavaDoc().addTagValue(JAVADOC_SEE, nestedClass.getName());
            method.addParameter(nestedClass, formattedName);
        }
        method.getJavaDoc().addTagValue(JAVADOC_PARAM, String.format("%s %s", formattedName, paramDescription));
    }
    return sb.toString();
}
Also used : ComponentType(com.vaadin.generator.metadata.ComponentType) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ComponentObjectType(com.vaadin.generator.metadata.ComponentObjectType) ComponentBasicType(com.vaadin.generator.metadata.ComponentBasicType)

Example 24 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project flow by vaadin.

the class ComponentGenerator method generateClassSource.

/*
     * Gets the JavaClassSource object (note, the license is added externally to
     * the source, since JavaClassSource doesn't support adding a comment to the
     * beginning of the file).
     */
private JavaClassSource generateClassSource(ComponentMetadata metadata, String basePackage) {
    String targetPackage = basePackage;
    String baseUrl = metadata.getBaseUrl();
    if (StringUtils.isNotBlank(baseUrl)) {
        // this is a fugly way to remove that
        if (baseUrl.contains("/src/")) {
            baseUrl = baseUrl.replace("/src/", "/");
        }
        String subPackage = ComponentGeneratorUtils.convertFilePathToPackage(baseUrl);
        if (StringUtils.isNotBlank(subPackage)) {
            int firstDot = subPackage.indexOf('.');
            if (firstDot > 0) {
                String firstSegment = subPackage.substring(0, firstDot);
                String lastSegment = subPackage.substring(firstDot + 1);
                subPackage = lastSegment.replace(".", "");
                if (!"vaadin".equals(firstSegment)) {
                    subPackage = firstSegment + "." + subPackage;
                }
            }
            targetPackage += "." + subPackage;
        }
    }
    JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
    javaClass.setPackage(targetPackage).setPublic().setAbstract(abstractClass).setName(getGeneratedClassName(metadata.getTag()));
    if (metadata.getParentTagName() != null) {
        javaClass.setSuperType(getGeneratedClassName(metadata.getParentTagName()) + GENERIC_TYPE_DECLARATION);
    } else {
        javaClass.setSuperType(Component.class);
        addInterfaces(metadata, javaClass);
    }
    javaClass.addTypeVariable().setName(GENERIC_TYPE).setBounds(javaClass.getName() + GENERIC_TYPE_DECLARATION);
    addClassAnnotations(metadata, javaClass);
    Map<String, MethodSource<JavaClassSource>> propertyToGetterMap = new HashMap<String, MethodSource<JavaClassSource>>();
    if (metadata.getProperties() != null) {
        generateEventsForPropertiesWithNotify(metadata);
        generateGettersAndSetters(metadata, javaClass, propertyToGetterMap);
    }
    if (metadata.getMethods() != null) {
        metadata.getMethods().stream().filter(function -> !ExclusionRegistry.isMethodExcluded(metadata.getTag(), function.getName())).forEach(function -> generateMethodFor(javaClass, function));
    }
    if (metadata.getEvents() != null) {
        metadata.getEvents().stream().filter(event -> !ExclusionRegistry.isEventExcluded(metadata.getTag(), event.getName())).forEach(event -> generateEventListenerFor(javaClass, metadata, event, propertyToGetterMap));
    }
    if (metadata.getSlots() != null && !metadata.getSlots().isEmpty()) {
        generateAdders(metadata, javaClass);
    }
    if (StringUtils.isNotEmpty(metadata.getDescription())) {
        addMarkdownJavaDoc(metadata.getDescription(), javaClass.getJavaDoc());
    }
    generateConstructors(javaClass);
    return javaClass;
}
Also used : Component(com.vaadin.flow.component.Component) Registration(com.vaadin.flow.shared.Registration) LoggerFactory(org.slf4j.LoggerFactory) ComponentFunctionData(com.vaadin.generator.metadata.ComponentFunctionData) ComponentBasicType(com.vaadin.generator.metadata.ComponentBasicType) StringUtils(org.apache.commons.lang3.StringUtils) ParameterSource(org.jboss.forge.roaster.model.source.ParameterSource) BehaviorRegistry(com.vaadin.generator.registry.BehaviorRegistry) ClassUtils(org.apache.commons.lang3.ClassUtils) Generated(javax.annotation.Generated) Roaster(org.jboss.forge.roaster.Roaster) ComponentPropertyData(com.vaadin.generator.metadata.ComponentPropertyData) Map(java.util.Map) Element(com.vaadin.flow.dom.Element) Synchronize(com.vaadin.flow.component.Synchronize) HasComponents(com.vaadin.flow.component.HasComponents) MethodSource(org.jboss.forge.roaster.model.source.MethodSource) Visibility(org.jboss.forge.roaster.model.Visibility) HasStyle(com.vaadin.flow.component.HasStyle) JavaDocSource(org.jboss.forge.roaster.model.source.JavaDocSource) Collection(java.util.Collection) Set(java.util.Set) Objects(java.util.Objects) List(java.util.List) JsonSerializable(com.vaadin.flow.component.JsonSerializable) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ComponentPropertyBaseData(com.vaadin.generator.metadata.ComponentPropertyBaseData) Optional(java.util.Optional) ComponentEventListener(com.vaadin.flow.component.ComponentEventListener) HasValue(com.vaadin.flow.component.HasValue) ComponentGenerationException(com.vaadin.generator.exception.ComponentGenerationException) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) DomEvent(com.vaadin.flow.component.DomEvent) Tag(com.vaadin.flow.component.Tag) Properties(java.util.Properties) JsonParser(com.fasterxml.jackson.core.JsonParser) Files(java.nio.file.Files) EventData(com.vaadin.flow.component.EventData) ComponentObjectType(com.vaadin.generator.metadata.ComponentObjectType) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PropertyNameRemapRegistry(com.vaadin.generator.registry.PropertyNameRemapRegistry) IOException(java.io.IOException) ExclusionRegistry(com.vaadin.generator.registry.ExclusionRegistry) ComponentEvent(com.vaadin.flow.component.ComponentEvent) File(java.io.File) HtmlImport(com.vaadin.flow.component.dependency.HtmlImport) JsonFactory(com.fasterxml.jackson.core.JsonFactory) ComponentMetadata(com.vaadin.generator.metadata.ComponentMetadata) ComponentType(com.vaadin.generator.metadata.ComponentType) JsonObject(elemental.json.JsonObject) ComponentEventData(com.vaadin.generator.metadata.ComponentEventData) HasText(com.vaadin.flow.component.HasText) NotSupported(com.vaadin.flow.component.NotSupported) Collections(java.util.Collections) InputStream(java.io.InputStream) HashMap(java.util.HashMap) MethodSource(org.jboss.forge.roaster.model.source.MethodSource) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource)

Example 25 with JavaClassSource

use of org.jboss.forge.roaster.model.source.JavaClassSource in project flow by vaadin.

the class NestedClassGenerator method build.

/**
 * Builds the Java class by using the defined settings.
 *
 * @return the final Java class source, ready to be embedded in the main
 *         class of the component.
 */
public JavaClassSource build() {
    JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
    javaClass.addInterface(JsonSerializable.class).setPublic().setStatic(true).setName(ComponentGeneratorUtils.generateValidJavaClassName(nameHint));
    javaClass.addField().setType(JsonObject.class).setPrivate().setName("internalObject");
    for (ComponentObjectTypeInnerType object : type.getInnerTypes()) {
        ComponentBasicType simpleType = getSimpleBasicType(object.getType());
        generateGetter(javaClass, object, simpleType);
        generateSetter(javaClass, object, simpleType);
    }
    generateToJson(javaClass);
    generateReadJson(javaClass);
    return javaClass;
}
Also used : JsonSerializable(com.vaadin.flow.component.JsonSerializable) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ComponentObjectTypeInnerType(com.vaadin.generator.metadata.ComponentObjectType.ComponentObjectTypeInnerType) ComponentBasicType(com.vaadin.generator.metadata.ComponentBasicType)

Aggregations

JavaClassSource (org.jboss.forge.roaster.model.source.JavaClassSource)95 File (java.io.File)37 ArrayList (java.util.ArrayList)28 Test (org.junit.Test)26 ParserResult (org.apache.camel.parser.ParserResult)19 List (java.util.List)15 IOException (java.io.IOException)14 MethodSource (org.jboss.forge.roaster.model.source.MethodSource)12 InputStream (java.io.InputStream)10 Collections (java.util.Collections)10 Roaster (org.jboss.forge.roaster.Roaster)10 BufferedReader (java.io.BufferedReader)8 HashMap (java.util.HashMap)8 Matcher (java.util.regex.Matcher)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 ObjectProperty (org.kie.workbench.common.services.datamodeller.core.ObjectProperty)8 Arrays (java.util.Arrays)7 Map (java.util.Map)7 Import (org.jboss.forge.roaster.model.source.Import)7 ClassTypeResolver (org.kie.soup.project.datamodel.commons.types.ClassTypeResolver)7