Java Code Examples for com.sun.codemodel.JDefinedClass#constructor()

The following examples show how to use com.sun.codemodel.JDefinedClass#constructor() . 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: ClassGenerator.java    From dremio-oss with 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 2
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateImplConstructors(final JDefinedClass impl, final JDefinedClass interfaceClazz) {
    final JMethod constructor = impl.constructor(JMod.PUBLIC);
    constructor.body().invoke("super")
            .arg(constructor.param(JMod.FINAL, com.mobi.rdf.api.Resource.class, "subjectIri"))
            .arg(constructor.param(JMod.FINAL, com.mobi.rdf.api.Model.class, "backingModel"))
            .arg(constructor.param(JMod.FINAL, ValueFactory.class, "valueFactory"))
            .arg(constructor.param(JMod.FINAL, ValueConverterRegistry.class, "valueConverterRegistry"));
    JDocComment basicDoc = constructor.javadoc();
    basicDoc.add("Construct a new " + interfaceClazz.name() + " with the subject IRI and the backing dataset");
    basicDoc.addParam("subjectIri").add("The subject of this " + interfaceClazz.name());
    basicDoc.addParam("valueFactory").add("The value factory to use for this " + interfaceClazz.name());
    basicDoc.addParam("backingModel").add("The backing dataset/model of this " + interfaceClazz.name());
    basicDoc.addParam("valueConverterRegistry")
            .add("The ValueConversionRegistry for this " + interfaceClazz.name());

    final JMethod constructor2 = impl.constructor(JMod.PUBLIC);
    constructor2.body().invoke("super").arg(constructor2.param(JMod.FINAL, String.class, "subjectIriStr"))
            .arg(constructor2.param(JMod.FINAL, com.mobi.rdf.api.Model.class, "backingModel"))
            .arg(constructor2.param(JMod.FINAL, ValueFactory.class, "valueFactory"))
            .arg(constructor2.param(JMod.FINAL, ValueConverterRegistry.class, "valueConversionRegistry"));
    JDocComment basicDoc2 = constructor2.javadoc();
    basicDoc2.add("Construct a new " + interfaceClazz.name() + " with the subject IRI and the backing dataset");
    basicDoc2.addParam("subjectIriStr").add("The subject of this " + interfaceClazz.name());
    basicDoc2.addParam("valueFactory").add("The value factory to use for this " + interfaceClazz.name());
    basicDoc2.addParam("backingModel").add("The backing dataset/model of this " + interfaceClazz.name());
    basicDoc2.addParam("valueConversionRegistry")
            .add("The ValueConversionRegistry for this " + interfaceClazz.name());

}
 
Example 3
Source File: JaxRsEnumRule.java    From apicurio-studio with 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 4
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private void renderPrivateJaxbConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = " + getInitString(fieldModel.fieldType) + ";");
	}
	method.javadoc().add("Private constructor used only by JAXB.");
}
 
Example 5
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 6
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private void renderBuilderClass(JDefinedClass classModel, List<FieldModel> fields, Class<?> contractInterface) throws Exception {
	
	// define constants class
	JDefinedClass builderClass = classModel._class(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, Util.BUILDER_CLASS_NAME);
	
	// create a literal version of the Builder class so that the code generator won't pre-pend Builder class references with outermost class
	JClass literalBuilderClass = codeModel.ref("Builder");
	
	// generate the javadoc on the top of the Elements class
	JDocComment javadoc = builderClass.javadoc();
	javadoc.append(Util.generateBuilderJavadoc(classModel.name(), contractInterface.getSimpleName()));
	
	builderClass._implements(contractInterface);
	builderClass._implements(ModelBuilder.class);
	builderClass._implements(Serializable.class);
	
	// render the builder fields
	for (FieldModel fieldModel : fields) {
		builderClass.field(JMod.PRIVATE, fieldModel.fieldType, fieldModel.fieldName);
	}
	
	// render default empty constructor for builder
	JMethod constructor = builderClass.constructor(JMod.PRIVATE);
	constructor.body().directStatement("// TODO modify this constructor as needed to pass any required values and invoke the appropriate 'setter' methods");

	renderBuilderDefaultCreate(builderClass, literalBuilderClass);
	renderBuilderCreateContract(builderClass, literalBuilderClass, fields, contractInterface);
	renderBuild(builderClass);
	renderGetters(builderClass, fields);
	renderSetters(builderClass, fields);
}
 
