Java Code Examples for com.sun.codemodel.JMod

The following examples show how to use com.sun.codemodel.JMod. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bats   Source File: ClassGenerator.java    License: 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 2
Source Project: Bats   Source File: ClassGenerator.java    License: 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 3
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 4
Source Project: kafka-connect-transform-xml   Source File: ConnectPlugin.java    License: 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 5
Source Project: avro-fastserde   Source File: FastDeserializerGenerator.java    License: 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 6
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 7
Source Project: dremio-oss   Source File: AggrFunctionHolder.java    License: 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 8
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 9
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: 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 10
Source Project: immutable-xjc   Source File: PluginImpl.java    License: 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 11
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 12
Source Project: jaxb2-rich-contract-plugin   Source File: MetaPlugin.java    License: 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 13
Source Project: jaxb-visitor   Source File: CreateTraversingVisitorClass.java    License: 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 14
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: 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 15
Source Project: jaxb-visitor   Source File: CreateVisitableInterface.java    License: 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 16
Source Project: jaxb-visitor   Source File: AddAcceptMethod.java    License: 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 17
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;
}
 
Example 18
Source Project: apicurio-studio   Source File: JaxRsEnumRule.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example 19
protected JFieldRef createField() {

		final JFieldVar field = outline.implClass.field(JMod.PROTECTED
				+ JMod.TRANSIENT,

		propertyListType, property.getName(false));
//		field.annotate(XmlTransient.class);
		return JExpr._this().ref(field);
	}
 
Example 20
Source Project: apicurio-studio   Source File: JaxRsEnumRule.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 21
Source Project: jaxb2-rich-contract-plugin   Source File: BoundPropertiesPlugin.java    License: MIT License 5 votes vote down vote up
private void createSupportProperty(final Outline outline,
									final ClassOutline classOutline,
									final Class<?> supportClass,
									final Class<?> listenerClass,
									final String aspectName) {
	final JCodeModel m = outline.getCodeModel();
	final JDefinedClass definedClass = classOutline.implClass;

	final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1);

	if (classOutline.getSuperClass() == null) { // only generate fields in topmost classes
		final JFieldVar supportField = definedClass.field(JMod.PROTECTED | JMod.FINAL | JMod.TRANSIENT, supportClass, aspectName + BoundPropertiesPlugin.SUPPORT_FIELD_SUFFIX, JExpr._new(m.ref(supportClass)).arg(JExpr._this()));
		final JMethod addMethod = definedClass.method(JMod.PUBLIC, m.VOID, "add" + aspectNameCap + "Listener");
		final JVar addParam = addMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
		addMethod.body().invoke(JExpr._this().ref(supportField), "add" + aspectNameCap + "Listener").arg(addParam);

		final JMethod removeMethod = definedClass.method(JMod.PUBLIC, m.VOID, "remove" + aspectNameCap + "Listener");
		final JVar removeParam = removeMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
		removeMethod.body().invoke(JExpr._this().ref(supportField), "remove" + aspectNameCap + "Listener").arg(removeParam);
	}
	final JMethod withMethod = definedClass.method(JMod.PUBLIC, definedClass, "with" + aspectNameCap + "Listener");
	final JVar withParam = withMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
	withMethod.body().invoke("add" + aspectNameCap + "Listener").arg(withParam);
	withMethod.body()._return(JExpr._this());

	if (classOutline.getSuperClass() != null) {
		withMethod.annotate(Override.class);
	}
}
 
Example 22
Source Project: jaxb2-rich-contract-plugin   Source File: MetaPlugin.java    License: MIT License 5 votes vote down vote up
private void generateNameOnlyMetaField(final PluginContext pluginContext, final JDefinedClass metaClass, final FieldOutline fieldOutline) {
	final PropertyOutline propertyOutline = new DefinedPropertyOutline(fieldOutline);
	final String constantName = getConstantName(fieldOutline);
	final Outline outline = pluginContext.outline;
	final String propertyName = constantName != null ? constantName : propertyOutline.getFieldName();
	final String metaFieldName = this.camelCase ? propertyName : fieldOutline.parent().parent().getModel().getNameConverter().toConstantName(propertyName);
	metaClass.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL | JMod.TRANSIENT, String.class, metaFieldName, JExpr.lit(propertyName));
}
 
Example 23
protected JFieldRef createField() {

		final JFieldVar field = outline.implClass.field(JMod.PROTECTED
				+ JMod.TRANSIENT,

		propertyListType, property.getName(false));
		// field.annotate(XmlTransient.class);
		annotate(field);
		return JExpr._this().ref(field);
	}
 
Example 24
protected JMethod generateObject$clone(final ClassOutline classOutline,
		final JDefinedClass theClass) {

	final JMethod clone = theClass.method(JMod.PUBLIC, theClass.owner()
			.ref(Object.class), "clone");
	clone.annotate(Override.class);
	{
		final JBlock body = clone.body();
		body._return(JExpr.invoke("copyTo").arg(
				JExpr.invoke("createNewInstance")));
	}
	return clone;
}
 
