com.sun.codemodel.JMod Java Examples

The following examples show how to use com.sun.codemodel.JMod. 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: 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 #2
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
JMethod generateNewCopyBuilderMethod(final boolean partial) {
	final JDefinedClass typeDefinition = this.typeOutline.isInterface() && ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() : this.definedClass;
	final int mods = this.implement ? this.definedClass.isAbstract() ? JMod.PUBLIC | JMod.ABSTRACT : JMod.PUBLIC : JMod.NONE;
	final JMethod copyBuilderMethod = typeDefinition.method(mods, this.builderClass.raw, this.settings.getNewCopyBuilderMethodName());
	final JTypeVar copyBuilderMethodTypeParam = copyBuilderMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
	final JVar parentBuilderParam = copyBuilderMethod.param(JMod.FINAL, copyBuilderMethodTypeParam, BuilderGenerator.PARENT_BUILDER_PARAM_NAME);
	final CopyGenerator copyGenerator = this.pluginContext.createCopyGenerator(copyBuilderMethod, partial);
	copyBuilderMethod.type(this.builderClass.raw.narrow(copyBuilderMethodTypeParam));
	final JMethod copyBuilderConvenienceMethod = typeDefinition.method(mods, this.builderClass.raw.narrow(this.pluginContext.voidClass), this.settings.getNewCopyBuilderMethodName());
	final CopyGenerator copyConvenienceGenerator = this.pluginContext.createCopyGenerator(copyBuilderConvenienceMethod, partial);
	if (this.implement && !this.definedClass.isAbstract()) {
		copyBuilderMethod.body()._return(copyGenerator.generatePartialArgs(this.pluginContext._new((JClass)copyBuilderMethod.type()).arg(parentBuilderParam).arg(JExpr._this()).arg(JExpr.TRUE)));
		copyBuilderConvenienceMethod.body()._return(copyConvenienceGenerator.generatePartialArgs(this.pluginContext.invoke(this.settings.getNewCopyBuilderMethodName()).arg(JExpr._null())));
	}
	if (this.typeOutline.getSuperClass() != null) {
		copyBuilderMethod.annotate(Override.class);
		copyBuilderConvenienceMethod.annotate(Override.class);
	}
	return copyBuilderMethod;
}
 
Example #3
Source File: MetaPlugin.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private void generateMetaClass(final PluginContext pluginContext, final ClassOutline classOutline, final ErrorHandler errorHandler) throws SAXException {
	try {
		final JDefinedClass metaClass = classOutline.implClass._class(JMod.PUBLIC | JMod.STATIC, this.metaClassName);
		final JMethod visitMethod = generateVisitMethod(classOutline);
		for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
			if (this.extended) {
				generateExtendedMetaField(pluginContext, metaClass, visitMethod, fieldOutline);
			} else {
				generateNameOnlyMetaField(pluginContext, metaClass, fieldOutline);
			}
		}
		visitMethod.body()._return(JExpr._this());
	} catch (final JClassAlreadyExistsException e) {
		errorHandler.error(new SAXParseException(getMessage("error.metaClassExists", classOutline.implClass.name(), this.metaClassName), classOutline.target.getLocator()));
	}
}
 
Example #4
Source File: MergeablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateMergeFrom$createNewInstance(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	final JMethod existingMethod = theClass.getMethod("createNewInstance",
			new JType[0]);
	if (existingMethod == null) {

		final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
				.owner().ref(Object.class), "createNewInstance");
		newMethod.annotate(Override.class);
		{
			final JBlock body = newMethod.body();
			body._return(JExpr._new(theClass));
		}
		return newMethod;
	} else {
		return existingMethod;
	}
}
 
Example #5
Source File: MergeablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateMergeFrom$mergeFrom0(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	JCodeModel codeModel = theClass.owner();
	final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
			codeModel.VOID, "mergeFrom");
	mergeFrom$mergeFrom.annotate(Override.class);
	{
		final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
		final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
		final JBlock body = mergeFrom$mergeFrom.body();

		final JVar mergeStrategy = body.decl(JMod.FINAL,
				codeModel.ref(MergeStrategy2.class), "strategy",
				createMergeStrategy(codeModel));

		body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
				.arg(left).arg(right).arg(mergeStrategy);
	}
	return mergeFrom$mergeFrom;
}
 