Example 7
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportingConstructor(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(initialOperation != null){
		throw new RuntimeException();
	}

	body.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, constructor.params(), type)));
}
 
Example 8
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createConstructor(JDefinedClass clazz, ExecutableElement executableElement, boolean hasExpression){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(hasExpression){
		JVar expressionParameter = constructor.param(String.class, "expression");

		body._if(expressionParameter.ne(JExpr._null()))._then().add(JExpr.invoke("report").arg(expressionParameter));
	}
}
 
Example 9
Source File: SelectorGenerator.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
private MetaInfoOutline generateMetaClass(final ClassOutline classOutline) {
	try {
		final JDefinedClass definedClass = classOutline.implClass;
		final JDefinedClass selectorClass = definedClass._class(JMod.PUBLIC | JMod.STATIC, this.selectorClassName);
		final JTypeVar rootTypeParam = selectorClass.generify("TRoot");
		final JTypeVar parentTypeParam = selectorClass.generify("TParent");
		rootTypeParam.bound(this.pluginContext.codeModel.ref(this.selectorBaseClass).narrow(rootTypeParam, this.pluginContext.codeModel.wildcard()));
		//parentTypeParam.bound(this.apiConstructs.codeModel.ref(Selector.class).narrow(parentTypeParam, this.apiConstructs.codeModel.wildcard()));

		final JMethod constructor = selectorClass.constructor(JMod.PUBLIC);
		final JVar rootParam = constructor.param(JMod.FINAL, rootTypeParam, "root");
		final JVar parentParam = constructor.param(JMod.FINAL, parentTypeParam, "parent");
		final JVar propertyNameParam = constructor.param(JMod.FINAL, this.pluginContext.stringClass, "propertyName");
		if(this.selectorParamName != null) {
			final JVar includeParam = constructor.param(JMod.FINAL, getSelectorParamType(this.pluginContext.codeModel.wildcard(), definedClass.wildcard()), this.selectorParamName);
			constructor.body().invoke("super").arg(rootParam).arg(parentParam).arg(propertyNameParam).arg(includeParam);
		} else {
			constructor.body().invoke("super").arg(rootParam).arg(parentParam).arg(propertyNameParam);
		}
		final JClass productMapType = this.pluginContext.codeModel.ref(Map.class).narrow(String.class).narrow(this.propertyPathClass);
		final JMethod buildChildrenMethod = selectorClass.method(JMod.PUBLIC, productMapType, "buildChildren");
		buildChildrenMethod.annotate(Override.class);
		final JVar productMapVar = buildChildrenMethod.body().decl(JMod.FINAL, productMapType, "products", JExpr._new(this.pluginContext.codeModel.ref(HashMap.class).narrow(String.class).narrow(this.propertyPathClass)));


		if(classOutline.getSuperClass() == null ) {
			selectorClass._extends(this.pluginContext.codeModel.ref(this.selectorBaseClass).narrow(rootTypeParam).narrow(parentTypeParam));
		}

		final JDefinedClass rootSelectorClass = definedClass._class(JMod.PUBLIC | JMod.STATIC, this.rootSelectorClassName);
		rootSelectorClass._extends(selectorClass.narrow(rootSelectorClass).narrow(Void.class));
		final JMethod rootSelectorConstructor = rootSelectorClass.constructor(JMod.NONE);
		if(this.selectorParamName != null) {
			final JVar rootSelectorClassIncludeParam = rootSelectorConstructor.param(JMod.FINAL, getSelectorParamType(this.pluginContext.voidClass, definedClass), this.selectorParamName);
			rootSelectorConstructor.body().invoke("super").arg(JExpr._null()).arg(JExpr._null()).arg(JExpr._null()).arg(rootSelectorClassIncludeParam);
		} else {
			rootSelectorConstructor.body().invoke("super").arg(JExpr._null()).arg(JExpr._null()).arg(JExpr._null());
		}

		final JMethod rootMethod = rootSelectorClass.method(JMod.STATIC | JMod.PUBLIC, rootSelectorClass, "_root");
		if(this.selectorParamName != null) {
			final JVar rootIncludeParam = rootMethod.param(JMod.FINAL, getSelectorParamType(this.pluginContext.voidClass, definedClass), this.selectorParamName);
			rootMethod.body()._return(JExpr._new(rootSelectorClass).arg(rootIncludeParam));
		} else {
			rootMethod.body()._return(JExpr._new(rootSelectorClass));
		}


		return new MetaInfoOutline(this, classOutline, selectorClass, rootTypeParam, parentTypeParam, buildChildrenMethod, productMapVar);
	} catch (final JClassAlreadyExistsException e) {
		SelectorGenerator.LOGGER.warning("Attempt to generate already existing class");
		return null;
	}
}
 
