com.sun.codemodel.JDocComment Java Examples

The following examples show how to use com.sun.codemodel.JDocComment. 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 void renderElementsClass(JDefinedClass classModel, List<FieldModel> fields) throws Exception {
	
	// define constants class
	JDefinedClass elementsClass = classModel._class(JMod.STATIC, Util.ELEMENTS_CLASS_NAME);
	
	// generate the javadoc on the top of the Elements class
	JDocComment javadoc = elementsClass.javadoc();
	javadoc.append(Util.ELEMENTS_CLASS_JAVADOC);
	
	// go through each field and create a corresponding constant
	for (FieldModel fieldModel : fields) {
		if (Util.isCommonElement(fieldModel.fieldName)) {
			continue;
		}
		JFieldVar elementFieldVar = elementsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.toConstantsVariable(fieldModel.fieldName));
		elementFieldVar.init(JExpr.lit(fieldModel.fieldName));
	}
}
 
Example #2
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private void renderConstantsClass(JDefinedClass classModel) throws Exception {
	
	// define constants class
	JDefinedClass constantsClass = classModel._class(JMod.STATIC, Util.CONSTANTS_CLASS_NAME);
	
	// generate the javadoc on the top of the Constants class
	JDocComment javadoc = constantsClass.javadoc();
	javadoc.append(Util.CONSTANTS_CLASS_JAVADOC);
	
	// render root element name
	JFieldVar rootElementField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.ROOT_ELEMENT_NAME_FIELD);
	rootElementField.init(JExpr.lit(Util.toLowerCaseFirstLetter(classModel.name())));
	
	// render type name
	JFieldVar typeNameField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.TYPE_NAME_FIELD);
	typeNameField.init(JExpr.lit(classModel.name() + Util.TYPE_NAME_SUFFIX));
          
}
 
Example #3
Source File: JavadocUtils.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
/**
 * Adds each paragraph to the tail of the javadoc comment section of {@link JDocComment}. Also adds a p tag between
 * each paragraph and hard wraps the text.
 */
static JDocComment appendJavadocCommentParagraphs(final JDocComment jDocComment, final String... paragraphs) {
    if (paragraphs != null) {
        for (int i = 0; i < paragraphs.length; i++) {
            if (paragraphs[i] != null && !paragraphs[i].isEmpty()) {
                // Add hard line breaks so we get readable javadoc
                String wrappedText = hardWrapTextForJavadoc(paragraphs[i]);
                jDocComment.append(wrappedText);
                if (i != paragraphs.length - 1) {
                    jDocComment.append("\n<P>\n");
                }
            }
        }
    }
    return jDocComment;
}
 
Example #4
Source File: JavadocUtils.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
/**
 * Adds a paragraph and optionally a p tag to the head of the passed {@link JDocComment}.
 * Also hard wraps the text.
 */
static JDocComment appendJavadocParagraph(final JDocCommentable jDocCommentable, final String paragraphText) {
    final JDocComment jDocComment = jDocCommentable.javadoc();
    if (paragraphText != null && !paragraphText.isEmpty()) {
        List<Object> jdocItems = new ArrayList<>(jDocComment);
        jDocComment.clear();

        // Add hard line breaks so we get readable javadoc
        String wrappedText = hardWrapTextForJavadoc(paragraphText);
        jDocComment.append(wrappedText + "\n\n");

        if (!jdocItems.isEmpty()) {
            Object firstItem = jdocItems.get(0);
            if (!(firstItem instanceof String) || !((String) firstItem).startsWith("<p>") ) {
                // We already had text in the comment section so add line break and p tag
                jDocComment.append("<P>\n");
            }
        }
        // add the removed items back in so we have our para at the head
        jDocComment.addAll(jdocItems);
    }
    return jDocComment;
}
 
Example #5
Source File: ClassCommentRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRule_shouldCreate_validClassComment() throws JClassAlreadyExistsException {

	JDefinedClass jClass = jCodeModel.rootPackage()._class("BaseController");
	JDocComment jDocComment = rule.apply(getControllerMetadata(), jClass);
	assertNotNull(jDocComment);
	assertThat(serializeModel(), containsString("* The BaseController class"));
}
 
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: PartialCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
@Override
public void generatePartialArgs(final JDocComment javadoc) {
	javadoc	.addParam(this.propertyTreeParam)
			.append(PartialCopyGenerator.RESOURCE_BUNDLE.getString("javadoc.method.param.propertyTree"));
	javadoc	.addParam(this.propertyTreeUseParam)
			.append(MessageFormat.format(PartialCopyGenerator.RESOURCE_BUNDLE.getString("javadoc.method.param.propertyTreeUse"), this.propertyTreeParam.name()));
}
 
Example #8
Source File: JavadocUtils.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
static void hardWrapCommentText(final JDocComment jDocComment) {
    for (int i = 0; i < jDocComment.size(); i++) {
        Object item = jDocComment.get(i);
        if (item instanceof String) {
            jDocComment.set(i, hardWrapTextForJavadoc((String) item));
        }
    }
}
 
