com.sun.codemodel.JInvocation Java Examples

The following examples show how to use com.sun.codemodel.JInvocation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitBooleanOperator(BooleanOperator call, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(call.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(call.getCompleteType());
    HoldingContainer returnContainer = super.visitBooleanOperator(call, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitBooleanOperator(call, generator);
}
 
Example #2
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holder, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (allowNewMethods && shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(holder.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(holder.getCompleteType());
    HoldingContainer returnContainer = super.visitFunctionHolderExpression(holder, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitFunctionHolderExpression(holder, generator);
}
 
Example #3
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitConvertExpression(ConvertExpression e, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(e.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(e.getCompleteType());
    HoldingContainer returnContainer = super.visitConvertExpression(e, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitConvertExpression(e, generator);
}
 
Example #4
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
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(_enum, fromValue);
}
 
Example #5
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JInvocation appendFieldsToString(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass toStringBuilderRef) {
	JInvocation invocation = JExpr._new(toStringBuilderRef).arg(JExpr._this());
	Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();

	if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) { // If
																				// this
																				// POJO
																				// has
																				// a
																				// superclass,
																				// append
																				// the
																				// superclass
																				// toString()
																				// method.
		invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("toString"));
	}

	while (iterator.hasNext()) {
		Map.Entry<String, JFieldVar> pair = iterator.next();
		invocation = invocation.invoke("append").arg(JExpr.lit(pair.getKey())).arg(pair.getValue());
	}

	return invocation;
}
 
Example #6
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitIfExpression(IfExpression ifExpr, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(ifExpr.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(ifExpr.getCompleteType());
    HoldingContainer returnContainer = super.visitIfExpression(ifExpr, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitIfExpression(ifExpr, generator);
}
 
Example #7
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JInvocation appendFieldsToHashCode(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass hashCodeBuilderRef) {
	JInvocation invocation = JExpr._new(hashCodeBuilderRef);
	Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();

	if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) { // If
																				// this
																				// POJO
																				// has
																				// a
																				// superclass,
																				// append
																				// the
																				// superclass
																				// hashCode()
																				// method.
		invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
	}

	while (iterator.hasNext()) {
		Map.Entry<String, JFieldVar> pair = iterator.next();
		invocation = invocation.invoke("append").arg(pair.getValue());
	}

	return invocation;
}
 
Example #8
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private void withEquals() {
	JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals");
	JVar otherObject = equals.param(Object.class, "other");

	Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class;
	if (!Config.getPojoConfig().isUseCommonsLang3()) {
		equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class;
	}

	JBlock body = equals.body();

	body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE);
	body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
	body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE);

	JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject));

	JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass);

	JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef);

	body._return(equalsBuilderInvocation.invoke("isEquals"));
}
 
Example #9
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
    if (!useGenericTypes) {
        return null;
    }
    if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
        int schemaId = getSchemaId(valueSchema);
        if (schemaVarMap.get(schemaId) != null) {
            return schemaVarMap.get(schemaId);
        } else {
            JVar schemaVar = schemaMapMethod.body().decl(codeModel.ref(Schema.class),
                    getVariableName(StringUtils.uncapitalize(variableName)), getValueType);
            registerSchema(valueSchema, schemaId, schemaVar);
            schemaVarMap.put(schemaId, schemaVar);
            return schemaVar;
        }
    } else {
        return null;
    }
}
 
Example #10
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private void processFixed(final Schema schema, JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putFixedIntoParent) {
    if (action.getShouldRead()) {
        JVar fixedBuffer = body.decl(codeModel.ref(byte[].class), getVariableName(schema.getName()))
                .init(JExpr.direct(" new byte[" + schema.getFixedSize() + "]"));

        body.directStatement(DECODER + ".readFixed(" + fixedBuffer.name() + ");");

        JInvocation createFixed = JExpr._new(schemaAssistant.classFromSchema(schema));
        if (useGenericTypes)
            createFixed = createFixed.arg(getSchemaExpr(schema));

        putFixedIntoParent.accept(body, createFixed.arg(fixedBuffer));
    } else {
        body.directStatement(DECODER + ".skipFixed(" + schema.getFixedSize() + ");");
    }
}
 
Example #11
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JInvocation appendFieldsToEquals(Map<String, JFieldVar> nonTransientAndNonStaticFields, JVar otherObject,
		JClass equalsBuilderRef) {
	JInvocation invocation = JExpr._new(equalsBuilderRef);
	Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();

	if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) {// If
																			// this
																			// POJO
																			// has
																			// a
																			// superclass,
																			// append
																			// the
																			// superclass
																			// equals()
																			// method.
		invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject));
	}

	while (iterator.hasNext()) {
		Map.Entry<String, JFieldVar> pair = iterator.next();
		invocation = invocation.invoke("append").arg(pair.getValue()).arg(otherObject.ref(pair.getKey()));
	}

	return invocation;
}
 
Example #12
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
 
Example #13
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
  if (!useGenericTypes) {
    return null;
  }
  if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
    long schemaId = Utils.getSchemaFingerprint(valueSchema);
    if (schemaVarMap.get(schemaId) != null) {
      return schemaVarMap.get(schemaId);
    } else {
      JVar schemaVar = generatedClass.field(JMod.PRIVATE | JMod.FINAL, Schema.class,
          getUniqueName(StringUtils.uncapitalize(variableName)));
      constructor.body().assign(JExpr.refthis(schemaVar.name()), getValueType);

      registerSchema(valueSchema, schemaId, schemaVar);
      return schemaVar;
    }
  } else {
    return null;
  }
}
 
