private JDefinedClass buildTemplateConstraint(String name) { try { JDefinedClass tplConstraint = codeModel._class(Config.CFG.getBasePackageName() + ".annot."+name, ClassType.ANNOTATION_TYPE_DECL); tplConstraint.annotate(Documented.class); tplConstraint.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME); tplConstraint.annotate(Target.class).paramArray("value").param(ElementType.TYPE).param(ElementType.ANNOTATION_TYPE).param(ElementType.FIELD).param(ElementType.METHOD); // Using direct as I don't know how to build default { } with code model tplConstraint.direct("\n" + " Class<?>[] groups() default {};\n" + " String message() default \"Invalid value\";\n" + " Class<? extends Payload>[] payload() default {};\n"); // Hack to force the import of javax.validation.Payload tplConstraint.javadoc().addThrows((JClass) codeModel._ref(Payload.class)).add("Force import"); return tplConstraint; } catch (JClassAlreadyExistsException e) { throw new RuntimeException("Tried to create an already existing class: " + name, e); } }
/** * Creates a new MetaJavaBean with random fields. * * @param fqn * The fully qualified name of the bean's class. * @param numFields * Number of simple type fields that will be added. */ public MetaJavaBean(JCodeModel cm, String fqn, int numFields) { super(cm, fqn, ClassType.CLASS); // Empty constructor getGeneratedClass().constructor(JMod.PUBLIC); // Init the simple fields this.fields = Maps.newHashMapWithExpectedSize(numFields); for (int i = 0; i < numFields; ++i) { String fieldName = "field" + Config.CFG.nextUniqueNum(); JavaBeanBasicField field = new JavaBeanBasicField(this, fieldName); fields.put(fieldName, field); } }
@Override public JType define(AbstractType t) { JDefinedClass defineClass = writer.defineClass(t, ClassType.INTERFACE); for (AbstractType st:t.superTypes()){ AbstractType superType = st; JType type = writer.getType(superType); defineClass._extends((JClass) type); } t.toPropertiesView().properties().forEach(p -> { String name = writer.propNameGenerator.name(p); JType propType = writer.getType(p.range(), false, false, p); //defineClass.field(JMod.PRIVATE, propType, name); defineClass.method(JMod.PUBLIC, propType, "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1)); defineClass.method(JMod.PUBLIC, writer.getModel()._ref(void.class), (p.range().isBoolean() ? "is" : "set") + Character.toUpperCase(name.charAt(0)) + name.substring(1)); }); writer.annotate(defineClass, t); return defineClass; }
public JDefinedClass defineClass(AbstractType t, ClassType type) { String fullyQualifiedName = nameGenerator.fullyQualifiedName(t); try { JDefinedClass _class = mdl._class(fullyQualifiedName, type); if (config.addGenerated) { _class.annotate(Generated.class).param("value", JavaWriter.class.getPackage().getName()).param("date", new Date().toString()); } if (t.hasDirectMeta(Description.class)) { String description = t.oneMeta(Description.class).value(); _class.javadoc().add(description); } return _class; } catch (JClassAlreadyExistsException e) { throw new IllegalStateException(e); } }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).contains("LIGHT_BLUE", "RED"); JEnumConstant lightBlue = enums.get("LIGHT_BLUE"); assertThat(lightBlue.javadoc().get(0)).isEqualTo("Colour of the sky"); List<JExpression> args = (List<JExpression>) FieldUtils.readField(lightBlue, "args", true); assertThat(args).hasSize(1); assertThat(args.get(0)).isInstanceOf(JStringLiteral.class); String literal = (String) FieldUtils.readField(args.get(0), "str", true); assertThat(literal).isEqualTo("lightBlue"); }
private byte[] generateJava() throws Exception { JDefinedClass classModel = codeModel._class(JMod.PUBLIC | JMod.FINAL, className, ClassType.CLASS); Class<?> contractInterface = Class.forName(contractInterfaceName); classModel._implements(contractInterface); classModel._extends(AbstractDataTransferObject.class); List<FieldModel> fields = determineFields(contractInterface); renderConstantsClass(classModel); renderElementsClass(classModel, fields); renderClassLevelAnnotations(classModel, fields); renderFields(classModel, fields); renderFutureElementsField(classModel); renderPrivateJaxbConstructor(classModel, fields); renderBuilderConstructor(classModel, fields); renderGetters(classModel, fields); renderBuilderClass(classModel, fields, contractInterface); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); codeModel.build(new SingleStreamCodeWriter(outputStream)); return outputStream.toByteArray(); }
@Override public void caseAPortDeclaration(APortDeclaration node ) { TypeModifierAdapter modap = new TypeModifierAdapter(context); for (PModifier m : node.getModifier()) { m.apply(modap); } int mods = modap.getMods(); JDefinedClass c = context.declare(mods, node.getIdentifier(), ClassType.CLASS); try { c.mods().setPublic(); // ports should be public so Kompics can load them c._extends(PortType.class); PortBodyAdapter pba = new PortBodyAdapter(c.instanceInit(), context); node.getPortBody().apply(pba); } finally { context.popScope(); } }
JDefinedClass declare(int mods, TIdentifier identifier, ClassType ctype, Optional<String> name) { if (current instanceof Scope.Typey) { try { Scope.Typey typeyScope = (Scope.Typey) current; Type t = typeyScope.declare(mods, identifier, ctype, name); global.addType(t); current = t.scope; scopeStack.push(current); //System.out.println("Pushing scope " + current); return t.definition; } catch (JClassAlreadyExistsException ex) { throw new RuntimeException(ex); } } else { Logger.error("Cannot add a type (" + identifier.getText() + ") to a Scope (" + current.getClass().getName() + ") that doesn't allow types!"); throw new RuntimeException("Invalid Scope for operation!"); } }
@Override public void generete(Const definition) throws Exception { JDefinedClass jExceptionClass = this.getJavaPackage()._class(JMod.PUBLIC, definition.getName(), ClassType.CLASS); jExceptionClass._extends(org.apache.thrift.TException.class); // this.context.getTypeRegistry().add(jExceptionClass); int[] count = { 0 }; // for (Const constDef : subprogram.constants) { JType fieldType = this.resolvType(definition.getType()); JExpression exp = this.buildStaticExpression(jConstantsClass, fieldType, definition.getName(), definition.getValue() , count); jConstantsClass.field(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, fieldType, definition.getName(), exp); // } }
@Override public void generete(Service definition) throws Exception { JDefinedClass jServiceClass = this.getJavaPackage()._class(JMod.PUBLIC, definition.getName(), ClassType.CLASS); JDefinedClass _interfaceIface = createServicesInterface(definition, jServiceClass); createServicesClient(definition, jServiceClass); createServicesProcessor(definition, jServiceClass, _interfaceIface); JDefinedClass _asyncInterfaceIface = createServicesAsyncInterface( definition, jServiceClass); createServicesAsyncClient(definition, jServiceClass); createServicesAsyncProcessor(definition, jServiceClass, _asyncInterfaceIface); }
public static String getThriftType(JCodeModel cm, JType jType) { if (cm.BOOLEAN.equals(jType) || cm.ref(Boolean.class).equals(jType)) { return "org.apache.thrift.protocol.TType.BOOL"; } else if (cm.BYTE.equals(jType) || cm.ref(Byte.class).equals(jType)) { return "org.apache.thrift.protocol.TType.BYTE"; } else if (cm.CHAR.equals(jType) || cm.ref(Character.class).equals(jType)) { return "org.apache.thrift.protocol.TType.STRING"; } else if (cm.DOUBLE.equals(jType) || cm.ref(Double.class).equals(jType)) { return "org.apache.thrift.protocol.TType.DOUBLE"; } else if (cm.FLOAT.equals(jType) || cm.ref(Float.class).equals(jType)) { return "org.apache.thrift.protocol.TType.DOUBLE"; } else if (cm.INT.equals(jType) || cm.ref(Integer.class).equals(jType)) { return "org.apache.thrift.protocol.TType.I32"; } else if (cm.LONG.equals(jType) || cm.ref(Long.class).equals(jType)) { return "org.apache.thrift.protocol.TType.I64"; } else if (cm.ref(String.class).equals(jType)) { return "org.apache.thrift.protocol.TType.STRING"; } else if (cm.SHORT.equals(jType) || cm.ref(Short.class).equals(jType)) { return "org.apache.thrift.protocol.TType.I16"; } else if (jType instanceof JDefinedClass && ClassType.ENUM.equals(((JDefinedClass) jType).getClassType())) { return "org.apache.thrift.protocol.TType.ENUM"; } else { return "org.apache.thrift.protocol.TType.STRUCT"; } }
public NodeGenerator(Symbols symbols, String pckg, JCodeModel model, Framework f, SymbolsGenerator symbolsGen) throws JClassAlreadyExistsException{ this.symbols = symbols; this.framework = f; this.symbolsGen = symbolsGen; this.model = model; this.pckg = pckg; String name = pckg == null ? VISITOR : pckg + "." + VISITOR; this.visitorInterface = model._class(name, ClassType.INTERFACE); CodeGenerator.appendJDocHeader(visitorInterface); name = pckg == null ? SYMBOLS : pckg + "." + SYMBOLS; this.eofTokenClass = this.defineEOFToken(); this.tokens = this.defineTokenNodes(); this.abstractNodes= this.defineAbstractNodes(); this.concreteNodes= this.defineConcreteNodes(); }
/** * @author Jennifer Zou * @param s * @return * @throws JClassAlreadyExistsException */ private JDefinedClass defineAbstractNode(String s) throws JClassAlreadyExistsException{ String name = pckg == null ? s + "AbstractNode" : pckg+"."+NODES+"."+s+"AbstractNode"; JDefinedClass asn= model._class(JMod.PUBLIC+JMod.ABSTRACT, name, ClassType.CLASS); CodeGenerator.appendJDocHeader(asn); asn._implements(framework.getNodeInterface().narrow(visitorInterface)); //declare the type method JMethod type= asn.method(JMod.PUBLIC, framework.getSymbolInterface(), TYPE); type.annotate(Override.class); type.body()._return(symbolsGen.getSymbolObj(s)); //define replace method JMethod replace= asn.method(JMod.PUBLIC, asn, REPLACE); replace.annotate(Override.class); replace.body()._return(JExpr._this()); //define toString() JMethod toString= asn.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._return(JExpr.invoke(JExpr.invoke(type), "toString")); return asn; }
private JDefinedClass defineClass(String pckg, JCodeModel model, Framework f) throws JClassAlreadyExistsException{ String name = pckg == null ? NAME : pckg + "." + NAME; JDefinedClass c = CodeGenerator.appendJDocHeader( model._class(JMod.PUBLIC, name, ClassType.ENUM)); JVar str = c.field(JMod.PRIVATE+JMod.FINAL, String.class, "name"); JMethod cons = c.constructor(JMod.PRIVATE); cons.body().assign(JExpr._this().ref(str), cons.param(String.class, "name")); JMethod defCons = c.constructor(JMod.PRIVATE); defCons.body().assign(JExpr._this().ref(str), JExpr._null()); JMethod toString = c.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._if(str.eq(JExpr._null()))._then()._return(JExpr.invoke(JExpr._super(), "toString")); toString.body()._return(str); c._implements(f.getSymbolInterface()); JMethod type = c.method(JMod.PUBLIC, int.class, "type"); type.annotate(Override.class); type.body()._return(JExpr.invoke(JExpr._this(), "ordinal")); return c; }
private void buildJavaClass() { try { JCodeModel codeModel = new JCodeModel(); JDefinedClass definedClass = codeModel._class(this.clazz.getCanonicalClassName(), ClassType.INTERFACE); definedClass.javadoc().append(this.clazz.getJavaDoc()); String genericType = this.clazz.getPackageName().replace(".service", ".model.ICollectionModel"); definedClass.generify("T extends " + genericType + "<?>"); this.appendClassMethods(codeModel, definedClass); codeModel.build(new File("src/main/java")); } catch (Exception ex) { throw new RuntimeException(ex); } }
private void createReportingValueClass(JCodeModel codeModel, String name, JPrimitiveType type) throws JClassAlreadyExistsException { JClass reportClazz = codeModel.ref("org.jpmml.evaluator.Report"); JDefinedClass clazz = codeModel._class(JMod.PUBLIC, "org.jpmml.evaluator.Reporting" + name, ClassType.CLASS); clazz._extends(codeModel.ref("org.jpmml.evaluator." + name)); clazz._implements(codeModel.ref("org.jpmml.evaluator.HasReport")); JFieldVar reportField = clazz.field(JMod.PRIVATE, reportClazz, "report", JExpr._null()); createCopyMethod(clazz); createOperationMethods(clazz, name, type); createReportMethod(clazz); createExpressionMethods(clazz); createAccessorMethods(clazz, reportField); createFormatMethod(clazz, type); }
public AbstractBaseMetaClass(JCodeModel cm, String fqn, ClassType ct) { try { this.generatedClass = cm._class(fqn, ct); } catch (JClassAlreadyExistsException e) { throw new IllegalStateException("Class: " + fqn + " already exists.", e); } }
@Override public JType define(AbstractType t) { JDefinedClass defineClass = owner.defineClass(t, ClassType.ENUM); Enum oneMeta = t.oneMeta(Enum.class); oneMeta.value().forEach(x -> { defineClass.enumConstant(owner.escape(x)); }); return defineClass; }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).containsExactly("LIGHT_BLUE", "RED", "YELLOW", "GREEN"); }
/** * Sets this Pojo's name * * @param pojoPackage The Package used to create POJO * @param className Class to be created * @return This instance */ public EnumBuilder withName(String pojoPackage, String className) { className = NamingHelper.convertToClassName(className); final String fullyQualifiedClassName = pojoPackage + "." + className; // Initiate package if necessary if (this.pojoPackage == null) { withPackage(pojoPackage); } // Builders should only have 1 active pojo under their responsibility if (this.pojo != null) { throw new IllegalStateException("Enum already created"); } try { // create the class logger.debug("Creating Enum " + fullyQualifiedClassName); this.pojo = this.pojoModel._class(fullyQualifiedClassName, ClassType.ENUM); // Handle Serialization // Do enums need to be serializable? //implementsSerializable(); } catch (JClassAlreadyExistsException e) { // class already exists - reuse it! logger.debug("Enum {} already exists. Reusing it!", fullyQualifiedClassName); this.pojo = this.pojoModel._getClass(fullyQualifiedClassName); } // Add to shortcuts this.codeModels.put(fullyQualifiedClassName, this.pojo); return this; }
@Override public Type declare(int mods, TIdentifier identifier, ClassType ctype, Optional<String> name) throws JClassAlreadyExistsException { String className; if (name.isPresent()) { className = name.get(); } else { className = identifier.getText(); } JDefinedClass child = type._class(mods, className, ctype); Type childT = new Type(this, new TypeScope(child, this), child, identifier); types.put(className, childT); return childT; }
@Override public Type declare(int mods, TIdentifier identifier, ClassType ctype, Optional<String> name) throws JClassAlreadyExistsException { String className; if (name.isPresent()) { className = name.get(); } else { className = identifier.getText(); } JDefinedClass child = pack._class(mods, className, ctype); Type childT = new Type(this, new TypeScope(child, this), child, identifier); types.put(className, childT); return childT; }
public Type declare(int mods, TIdentifier identifier, ClassType ctype, Optional<String> name, FileScope directParent) throws JClassAlreadyExistsException { String className; if (name.isPresent()) { className = name.get(); } else { className = identifier.getText(); } JDefinedClass child = pack._class(mods, className, ctype); Type childT = new Type(this, new TypeScope(child, directParent), child, identifier); types.put(className, childT); return childT; }
private static void createRetrieveIdEnum(List<Retrieve> retrieves, String packageName, File destinationDir) throws JClassAlreadyExistsException, IOException { JCodeModel codeModel = new JCodeModel(); JDefinedClass enumClass = codeModel._class(JMod.PUBLIC, String.format("%s.MapEngineRetrieveId", packageName), ClassType.ENUM); for (Retrieve retrieve : retrieves) { enumClass.enumConstant(retrieve.getId()); } codeModel.build(destinationDir); }
@Override public void generete(AbstractStruct definition) throws Exception { JDefinedClass jStructClass = this.getJavaPackage()._class(JMod.PUBLIC, definition.getName(), ClassType.CLASS); Map<String, JType> fields = new HashMap<>(); if (definition.getFields() != null) for (ThriftField field : definition.getFields()) { JType fieldType = this.resolvType(field.getType()); if (fieldType == null){ fieldType = this.codeModel.directClass(field.getType().toString()); } fields.put(field.getName(), fieldType); } new StructCodeGeneratorHelper().whithCodeModel(this.codeModel).buildStruct(fields, jStructClass); }
public ConstantsCodeGenerator() { try { jConstantsClass = this.getJavaPackage()._class(JMod.PUBLIC | JMod.FINAL, "Constant", ClassType.CLASS); } catch (JClassAlreadyExistsException e) { e.printStackTrace(); } }
private JDefinedClass generateEnum(EnumDataSchema schema) throws JClassAlreadyExistsException { JDefinedClass enumClass = getPackage(schema.getNamespace())._class(JMod.PUBLIC, escapeReserved(schema.getName()), ClassType.ENUM); enumClass.javadoc().append(schema.getDoc()); setDeprecatedAnnotationAndJavadoc(schema, enumClass); registerGeneratedClass(schema, enumClass); generateSchemaField(enumClass, schema); for (String value: schema.getSymbols()) { if (isReserved(value)) { throw new IllegalArgumentException("Enum contains Java reserved symbol: " + value + " schema: " + schema); } JEnumConstant enumConstant = enumClass.enumConstant(value); String enumConstantDoc = schema.getSymbolDocs().get(value); if (enumConstantDoc != null) { enumConstant.javadoc().append(enumConstantDoc); } setDeprecatedAnnotationAndJavadoc(schema, value, enumConstant); } enumClass.enumConstant(DataTemplateUtil.UNKNOWN_ENUM); return enumClass; }
private void generateBuilderInterface(final Map<String, BuilderOutline> builderOutlines, final DefinedInterfaceOutline interfaceOutline) throws SAXException { try { builderOutlines.put(interfaceOutline.getImplClass().fullName(), new BuilderOutline(interfaceOutline, /* interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getFluentClassName().getInterfaceName(), ClassType.INTERFACE) */ interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getBuilderClassName().getInterfaceName(), ClassType.INTERFACE) /*interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getWrapperClassName().getInterfaceName(), ClassType.INTERFACE), interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getModifierClassName().getInterfaceName(), ClassType.INTERFACE) */ )); } catch (final JClassAlreadyExistsException e) { this.pluginContext.errorHandler.error(new SAXParseException(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("error.interface-exists"), interfaceOutline.getImplClass().fullName(), PluginContext.BUILDER_INTERFACE_NAME), interfaceOutline.getSchemaComponent().getLocator())); } }
/** * check if a JType is an enum type * * @param jType * @return boolean */ private static boolean isEnum(JType jType) { if (jType instanceof JDefinedClass) { // is enum? JDefinedClass jDefinedClass = (JDefinedClass) jType; ClassType classType = jDefinedClass.getClassType(); if (classType == ClassType.ENUM) { return true; } } return false; }
private void buildJavaClass() { try { JCodeModel codeModel = new JCodeModel(); JDefinedClass definedClass = codeModel._class(this.clazz.getCanonicalClassName(), ClassType.INTERFACE); definedClass.javadoc().append(this.clazz.getJavaDoc()); definedClass.generify("T extends IModel"); this.appendClassMethods(codeModel, definedClass); codeModel.build(new File("src/main/java")); } catch (Exception ex) { throw new RuntimeException(ex); } }
private void buildJavaClass() { try { JCodeModel codeModel = new JCodeModel(); JDefinedClass definedClass = codeModel._class(this.clazz.getCanonicalClassName(), ClassType.INTERFACE); definedClass.javadoc().append(this.clazz.getJavaDoc()); codeModel.build(new File("src/main/java")); } catch (Exception ex) { throw new RuntimeException(ex); } }
private void buildJavaClass() { try { JCodeModel codeModel = new JCodeModel(); JDefinedClass definedClass = codeModel._class(this.clazz.getCanonicalClassName(), ClassType.INTERFACE); definedClass.javadoc().append(this.clazz.getJavaDoc()); this.appendClassMethods(codeModel, definedClass); codeModel.build(new File("src/main/java")); } catch (Exception ex) { throw new RuntimeException(ex); } }
private void createReportingVectorClass(JCodeModel codeModel, String name, JPrimitiveType type) throws JClassAlreadyExistsException { JDefinedClass clazz = codeModel._class(JMod.ABSTRACT | JMod.PUBLIC, "org.jpmml.evaluator.Reporting" + name, ClassType.CLASS); clazz._extends(codeModel.ref("org.jpmml.evaluator." + name)); JFieldVar expressionField = clazz.field(JMod.PRIVATE, String.class, "expression", JExpr.lit("")); createNewReportMethod(clazz); createOperationMethods(clazz, name, type); createValueMethods(clazz, type); createReportMethod(clazz); createAccessorMethods(clazz, expressionField); }
private void generateClass(JCodeModel codeModel) throws Exception { JDefinedClass definedClass = codeModel._class(className, ClassType.INTERFACE); if (localizableClass.isInterface()) { definedClass._implements(localizableClass); } else { definedClass._extends(localizableClass); } generateFromPropertiesFile(definedClass); }
public AbstractMetaInterface(JCodeModel cm, String fqn) { super(cm, fqn, ClassType.INTERFACE); }
protected JDefinedClass _class(final String name, final ClassType clazz) throws JClassAlreadyExistsException { ensureThatArgument(name, notNull()); ensureThatArgument(clazz, notNull()); return this.codeModel._class(name, ClassType.CLASS); }