Example #9
Source File: InterfaceBuilder.java    From aem-component-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Adds Javadoc to the method based on the information in the property and the generation config options.
 *
 * @param method
 * @param property
 */
private void addJavadocToMethod(JMethod method, Property property) {
    String javadocStr = null;
    if (StringUtils.isNotBlank(property.getJavadoc())) {
        javadocStr = property.getJavadoc();
    } else if (generationConfig.getOptions() != null && generationConfig.getOptions().isHasGenericJavadoc()) {
        javadocStr = "Get the " + property.getField() + ".";
    }
    if (StringUtils.isNotBlank(javadocStr)) {
        JDocComment javadoc = method.javadoc();
        javadoc.append(javadocStr).append("");
        javadoc.append("\n\n@return " + StringEscapeUtils.escapeHtml4(getGetterMethodReturnType(property).name()));
    }
}
 
Example #10
Source File: MethodCommentRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRule_shouldCreate_validMethodComment() throws JClassAlreadyExistsException {

	JDefinedClass jClass = jCodeModel.rootPackage()._class("TestController");
	JMethod jMethod = jClass.method(JMod.PUBLIC, ResponseEntity.class, "getBaseById");
	JDocComment jDocComment = rule.apply(getEndpointMetadata(2), jMethod);
	assertNotNull(jDocComment);
	assertThat(serializeModel(), containsString("* Get base entity by ID"));
}
 
Example #11
Source File: MethodCommentRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDocComment apply(ApiActionMetadata endpointMetadata, JMethod generatableType) {
	String comments = "No description";
	if (endpointMetadata.getDescription() != null) {
		comments = endpointMetadata.getDescription();
	}
	return generatableType.javadoc().append(comments);
}
 
Example #12
Source File: ClassCommentRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDocComment apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) {
	String comments = "No description";
	if (controllerMetadata.getDescription() != null) {
		comments = controllerMetadata.getDescription();
	}
	generatableType.javadoc().append(comments);
	generatableType.javadoc().append("\n(Generated with springmvc-raml-parser v." + CodeModelHelper.getVersion() + ")");
	return generatableType.javadoc();
}
 
Example #13
Source File: AbstractBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
public AbstractBuilder withClassComment(String classComment) {
	pojoCreationCheck();
	JDocComment javadoc = this.pojo.javadoc();
	// javadoc.add
	javadoc.add(toJavaComment(classComment));
	javadoc.add("\n\nGenerated using springmvc-raml-plugin on " + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));
	return this;
}
 
Example #14
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateGetterMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                                 final String name, final String fieldName, final IRI propertyIri, final JClass type, final boolean thingResource) {
    final JMethod method = clazz.method(JMod.PUBLIC, type,
            generateMethodName(type.equals(boolean.class) ? "is" : "get", name) + (thingResource ? "_resource" : ""));
    method._throws(OrmException.class);
    final JDocComment comment = method.javadoc();
    comment.add("Get the " + fieldName + " property from this instance of a " + (interfaceIri != null ? interfaceIri.stringValue() : getOntologyName(this.packageName, this.ontologyName))
            + "' type.<br><br>" + getFieldComment(propertyIri));
    comment.addReturn().add("The " + fieldName + " {@link " + type.binaryName() + "} value for this instance");
    return method;
}
 
Example #15
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private JMethod generateClearerMethodForInterface(final JDefinedClass clazz, final IRI interfaceIri,
                                                  final String name, final String fieldName, final IRI propertyIri) {
    final JMethod method = clazz.method(JMod.PUBLIC, boolean.class, generateMethodName("clear", name));
    final JDocComment comment = method.javadoc();
    comment.add("Clear the " + fieldName + " property from this instance of a " + interfaceIri + ".");
    comment.addReturn().add("Whether or not data was removed for this property/instance");
    return method;
}
 
Example #16
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 #17
Source File: GenericJavaClassRule.java    From springmvc-raml-plugin with Apache License 2.0 4 votes vote down vote up
public GenericJavaClassRule setMethodCommentRule(Rule<JMethod, JDocComment, ApiActionMetadata> methodCommentRule) {
	this.methodCommentRule = Optional.ofNullable(methodCommentRule);
	return this;
}
 
Example #18
Source File: GenericJavaClassRule.java    From springmvc-raml-plugin with Apache License 2.0 4 votes vote down vote up
public GenericJavaClassRule setClassCommentRule(Rule<JDefinedClass, JDocComment, ApiResourceMetadata> classCommentRule) {
	this.classCommentRule = Optional.ofNullable(classCommentRule);
	return this;
}
 
