Search in sources :

Example 1 with TsModel

use of cz.habarta.typescript.generator.emitter.TsModel in project typescript-generator by vojtechhabarta.

the class ModelCompilerTest method testIntermediateInterfacesWithoutTypeParams.

@Test
public void testIntermediateInterfacesWithoutTypeParams() throws Exception {
    final Settings settings = TestUtils.settings();
    final Jackson2Parser jacksonParser = new Jackson2Parser(settings, new DefaultTypeProcessor());
    final Model model = jacksonParser.parseModel(Implementation.class);
    final ModelCompiler modelCompiler = new TypeScriptGenerator(settings).getModelCompiler();
    final TsModel result = modelCompiler.javaToTypeScript(model);
    Assert.assertThat(result.getBean(WithoutTypeParam.class).getProperties().get(0).tsType, CoreMatchers.instanceOf(TsType.UnionType.class));
}
Also used : Jackson2Parser(cz.habarta.typescript.generator.parser.Jackson2Parser) TsModel(cz.habarta.typescript.generator.emitter.TsModel) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) Model(cz.habarta.typescript.generator.parser.Model) TsModel(cz.habarta.typescript.generator.emitter.TsModel)

Example 2 with TsModel

use of cz.habarta.typescript.generator.emitter.TsModel in project typescript-generator by vojtechhabarta.

the class EnumConstantsExtensionTest method basicTest.

@Test
public void basicTest() {
    final List<String> lines = new ArrayList<>();
    final EmitterExtension.Writer writer = new EmitterExtension.Writer() {

        @Override
        public void writeIndentedLine(String line) {
            lines.add(line);
        }
    };
    final Settings settings = new Settings();
    settings.sortDeclarations = true;
    final TypeProcessor typeProcessor = new DefaultTypeProcessor();
    final Model model = new Jackson2Parser(settings, typeProcessor).parseModel(Direction.class);
    final TsModel tsModel = new ModelCompiler(settings, typeProcessor).javaToTypeScript(model);
    new EnumConstantsExtension().emitElements(writer, settings, false, tsModel);
    String indent = settings.indentString;
    Assert.assertEquals(7, lines.size());
    Assert.assertEquals("", lines.get(0));
    Assert.assertEquals("const Direction = {", lines.get(1));
    Assert.assertEquals(indent + "North: <Direction>\"North\",", lines.get(2));
    Assert.assertEquals(indent + "East: <Direction>\"East\",", lines.get(3));
    Assert.assertEquals(indent + "South: <Direction>\"South\",", lines.get(4));
    Assert.assertEquals(indent + "West: <Direction>\"West\",", lines.get(5));
    Assert.assertEquals("}", lines.get(6));
}
Also used : Jackson2Parser(cz.habarta.typescript.generator.parser.Jackson2Parser) EmitterExtension(cz.habarta.typescript.generator.emitter.EmitterExtension) ArrayList(java.util.ArrayList) TsModel(cz.habarta.typescript.generator.emitter.TsModel) EnumConstantsExtension(cz.habarta.typescript.generator.ext.EnumConstantsExtension) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) Model(cz.habarta.typescript.generator.parser.Model) TsModel(cz.habarta.typescript.generator.emitter.TsModel) Test(org.junit.Test)

Example 3 with TsModel

use of cz.habarta.typescript.generator.emitter.TsModel in project openremote by openremote.

the class AssetModelInfoExtension method emitElements.