Example #6
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
final void generateCopyToMethod(final boolean partial) {
	if (this.implement) {
		final JDefinedClass typeDefinition = this.typeOutline.isInterface() && ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() : this.definedClass;
		final JMethod copyToMethod = typeDefinition.method(JMod.PUBLIC, this.pluginContext.voidType, this.settings.getCopyToMethodName());
		final JTypeVar typeVar = copyToMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
		final JVar otherParam = copyToMethod.param(JMod.FINAL, this.builderClass.raw.narrow(typeVar), BuilderGenerator.OTHER_PARAM_NAME);
		final CopyGenerator cloneGenerator = this.pluginContext.createCopyGenerator(copyToMethod, partial);
		final JBlock body = copyToMethod.body();
		final JVar otherRef;
		if (this.typeOutline.getSuperClass() != null) {
			body.add(cloneGenerator.generatePartialArgs(this.pluginContext.invoke(JExpr._super(), copyToMethod.name()).arg(otherParam)));
		}
		otherRef = otherParam;
		generateFieldCopyExpressions(cloneGenerator, body, otherRef, JExpr._this());
		copyToMethod.javadoc().append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo")));
		copyToMethod.javadoc().addParam(otherParam).append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo.param.other")));
	}
}
 
Example #7
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private JMethod createMethod(final Schema schema, boolean read) {
    if (!Schema.Type.RECORD.equals(schema.getType())) {
        throw new FastDeserializerGeneratorException(
                "Methods are defined only for records, not for " + schema.getType());
    }
    if (methodAlreadyDefined(schema, read)) {
        throw new FastDeserializerGeneratorException("Method already exists for: " + schema.getFullName());
    }

    JMethod method = deserializerClass.method(JMod.PUBLIC,
            read ? schemaAssistant.classFromSchema(schema) : codeModel.VOID,
            getVariableName("deserialize" + schema.getName()));

    method._throws(IOException.class);
    method.param(Decoder.class, DECODER);

    (read ? deserializeMethodMap : skipMethodMap).put(schema.getFullName(), method);

    return method;
}
 
Example #8
Source File: ConnectPlugin.java    From kafka-connect-transform-xml with Apache License 2.0 6 votes vote down vote up
void processToStruct(JFieldVar schemaField, JCodeModel codeModel, ClassOutline classOutline) {
  final Map<String, JFieldVar> fields = classOutline.implClass.fields();
  final JClass structClass = codeModel.ref(Struct.class);
  final JMethod method = classOutline.implClass.method(JMod.PUBLIC, structClass, "toStruct");
  final JBlock methodBody = method.body();
  final JVar structVar = methodBody.decl(structClass, "struct", JExpr._new(structClass).arg(schemaField));

  for (final Map.Entry<String, JFieldVar> field : fields.entrySet()) {
    log.trace("processSchema() - processing name = '{}' type = '{}'", field.getKey(), field.getValue().type().name());
    if (schemaField.name().equals(field.getKey())) {
      log.trace("processSchema() - skipping '{}' cause we added it.", field.getKey());
      continue;
    }

    methodBody.invoke(structVar, "put")
        .arg(field.getKey())
        .arg(JExpr.ref(JExpr._this(), field.getKey()));
  }

  methodBody._return(structVar);
}
 
Example #9
Source File: AggrFunctionHolder.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, 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;
}
 