Example 25
Source Project: springmvc-raml-plugin   Source File: SpringRulesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void applyRestControllerAnnotationRule_shouldCreate_validClassAnnotation() throws JClassAlreadyExistsException {
	SpringRestControllerAnnotationRule rule = new SpringRestControllerAnnotationRule();

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
	rule.apply(getControllerMetadata(), jClass);

	assertThat(jClass, is(notNullValue()));
	assertThat(jClass.name(), equalTo("MyClass"));
	assertThat(serializeModel(), containsString("import org.springframework.web.bind.annotation.RestController;"));
	assertThat(serializeModel(), containsString("@RestController"));
}
 
Example 26
Source Project: apicurio-studio   Source File: JaxRsEnumRule.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Source Project: raml-module-builder   Source File: ClientGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void generateCloseClient(){
  JMethod jmCreate = method(JMod.PUBLIC, void.class, "close");
  jmCreate.javadoc().add("Close the client. Closing will close down any "
      + "pooled connections. Clients should always be closed after use.");
  JBlock body = jmCreate.body();

  body.directStatement("httpClient.close();");
}
 
Example 28
Source Project: dremio-oss   Source File: ClassGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
  this.codeGenerator = codeGenerator;
  this.clazz = clazz;
  this.mappings = mappingSet;
  this.sig = signature;
  this.evaluationVisitor = eval;
  this.model = Preconditions.checkNotNull(model, "Code model object cannot be null.");
  blocks = new LinkedList[sig.size()];

  for (int i =0; i < sig.size(); i++) {
    blocks[i] = Lists.newLinkedList();
  }
  rotateBlock();

  for (SignatureHolder child : signature.getChildHolders()) {
    final String innerClassName = child.getSignatureClass().getSimpleName();
    final JDefinedClass innerClazz;
    // we need to extend the template class and avoid using static inner classes.
    innerClazz = clazz._class(JMod.FINAL, innerClassName)._extends(child.getSignatureClass());

    // we also need to delegate any inner class constructors.
    for(Constructor<?> c : child.getSignatureClass().getDeclaredConstructors()){
      final Class<?>[] params = c.getParameterTypes();
      JMethod constructor = innerClazz.constructor(JMod.PUBLIC);
      JBlock block = constructor.body();
      JInvocation invoke = block.invoke("super");
      block.invoke(SignatureHolder.INIT_METHOD);

      // start at 1 since first parameter is the parent class
      for (int i = 1; i < params.length; i++) {
        constructor.param(params[i], "arg" + i);
        invoke.arg(JExpr.direct("arg" + i));
      }
    }

    innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
  }
}
 
Example 29
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: MIT License 5 votes vote down vote up
private void overrideAddMethods(final PropertyOutline propertyOutline,
                                final QName elementName, final JType elementType) {
	final JClass iterableType = this.pluginContext.iterableClass.narrow(elementType instanceof JClass ? ((JClass)elementType).wildcard() : elementType);
	final String fieldName = this.pluginContext.toVariableName(elementName.getLocalPart());
	final String propertyName = this.pluginContext.toPropertyName(elementName.getLocalPart());
	final JMethod addIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	addIterableMethod.annotate(Override.class);
	final JVar addIterableParam = addIterableMethod.param(JMod.FINAL, iterableType, fieldName + "_");
	generateAddMethodJavadoc(addIterableMethod, addIterableParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final JMethod addVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	addVarargsMethod.annotate(Override.class);
	final JVar addVarargsParam = addVarargsMethod.varParam(elementType, fieldName + "_");
	generateAddMethodJavadoc(addVarargsMethod, addVarargsParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType);
	final JMethod addMethod;
	if (childBuilderOutline != null && !childBuilderOutline.getClassOutline().getImplClass().isAbstract()) {
		addMethod = this.builderClass.raw.method(JMod.PUBLIC, childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard()), PluginContext.ADD_METHOD_PREFIX + propertyName);
		addMethod.annotate(Override.class);
		generateBuilderMethodJavadoc(addMethod, "add", fieldName, propertyOutline.getSchemaAnnotationText().orElse(null));
	} else {
		addMethod = null;
	}
	if (this.implement) {
		addVarargsMethod.body().add(JExpr._super().invoke(addVarargsMethod).arg(addVarargsParam));
		addVarargsMethod.body()._return(JExpr._this());
		addIterableMethod.body().add(JExpr._super().invoke(addIterableMethod).arg(addIterableParam));
		addIterableMethod.body()._return(JExpr._this());
		if (addMethod != null) {
			addMethod.body()._return(JExpr.cast(childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard()), JExpr._super().invoke(addMethod)));
		}
	}
}
 
Example 30
@Test
public void applyClassFieldDeclarationRule_shouldCreate_validNonAutowiredField() throws JClassAlreadyExistsException {
	ClassFieldDeclarationRule rule = new ClassFieldDeclarationRule("field", String.class, false);

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
	jClass._implements(Serializable.class);
	rule.apply(getControllerMetadata(), jClass);

	assertFalse(serializeModel().contains("import org.springframework.beans.factory.annotation.Autowired;"));
	assertFalse((serializeModel().contains("@Autowired")));
	assertThat(serializeModel(), containsString("private String field;"));
}