Java Code Examples for com.sun.codemodel.JDefinedClass#_extends

The following examples show how to use com.sun.codemodel.JDefinedClass#_extends . 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: InterfaceBuilder.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
@SafeVarargs
private final JDefinedClass buildInterface(String interfaceName, String comment, List<Property>... propertiesLists) {
    try {
        JPackage jPackage = codeModel._package(generationConfig.getProjectSettings().getModelInterfacePackage());
        JDefinedClass interfaceClass = jPackage._interface(interfaceName);
        interfaceClass.javadoc().append(comment);
        interfaceClass.annotate(codeModel.ref("org.osgi.annotation.versioning.ConsumerType"));

        if (this.isAllowExporting) {
            interfaceClass._extends(codeModel.ref(ComponentExporter.class));
        }
        if (propertiesLists != null) {
            for (List<Property> properties : propertiesLists) {
                addGettersWithoutFields(interfaceClass, properties);
            }
        }
        return interfaceClass;
    } catch (JClassAlreadyExistsException e) {
        LOG.error("Failed to generate child interface.", e);
    }

    return null;
}
 
Example 2
Source File: CxfWSDLImporter.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) {
    
  final JClass parentClass = theClass._extends();
  if (parentClass != null && parentClass instanceof JDefinedClass) {
    _importFields((JDefinedClass)parentClass, index, structure);
  }
  for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) {
    Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().erasure().fullName());

    String fieldName = entry.getKey();
    if (fieldName.startsWith("_")) {
      if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) {
        fieldName = fieldName.substring(1); //it was prefixed with '_' so we should use the original name.
      }
    }

    structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass);
  }
}
 
Example 3
Source File: CodeGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
CodeGenerator(CodeCompiler compiler, MappingSet mappingSet, TemplateClassDefinition<T> definition, FunctionContext functionContext) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.compiler = compiler;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    clazz = clazz._extends(model.directClass(definition.getTemplateClassName()));
    clazz.constructor(JMod.PUBLIC).body().invoke(SignatureHolder.INIT_METHOD);
    rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(functionContext), clazz, model);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 4
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static JMethod getMethod(JDefinedClass theClass, String name,
		JType[] arguments) {
	final JMethod method = theClass.getMethod(name, arguments);
	if (method != null) {
		return method;
	} else {
		final JClass draftSuperClass = theClass._extends();
		if (draftSuperClass == null
				|| !(draftSuperClass instanceof JDefinedClass)) {
			return null;
		} else {
			final JDefinedClass superClass = (JDefinedClass) draftSuperClass;
			return getMethod(superClass, name, arguments);
		}
	}
}
 
Example 5
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private byte[] generateJava() throws Exception {
	
	JDefinedClass classModel = codeModel._class(JMod.PUBLIC | JMod.FINAL, className, ClassType.CLASS);
	Class<?> contractInterface = Class.forName(contractInterfaceName);
	classModel._implements(contractInterface);
          classModel._extends(AbstractDataTransferObject.class);
	
	List<FieldModel> fields = determineFields(contractInterface);
	
	renderConstantsClass(classModel);
	renderElementsClass(classModel, fields);
	renderClassLevelAnnotations(classModel, fields);
	renderFields(classModel, fields);
	renderFutureElementsField(classModel);			
	renderPrivateJaxbConstructor(classModel, fields);
	renderBuilderConstructor(classModel, fields);
	renderGetters(classModel, fields);
	renderBuilderClass(classModel, fields, contractInterface);

	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	codeModel.build(new SingleStreamCodeWriter(outputStream));
	return outputStream.toByteArray();
	
}
 
Example 6
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createReportingValueClass(JCodeModel codeModel, Class<? extends Value<?>> valueClazz, JPrimitiveType type) throws JClassAlreadyExistsException {
	JClass reportClazz = codeModel.ref(Report.class);

	JDefinedClass reportingValueClazz = codeModel._class(JMod.PUBLIC, asReportingClass(valueClazz), ClassType.CLASS);
	reportingValueClazz._extends(codeModel.ref(valueClazz));
	reportingValueClazz._implements(codeModel.ref(HasReport.class));

	JFieldVar reportField = reportingValueClazz.field(JMod.PRIVATE, reportClazz, "report", JExpr._null());

	createCopyMethod(reportingValueClazz);
	createOperationMethods(reportingValueClazz, valueClazz, type);
	createReportMethod(reportingValueClazz);
	createExpressionMethods(reportingValueClazz);
	createAccessorMethods(reportingValueClazz, reportField);
	createFormatMethod(reportingValueClazz, type);
}
 