Example #10
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EqualsArguments cast(String suffix, JBlock block,
		JType jaxbElementType, boolean suppressWarnings) {
	final JVar castedLeftValue = block.decl(JMod.FINAL, jaxbElementType,
			leftValue().name() + suffix,
			JExpr.cast(jaxbElementType, leftValue()));
	if (suppressWarnings) {
		castedLeftValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	final JVar castedRightValue = block.decl(JMod.FINAL, jaxbElementType,
			rightValue().name() + suffix,
			JExpr.cast(jaxbElementType, rightValue()));
	if (suppressWarnings) {
		castedRightValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	return new EqualsArguments(getCodeModel(), castedLeftValue, JExpr.TRUE,
			castedRightValue, JExpr.TRUE);
}
 
Example #11
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generate(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodNamer.apply(implClass.name()));
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");
    travVizBloc.assign(retVal,
            JExpr.invoke(beanVar, "accept").arg(JExpr.invoke("getVisitor")));
    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    // case to traverse after the visit
    addTraverseBlock(travViz, beanVar, false);
    travVizBloc._return(retVal);
}
 
Example #12
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 #13
Source File: CreateVisitableInterface.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
@Override
  protected void run(Set<ClassOutline> classes, Set<JClass> directClasses) {
      final JDefinedClass _interface = outline.getClassFactory().createInterface(jpackage, "Visitable", null);
setOutput( _interface );
final JMethod _method = getOutput().method(JMod.NONE, void.class, "accept");
final JTypeVar returnType = _method.generify("R");
final JTypeVar exceptionType = _method.generify("E", Throwable.class);
_method.type(returnType);
_method._throws(exceptionType);
final JClass narrowedVisitor = visitor.narrow(returnType, exceptionType);
_method.param(narrowedVisitor, "aVisitor");
      
      for(ClassOutline classOutline : classes) {
          classOutline.implClass._implements(getOutput());
      }
  }
 
Example #14
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 #15
Source File: AddAcceptMethod.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
public void run(Set<ClassOutline> sorted, JDefinedClass visitor) {
        // skip over abstract classes
// add the accept method to the bean
        sorted.stream().filter(classOutline -> !classOutline.target.isAbstract()).forEach(classOutline -> {
            // add the accept method to the bean
            JDefinedClass beanImpl = classOutline.implClass;
            final JMethod acceptMethod = beanImpl.method(JMod.PUBLIC, void.class, "accept");
            final JTypeVar returnType = acceptMethod.generify("R");
            final JTypeVar exceptionType = acceptMethod.generify("E", Throwable.class);
            acceptMethod.type(returnType);
            acceptMethod._throws(exceptionType);
            final JClass narrowedVisitor = visitor.narrow(returnType, exceptionType);
            JVar vizParam = acceptMethod.param(narrowedVisitor, "aVisitor");
            JBlock block = acceptMethod.body();
            String methodName = visitMethodNamer.apply(beanImpl.name());
            block._return(vizParam.invoke(methodName).arg(JExpr._this()));
        });
    }
 
Example #16
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * declare a constant field for the class.
 * argument {@code function} holds the constant value which
 * returns a value holder must be set to the class field when the class instance created.
 * the class field innerClassField will be created if innerClassGenerator exists.
 *
 * @param prefix the prefix name of class field
 * @param t the type of class field
 * @param init init expression
 * @param function the function holds the constant value
 * @return the depth of nested class, class field
 */
public Pair<Integer, JVar> declareClassConstField(String prefix, JType t, JExpression init,
                                                  Function<DrillBuf, ? extends ValueHolder> function) {
  JVar var;
  int depth = 1;
  if (innerClassGenerator != null) {
    Pair<Integer, JVar> nested = innerClassGenerator.declareClassConstField(prefix, t, init, function);
    depth = nested.getKey() + 1;
    var = nested.getValue();
  } else {
    var = clazz.field(JMod.NONE, t, prefix + index++, init);
  }
  Pair<Integer, JVar> depthVar = Pair.of(depth, var);
  constantVars.put(depthVar, function);
  return depthVar;
}
 
Example #17
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JMethod generateConveniencePartialCopyMethod(final TypeOutline paramType, final JMethod partialCopyOfMethod, final String methodName, final JExpression propertyTreeUseArg) {
	if (paramType.getSuperClass() != null) {
		generateConveniencePartialCopyMethod(paramType.getSuperClass(), partialCopyOfMethod, methodName, propertyTreeUseArg);
	}
	final JMethod conveniencePartialCopyMethod = this.definedClass.method(JMod.PUBLIC | JMod.STATIC, this.builderClass.raw.narrow(Void.class), methodName);
	final JVar partialOtherParam = conveniencePartialCopyMethod.param(JMod.FINAL, paramType.getImplClass(), BuilderGenerator.OTHER_PARAM_NAME);
	final JVar propertyPathParam = conveniencePartialCopyMethod.param(JMod.FINAL, PropertyTree.class, PartialCopyGenerator.PROPERTY_TREE_PARAM_NAME);
	conveniencePartialCopyMethod.body()._return(JExpr.invoke(partialCopyOfMethod).arg(partialOtherParam).arg(propertyPathParam).arg(propertyTreeUseArg));
	return conveniencePartialCopyMethod;
}
 
Example #18
Source File: JpaUnitRunnerTest.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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
 
Example #19
Source File: HashCodeArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public HashCodeArguments property(JBlock block, String propertyName,
		String propertyMethod, JType declarablePropertyType,
		JType propertyType, Collection<JType> possiblePropertyTypes) {
	block.assign(currentHashCode(),
			currentHashCode().mul(JExpr.lit(multiplier())));		
	final JVar propertyValue = block.decl(JMod.FINAL,
			declarablePropertyType, value().name() + propertyName, value()
					.invoke(propertyMethod));
	// We assume that primitive properties are always set
	boolean isAlwaysSet = propertyType.isPrimitive();
	final JExpression propertyHasSetValue = isAlwaysSet ? JExpr.TRUE
			: propertyValue.ne(JExpr._null());
	return spawn(propertyValue, propertyHasSetValue);
}
 
Example #20
Source File: ToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod generateToString$append(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod toString$append = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "append");
	toString$append.annotate(Override.class);
	{

		final JVar locator = toString$append.param(ObjectLocator.class,
				"locator");
		final JVar buffer = toString$append.param(StringBuilder.class,
				"buffer");
		final JVar toStringStrategy = toString$append.param(
				ToStringStrategy2.class, "strategy");

		final JBlock body = toString$append.body();

		body.invoke(toStringStrategy, "appendStart").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body.invoke("appendFields").arg(locator).arg(buffer)
				.arg(toStringStrategy);
		body.invoke(toStringStrategy, "appendEnd").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body._return(buffer);
	}
	return toString$append;
}
 
