private void addJsonTypeInfo(JDefinedClass klass, ObjectTypeDeclaration type) { if (!context.getConfig().isJacksonTypeInfo()) { return; } if (type.discriminator() == null) { return; } List<String> derivedTypes = context.getApiModel().findDerivedTypes(type.name()); if (derivedTypes.isEmpty()) { return; } JAnnotationUse typeInfo = klass.annotate(JsonTypeInfo.class); typeInfo.param("use", Id.NAME); typeInfo.param("include", As.EXISTING_PROPERTY); typeInfo.param("property", type.discriminator()); JAnnotationUse subTypes = klass.annotate(JsonSubTypes.class); JAnnotationArrayMember typeArray = subTypes.paramArray(VALUE); for (String derivedType : derivedTypes) { JDefinedClass subtype = pkg._getClass(derivedType); typeArray.annotate(Type.class).param(VALUE, subtype); } }
/** * Calls the correct {@link JAnnotationUse} <code>param</code> method. * * @param annot * The annotation in which the parameter will be added. * @param key * The parameter's key. * @param value * The parameter's value. */ public static void addAnnotParam(JAnnotationUse annot, String key, Object value) { if (value == null) { // Null values not accepted throw new RuntimeException("Null values not supported as annotation parameters"); } else if (value instanceof Boolean) { annot.param(key, (Boolean) value); } else if (value instanceof Integer) { annot.param(key, (Integer) value); } else if (value instanceof String) { annot.param(key, (String) value); } else if (value instanceof Class<?>) { annot.param(key, (Class<?>) value); } else if (value instanceof JType) { annot.param(key, (JType) value); } else if (value.getClass().isArray()) { Object[] valueArr = (Object[]) value; JAnnotationArrayMember aux = annot.paramArray(key); for (int i = 0; i < valueArr.length; ++i) { addAnnotArrayParam(aux, valueArr[i]); } } else { throw new RuntimeException("Impossible to construct annotation param for: " + value); } }
private void addParam(JAnnotationArrayMember annotate, Object value) { if (value instanceof String) { annotate.param("" + value); } if (value instanceof Double) { annotate.param((Double) value); } if (value instanceof Long) { annotate.param((Long) value); } if (value instanceof Float) { annotate.param((Float) value); } if (value instanceof Boolean) { annotate.param((Boolean) value); } if (value instanceof Integer) { annotate.param((Integer) value); } }
@Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } }
public static void suppressWarnings(JMethod method, String... values) { JAnnotationUse annotation = method.annotate(SuppressWarnings.class); JAnnotationArrayMember member = annotation.paramArray("value"); for( String value : values ) { member.param(value); } }
private static void addAnnotArrayParam(JAnnotationArrayMember aux, Object value) { if (value instanceof JType) { aux.param((JType) value); // return aux.param((JType)value); ?? No Javadoc defining how to use the API } else { throw new RuntimeException("Impossible to construct annotation param array for: " + value); } }
private void addInline(JAnnotationArrayMember inlines, String name, String returnType) throws JClassAlreadyExistsException { inlines.annotate(Inline.class) .param("type", new JCodeModel()._class("io.fabric8.docker.api.model.Doneable")) .param("returnType", new JCodeModel()._class(returnType)) .param("name", name) .param("value", "done"); }
/** * <p>addProducesAnnotation.</p> * * @param uniqueResponseMimeTypes a {@link java.util.Collection} object. * @param method a {@link com.sun.codemodel.JMethod} object. */ protected void addProducesAnnotation( final Collection<MimeType> uniqueResponseMimeTypes, final JMethod method) { if (uniqueResponseMimeTypes.isEmpty()) { return; } final JAnnotationArrayMember paramArray = method.annotate( Produces.class).paramArray(DEFAULT_ANNOTATION_PARAMETER); for (final MimeType responseMimeType : uniqueResponseMimeTypes) { paramArray.param(responseMimeType.getType()); } }
@Override public boolean run(final Outline outline, final Options options, final ErrorHandler errorHandler) { final JClass xmlNsClass = outline.getCodeModel().ref(XmlNs.class); final JClass xmlSchemaClass = outline.getCodeModel().ref(XmlSchema.class); for (PackageOutline packageOutline : outline.getAllPackageContexts()) { final JPackage p = packageOutline._package(); // get the target namespaces of all schemas that bind to the current package final Set<String> packageNamespaces = getPackageNamespace(packageOutline); // is there any prefix binding defined for the current package ? final Model packageModel = getPackageModel((PackageOutlineImpl) packageOutline); final List<Pair> list = getPrefixBinding(packageModel, packageNamespaces); acknowledgePrefixAnnotations(packageModel); if (list == null || list.isEmpty()) { // no prefix binding, nothing to do continue; } // add XML namespace prefix annotations final JAnnotationUse xmlSchemaAnnotation = getOrAddXmlSchemaAnnotation(p, xmlSchemaClass); if (xmlSchemaAnnotation == null) { throw new RuntimeException("Unable to get/add 'XmlSchema' annotation to package [" + p.name() + "]"); } final JAnnotationArrayMember members = xmlSchemaAnnotation.paramArray("xmlns"); for (Pair pair : list) { addNamespacePrefix(xmlNsClass, members, pair.getNamespace(), pair.getPrefix()); } } return true; }
private void renderClassLevelAnnotations(JDefinedClass classModel, List<FieldModel> fields) throws Exception { JFieldRef constantsClass = classModel.staticRef(Util.CONSTANTS_CLASS_NAME); JFieldRef elementsClass = classModel.staticRef(Util.ELEMENTS_CLASS_NAME); JClass coreConstants = codeModel.ref(CoreConstants.class); JFieldRef commonElementsRef = coreConstants.staticRef("CommonElements"); // XmlRootElement JAnnotationUse rootElementAnnotation = classModel.annotate(XmlRootElement.class); rootElementAnnotation.param("name", constantsClass.ref(Util.ROOT_ELEMENT_NAME_FIELD)); // XmlAccessorType JAnnotationUse xmlAccessorTypeAnnotation = classModel.annotate(XmlAccessorType.class); xmlAccessorTypeAnnotation.param("value", XmlAccessType.NONE); // XmlType JAnnotationUse xmlTypeAnnotation = classModel.annotate(XmlType.class); xmlTypeAnnotation.param("name", constantsClass.ref(Util.TYPE_NAME_FIELD)); JAnnotationArrayMember propOrderMember = xmlTypeAnnotation.paramArray("propOrder"); for (FieldModel field : fields) { if (Util.isCommonElement(field.fieldName)) { propOrderMember.param(commonElementsRef.ref(Util.toConstantsVariable(field.fieldName))); } else { propOrderMember.param(elementsClass.ref(Util.toConstantsVariable(field.fieldName))); } } propOrderMember.param(commonElementsRef.ref("FUTURE_ELEMENTS")); }
@Override public void caseAAnnotationElementValue(AAnnotationElementValue node) { final JAnnotationArrayMember annarr = ann.paramArray(id); AnnotationAdapter aa = new AnnotationAdapter(new Annotatable(){ @Override public JAnnotationUse annotate(JClass atype) { return annarr.annotate(atype); } }, context); node.getAnnotation().apply(aa); }
@Override public void caseAArrayElementValue(AArrayElementValue node) { final JAnnotationArrayMember annarr = ann.paramArray(id); AnnotationArrayAdapter aaa = new AnnotationArrayAdapter(annarr, context); AElementValueArrayInitializer aevi = (AElementValueArrayInitializer) node.getElementValueArrayInitializer(); for (PElementValue val : aevi.getElementValue()) { val.apply(aaa); } }
/** * Adding nested Annotations in JModel * @throws Exception */ // unused //@Test public void testNestedAnnotations() throws Exception{ JCodeModel jmod = new JCodeModel(); // adding a test package JPackage pack = jmod._package("testNestedAnnotations"); // building an interface JDefinedClass interface1 = pack._interface("Interface1"); // adding annotations JDefinedClass annotation1 = pack._annotationTypeDeclaration("Annot1"); JDefinedClass annotation2 = pack._annotationTypeDeclaration("Annot2"); // adding a method for annotation2 annotation1.method(JMod.NONE, String.class, "value"); //adding a method which has an annotation as type to annotation1 annotation2.method(JMod.NONE, annotation1.array(), "value"); // add an annotation to the Interface JAnnotationArrayMember paramarray = interface1.annotate(annotation2).paramArray("value"); paramarray.annotate(annotation1).param("value", "a"); //paramarray.annotate(annotation1).param("value", "b"); //paramarray.annotate(annotation1).param("value", "c"); jmod.build(new SingleStreamCodeWriter(System.out)); }
public JAnnotationUse visitArrayAnnotationField( XArrayAnnotationField<?> field) { String fieldName = field.getName(); final JAnnotationArrayMember annotationArrayMember = this.annotationUse .paramArray(fieldName); for (final XAnnotationValue<?> annotationValue : field .getAnnotationValues()) { annotationValue.accept(new AnnotatingArrayValueVisitor( this.codeModel, annotationArrayMember)); } return this.annotationUse; }
/** * Parse the annotations on the field to see if there is an XmlElements * annotation on it. If so, we'll check this annotation to see if it * refers to any classes that are external from our code schema compile. * If we find any, then we'll add them to our visitor. * @param outline root of the generated code * @param field parses the xml annotations looking for an external class * @param directClasses set of direct classes to append to * @throws IllegalAccessException throw if there's an error introspecting the annotations */ private static void parseXmlAnnotations(Outline outline, FieldOutline field, Set<String> directClasses) throws IllegalAccessException { if (field instanceof UntypedListField) { JFieldVar jfv = (JFieldVar) FieldHack.listField.get(field); for(JAnnotationUse jau : jfv.annotations()) { JClass jc = jau.getAnnotationClass(); if (jc.fullName().equals(XmlElements.class.getName())) { JAnnotationArrayMember value = (JAnnotationArrayMember) jau.getAnnotationMembers().get("value"); for(JAnnotationUse anno : value.annotations()) { handleXmlElement(outline, directClasses, anno.getAnnotationMembers().get("type")); } } } } }
public JAnnotationArrayMember visit(XXAnnotationAnnotationValue<?> value) { final XAnnotation<?> xannotation = value.getXAnnotation(); // TODO illegal call to getAnnotationClass(), use // getAnnotationClassName(); final JAnnotationUse annotationUse = annotationArrayMember .annotate(xannotation.getAnnotationClass()); for (final XAnnotationField<?> field : xannotation.getFieldsList()) { field.accept(new AnnotatingVisitor(this.codeModel, annotationUse)); } return this.annotationArrayMember; }
public JAnnotationArrayMember visit(XArrayClassAnnotationValue<?, ?> value) { JType type = CodeModelUtils.ref(this.codeModel, value.getItemClassName()); for (int index = 0; index < value.getDimension(); index++) { type = type.array(); } return param(type); }
private JAnnotationArrayMember param(final JType type) { if (type instanceof JClass) { return annotationArrayMember.param((JClass) type); } else { return annotationArrayMember.param(new JExpressionImpl() { public void generate(JFormatter f) { f.g(type).p(".class"); } }); } }
@Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { //We just want to make sure we avoid infinite loops clazz.annotate(JsonDeserialize.class) .param("using", JsonDeserializer.None.class); clazz.annotate(ToString.class); clazz.annotate(EqualsAndHashCode.class); try { JAnnotationArrayMember inlines = clazz.annotate(Buildable.class) .param("editableEnabled", true) .param("validationEnabled", true) .param("generateBuilderPackage", true) .param("builderPackage", "io.fabric8.docker.api.builder") .paramArray("inline"); inlines.annotate(Inline.class) .param("type", new JCodeModel()._class("io.fabric8.docker.api.model.Doneable")) .param("prefix", "Doneable") .param("value", "done"); //Let's get our hands dirty and add annotations so that we generate custom Inline methods if (clazz.name().equals("NetworkCreate")) { inlines.annotate(Inline.class) .param("type", new JCodeModel()._class("io.fabric8.docker.api.model.Doneable")) .param("returnType", new JCodeModel()._class("io.fabric8.docker.api.model.NetworkCreateResponse")) .param("name", "InlineNetworkCreate") .param("value", "done"); } if (clazz.name().equals("AuthConfig")) { addInline(inlines, "InlineAuth", "java.lang.Boolean"); } if (clazz.name().equals("NetworkCreate")) { addInline(inlines, "InlineNetworkCreate", "io.fabric8.docker.api.model.NetworkCreateResponse"); } if (clazz.name().equals("VolumeCreateRequest")) { addInline(inlines, "InlineVolumeCreate", "io.fabric8.docker.api.model.Volume"); } if (clazz.name().equals("ExecConfig")) { addInline(inlines, "InlineExecConfig", "io.fabric8.docker.api.model.ContainerExecCreateResponse"); } } catch (JClassAlreadyExistsException e) { e.printStackTrace(); } }
private static void addNamespacePrefix(JClass xmlNsClass, JAnnotationArrayMember members, String namespace, String prefix) { final JAnnotationUse ns = members.annotate(xmlNsClass); ns.param("namespaceURI", namespace); ns.param("prefix", prefix); }
@Test public void testClassWithPersistenceContextWithWithOverwrittenConfiguration() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JAnnotationArrayMember propArray = jAnnotation.paramArray("properties"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.url").param("value", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.driver").param("value", "org.h2.Driver"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.password").param("value", "test"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.user").param("value", "test"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@Test public void testClassWithPersistenceContextWithWithOverwrittenConfiguration() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JAnnotationArrayMember propArray = jAnnotation.paramArray("properties"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.url").param("value", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.driver").param("value", "org.h2.Driver"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.password").param("value", "test"); propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.user").param("value", "test"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final JpaUnitRunner runner = new JpaUnitRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
AnnotationArrayAdapter(JAnnotationArrayMember ann, ResolutionContext context) { this.ann = ann; this.context = context; }
/** * Write Annotations to the Package */ private void annotatePackage(){ // Base URI // Comments JDocComment jdoc = jpack.javadoc(); jdoc.append("Automatically generated Package from Ontology\n"); jdoc.append("Ontology URI: <code>"); jdoc.append(ontologyUri); jdoc.append("</code></br>\n"); if(this.ontologyPhysicalUri != null) jdoc.append("Loaded from URI: <code>").append(ontologyPhysicalUri).append("</code>"); //Annotation jpack.annotate(OwlOntology.class).param("uri", ontologyUri); // OWL Imports Set<OWLImportsDeclaration> imports = ontology.getImportsDeclarations(); if(!imports.isEmpty()){ JAnnotationArrayMember annot = jpack.annotate(OwlImports.class).paramArray("uris"); jdoc.append("</br>\nImported Ontologies:\n<ul>"); for(OWLImportsDeclaration imprt : imports ){ jdoc.append("\t<li><code>").append(imprt.getImportedOntologyURI().toString()).append("</code></li>\n"); annot.param(imprt.getImportedOntologyURI().toString()); } jdoc.append("<ul>\n</br>\n</br>\n"); } // owl annotations for(OWLOntologyAnnotationAxiom oaxiom : ontology.getAnnotations(ontology)){ OWLAnnotation<?> oannot = oaxiom.getAnnotation(); log.debug("Ontology annotation {}", oannot); if( oannot.isAnnotationByConstant() ){ String value = oannot.getAnnotationValueAsConstant().getLiteral(); jdoc.add("\nOWL Annotation "); //jdoc.append(oannot.toString()); jdoc.append(": "); jdoc.append(value); jdoc.append("</br>"); } else { } } }
public AnnotatingArrayValueVisitor(JCodeModel codeModel, JAnnotationArrayMember annotationArrayMember) { super(codeModel, annotationArrayMember); this.annotationArrayMember = annotationArrayMember; }
@Override public JAnnotationArrayMember visit(XStringAnnotationValue value) { return annotationArrayMember.param(StringUtils.normalizeString(value .getValue())); }
public AnnotatingArrayValueVisitor(JCodeModel codeModel, JAnnotationArrayMember annotationArrayMember) { this.codeModel = codeModel; this.annotationArrayMember = annotationArrayMember; }
public JAnnotationArrayMember visit(XBooleanAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }
public JAnnotationArrayMember visit(XByteAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }
public JAnnotationArrayMember visit(XCharAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }
public JAnnotationArrayMember visit(XDoubleAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }
public JAnnotationArrayMember visit(XFloatAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }
public JAnnotationArrayMember visit(XIntAnnotationValue value) { return annotationArrayMember.param(value.getValue()); }