Example 7
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JDefinedClass generateBuilderClass(JDefinedClass clazz) {
    JDefinedClass builderClass = null;
    String builderClassName = getBuilderClassName(clazz);
    try {
        builderClass = clazz._class(JMod.PUBLIC | JMod.STATIC, builderClassName);
        if (builderInheritance) {
            for (JClass superClass = clazz._extends(); superClass != null; superClass = superClass._extends()) {
                JClass superClassBuilderClass = getBuilderClass(superClass);
                if (superClassBuilderClass != null) {
                    builderClass._extends(superClassBuilderClass);
                    break;
                }
            }
        }
    } catch (JClassAlreadyExistsException e) {
        this.log(Level.WARNING, "builderClassExists", builderClassName);
    }
    return builderClass;
}
 
Example 8
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JDefinedClass generateOntologyThing() throws OntologyToJavaException {
    try {
        final JDefinedClass ontologyThing = codeModel._class(JMod.PUBLIC, getOntologyName(this.packageName, this.ontologyName), ClassType.INTERFACE);
        ontologyThing._extends(codeModel.ref(Thing.class));
        // Track field names to the IRI.
        final Map<String, IRI> fieldIriMap = new HashMap<>();
        final Map<String, IRI> rangeMap = new HashMap<>();
        // Identify all no domain properties from THIS ontology
        identifyAllDomainProperties(model).stream().filter(resource -> resource instanceof IRI).forEach(resource -> {
            // Set a static final field for the IRI.
            final String fieldName = getName(false, (IRI) resource, this.model);
            final IRI range = getRangeOfProperty((IRI) resource);
            ontologyThing.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, String.class, fieldName + "_IRI",
                    JExpr.lit(resource.stringValue())).javadoc()
                    .add("IRI of the predicate that this property will represent.<br><br>Domain: " + range);
            fieldIriMap.put(fieldName + "_IRI", (IRI) resource);
            rangeMap.put(fieldName, range);
        });
        interfaceFieldIriMap.put(ontologyThing, fieldIriMap);
        interfaceFieldRangeMap.put(ontologyThing, rangeMap);
        //TODO, null, or create some kind of unique IRI?
        interfaces.put(null, ontologyThing);
        return ontologyThing;
    } catch (JClassAlreadyExistsException e) {
        throw new OntologyToJavaException("Ontology Super Thing class already exists, or conflicts with an existing class...", e);
    }
}
 
Example 9
Source File: JClassUtilsTest.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void correctlyChecksIsInstanceOf()
		throws JClassAlreadyExistsException {

	final JClass arrayList = codeModel.ref("java.util.ArrayList");
	Assert.assertTrue(JClassUtils.isInstanceOf(arrayList, Collection.class));
	final JDefinedClass subArrayList = codeModel._class("SubArrayList");
	subArrayList._extends(arrayList);
	Assert.assertTrue(JClassUtils.isInstanceOf(subArrayList,
			Collection.class));

	final JClass subArrayListOfObjects = subArrayList.narrow(Object.class);
	Assert.assertTrue(JClassUtils.isInstanceOf(subArrayListOfObjects,
			Collection.class));

	final JDefinedClass subExternalizable = codeModel
			._class("SubExternalizable");
	subExternalizable._implements(Externalizable.class);
	Assert.assertTrue(JClassUtils.isInstanceOf(subExternalizable,
			Externalizable.class));

	subArrayList._implements(subExternalizable);
	Assert.assertTrue(JClassUtils.isInstanceOf(subArrayList,
			Externalizable.class));

	Assert.assertFalse(JClassUtils.isInstanceOf(codeModel.NULL,
			Collection.class));

}
 
Example 10
Source File: InheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JClass generateExtends(final JDefinedClass theClass,
		final ExtendsClass extendsClass, Map<String, JClass> knownClasses) {
	if (extendsClass.getClassName() != null) {
		final String _class = extendsClass.getClassName();
		final JClass targetClass = parseClass(_class, theClass.owner(),
				knownClasses);
		theClass._extends(targetClass);
		return targetClass;
	} else {
		return null;
	}
}
 
Example 11
Source File: AutoInheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void generateExtends(JDefinedClass theClass, String name) {
	if (name != null) {
		final JClass targetClass = theClass.owner().ref(name);
		if (theClass._extends() == theClass.owner().ref(Object.class)) {
			theClass._extends(targetClass);
		}
	}
}
 
Example 12
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
private void createReportingVectorClass(JCodeModel codeModel, Class<? extends Vector<?>> vectorClazz, JPrimitiveType type) throws JClassAlreadyExistsException {
	JDefinedClass reportingVectorClazz = codeModel._class(JMod.ABSTRACT | JMod.PUBLIC, asReportingClass(vectorClazz), ClassType.CLASS);
	reportingVectorClazz._extends(codeModel.ref(vectorClazz));

	JFieldVar expressionField = reportingVectorClazz.field(JMod.PRIVATE, String.class, "expression", JExpr.lit(""));

	createNewReportMethod(reportingVectorClazz);
	createOperationMethods(reportingVectorClazz, vectorClazz, type);
	createValueMethods(reportingVectorClazz, type);
	createReportMethod(reportingVectorClazz);
	createAccessorMethods(reportingVectorClazz, expressionField);
}
 