@SuppressWarnings("rawtypes")
@Override
public void emitElements(Writer writer, Settings settings, boolean exportKeyword, TsModel model) {
    Map<String, String> assetMap = new HashMap<>();
    Map<String, String> otherMap = new HashMap<>();
    Arrays.stream(ValueUtil.getAssetInfos(null)).forEach(assetModelInfo -> {
        String assetDescriptorName = assetModelInfo.getAssetDescriptor().getName();
        assetMap.put(assetDescriptorName.toUpperCase(Locale.ROOT), assetDescriptorName);
        // Store attributes
        Arrays.stream(assetModelInfo.getAttributeDescriptors()).forEach(attributeDescriptor -> {
            String attributeName = attributeDescriptor.getName();
            otherMap.put(attributeName.toUpperCase(Locale.ROOT), attributeName);
        });
    });
    emitEnum(writer, "WellknownAssets", assetMap);
    writer.writeIndentedLine("");
    emitEnum(writer, "WellknownAttributes", otherMap);
    otherMap.clear();
    Arrays.stream(ValueUtil.getMetaItemDescriptors()).forEach(metaItemDescriptor -> {
        String metaName = metaItemDescriptor.getName();
        otherMap.put(metaName.toUpperCase(Locale.ROOT), metaName);
    });
    writer.writeIndentedLine("");
    emitEnum(writer, "WellknownMetaItems", otherMap);
    otherMap.clear();
    Arrays.stream(ValueUtil.getValueDescriptors()).forEach(valueDescriptor -> {
        String valueTypeName = valueDescriptor.getName();
        otherMap.put(valueTypeName.toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9]", ""), valueTypeName);
    });
    writer.writeIndentedLine("");
    emitEnum(writer, "WellknownValueTypes", otherMap);
    otherMap.clear();
    Arrays.stream(Constants.class.getFields()).filter(f -> f.getName().startsWith("UNITS_")).forEach(unitField -> {
        String unitName = unitField.getName().substring(6);
        try {
            otherMap.put(unitName.toUpperCase(Locale.ROOT), (String) unitField.get(null));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    });
    writer.writeIndentedLine("");
    emitEnum(writer, "WellknownUnitTypes", otherMap);
    otherMap.clear();
    Arrays.stream(Ruleset.class.getFields()).filter(f -> f.getType() == MetaItemDescriptor.class).forEach(rulesetMeta -> {
        try {
            MetaItemDescriptor metaItemDescriptor = (MetaItemDescriptor) rulesetMeta.get(null);
            otherMap.put(metaItemDescriptor.getName().toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9]", ""), metaItemDescriptor.getName());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    });
    writer.writeIndentedLine("");
    emitEnum(writer, "WellknownRulesetMetaItems", otherMap);
}
Also used : Ruleset(org.openremote.model.rules.Ruleset) java.util(java.util) EmitterExtensionFeatures(cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures) MetaItemDescriptor(org.openremote.model.value.MetaItemDescriptor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Extension(cz.habarta.typescript.generator.Extension) ValueUtil(org.openremote.model.util.ValueUtil) Constants(org.openremote.model.Constants) Settings(cz.habarta.typescript.generator.Settings) TsModel(cz.habarta.typescript.generator.emitter.TsModel) AgentModelProvider(org.openremote.agent.protocol.AgentModelProvider) Ruleset(org.openremote.model.rules.Ruleset) Constants(org.openremote.model.Constants) MetaItemDescriptor(org.openremote.model.value.MetaItemDescriptor)

Example 4 with TsModel

use of cz.habarta.typescript.generator.emitter.TsModel in project openremote by openremote.

the class JsonSerializeExtension method getTransformers.

@Override
public List<cz.habarta.typescript.generator.Extension.TransformerDefinition> getTransformers() {
    return Arrays.asList(new cz.habarta.typescript.generator.Extension.TransformerDefinition(ModelCompiler.TransformationPhase.BeforeTsModel, new ModelTransformer() {

        @Override
        public TsModel transformModel(SymbolTable symbolTable, TsModel model) {
            return model;
        }

        @Override
        public Model transformModel(SymbolTable symbolTable, Model model) {
            // Look for @JsonSerialize annotation and modify the property type accordingly
            List<BeanModel> beans = model.getBeans();
            beans.replaceAll(bean -> {
                AtomicBoolean modified = new AtomicBoolean(false);
                List<PropertyModel> properties = bean.getProperties().stream().map(p -> {
                    Member member = p.getOriginalMember();
                    JsonSerialize jsonSerialize = null;
                    if (member instanceof Field) {
                        Field field = (Field) member;
                        jsonSerialize = field.getAnnotation(JsonSerialize.class);
                    } else if (member instanceof Method) {
                        Method method = (Method) member;
                        jsonSerialize = method.getAnnotation(JsonSerialize.class);
                    }
                    if (jsonSerialize != null) {
                        // TODO: Add support for other options
                        if (jsonSerialize.as() != Void.class) {
                            modified.set(true);
                            return new PropertyModel(p.getName(), jsonSerialize.as(), p.isOptional(), p.getAccess(), p.getOriginalMember(), p.getPullProperties(), p.getContext(), p.getComments());
                        }
                        if (jsonSerialize.converter() != Converter.None.class) {
                            // Type info is not accessible with reflection so instantiate the converter
                            Method convertMethod = Arrays.stream(jsonSerialize.converter().getMethods()).filter(m -> m.getName().equals("convert")).findFirst().orElse(null);
                            if (convertMethod != null) {
                                modified.set(true);
                                return new PropertyModel(p.getName(), convertMethod.getGenericReturnType(), p.isOptional(), p.getAccess(), p.getOriginalMember(), p.getPullProperties(), p.getContext(), p.getComments());
                            }
                        }
                    }
                    return p;
                }).collect(Collectors.toList());
                if (modified.get()) {
                    return new BeanModel(bean.getOrigin(), bean.getParent(), bean.getTaggedUnionClasses(), bean.getDiscriminantProperty(), bean.getDiscriminantLiteral(), bean.getInterfaces(), properties, bean.getComments());
                }
                return bean;
            });
            return model;
        }
    }));
}
Also used : Arrays(java.util.Arrays) Converter(com.fasterxml.jackson.databind.util.Converter) PropertyModel(cz.habarta.typescript.generator.parser.PropertyModel) EmitterExtensionFeatures(cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures) Member(java.lang.reflect.Member) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Field(java.lang.reflect.Field) TsModel(cz.habarta.typescript.generator.emitter.TsModel) Collectors(java.util.stream.Collectors) List(java.util.List) ModelTransformer(cz.habarta.typescript.generator.compiler.ModelTransformer) JsonSerialize(com.fasterxml.jackson.databind.annotation.JsonSerialize) SymbolTable(cz.habarta.typescript.generator.compiler.SymbolTable) BeanModel(cz.habarta.typescript.generator.parser.BeanModel) Model(cz.habarta.typescript.generator.parser.Model) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) Method(java.lang.reflect.Method) BeanModel(cz.habarta.typescript.generator.parser.BeanModel) PropertyModel(cz.habarta.typescript.generator.parser.PropertyModel) SymbolTable(cz.habarta.typescript.generator.compiler.SymbolTable) Method(java.lang.reflect.Method) JsonSerialize(com.fasterxml.jackson.databind.annotation.JsonSerialize) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Field(java.lang.reflect.Field) ModelTransformer(cz.habarta.typescript.generator.compiler.ModelTransformer) TsModel(cz.habarta.typescript.generator.emitter.TsModel) PropertyModel(cz.habarta.typescript.generator.parser.PropertyModel) TsModel(cz.habarta.typescript.generator.emitter.TsModel) BeanModel(cz.habarta.typescript.generator.parser.BeanModel) Model(cz.habarta.typescript.generator.parser.Model) Member(java.lang.reflect.Member)

Example 5 with TsModel

use of cz.habarta.typescript.generator.emitter.TsModel in project typescript-generator by vojtechhabarta.

the class ModelCompilerTest method testIntermediateInterfacesWithTypeParams.

@Test
public void testIntermediateInterfacesWithTypeParams() throws Exception {
    final Settings settings = TestUtils.settings();
    final Jackson2Parser jacksonParser = new Jackson2Parser(settings, new DefaultTypeProcessor());
    final Model model = jacksonParser.parseModel(Implementation.class);
    final ModelCompiler modelCompiler = new TypeScriptGenerator(settings).getModelCompiler();
    final TsModel result = modelCompiler.javaToTypeScript(model);
    Assert.assertThat(result.getBean(WithTypeParam.class).getProperties().get(0).tsType, CoreMatchers.instanceOf(TsType.UnionType.class));
}
Also used : Jackson2Parser(cz.habarta.typescript.generator.parser.Jackson2Parser) TsModel(cz.habarta.typescript.generator.emitter.TsModel) ModelCompiler(cz.habarta.typescript.generator.compiler.ModelCompiler) Model(cz.habarta.typescript.generator.parser.Model) TsModel(cz.habarta.typescript.generator.emitter.TsModel)

Aggregations

TsModel (cz.habarta.typescript.generator.emitter.TsModel)7 ModelCompiler (cz.habarta.typescript.generator.compiler.ModelCompiler)5 Model (cz.habarta.typescript.generator.parser.Model)5 Jackson2Parser (cz.habarta.typescript.generator.parser.Jackson2Parser)4 Settings (cz.habarta.typescript.generator.Settings)2 ModelTransformer (cz.habarta.typescript.generator.compiler.ModelTransformer)2 SymbolTable (cz.habarta.typescript.generator.compiler.SymbolTable)2 EmitterExtension (cz.habarta.typescript.generator.emitter.EmitterExtension)2 EmitterExtensionFeatures (cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures)2 Field (java.lang.reflect.Field)2 Test (org.junit.Test)2 JsonSerialize (com.fasterxml.jackson.databind.annotation.JsonSerialize)1 Converter (com.fasterxml.jackson.databind.util.Converter)1 DefaultTypeProcessor (cz.habarta.typescript.generator.DefaultTypeProcessor)1 Extension (cz.habarta.typescript.generator.Extension)1 TypeProcessor (cz.habarta.typescript.generator.TypeProcessor)1 EnumMemberModel (cz.habarta.typescript.generator.compiler.EnumMemberModel)1 TsBeanModel (cz.habarta.typescript.generator.emitter.TsBeanModel)1 TsEnumModel (cz.habarta.typescript.generator.emitter.TsEnumModel)1 EnumConstantsExtension (cz.habarta.typescript.generator.ext.EnumConstantsExtension)1