Example #19
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public void generateClassMeta(String className) {

    String mapType = System.getProperty("json.type");
    if ("mongo".equals(mapType)) {
      mappingType = "mongo";
    }

    /* Adding packages here */
    JPackage jp = jcodeModel._package(RTFConsts.CLIENT_GEN_PACKAGE);

    try {
      /* Giving Class Name to Generate */
      this.className = className.substring(RTFConsts.INTERFACE_PACKAGE.length() + 1);
      jc = jp._class(this.className + CLIENT_CLASS_SUFFIX);
      JDocComment com = jc.javadoc();
      com.add("Auto-generated code - based on class " + className);

      /* class variable tenant id */
      tenantId = jc.field(JMod.PRIVATE, String.class, TENANT_ID);

      JFieldVar tokenVar = jc.field(JMod.PRIVATE, String.class, TOKEN);

      okapiUrl = jc.field(JMod.PRIVATE, String.class, OKAPI_URL);

      /* class variable to http options */
      JFieldVar options = jc.field(JMod.PRIVATE, HttpClientOptions.class, "options");

      /* class variable to http client */
      JFieldVar httpClient = jc.field(JMod.PRIVATE, HttpClient.class, "httpClient");

      addConstructorOkapi6Args(tokenVar, options, httpClient);
      addConstructorOkapi4Args();
      addConstructorOkapi3Args();

      addConstructor7Args();
      addConstructor5Args();
      addConstructor4Args();
      addConstructor0Args();

    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

  }
 
Example #20
Source File: FullCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
@Override
public void generatePartialArgs(final JDocComment javadoc) {
}
 
Example #21
Source File: GroupInterfaceGenerator.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
private DefinedInterfaceOutline createInterfaceDeclaration(final XSDeclaration groupDecl) throws SAXException {
	final PackageOutline packageOutline = findPackageForNamespace(groupDecl.getTargetNamespace());
	if (packageOutline == null) {
		this.pluginContext.errorHandler.error(new SAXParseException(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("error.package-not-found"), groupDecl.getTargetNamespace()), groupDecl.getLocator()));
		return null;
	}

	final JPackage container = packageOutline._package();
	final ClassOutline dummyImplementation = this.pluginContext.classesBySchemaComponent.get(PluginContext.getQName(groupDecl));
	if (dummyImplementation == null) {
		this.pluginContext.errorHandler.error(new SAXParseException(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("error.no-implementation"), this.pluginContext.outline.getModel().getNameConverter().toClassName(groupDecl.getName()), groupDecl.getTargetNamespace(), groupDecl.getName()), groupDecl.getLocator()));
		return null;
	}

	final String interfaceName = dummyImplementation.implClass.name();
	container.remove(dummyImplementation.implClass);
	final JDefinedClass groupInterface;
	final JDefinedClass supportInterface;
	try {
		groupInterface = container._interface(JMod.PUBLIC, interfaceName);
		supportInterface = this.settings.isGeneratingSupportInterface() ? container._interface(JMod.PUBLIC, interfaceName + this.settings.getSupportInterfaceNameSuffix())._implements(groupInterface) : null;
	} catch (final JClassAlreadyExistsException e) {
		this.pluginContext.errorHandler.error(new SAXParseException(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("error.interface-exists"), interfaceName, ""), groupDecl.getLocator()));
		return null;
	}
	final DefinedInterfaceOutline interfaceDecl = new DefinedInterfaceOutline(groupDecl, groupInterface, dummyImplementation, supportInterface);

	// Generate Javadoc with schema fragment
	final StringWriter out = new StringWriter();
	out.write("<pre>\n");
	final SchemaWriter sw = new SchemaWriter(new JavadocEscapeWriter(out));
	groupDecl.visit(sw);
	out.write("</pre>");

	final JDocComment comment = groupInterface.javadoc();
	comment.append(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("comment.generated-from-xs-decl.header")).
			append("\n").
			append(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("comment.generated-from-xs-decl.qname"),
					groupDecl.getTargetNamespace(),
					groupDecl.getName())).
			append("\n").
			append(MessageFormat.format(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("comment.generated-from-xs-decl.locator"),
					groupDecl.getLocator().getSystemId(),
					groupDecl.getLocator().getLineNumber(),
					groupDecl.getLocator().getColumnNumber()))
			.append("\n")
			.append(GroupInterfaceGenerator.RESOURCE_BUNDLE.getString("comment.generated-from-xs-decl.source"))
			.append("\n")
			.append(out.toString());


	for (final PropertyUse propertyUse : findChildDecls(groupDecl)) {
		final FieldOutline field = findField(dummyImplementation, propertyUse);
		if (field != null) {
			generateProperty(interfaceDecl, field);
		}
	}

	if(this.declareVisitMethod) {
		final JDefinedClass target = supportInterface != null ? supportInterface : groupInterface;
		target.method(JMod.NONE, target, this.pluginContext.findPlugin(MetaPlugin.class).getVisitMethodName()).param(JMod.FINAL, PropertyVisitor.class, "visitor_");
	}

	return interfaceDecl;
}
 
Example #22
Source File: CopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License votes vote down vote up
void generatePartialArgs(JDocComment javadoc);