Example 10
Source File: Translator.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
/**
 * Transforms a single class.
 */
public void translate(String fqcn, String outfqcn, String sourceJarName) throws JClassAlreadyExistsException {
    final JDefinedClass $output = codeModel._class(outfqcn);
    $output.annotate(Generated.class).param("value", Translator.class.getName()).param("date", new Date().toString()).param("comments", "based on " + sourceJarName);
    $output.annotate(SuppressWarnings.class).param("value", "rawtypes");
    $output.constructor(JMod.PRIVATE);

    CompilationUnitTree dgmCut = getDefaultGroovyMethodCompilationUnitTree(parsed, fqcn);

    overloadsResolved.clear();
    ClassSymbol dgm = (ClassSymbol) elements.getTypeElement(fqcn);
    dgm.accept(new ElementScanner7<Void,Void>() {
        @Override
        public Void visitExecutable(ExecutableElement e, Void __) {
            if (translatable.contains(fqcn + "." + e)) {
                overloadsResolved.put(mangledName(e), e);
            }
            // System.err.println("Not translating " + e.getAnnotationMirrors() + " " + e.getModifiers() + " " + fqcn + "." + e);
            // TODO else if it is public and has a Closure argument, translate to a form that just throws UnsupportedOperationException when called in CPS mode
            return null;
        }
    },null);
    // TODO verify that we actually found everything listed in translatables
    overloadsResolved.forEach((overloadResolved, e) -> {
        try {
            translateMethod(dgmCut, e, $output, fqcn, overloadResolved);
        } catch (Exception x) {
            throw new RuntimeException("Unable to transform " + fqcn + "." + e, x);
        }
    });

    /*
        private static MethodLocation loc(String methodName) {
            return new MethodLocation(CpsDefaultGroovyMethods.class,methodName);
        }
    */

    JClass $MethodLocation = codeModel.ref("com.cloudbees.groovy.cps.MethodLocation");
    $output.method(JMod.PRIVATE|JMod.STATIC, $MethodLocation, "loc").tap( m -> {
        JVar $methodName = m.param(String.class, "methodName");
        m.body()._return(JExpr._new($MethodLocation).arg($output.dotclass()).arg($methodName));
    });

    // Record the fqcn we've already translated for possible use later.
    otherTranslated.put(fqcn, $output);
}
 
Example 11
Source File: PluginImpl.java    From immutable-xjc with MIT License 4 votes vote down vote up
private JMethod createConstructor(final JDefinedClass clazz, final int visibility) {
    return clazz.constructor(visibility);
}