Example #14
Source File: DrillComplexWriterAggFuncHolder.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public JVar[] renderStart(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, FieldReference fieldReference) {
  if (!classGenerator.getMappingSet().isHashAggMapping()) {  //Declare workspace vars for non-hash-aggregation.
    JInvocation container = classGenerator.getMappingSet().getOutgoing().invoke("getOutgoingContainer");

    complexWriter = classGenerator.declareClassField("complexWriter", classGenerator.getModel()._ref(ComplexWriter.class));
    writerIdx = classGenerator.declareClassField("writerIdx", classGenerator.getModel()._ref(int.class));
    lastWriterIdx = classGenerator.declareClassField("lastWriterIdx", classGenerator.getModel()._ref(int.class));
    //Default name is "col", if not passed in a reference name for the output vector.
    String refName = fieldReference == null ? "col" : fieldReference.getRootSegment().getPath();
    JClass cwClass = classGenerator.getModel().ref(VectorAccessibleComplexWriter.class);
    classGenerator.getSetupBlock().assign(complexWriter, cwClass.staticInvoke("getWriter").arg(refName).arg(container));
    classGenerator.getSetupBlock().assign(writerIdx, JExpr.lit(0));
    classGenerator.getSetupBlock().assign(lastWriterIdx, JExpr.lit(-1));

    JVar[] workspaceJVars = declareWorkspaceVariables(classGenerator);
    generateBody(classGenerator, ClassGenerator.BlockType.SETUP, setup(), null, workspaceJVars, true);
    return workspaceJVars;
  } else {
    return super.renderStart(classGenerator, inputVariables, fieldReference);
  }
}
 
Example #15
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * 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")));
}
 
Example #16
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
static
private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){
	JInvocation invocation;

	if(method.type() != null){
		invocation = JExpr._super().invoke(method.name());
	} else

	{
		invocation = JExpr.invoke("super");
	}

	List<JVar> parameters = method.params();
	for(JVar parameter : parameters){
		invocation.arg(parameter);
	}

	return invocation;
}
 
Example #17
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JMethod addAddMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) {
    List<JClass> typeParams = ((JClass) getJavaType(field)).getTypeParameters();
    if (!typeParams.iterator().hasNext()) {
        return null;
    }
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "add" + StringUtils.capitalize(field.name()));
    JBlock block = method.body();
    String fieldName = field.name();
    JVar param = method.param(JMod.FINAL, typeParams.iterator().next(), fieldName);
    if (inherit) {
        generateSuperCall(method);
    } else {
        JInvocation invocation = JExpr.refthis(fieldName).invoke("add").arg(param);
        block.add(invocation);
    }
    block._return(JExpr._this());
    return method;
}
 
Example #18
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private void generateSuperCall(JMethod method) {
    method.annotate(Override.class);
    JBlock block = method.body();
    JInvocation superInvocation = block.invoke(JExpr._super(), method);
    for (JVar param : method.params()) {
        superInvocation.arg(param);
    }
}
 
Example #19
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private JInvocation createReportInvocation(JDefinedClass clazz, String operation, List<JVar> parameters, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	return createReportInvocation(clazz, JExpr._new(stringBuilderClazz).arg(JExpr.lit(256)), operation, parameters, type);
}
 
Example #20
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JInvocation invokeListener(final JBlock block, final JFieldVar field, final JVar oldValueVar, final JVar setterArg, final String aspectName) {
	final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1);
	final JInvocation fvcInvoke = block.invoke(JExpr._this().ref(aspectName + BoundPropertiesPlugin.SUPPORT_FIELD_SUFFIX), "fire" + aspectNameCap);
	fvcInvoke.arg(JExpr.lit(field.name()));
	fvcInvoke.arg(oldValueVar);
	fvcInvoke.arg(setterArg);
	return fvcInvoke;
}
 
Example #21
Source File: ImmutablePlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JInvocation generateImmutableListInstantiation(final PluginContext pluginContext, final JFieldRef fieldRef, final JType elementType) {
	if (this.overrideCollectionClass == null) {
		return pluginContext.unmodifiableList(fieldRef);
	} else {
		final JClass overrideCollection = pluginContext.codeModel.ref(this.overrideCollectionClass);
		if (overrideCollection.isAssignableFrom(pluginContext.codeModel.ref(Collection.class))) {
			return pluginContext.unmodifiableList(fieldRef);
		} else {
			return JExpr._new(overrideCollection.narrow(elementType)).arg(fieldRef);
		}
	}
}
 
Example #22
Source File: PartialCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
@Override
public JExpression generatePartialArgs(final JExpression expression) {
	if(expression instanceof JInvocation) {
		return ((JInvocation)expression).arg(this.fieldPathVar).arg(getPropertyTreeUseParam());
	} else if(expression instanceof JTypedInvocation) {
		return ((JTypedInvocation)expression).arg(this.fieldPathVar).arg(getPropertyTreeUseParam());
	} else {
		return expression;
	}
}
 
Example #23
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() 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 emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
    }
}
 
Example #24
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() 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, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.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"));
}
 
Example #25
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #26
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitWithoutUnitNameSpecified() 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, EntityManagerFactory.class, "emf");
    emField.annotate(PersistenceUnit.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("JpaUnitException expected");
    } catch (final JpaUnitException e) {

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example #27
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() 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");
    emField.annotate(PersistenceContext.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("JpaUnitException expected");
    } catch (final JpaUnitException e) {

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example #28
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() 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, "emf");
    emField.annotate(PersistenceUnit.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
    }
}
 
Example #29
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextFieldOfWrongType() 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, EntityManagerFactory.class, "em");
    emField.annotate(PersistenceContext.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager"));
    }
}
 
Example #30
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceContextFields() 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 em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
    em1Field.annotate(PersistenceContext.class);
    final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
    em2Field.annotate(PersistenceContext.class);
    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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("Only single field is allowed"));
    }
}