@Override public org.jsonschema2pojo.rules.Rule<JPackage, JType> getObjectRule() { final org.jsonschema2pojo.rules.Rule<JPackage, JType> workingRule = super.getObjectRule(); return new org.jsonschema2pojo.rules.Rule<JPackage, JType>() { @Override public JType apply(String nodeName, JsonNode node, JPackage generatableType, Schema currentSchema) { JType objectType = workingRule.apply(nodeName, node, generatableType, currentSchema); if( objectType instanceof JDefinedClass ) { JDefinedClass jclass = (JDefinedClass)objectType; jclass.method(JMod.PUBLIC, jclass.owner().BOOLEAN, "brokenMethod").body(); } return objectType; } }; }
private void addFactoryMethod(JDefinedClass _enum, JType backingType) { JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType); JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue"); JVar valueParam = fromValue.param(backingType, "value"); JBlock body = fromValue.body(); JVar constant = body.decl(_enum, "constant"); constant.init(quickLookupMap.invoke("get").arg(valueParam)); JConditional _if = body._if(constant.eq(JExpr._null())); JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class)); JExpression expr = valueParam; // if string no need to add "" if(!isString(backingType)){ expr = expr.plus(JExpr.lit("")); } illegalArgumentException.arg(expr); _if._then()._throw(illegalArgumentException); _if._else()._return(constant); ruleFactory.getAnnotator().enumCreatorMethod(fromValue); }
private void addToString(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString"); Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes())); JBlock body = toString.body(); Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class; JClass toStringBuilderClass = jclass.owner().ref(toStringBuilder); JInvocation toStringBuilderInvocation = JExpr._new(toStringBuilderClass).arg(JExpr._this()); if (!jclass._extends().fullName().equals(Object.class.getName())) { toStringBuilderInvocation = toStringBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("toString")); } for (JFieldVar fieldVar : fields.values()) { if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } toStringBuilderInvocation = toStringBuilderInvocation.invoke("append").arg(fieldVar.name()).arg(fieldVar); } body._return(toStringBuilderInvocation.invoke("toString")); toString.annotate(Override.class); }
private void addHashCode(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode"); Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class; JBlock body = hashCode.body(); JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder); JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass); if (!jclass._extends().fullName().equals(Object.class.getName())) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); }
/** * 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); } }
/** * Creates a random MetaField * * @param owner * The class that owns this field. * @param name * The name of the meta field. */ public JavaBeanBasicField(MetaJavaBean owner, String name) { super(owner, name); this.basicType = BasicType.getRandom(); // Generate the field declaration JDefinedClass ownerClass = owner.getGeneratedClass(); this.generatedField = ownerClass.field(JMod.PRIVATE, basicType.getTypeClass(), name); // The getter getter = ownerClass.method(JMod.PUBLIC, basicType.getTypeClass(), "get" + name.substring(0, 1).toUpperCase() + name.substring(1)); getter.body()._return(this.generatedField); // And the setter setter = ownerClass.method(JMod.PUBLIC, void.class, "set" + name.substring(0, 1).toUpperCase() + name.substring(1)); JVar setterParam = setter.param(basicType.getTypeClass(), name); setter.body().assign(JExpr._this().ref(this.generatedField), setterParam); }
public JavaBeanRefField(MetaJavaBean owner, String name, MetaJavaBean refBean) { super(owner, name); this.refBean = refBean; // Generate the field declaration JDefinedClass ownerClass = owner.getGeneratedClass(); this.generatedField = ownerClass.field(JMod.PRIVATE, refBean.getGeneratedClass(), name); // The getter getter = ownerClass.method(JMod.PUBLIC, refBean.getGeneratedClass(), "get"+name.substring(0, 1).toUpperCase()+name.substring(1)); getter.body()._return(this.generatedField); // The setter setter = ownerClass.method(JMod.PUBLIC, void.class, "set"+name.substring(0, 1).toUpperCase()+name.substring(1)); JVar setterParam = setter.param(refBean.getGeneratedClass(), name); setter.body().assign(JExpr._this().ref(this.generatedField), setterParam); }
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(returnValue.type, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValue.type), returnValue.name, JExpr._new(g.getHolderType(returnValue.type))); addProtectedBlock(g, sub, output, null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset, null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup, null, workspaceJVars, false); return out; }
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(resolvedOutput, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, resolvedOutput.getHolderType(g.getModel()), getReturnName(), JExpr._new(resolvedOutput.getHolderType(g.getModel()))); addProtectedBlock(g, sub, output(), null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false); return out; }
CodeGenerator(CodeCompiler compiler, MappingSet mappingSet, TemplateClassDefinition<T> definition) { Preconditions.checkNotNull(definition.getSignature(), "The signature for defintion %s was incorrectly initialized.", definition); this.definition = definition; this.compiler = compiler; this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber(); this.fqcn = PACKAGE_NAME + "." + className; try { this.model = new JCodeModel(); JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className); clazz = clazz._extends(model.directClass(definition.getTemplateClassName())); clazz.constructor(JMod.PUBLIC).body().invoke(SignatureHolder.INIT_METHOD); rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(), clazz, model); } catch (JClassAlreadyExistsException e) { throw new IllegalStateException(e); } }
private JFieldVar listMember( final JDefinedClass instance, final JType clazz, final String name, final String[] generics, final boolean isNullable, final boolean isCollectionNullable) { final JFieldVar field = instance.field(JMod.FINAL | JMod.PRIVATE, clazz, name); if (isNullable && isCollectionNullable) { return field; } final JType type = withoutGenerics(clazz.fullName()).startsWith(JAVA_UTIL_LIST) ? _type(JAVA_UTIL_ARRAYLIST, generics) : clazz; field.init(JExpr._new(type)); return field; }
public JVar create( final JDefinedClass instance, final boolean returnInstance, final JFieldVar field, final String name, final boolean isImutable, final boolean isNullable, final boolean isArrayNullable, final boolean isCollectionNullable, final List<Annotation> annotations) throws CreationException { final JMethod method = instance.method(JMod.PUBLIC, returnInstance ? instance : _void(), name); annotate(method, annotations); final JVar variable = addParameter( method, returnInstance ? JExpr._this() : null, field, isImutable, isNullable, isArrayNullable, isCollectionNullable); if (returnInstance) { method.body()._return(JExpr._this()); } return variable; }
public JMethod createCreateBeanMethod(final JDefinedClass bean) { final JMethod method = bean.method(JMod.PRIVATE | JMod.STATIC, bean, "_createBean"); final JVar param = method.param( _classByNames(java.lang.Class.class.getName(), MessageFormat.format("? extends {0}", bean.name())), "clazz"); final JClass invokerClass = _classByNames( "net.anwiba.commons.reflection.ReflectionConstructorInvoker", bean.name()); final JTryBlock _try = method.body()._try(); final JVar invoker = _try.body().decl(invokerClass, "invoker", JExpr._new(invokerClass).arg(param)); //$NON-NLS-1$ _try.body()._return(invoker.invoke("invoke")); final JCatchBlock _catch = _try._catch(_classByNames(java.lang.reflect.InvocationTargetException.class.getName())); final JVar exception = _catch.param("exception"); //$NON-NLS-1$ _catch.body()._throw(JExpr._new(_classByNames(java.lang.RuntimeException.class.getName())).arg(exception)); return method; }
public void createEquals(final JDefinedClass bean, final Iterable<JFieldVar> fields) { final JMethod method = bean.method(JMod.PUBLIC, this.codeModel.BOOLEAN, "equals"); method.annotate(java.lang.Override.class); final JVar object = method.param(_type(java.lang.Object.class.getName()), "object"); final JBlock block = method.body(); block._if(JExpr._this().eq(object))._then()._return(JExpr.TRUE); block._if(object._instanceof(bean).not())._then()._return(JExpr.FALSE); JExpression result = JExpr.TRUE; final JExpression other = block.decl(bean, "other", JExpr.cast(bean, object)); final JClass objectUtilities = _classByNames(net.anwiba.commons.lang.object.ObjectUtilities.class.getName()); for (final JFieldVar field : fields) { result = result.cand(objectUtilities.staticInvoke("equals").arg(JExpr.refthis(field.name())).arg(other.ref(field))); } block._return(result); }
@SafeVarargs public static JVar addMapParameter( final JMethod method, final JFieldVar field, final JType nameType, final String nameVariableName, final JType valueType, final String valueVariableName, final boolean isInjection, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar nameParam = method.param(JMod.FINAL, nameType, nameVariableName); final JVar valueParam = method.param(JMod.FINAL, valueType, valueVariableName); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(nameParam); closure.execute(valueParam); } if (isInjection) { method.body().invoke("_inject").arg(nameParam).arg(valueParam); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("put").arg(nameParam).arg(valueParam)); //$NON-NLS-1$ return valueParam; }
@SafeVarargs public static JVar setMapParameters( final JMethod method, final JFieldVar field, final boolean isClearEnabled, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar param = method.param(JMod.FINAL, field.type(), field.name()); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(param); } if (isClearEnabled) { method.body().add(JExpr.refthis(field.name()).invoke("clear")); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("putAll").arg(param)); //$NON-NLS-1$ return param; }
@SafeVarargs public static JVar addListParameter( final JMethod method, final JFieldVar field, final boolean isClearEnabled, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar param = method.param(JMod.FINAL, field.type(), field.name()); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(param); } if (isClearEnabled) { method.body().add(JExpr.refthis(field.name()).invoke("clear")); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("addAll").arg(param)); //$NON-NLS-1$ return param; }
/** * <p>createResourceMethod.</p> * * @param resourceInterface a {@link com.sun.codemodel.JDefinedClass} object. * @param methodName a {@link java.lang.String} object. * @param returnType a {@link com.sun.codemodel.JType} object. * @return a {@link com.sun.codemodel.JMethod} object. */ public JMethod createResourceMethod(final JDefinedClass resourceInterface, final String methodName, final JType returnType) { final Set<String> existingMethodNames = resourcesMethods.get(resourceInterface.name()); String actualMethodName; int i = -1; while (true) { actualMethodName = methodName + (++i == 0 ? "" : Integer.toString(i)); if (!existingMethodNames.contains(actualMethodName)) { existingMethodNames.add(actualMethodName); break; } } return resourceInterface.method(JMod.NONE, returnType, actualMethodName); }
protected JClass createResourceMethodReturnType(final String methodName, final Action action, final JDefinedClass resourceInterface) throws Exception { final JDefinedClass responseClass = resourceInterface._class(capitalize(methodName) + "Response") ._extends(context.getResponseWrapperType()); final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE); responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate"); responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate")); for (final Response statusCodeAndResponse : action.responses()) { createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse); } return responseClass; }
private JDefinedClass createResourceMethodReturnType(final String methodName, final Action action, final JDefinedClass resourceInterface) throws Exception { final JDefinedClass responseClass = resourceInterface._class(capitalize(methodName) + "Response") ._extends(context.getResponseWrapperType()); final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE); responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate"); responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate")); for (final Response statusCodeAndResponse : action.responses()) { createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse); } return responseClass; }
@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; }
@Override public void customize(ClassCustomizerParameters parameters) { parameters.clazz._implements(Cloneable.class); parameters.clazz.method(JMod.PUBLIC, parameters.clazz, "clone").body().add(new JStatement() { @Override public void state(JFormatter f) { f.p("try {"); f.nl(); f.p("return ("+parameters.clazz.name()+")super.clone();"); f.nl(); f.p("} catch (CloneNotSupportedException e){ throw new IllegalStateException(e);}"); f.nl(); } }); }
private void addDiscriminator(JDefinedClass klass, ObjectTypeDeclaration type) { if (type.discriminator() == null) { return; } String discriminatorValue = type.discriminatorValue(); if (discriminatorValue == null) { discriminatorValue = type.name(); } JFieldVar field = klass.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, codeModel._ref(String.class), DISCRIMINATOR); field.init(JExpr.lit(discriminatorValue)); if (context.getConfig().isDiscriminatorMutable()) { klass.constructor(JMod.PUBLIC).body().invoke(getSetterName(type.discriminator())) .arg(field); } else { generateDiscriminatorGetter(type, klass, type.discriminator()); } }
/** * @param klass * @param property */ private void generateAdditionalPropertiesFieldAndAccessors(JDefinedClass klass, TypeDeclaration property) { String fieldName = Names.buildVariableName(property); JClass mapType = codeModel.ref(Map.class).narrow(String.class, Object.class); JFieldVar field = klass.field(JMod.PRIVATE, mapType, fieldName); annotateFieldWithPropertyName(field, property); JMethod getter = klass.method(JMod.PUBLIC, mapType, getGetterName(fieldName)); getter.body()._return(field); if (property.description() != null) { getter.javadoc().add(property.description().value()); } generateSetter(klass, mapType, fieldName); }
private void generateListFieldAndAccessors(JDefinedClass klass, ArrayTypeDeclaration property) { String fieldName = Names.buildVariableName(property); String itemTypeName = context.getApiModel().getItemType(property); JType elementType = findTypeVar(klass, property).orElse(context.getJavaType(itemTypeName)); JClass listType = codeModel.ref(List.class).narrow(elementType); JFieldVar field = klass.field(JMod.PRIVATE, listType, fieldName); annotateFieldWithPropertyName(field, property); JMethod getter = klass.method(JMod.PUBLIC, listType, getGetterName(fieldName)); getter.body()._return(field); if (property.description() != null) { getter.javadoc().add(property.description().value()); } generateSetter(klass, listType, fieldName); }
private void generateObjectFieldAndAccessors(JDefinedClass klass, TypeDeclaration property) { String fieldName = Names.buildVariableName(property); JType jtype = findTypeVar(klass, property).orElse(context.getJavaType(property)); List<String> args = Annotations.getStringAnnotations(property, TYPE_ARGS); if (!args.isEmpty()) { JClass jclass = (JClass) jtype; for (String arg : args) { JType typeArg = findTypeParam(klass, arg).get(); jclass = jclass.narrow(typeArg); } jtype = jclass; } JFieldVar field = klass.field(JMod.PRIVATE, jtype, fieldName); annotateFieldWithPropertyName(field, property); generateGetter(property, klass, field, this::getGetterName); generateSetter(klass, jtype, fieldName); }
private void buildNonVoidMethods(Method method, int numResponseTypes) { for (int bodyIndex = 0; bodyIndex < numResponseTypes; bodyIndex++) { TypeDeclaration body = method.responses().get(0).body().get(bodyIndex); String methodName = buildMethodName(method, bodyIndex); JMethod codeMethod = klass.method(JMod.NONE, klass, methodName); addJavadoc(method, codeMethod); addSubresourcePath(codeMethod); addHttpMethodAnnotation(method.method(), codeMethod); addBodyParameters(method, codeMethod); addPathParameters(method, codeMethod); addQueryParameters(method, codeMethod); addReturnType(method, codeMethod, body); addProduces(codeMethod, body); } }
@Test public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception { final String simpleClassName = "EntityClass"; final String nodeLabel = "ENTITY_CLASS"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.annotate(Table.class).param("name", nodeLabel); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass)); assertThat(clazz, equalTo(entityClass)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, String.class, idPropertyName).annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@BeforeClass public static void generateTestModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "A"); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, Long.class, "id").annotate(Id.class); jClass.field(JMod.PRIVATE, String.class, "value"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); entityAClass = loadClass(testFolder.getRoot(), jClass.name()); }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@BeforeClass public static void generateModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class); jAnnotationUse.param("value", "Script.file"); jClass.annotate(Cleanup.class); final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField"); jField.annotate(PersistenceContext.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jAnnotationUse = jMethod.annotate(InitialDataSets.class); jAnnotationUse.param("value", "InitialDataSets.file"); jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class); jAnnotationUse.param("value", "ApplyScriptsAfter.file"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); cut = loadClass(testFolder.getRoot(), jClass.name()); }
/** * Creates {@link #innerClassGenerator} with inner class * if {@link #hasMaxIndexValue()} returns {@code true}. * * @return true if splitting happened. */ private boolean createNestedClass() { if (hasMaxIndexValue()) { // all new fields will be declared in the class from innerClassGenerator if (innerClassGenerator == null) { try { JDefinedClass innerClazz = clazz._class(JMod.PRIVATE, clazz.name() + "0"); innerClassGenerator = new ClassGenerator<>(codeGenerator, mappings, sig, evaluationVisitor, innerClazz, model, optionManager); } catch (JClassAlreadyExistsException e) { throw new DrillRuntimeException(e); } oldBlocks = blocks; innerClassGenerator.index = index; innerClassGenerator.maxIndex += index; // blocks from the inner class should be used setupInnerClassBlocks(); return true; } return innerClassGenerator.createNestedClass(); } return false; }
/** * The code generator creates a method called __DRILL_INIT__ which takes the * place of the constructor when the code goes though the byte code merge. * For Plain-old Java, we call the method from a constructor created for * that purpose. (Generated code, fortunately, never includes a constructor, * so we can create one.) Since the init block throws an exception (which * should never occur), the generated constructor converts the checked * exception into an unchecked one so as to not require changes to the * various places that create instances of the generated classes. * * Example:<code><pre> * public StreamingAggregatorGen1() { * try { * __DRILL_INIT__(); * } catch (SchemaChangeException e) { * throw new UnsupportedOperationException(e); * } * }</pre></code> * * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's * introspection package. But, Drill prefers Java 7 which only provides * parameter types. */ private void addCtor(Class<?>[] parameters) { JMethod ctor = clazz.constructor(JMod.PUBLIC); JBlock body = ctor.body(); // If there are parameters, need to pass them to the super class. if (parameters.length > 0) { JInvocation superCall = JExpr.invoke("super"); // This case only occurs for nested classes, and all nested classes // in Drill are inner classes. Don't pass along the (hidden) // this$0 field. for (int i = 1; i < parameters.length; i++) { Class<?> p = parameters[i]; superCall.arg(ctor.param(model._ref(p), "arg" + i)); } body.add(superCall); } JTryBlock tryBlock = body._try(); tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD); JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class)); catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e"))); }
@Override public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, JVar[] workspaceJVars, FieldReference fieldReference) { HoldingContainer out = classGenerator.declare(getReturnType(), false); JBlock sub = new JBlock(); classGenerator.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, classGenerator.getHolderType(getReturnType()), getReturnValue().getName(), JExpr._new(classGenerator.getHolderType(getReturnType()))); addProtectedBlock(classGenerator, sub, output(), null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!classGenerator.getMappingSet().isHashAggMapping()) { generateBody(classGenerator, BlockType.RESET, reset(), null, workspaceJVars, false); } generateBody(classGenerator, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false); return out; }
private JFieldVar addQuickLookupMap(JDefinedClass _enum, JType backingType) { JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum); JFieldVar lookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS"); JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum); lookupMap.init(JExpr._new(lookupImplType)); JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values")); JInvocation put = forEach.body().invoke(lookupMap, "put"); put.arg(forEach.var().ref("value")); put.arg(forEach.var()); return lookupMap; }
private JFieldVar addValueField(JDefinedClass _enum, JType type) { JFieldVar valueField = _enum.field(JMod.PRIVATE | JMod.FINAL, type, VALUE_FIELD_NAME); JMethod constructor = _enum.constructor(JMod.PRIVATE); JVar valueParam = constructor.param(type, VALUE_FIELD_NAME); JBlock body = constructor.body(); body.assign(JExpr._this().ref(valueField), valueParam); return valueField; }
private void addToString(JDefinedClass _enum, JFieldVar valueField) { JMethod toString = _enum.method(JMod.PUBLIC, String.class, "toString"); JBlock body = toString.body(); JExpression toReturn = JExpr._this().ref(valueField); if(!isString(valueField.type())){ toReturn = toReturn.plus(JExpr.lit("")); } body._return(toReturn); toString.annotate(Override.class); }