Example #21
Source File: AnyAttributePropertyOutline.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JFieldVar generateField() {
	final JFieldVar field = referenceClass.field(
			JMod.PROTECTED,
			type,
			propertyInfo.getPrivateName(),

			JExpr._new(codeModel.ref(HashMap.class).narrow(QName.class)
					.narrow(Object.class)));
	return field;
}
 
Example #22
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithoutPersistenceContextField() 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 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("EntityManagerFactory or EntityManager field annotated"));
    }
}
 
Example #23
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 #24
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public EqualsArguments iterator(JBlock block, JType elementType) {
	final JVar leftListIterator = block.decl(JMod.FINAL, getCodeModel()
			.ref(ListIterator.class).narrow(elementType), leftValue()
			.name() + "ListIterator", leftValue().invoke("listIterator"));
	final JVar rightListIterator = block.decl(JMod.FINAL, getCodeModel()
			.ref(ListIterator.class).narrow(elementType), rightValue()
			.name() + "ListIterator", rightValue().invoke("listIterator"));

	return spawn(rightListIterator, JExpr.TRUE, leftListIterator,
			JExpr.TRUE);
}
 
Example #25
Source File: MethodParamsRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRule_shouldCreate_validMethodParams() throws JClassAlreadyExistsException {

	JDefinedClass jClass = jCodeModel.rootPackage()._class("TestController");
	JMethod jMethod = jClass.method(JMod.PUBLIC, ResponseEntity.class, "getBaseById");
	jMethod = rule.apply(getEndpointMetadata(2), ext(jMethod, jCodeModel));

	assertThat(jMethod.params(), hasSize(1));
	assertThat(serializeModel(), containsString("getBaseById(String id)"));
}
 
Example #26
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private void withHashCode() {
	JMethod hashCode = this.pojo.method(JMod.PUBLIC, int.class, "hashCode");

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

	JClass hashCodeBuilderRef = this.pojo.owner().ref(hashCodeBuilderClass);

	JInvocation hashCodeBuilderInvocation = appendFieldsToHashCode(getNonTransientAndNonStaticFields(), hashCodeBuilderRef);

	hashCode.body()._return(hashCodeBuilderInvocation.invoke("toHashCode"));
}
 
Example #27
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 #28
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private void renderBuilderConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	method.param(codeModel.ref("Builder"), "builder");
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = builder." + Util.generateGetter(fieldModel.fieldName, isBoolean(fieldModel.fieldType)) + ";");
	}
}
 
Example #29
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"));
    }
}
 
Example #30
Source File: ConstantPropertyOutline.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JFieldVar generateField() {
	// generate the constant
	JExpression value = createValue();

	JFieldVar field = referenceClass.field(JMod.PUBLIC | JMod.STATIC
			| JMod.FINAL, type, propertyInfo.getPublicName(), value);

	annotate(field);

	return field;
}