Example 13
Source File: CxfWSDLImporter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) {

        final JClass parentClass = theClass._extends();
        if (parentClass instanceof JDefinedClass) {
            _importFields((JDefinedClass) parentClass, index, structure);
        }
        for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) {

            String fieldName = entry.getKey();
            if (fieldName.startsWith("_")) {
                if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) {
                    fieldName = fieldName.substring(1); // it was prefixed with '_' so we should use the original name.
                }
            }

            final JType fieldType = entry.getValue().type();
            final Class<?> fieldClass = ReflectUtil.loadClass(fieldType.boxify().erasure().fullName());
            final Class<?> fieldParameterClass;
            if (fieldType instanceof JClass) {
                final JClass fieldClassType = (JClass) fieldType;
                final List<JClass> fieldTypeParameters = fieldClassType.getTypeParameters();
                if (fieldTypeParameters.size() > 1) {
                    throw new FlowableException(
                            String.format("Field type '%s' with more than one parameter is not supported: %S",
                                    fieldClassType, fieldTypeParameters));
                } else if (fieldTypeParameters.isEmpty()) {
                    fieldParameterClass = null;
                } else {
                    final JClass fieldParameterType = fieldTypeParameters.get(0);

                    // Hack because JClass.fullname() doesn't return the right class fullname for a nested class to be
                    // loaded from classloader. It should be contain "$" instead of "." as separator
                    boolean isFieldParameterTypeNeestedClass = false;
                    final Iterator<JDefinedClass> theClassNeestedClassIt = theClass.classes();
                    while (theClassNeestedClassIt.hasNext() && !isFieldParameterTypeNeestedClass) {
                        final JDefinedClass neestedType = theClassNeestedClassIt.next();
                        if (neestedType.name().equals(fieldParameterType.name())) {
                            isFieldParameterTypeNeestedClass = true;
                        }
                    }
                    if (isFieldParameterTypeNeestedClass) {
                        // The parameter type is a nested class
                        fieldParameterClass = ReflectUtil
                                .loadClass(theClass.erasure().fullName() + "$" + fieldParameterType.name());
                    } else {
                        // The parameter type is not a nested class
                        fieldParameterClass = ReflectUtil.loadClass(fieldParameterType.erasure().fullName());
                    }
                }
            } else {
                fieldParameterClass = null;
            }

            structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass, fieldParameterClass);
        }
    }
 
Example 14
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 15
Source File: JAXBDataBinding.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void fillInFields(Writer writer, String indent,
                              String path, String varName,
                              JDefinedClass tp) throws IOException {
    JClass sp = tp._extends();
    if (sp instanceof JDefinedClass) {
        fillInFields(writer, indent, path, varName, (JDefinedClass)sp);
    }

    Collection<JMethod> methods = tp.methods();
    for (JMethod m : methods) {
        if (m.name().startsWith("set")) {
            writer.write("\n");
            writer.write(indent);
            if (DEFAULT_TYPE_MAP.contains(m.listParamTypes()[0].fullName())) {
                writer.write(varName);
                writer.write(".");
                writer.write(m.name());
                writer.write("(");
                writeDefaultType(writer, m.listParamTypes()[0], path + "/" + m.name().substring(3));
                writer.write(");");
            } else {
                int idx = path.indexOf("/" + m.name().substring(3) + "/");
                if (idx > 0) {
                    idx = path.indexOf("/" + m.name().substring(3) + "/", idx + 1);
                }
                boolean hasTwo = idx > 0;
                if (!hasTwo) {
                    writeDefaultValue(writer, indent,
                                      path + "/" + m.name().substring(3),
                                      varName + m.name().substring(3),
                                      m.listParamTypes()[0]);
                    writer.write("\n");
                }
                writer.write(indent);
                writer.write(varName);
                writer.write(".");
                writer.write(m.name());
                writer.write("(");
                if (!hasTwo) {
                    writer.write(varName + m.name().substring(3));
                } else {
                    writer.write("null");
                }
                writer.write(");");
            }
        } else if (m.type().fullName().startsWith("java.util.List")) {
            writer.write("\n");
            writer.write(indent);
            writeDefaultValue(writer, indent,
                              path + "/" + m.name().substring(3),
                              varName + m.name().substring(3),
                              m.type());
            writer.write("\n");
            writer.write(indent);
            writer.write(varName);
            writer.write(".");
            writer.write(m.name());
            writer.write("().addAll(");
            writer.write(varName + m.name().substring(3));
            writer.write(");");
        }
    }
}
 
Example 16
Source File: PluginImpl.java    From immutable-xjc with MIT License 4 votes vote down vote up
private boolean hasSuperClass(final JDefinedClass builderClass) {
    // we have to account for java.lang.Object, which we don't care about...
    return builderClass._extends() != null && builderClass._extends()._extends() != null;
}