com.sun.codemodel.ClassType Java Examples

The following examples show how to use com.sun.codemodel.ClassType. 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: 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 #2
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 #3
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateImplementations() throws OntologyToJavaException {
    final Collection<String> issues = new ArrayList<>();
    interfaces.forEach((classIri, interfaceClass) -> {
        if (classIri != null) {
            try {
                /*
                 * Define the implementation class, wire it to the correct
                 * interface and extend Thing.
                 */
                final JDefinedClass impl = codeModel._class(JMod.PUBLIC,
                        packageName + "." + interfaceClass.name() + "Impl", ClassType.CLASS);
                interfaceImplMap.put(interfaceClass, impl);
                impl._extends(codeModel.ref(ThingImpl.class));
                impl._implements(interfaceClass);
                impl.javadoc().add("This implementation of the '" + classIri.stringValue()
                        + "' entity will allow developers to work in native java POJOs.");
                // Constructors - call super from Thing.
                generateImplConstructors(impl, interfaceClass);
                // Build methods for impl based on interfaces.
                recurseImplementations(impl, interfaceClass);

                // Generate default impl.
                interfaceClass.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL,
                        codeModel.ref(Class.class).narrow(interfaceClass.wildcard()), DEFAULT_IMPL_FIELD,
                        impl.dotclass()).javadoc().add("The default implementation for this interface");
            } catch (Exception e) {
                LOG.error("Issue generating implementation for '" + classIri.stringValue() + "': " + e.getMessage(), e);
                issues.add("Issue generating implementation for '" + classIri.stringValue() + "': " + e.getMessage());
            }
        }
    });
    if (!issues.isEmpty()) {
        throw new OntologyToJavaException("Could not generate POJOs from ontology due to the following issues:\n\t"
                + StringUtils.join(issues, "\n\t") + "\n\n");
    }
}
 
Example #4
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 #5
Source File: EnumBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Sets this Pojo's name
 * 
 * @param pojoPackage
 *            The Package used to create POJO
 * @param className
 *            Class to be created
 * @return This instance
 */
public EnumBuilder withName(String pojoPackage, String className) {
	className = NamingHelper.convertToClassName(className);

	final String fullyQualifiedClassName = pojoPackage + "." + className;
	// Initiate package if necessary
	if (this.pojoPackage == null) {
		withPackage(pojoPackage);
	}
	// Builders should only have 1 active pojo under their responsibility
	if (this.pojo != null) {
		throw new IllegalStateException("Enum already created");
	}

	try {
		// create the class
		logger.debug("Creating Enum " + fullyQualifiedClassName);
		this.pojo = this.pojoModel._class(fullyQualifiedClassName, ClassType.ENUM);

		// Handle Serialization
		// Do enums need to be serializable?
		// implementsSerializable();
	} catch (JClassAlreadyExistsException e) {
		// class already exists - reuse it!
		logger.debug("Enum {} already exists. Reusing it!", fullyQualifiedClassName);
		this.pojo = this.pojoModel._getClass(fullyQualifiedClassName);
	}

	// Add to shortcuts
	this.codeModels.put(fullyQualifiedClassName, this.pojo);
	return this;
}
 
Example #6
Source File: GroupInterfaceGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private void generateBuilderInterface(final Map<String, BuilderOutline> builderOutlines, final DefinedInterfaceOutline interfaceOutline) throws SAXException {
	try {
		builderOutlines.put(interfaceOutline.getImplClass().fullName(), new BuilderOutline(interfaceOutline,
				/* interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getFluentClassName().getInterfaceName(), ClassType.INTERFACE) */
				interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getBuilderClassName().getInterfaceName(), ClassType.INTERFACE)
				/*interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getWrapperClassName().getInterfaceName(), ClassType.INTERFACE),
				interfaceOutline.getImplClass()._class(JMod.NONE, this.settings.getBuilderGeneratorSettings().getModifierClassName().getInterfaceName(), ClassType.INTERFACE) */
				));
	} catch (final JClassAlreadyExistsException e) {
		this.pluginContext.errorHandler.error(new SAXParseException(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("error.interface-exists"), interfaceOutline.getImplClass().fullName(), PluginContext.BUILDER_INTERFACE_NAME), interfaceOutline.getSchemaComponent().getLocator()));
	}
}
 
Example #7
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 #8
Source File: ClassModelBuilder.java    From mxjc with MIT License 5 votes vote down vote up
/**
 * check if a JType is an enum type
 * 
 * @param jType
 * @return boolean
 */
private static boolean isEnum(JType jType) {
	if (jType instanceof JDefinedClass) { // is enum?
		JDefinedClass jDefinedClass = (JDefinedClass) jType;
		ClassType classType = jDefinedClass.getClassType();
		if (classType == ClassType.ENUM) {
			return true;
		}
	}
	return false;
}
 
Example #9
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Generate each individual interface with its static final predicate
 * fields.
 *
 * @throws OntologyToJavaException
 */
private void generateIndividualInterfaces() throws OntologyToJavaException {
    final List<String> issues = new ArrayList<>();

    final JDefinedClass ontologyThing = generateOntologyThing();

    identifyClasses().forEach(classIri -> {
        try {
            final Model modelOfThisClass = this.model.filter(classIri, null, null);

            final String className = packageName + "." + getName(true, classIri, modelOfThisClass);

            List<IRI> ancestors = new ArrayList<>();
            getAncestors(classIri, ancestors);

            JDefinedClass clazz = codeModel._class(JMod.PUBLIC, className, ClassType.INTERFACE);
            if (!clazz.equals(ontologyThing)) {
                clazz._extends(ontologyThing);
            }

            clazz.javadoc().add("Generated class representing things with the type: " + classIri.stringValue());

            clazz.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, String.class, CLASS_TYPE_IRI_FIELD,
                    JExpr.lit(classIri.stringValue())).javadoc().add("The rdf:type IRI of this class.");

            // Track field names to the IRI.
            final Map<String, IRI> fieldIriMap = new HashMap<>();
            final Map<String, IRI> rangeMap = new HashMap<>();


            // Look for properties on this domain.
            final Collection<Resource> resources = this.model.filter(null, RDFS.DOMAIN, classIri).subjects().stream().filter(subj -> {
                for (final IRI ancestorIri : ancestors) {
                    if (this.model.filter(subj, RDFS.DOMAIN, ancestorIri).size() > 0) {
                        return false;
                    }
                }
                return true;
            }).collect(Collectors.toSet());
            resources.stream().filter(resource -> resource instanceof IRI).forEach(resource -> {
                LOG.debug("Adding '" + resource.stringValue() + "' to '" + classIri.stringValue()
                        + "' as it specifies it in its range");

                // Set a static final field for the IRI.
                final String fieldName = getName(false, (IRI) resource, this.model);
                final IRI range = getRangeOfProperty((IRI) resource);
                clazz.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);
            });
            nameInterfaceMap.put(clazz.fullName(), clazz);
            interfaceFieldIriMap.put(clazz, fieldIriMap);
            interfaceFieldRangeMap.put(clazz, rangeMap);
            interfaces.put(classIri, clazz);
        } catch (Exception e) {
            LOG.error("Issue generating interface for '" + classIri.stringValue() + "': " + e.getMessage(), e);
            issues.add("Issue generating interface for '" + classIri.stringValue() + "': " + e.getMessage());
        }
    });

    if (!issues.isEmpty()) {
        throw new OntologyToJavaException("Could not generate POJOs from ontology due to the following issues:\n\t"
                + StringUtils.join(issues, "\n\t") + "\n\n");
    }

}