Search in sources :

Example 1 with XmlElements

use of jakarta.xml.bind.annotation.XmlElements in project glassfish-hk2 by eclipse-ee4j.

the class Generator method generate.

/**
 * Converts the given interface into a JAXB implementation proxy
 *
 * @param convertMe
 * @param superClazz
 * @param defaultClassPool
 * @return
 * @throws Throwable
 */
public static CtClass generate(AltClass convertMe, CtClass superClazz, ClassPool defaultClassPool) throws Throwable {
    String modelOriginalInterface = convertMe.getName();
    String modelTranslatedClass = Utilities.getProxyNameFromInterfaceName(modelOriginalInterface);
    if (DEBUG_METHODS) {
        Logger.getLogger().debug("Converting " + convertMe.getName() + " to " + modelTranslatedClass);
    }
    CtClass targetCtClass = defaultClassPool.makeClass(modelTranslatedClass);
    ClassFile targetClassFile = targetCtClass.getClassFile();
    targetClassFile.setVersionToJava5();
    ConstPool targetConstPool = targetClassFile.getConstPool();
    ModelImpl compiledModel = new ModelImpl(modelOriginalInterface, modelTranslatedClass);
    AnnotationsAttribute ctAnnotations = null;
    String[] propOrder = null;
    for (AltAnnotation convertMeAnnotation : convertMe.getAnnotations()) {
        if (NO_COPY_ANNOTATIONS.contains(convertMeAnnotation.annotationType())) {
            // we do not want them to do
            continue;
        }
        if (ctAnnotations == null) {
            ctAnnotations = new AnnotationsAttribute(targetConstPool, AnnotationsAttribute.visibleTag);
        }
        if (XmlRootElement.class.getName().equals(convertMeAnnotation.annotationType())) {
            QName modelRootName = GeneratorUtilities.convertXmlRootElementName(convertMeAnnotation, convertMe);
            compiledModel.setRootName(modelRootName);
            String modelRootNameNamespace = QNameUtilities.getNamespace(modelRootName);
            String modelRootNameKey = modelRootName.getLocalPart();
            XmlRootElement replacement = new XmlRootElementImpl(modelRootNameNamespace, modelRootNameKey);
            createAnnotationCopy(targetConstPool, replacement, ctAnnotations);
        } else {
            createAnnotationCopy(targetConstPool, convertMeAnnotation, ctAnnotations);
        }
        if (XmlType.class.getName().equals(convertMeAnnotation.annotationType())) {
            propOrder = convertMeAnnotation.getStringArrayValue("propOrder");
        }
    }
    if (ctAnnotations != null) {
        targetClassFile.addAttribute(ctAnnotations);
    }
    CtClass originalCtClass = defaultClassPool.getOrNull(convertMe.getName());
    if (originalCtClass == null) {
        originalCtClass = defaultClassPool.makeInterface(convertMe.getName());
    }
    targetCtClass.setSuperclass(superClazz);
    targetCtClass.addInterface(originalCtClass);
    NameInformation xmlNameMap = GeneratorUtilities.getXmlNameMap(convertMe);
    Set<QName> alreadyAddedNaked = new LinkedHashSet<QName>();
    List<AltMethod> allMethods = convertMe.getMethods();
    if (DEBUG_METHODS) {
        Logger.getLogger().debug("Analyzing " + allMethods.size() + " methods of " + convertMe.getName());
    }
    allMethods = Utilities.prioritizeMethods(allMethods, propOrder, xmlNameMap);
    Set<String> setters = new LinkedHashSet<String>();
    Map<String, MethodInformationI> getters = new LinkedHashMap<String, MethodInformationI>();
    Map<String, GhostXmlElementData> elementsMethods = new LinkedHashMap<String, GhostXmlElementData>();
    for (AltMethod wrapper : allMethods) {
        MethodInformationI mi = Utilities.getMethodInformation(wrapper, xmlNameMap);
        if (mi.isKey()) {
            compiledModel.setKeyProperty(mi.getRepresentedProperty());
        }
        String miRepPropNamespace = QNameUtilities.getNamespace(mi.getRepresentedProperty());
        String miRepProp = (mi.getRepresentedProperty() == null) ? null : mi.getRepresentedProperty().getLocalPart();
        if (!MethodType.CUSTOM.equals(mi.getMethodType())) {
            createInterfaceForAltClassIfNeeded(mi.getGetterSetterType(), defaultClassPool);
        } else {
            // Custom methods can have all sorts of missing types, need to do all return and param types
            AltMethod original = mi.getOriginalMethod();
            AltClass originalReturn = original.getReturnType();
            if (!ClassAltClassImpl.VOID.equals(originalReturn)) {
                createInterfaceForAltClassIfNeeded(originalReturn, defaultClassPool);
            }
            for (AltClass parameter : original.getParameterTypes()) {
                createInterfaceForAltClassIfNeeded(parameter, defaultClassPool);
            }
        }
        if (DEBUG_METHODS) {
            Logger.getLogger().debug("Analyzing method " + mi + " of " + convertMe.getSimpleName());
        }
        String name = wrapper.getName();
        StringBuffer sb = new StringBuffer("public ");
        AltClass originalRetType = wrapper.getReturnType();
        boolean isVoid;
        if (originalRetType == null || void.class.getName().equals(originalRetType.getName())) {
            sb.append("void ");
            isVoid = true;
        } else {
            sb.append(getCompilableClass(originalRetType) + " ");
            isVoid = false;
        }
        sb.append(name + "(");
        AltClass childType = null;
        boolean getterOrSetter = false;
        boolean isReference = false;
        boolean isSetter = false;
        if (MethodType.SETTER.equals(mi.getMethodType())) {
            getterOrSetter = true;
            isSetter = true;
            setters.add(mi.getRepresentedProperty().getLocalPart());
            childType = mi.getBaseChildType();
            isReference = mi.isReference();
            sb.append(getCompilableClass(mi.getGetterSetterType()) + " arg0) { super._setProperty(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\", arg0); }");
        } else if (MethodType.GETTER.equals(mi.getMethodType())) {
            getterOrSetter = true;
            getters.put(mi.getRepresentedProperty().getLocalPart(), mi);
            childType = mi.getBaseChildType();
            isReference = mi.isReference();
            String cast = "";
            String superMethodName = "_getProperty";
            if (int.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "I";
            } else if (long.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "J";
            } else if (boolean.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "Z";
            } else if (byte.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "B";
            } else if (char.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "C";
            } else if (short.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "S";
            } else if (float.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "F";
            } else if (double.class.getName().equals(mi.getGetterSetterType().getName())) {
                superMethodName += "D";
            } else {
                cast = "(" + getCompilableClass(mi.getGetterSetterType()) + ") ";
            }
            sb.append(") { return " + cast + "super." + superMethodName + "(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\"); }");
        } else if (MethodType.LOOKUP.equals(mi.getMethodType())) {
            sb.append("java.lang.String arg0) { return (" + getCompilableClass(originalRetType) + ") super._lookupChild(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\", arg0); }");
        } else if (MethodType.ADD.equals(mi.getMethodType())) {
            String returnClause = "";
            if (!isVoid) {
                createInterfaceForAltClassIfNeeded(originalRetType, defaultClassPool);
                returnClause = "return (" + getCompilableClass(originalRetType) + ") ";
            }
            List<AltClass> paramTypes = wrapper.getParameterTypes();
            if (paramTypes.size() == 0) {
                sb.append(") { " + returnClause + "super._doAdd(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\", null, null, -1); }");
            } else if (paramTypes.size() == 1) {
                createInterfaceForAltClassIfNeeded(paramTypes.get(0), defaultClassPool);
                sb.append(paramTypes.get(0).getName() + " arg0) { " + returnClause + "super._doAdd(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\",");
                if (paramTypes.get(0).isInterface()) {
                    sb.append("arg0, null, -1); }");
                } else if (String.class.getName().equals(paramTypes.get(0).getName())) {
                    sb.append("null, arg0, -1); }");
                } else {
                    sb.append("null, null, arg0); }");
                }
            } else {
                sb.append(paramTypes.get(0).getName() + " arg0, int arg1) { " + returnClause + "super._doAdd(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\",");
                if (paramTypes.get(0).isInterface()) {
                    createInterfaceForAltClassIfNeeded(paramTypes.get(0), defaultClassPool);
                    sb.append("arg0, null, arg1); }");
                } else {
                    sb.append("null, arg0, arg1); }");
                }
            }
        } else if (MethodType.REMOVE.equals(mi.getMethodType())) {
            List<AltClass> paramTypes = wrapper.getParameterTypes();
            String cast = "";
            String function = "super._doRemoveZ(\"";
            String doReturn = "return";
            if (!boolean.class.getName().equals(originalRetType.getName())) {
                if (void.class.getName().equals(originalRetType.getName())) {
                    doReturn = "";
                } else {
                    cast = "(" + getCompilableClass(originalRetType) + ") ";
                }
                function = "super._doRemove(\"";
            }
            if (paramTypes.size() == 0) {
                sb.append(") { " + doReturn + " " + cast + function + miRepPropNamespace + "\",\"" + miRepProp + "\", null, -1, null); }");
            } else if (String.class.getName().equals(paramTypes.get(0).getName())) {
                sb.append("java.lang.String arg0) { " + doReturn + " " + cast + function + miRepPropNamespace + "\",\"" + miRepProp + "\", arg0, -1, null); }");
            } else if (int.class.getName().equals(paramTypes.get(0).getName())) {
                sb.append("int arg0) { " + doReturn + " " + cast + function + miRepPropNamespace + "\",\"" + miRepProp + "\", null, arg0, null); }");
            } else {
                sb.append(paramTypes.get(0).getName() + " arg0) { " + doReturn + " " + cast + function + miRepPropNamespace + "\",\"" + miRepProp + "\", null, -1, arg0); }");
            }
        } else if (MethodType.CUSTOM.equals(mi.getMethodType())) {
            List<AltClass> paramTypes = wrapper.getParameterTypes();
            StringBuffer classSets = new StringBuffer();
            StringBuffer valSets = new StringBuffer();
            int lcv = 0;
            for (AltClass paramType : paramTypes) {
                createInterfaceForAltClassIfNeeded(paramType, defaultClassPool);
                if (lcv == 0) {
                    sb.append(getCompilableClass(paramType) + " arg" + lcv);
                } else {
                    sb.append(", " + getCompilableClass(paramType) + " arg" + lcv);
                }
                classSets.append("mParams[" + lcv + "] = " + getCompilableClass(paramType) + ".class;\n");
                valSets.append("mVars[" + lcv + "] = ");
                if (int.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Integer(arg" + lcv + ");\n");
                } else if (long.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Long(arg" + lcv + ");\n");
                } else if (boolean.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Boolean(arg" + lcv + ");\n");
                } else if (byte.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Byte(arg" + lcv + ");\n");
                } else if (char.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Character(arg" + lcv + ");\n");
                } else if (short.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Short(arg" + lcv + ");\n");
                } else if (float.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Float(arg" + lcv + ");\n");
                } else if (double.class.getName().equals(paramType.getName())) {
                    valSets.append("new java.lang.Double(arg" + lcv + ");\n");
                } else {
                    valSets.append("arg" + lcv + ";\n");
                }
                lcv++;
            }
            sb.append(") { Class[] mParams = new Class[" + paramTypes.size() + "];\n");
            sb.append("Object[] mVars = new Object[" + paramTypes.size() + "];\n");
            sb.append(classSets.toString());
            sb.append(valSets.toString());
            String cast = "";
            String superMethodName = "_invokeCustomizedMethod";
            if (int.class.getName().equals(originalRetType.getName())) {
                superMethodName += "I";
            } else if (long.class.getName().equals(originalRetType.getName())) {
                superMethodName += "J";
            } else if (boolean.class.getName().equals(originalRetType.getName())) {
                superMethodName += "Z";
            } else if (byte.class.getName().equals(originalRetType.getName())) {
                superMethodName += "B";
            } else if (char.class.getName().equals(originalRetType.getName())) {
                superMethodName += "C";
            } else if (short.class.getName().equals(originalRetType.getName())) {
                superMethodName += "S";
            } else if (float.class.getName().equals(originalRetType.getName())) {
                superMethodName += "F";
            } else if (double.class.getName().equals(originalRetType.getName())) {
                superMethodName += "D";
            } else if (!isVoid) {
                cast = "(" + getCompilableClass(originalRetType) + ") ";
            }
            if (!isVoid) {
                sb.append("return " + cast);
            }
            sb.append("super." + superMethodName + "(\"" + name + "\", mParams, mVars);}");
        } else {
            throw new AssertionError("Unknown method type: " + mi.getMethodType());
        }
        if (DEBUG_METHODS) {
            // Hidden behind static because of potential expensive toString costs
            Logger.getLogger().debug("Adding method for " + convertMe.getSimpleName() + " with implementation " + sb);
        }
        CtMethod addMeCtMethod;
        try {
            addMeCtMethod = CtNewMethod.make(sb.toString(), targetCtClass);
        } catch (CannotCompileException cce) {
            MultiException me = new MultiException(cce);
            me.addError(new AssertionError("Cannot compile method with source " + sb.toString()));
            throw me;
        }
        if (wrapper.isVarArgs()) {
            addMeCtMethod.setModifiers(addMeCtMethod.getModifiers() | Modifier.VARARGS);
        }
        if (mi.getListParameterizedType() != null) {
            addListGenericSignature(addMeCtMethod, mi.getListParameterizedType(), isSetter);
        }
        MethodInfo methodInfo = addMeCtMethod.getMethodInfo();
        ConstPool methodConstPool = methodInfo.getConstPool();
        ctAnnotations = null;
        for (AltAnnotation convertMeAnnotation : wrapper.getAnnotations()) {
            if (NO_COPY_ANNOTATIONS_METHOD.contains(convertMeAnnotation.annotationType())) {
                continue;
            }
            if (ctAnnotations == null) {
                ctAnnotations = new AnnotationsAttribute(methodConstPool, AnnotationsAttribute.visibleTag);
            }
            if ((childType != null) && XmlElement.class.getName().equals(convertMeAnnotation.annotationType())) {
                String translatedClassName = Utilities.getProxyNameFromInterfaceName(childType.getName());
                java.lang.annotation.Annotation anno = new XmlElementImpl(convertMeAnnotation.getStringValue("name"), convertMeAnnotation.getBooleanValue("nillable"), convertMeAnnotation.getBooleanValue("required"), convertMeAnnotation.getStringValue("namespace"), convertMeAnnotation.getStringValue("defaultValue"), translatedClassName);
                createAnnotationCopy(methodConstPool, anno, ctAnnotations);
            } else if (getterOrSetter && XmlElements.class.getName().equals(convertMeAnnotation.annotationType())) {
                QName representedProperty = mi.getRepresentedProperty();
                AltAnnotation[] elements = convertMeAnnotation.getAnnotationArrayValue("value");
                if (elements == null)
                    elements = new AltAnnotation[0];
                elementsMethods.put(representedProperty.getLocalPart(), new GhostXmlElementData(elements, mi.getGetterSetterType()));
            // Note the XmlElements is NOT copied to the proxy, the ghost methods will get the XmlElements
            } else {
                createAnnotationCopy(methodConstPool, convertMeAnnotation, ctAnnotations);
            }
        }
        if (getterOrSetter) {
            String originalMethodName = mi.getOriginalMethodName();
            List<XmlElementData> aliases = xmlNameMap.getAliases(mi.getRepresentedProperty().getLocalPart());
            boolean required = mi.isRequired();
            if ((childType != null) || (aliases != null)) {
                if (!isReference) {
                    AliasType aType = (aliases == null) ? AliasType.NORMAL : AliasType.HAS_ALIASES;
                    AltClass useChildType = (childType == null) ? mi.getListParameterizedType() : childType;
                    AdapterInformation adapterInformation = mi.getAdapterInformation();
                    String adapterClass = (adapterInformation == null) ? null : adapterInformation.getAdapter().getName();
                    if (useChildType.isInterface()) {
                        compiledModel.addChild(useChildType.getName(), QNameUtilities.getNamespace(mi.getRepresentedProperty()), mi.getRepresentedProperty().getLocalPart(), mi.getRepresentedProperty().getLocalPart(), getChildType(mi.isList(), mi.isArray()), mi.getDefaultValue(), aType, mi.getWrapperTag(), adapterClass, required, originalMethodName);
                    } else {
                        compiledModel.addNonChild(QNameUtilities.getNamespace(mi.getRepresentedProperty()), mi.getRepresentedProperty().getLocalPart(), mi.getDefaultValue(), mi.getGetterSetterType().getName(), mi.getListParameterizedType().getName(), false, Format.ELEMENT, aType, null, required, originalMethodName);
                    }
                    if (aliases != null) {
                        for (XmlElementData alias : aliases) {
                            String aliasType = alias.getType();
                            if (aliasType == null)
                                aliasType = useChildType.getName();
                            if (alias.isTypeInterface()) {
                                compiledModel.addChild(aliasType, alias.getNamespace(), alias.getName(), alias.getAlias(), getChildType(mi.isList(), mi.isArray()), alias.getDefaultValue(), AliasType.IS_ALIAS, mi.getWrapperTag(), adapterClass, required, originalMethodName);
                            } else {
                                compiledModel.addNonChild(alias.getNamespace(), alias.getName(), alias.getDefaultValue(), mi.getGetterSetterType().getName(), aliasType, false, Format.ELEMENT, AliasType.IS_ALIAS, alias.getAlias(), required, originalMethodName);
                            }
                        }
                    }
                } else {
                    // Is a reference
                    String listPType = (mi.getListParameterizedType() == null) ? null : mi.getListParameterizedType().getName();
                    compiledModel.addNonChild(mi.getRepresentedProperty(), mi.getDefaultValue(), mi.getGetterSetterType().getName(), listPType, true, mi.getFormat(), AliasType.NORMAL, null, required, originalMethodName);
                }
            } else {
                String listPType = (mi.getListParameterizedType() == null) ? null : mi.getListParameterizedType().getName();
                compiledModel.addNonChild(mi.getRepresentedProperty(), mi.getDefaultValue(), mi.getGetterSetterType().getName(), listPType, false, mi.getFormat(), AliasType.NORMAL, null, required, originalMethodName);
            }
        }
        if (getterOrSetter && childType != null && xmlNameMap.hasNoXmlElement(mi.getRepresentedProperty().getLocalPart()) && !alreadyAddedNaked.contains(mi.getRepresentedProperty())) {
            alreadyAddedNaked.add(mi.getRepresentedProperty());
            if (ctAnnotations == null) {
                ctAnnotations = new AnnotationsAttribute(methodConstPool, AnnotationsAttribute.visibleTag);
            }
            java.lang.annotation.Annotation convertMeAnnotation;
            String translatedClassName = Utilities.getProxyNameFromInterfaceName(childType.getName());
            convertMeAnnotation = new XmlElementImpl(JAXB_DEFAULT_STRING, false, false, JAXB_DEFAULT_STRING, JAXB_DEFAULT_DEFAULT, translatedClassName);
            if (DEBUG_METHODS) {
                Logger.getLogger().debug("Adding ghost XmlElement for " + convertMe.getSimpleName() + " with data " + convertMeAnnotation);
            }
            createAnnotationCopy(methodConstPool, convertMeAnnotation, ctAnnotations);
        }
        if (ctAnnotations != null) {
            methodInfo.addAttribute(ctAnnotations);
        }
        targetCtClass.addMethod(addMeCtMethod);
    }
    // Now generate the invisible setters for JAXB
    for (Map.Entry<String, MethodInformationI> getterEntry : getters.entrySet()) {
        String getterProperty = getterEntry.getKey();
        MethodInformationI mi = getterEntry.getValue();
        String miRepPropNamespace = QNameUtilities.getNamespace(mi.getRepresentedProperty());
        String miRepProp = mi.getRepresentedProperty().getLocalPart();
        if (setters.contains(getterProperty))
            continue;
        String getterName = mi.getOriginalMethod().getName();
        String setterName = Utilities.convertToSetter(getterName);
        StringBuffer sb = new StringBuffer("private void " + setterName + "(");
        sb.append(getCompilableClass(mi.getGetterSetterType()) + " arg0) { super._setProperty(\"" + miRepPropNamespace + "\",\"" + miRepProp + "\", arg0); }");
        CtMethod addMeCtMethod = CtNewMethod.make(sb.toString(), targetCtClass);
        targetCtClass.addMethod(addMeCtMethod);
        if (mi.getListParameterizedType() != null) {
            addListGenericSignature(addMeCtMethod, mi.getListParameterizedType(), true);
        }
        if (DEBUG_METHODS) {
            Logger.getLogger().debug("Adding ghost setter method for " + convertMe.getSimpleName() + " with implementation " + sb);
        }
    }
    int elementCount = 0;
    for (Map.Entry<String, GhostXmlElementData> entry : elementsMethods.entrySet()) {
        String basePropName = entry.getKey();
        GhostXmlElementData gxed = entry.getValue();
        AltAnnotation[] xmlElements = gxed.xmlElements;
        String baseSetSetterName = "set_" + basePropName;
        String baseGetterName = "get_" + basePropName;
        for (AltAnnotation xmlElement : xmlElements) {
            String elementName = xmlElement.getStringValue("name");
            String elementNamespace = xmlElement.getStringValue("namespace");
            String ghostMethodName = baseSetSetterName + "_" + elementCount;
            String ghostMethodGetName = baseGetterName + "_" + elementCount;
            elementCount++;
            AltClass ac = (AltClass) xmlElement.getAnnotationValues().get("type");
            {
                // Create the setter
                StringBuffer ghostBufferSetter = new StringBuffer("private void " + ghostMethodName + "(");
                ghostBufferSetter.append(getCompilableClass(gxed.getterSetterType) + " arg0) { super._setProperty(\"" + elementNamespace + "\",\"" + elementName + "\", arg0); }");
                if (DEBUG_METHODS) {
                    Logger.getLogger().debug("Adding ghost XmlElements setter method for " + convertMe.getSimpleName() + " with implementation " + ghostBufferSetter);
                }
                CtMethod elementsCtMethod = CtNewMethod.make(ghostBufferSetter.toString(), targetCtClass);
                addListGenericSignature(elementsCtMethod, ac, true);
                targetCtClass.addMethod(elementsCtMethod);
            }
            {
                // Create the getter
                StringBuffer ghostBufferGetter = new StringBuffer("private " + getCompilableClass(gxed.getterSetterType) + " " + ghostMethodGetName + "() { return (" + getCompilableClass(gxed.getterSetterType) + ") super._getProperty(\"" + elementNamespace + "\",\"" + elementName + "\"); }");
                CtMethod elementsCtMethodGetter = CtNewMethod.make(ghostBufferGetter.toString(), targetCtClass);
                addListGenericSignature(elementsCtMethodGetter, ac, false);
                MethodInfo elementsMethodInfo = elementsCtMethodGetter.getMethodInfo();
                ConstPool elementsMethodConstPool = elementsMethodInfo.getConstPool();
                AnnotationsAttribute aa = new AnnotationsAttribute(elementsMethodConstPool, AnnotationsAttribute.visibleTag);
                String translatedClassName;
                if (ac.isInterface()) {
                    translatedClassName = Utilities.getProxyNameFromInterfaceName(ac.getName());
                } else {
                    translatedClassName = ac.getName();
                }
                XmlElement xElement = new XmlElementImpl(elementName, xmlElement.getBooleanValue("nillable"), xmlElement.getBooleanValue("required"), xmlElement.getStringValue("namespace"), xmlElement.getStringValue("defaultValue"), translatedClassName);
                createAnnotationCopy(elementsMethodConstPool, xElement, aa);
                elementsMethodInfo.addAttribute(aa);
                if (DEBUG_METHODS) {
                    Logger.getLogger().debug("Adding ghost XmlElements getter method for " + convertMe.getSimpleName() + " with implementation " + ghostBufferGetter);
                    Logger.getLogger().debug("with XmlElement " + xElement);
                }
                targetCtClass.addMethod(elementsCtMethodGetter);
            }
        }
    }
    generateStaticModelFieldAndAbstractMethodImpl(targetCtClass, compiledModel, defaultClassPool);
    return targetCtClass;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConstPool(javassist.bytecode.ConstPool) MethodInformationI(org.glassfish.hk2.xml.internal.alt.MethodInformationI) AdapterInformation(org.glassfish.hk2.xml.internal.alt.AdapterInformation) CannotCompileException(javassist.CannotCompileException) AltClass(org.glassfish.hk2.xml.internal.alt.AltClass) XmlElementImpl(org.glassfish.hk2.xml.jaxb.internal.XmlElementImpl) LinkedHashMap(java.util.LinkedHashMap) XmlRootElementImpl(org.glassfish.hk2.xml.jaxb.internal.XmlRootElementImpl) XmlElements(jakarta.xml.bind.annotation.XmlElements) AltMethod(org.glassfish.hk2.xml.internal.alt.AltMethod) List(java.util.List) AltAnnotation(org.glassfish.hk2.xml.internal.alt.AltAnnotation) XmlRootElement(jakarta.xml.bind.annotation.XmlRootElement) ClassFile(javassist.bytecode.ClassFile) QName(javax.xml.namespace.QName) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) XmlType(jakarta.xml.bind.annotation.XmlType) CtClass(javassist.CtClass) XmlElement(jakarta.xml.bind.annotation.XmlElement) MethodInfo(javassist.bytecode.MethodInfo) MultiException(org.glassfish.hk2.api.MultiException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) CtMethod(javassist.CtMethod)

Example 2 with XmlElements

use of jakarta.xml.bind.annotation.XmlElements in project jaxb-ri by eclipse-ee4j.

the class ElementPropertyInfoImpl method getTypes.

@Override
public List<? extends TypeRefImpl<TypeT, ClassDeclT>> getTypes() {
    if (types == null) {
        types = new FinalArrayList<>();
        XmlElement[] ann = null;
        XmlElement xe = seed.readAnnotation(XmlElement.class);
        XmlElements xes = seed.readAnnotation(XmlElements.class);
        if (xe != null && xes != null) {
            parent.builder.reportError(new IllegalAnnotationException(Messages.MUTUALLY_EXCLUSIVE_ANNOTATIONS.format(nav().getClassName(parent.getClazz()) + '#' + seed.getName(), xe.annotationType().getName(), xes.annotationType().getName()), xe, xes));
        }
        isRequired = true;
        if (xe != null)
            ann = new XmlElement[] { xe };
        else if (xes != null)
            ann = xes.value();
        if (ann == null) {
            // default
            TypeT t = getIndividualType();
            if (!nav().isPrimitive(t) || isCollection())
                isRequired = false;
            // nillableness defaults to true if it's collection
            types.add(createTypeRef(calcXmlName((XmlElement) null), t, isCollection(), null));
        } else {
            for (XmlElement item : ann) {
                // TODO: handle defaulting in names.
                QName name = calcXmlName(item);
                TypeT type = reader().getClassValue(item, "type");
                if (nav().isSameType(type, nav().ref(XmlElement.DEFAULT.class)))
                    type = getIndividualType();
                if ((!nav().isPrimitive(type) || isCollection()) && !item.required())
                    isRequired = false;
                types.add(createTypeRef(name, type, item.nillable(), getDefaultValue(item.defaultValue())));
            }
        }
        types = Collections.unmodifiableList(types);
        assert !types.contains(null);
    }
    return types;
}
Also used : XmlElements(jakarta.xml.bind.annotation.XmlElements) QName(javax.xml.namespace.QName) XmlElement(jakarta.xml.bind.annotation.XmlElement) IllegalAnnotationException(org.glassfish.jaxb.core.v2.runtime.IllegalAnnotationException)

Example 3 with XmlElements

use of jakarta.xml.bind.annotation.XmlElements in project glassfish-hk2 by eclipse-ee4j.

the class GeneratorUtilities method getXmlNameMap.

public static NameInformation getXmlNameMap(AltClass convertMe) {
    Map<String, XmlElementData> xmlNameMap = new LinkedHashMap<String, XmlElementData>();
    Set<String> unmappedNames = new LinkedHashSet<String>();
    Map<String, String> addMethodToVariableMap = new LinkedHashMap<String, String>();
    Map<String, String> removeMethodToVariableMap = new LinkedHashMap<String, String>();
    Map<String, String> lookupMethodToVariableMap = new LinkedHashMap<String, String>();
    Set<String> referenceSet = new LinkedHashSet<String>();
    Map<String, List<XmlElementData>> aliasMap = new LinkedHashMap<String, List<XmlElementData>>();
    XmlElementData valueData = null;
    XmlElementData xmlAnyAttributeData = null;
    boolean hasAnElement = false;
    for (AltMethod originalMethod : convertMe.getMethods()) {
        String originalMethodName = originalMethod.getName();
        String setterVariable = Utilities.isSetter(originalMethod);
        if (setterVariable == null) {
            setterVariable = Utilities.isGetter(originalMethod);
            if (setterVariable == null)
                continue;
        }
        if (isSpecifiedReference(originalMethod)) {
            referenceSet.add(setterVariable);
        }
        AltAnnotation pluralOf = null;
        AltAnnotation xmlElement = originalMethod.getAnnotation(XmlElement.class.getName());
        AltAnnotation xmlElements = originalMethod.getAnnotation(XmlElements.class.getName());
        AltAnnotation xmlElementWrapper = originalMethod.getAnnotation(XmlElementWrapper.class.getName());
        AltAnnotation xmlAttribute = originalMethod.getAnnotation(XmlAttribute.class.getName());
        AltAnnotation xmlValue = originalMethod.getAnnotation(XmlValue.class.getName());
        AltAnnotation xmlAnyAttribute = originalMethod.getAnnotation(XmlAnyAttribute.class.getName());
        String xmlElementWrapperName = (xmlElementWrapper == null) ? null : xmlElementWrapper.getStringValue("name");
        if (xmlElementWrapperName != null && xmlElementWrapperName.isEmpty()) {
            xmlElementWrapperName = setterVariable;
        }
        checkOnlyOne(convertMe, originalMethod, xmlElement, xmlElements);
        checkOnlyOne(convertMe, originalMethod, xmlElement, xmlAttribute);
        checkOnlyOne(convertMe, originalMethod, xmlElements, xmlAttribute);
        checkOnlyOne(convertMe, originalMethod, xmlElement, xmlValue);
        checkOnlyOne(convertMe, originalMethod, xmlElements, xmlValue);
        checkOnlyOne(convertMe, originalMethod, xmlAttribute, xmlValue);
        checkOnlyOne(convertMe, originalMethod, xmlElement, xmlAnyAttribute);
        checkOnlyOne(convertMe, originalMethod, xmlElements, xmlAnyAttribute);
        checkOnlyOne(convertMe, originalMethod, xmlAttribute, xmlAnyAttribute);
        checkOnlyOne(convertMe, originalMethod, xmlValue, xmlAnyAttribute);
        if (xmlElements != null) {
            hasAnElement = true;
            // First add the actual method so it is known to the system
            pluralOf = originalMethod.getAnnotation(PluralOf.class.getName());
            String defaultValue = Generator.JAXB_DEFAULT_DEFAULT;
            xmlNameMap.put(setterVariable, new XmlElementData("", setterVariable, setterVariable, defaultValue, Format.ELEMENT, null, true, xmlElementWrapperName, false, originalMethodName));
            String aliasName = setterVariable;
            AltAnnotation[] allXmlElements = xmlElements.getAnnotationArrayValue("value");
            List<XmlElementData> aliases = new ArrayList<XmlElementData>(allXmlElements.length);
            aliasMap.put(setterVariable, aliases);
            for (AltAnnotation allXmlElement : allXmlElements) {
                defaultValue = allXmlElement.getStringValue("defaultValue");
                String allXmlElementNamespace = allXmlElement.getStringValue("namespace");
                String allXmlElementName = allXmlElement.getStringValue("name");
                boolean allXmlElementRequired = allXmlElement.getBooleanValue("required");
                AltClass allXmlElementType = (AltClass) allXmlElement.getAnnotationValues().get("type");
                String allXmlElementTypeName = (allXmlElementType == null) ? null : allXmlElementType.getName();
                boolean allXmlElementTypeInterface = (allXmlElementType == null) ? true : allXmlElementType.isInterface();
                if (Generator.JAXB_DEFAULT_STRING.equals(allXmlElementName)) {
                    throw new IllegalArgumentException("The name field of an XmlElement inside an XmlElements must have a specified name");
                } else {
                    aliases.add(new XmlElementData(allXmlElementNamespace, allXmlElementName, aliasName, defaultValue, Format.ELEMENT, allXmlElementTypeName, allXmlElementTypeInterface, xmlElementWrapperName, allXmlElementRequired, originalMethodName));
                }
            }
        } else if (xmlElement != null) {
            hasAnElement = true;
            // Get the pluralOf from the method
            pluralOf = originalMethod.getAnnotation(PluralOf.class.getName());
            String defaultValue = xmlElement.getStringValue("defaultValue");
            String namespace = xmlElement.getStringValue("namespace");
            String name = xmlElement.getStringValue("name");
            boolean required = xmlElement.getBooleanValue("required");
            if (Generator.JAXB_DEFAULT_STRING.equals(name)) {
                xmlNameMap.put(setterVariable, new XmlElementData(namespace, setterVariable, setterVariable, defaultValue, Format.ELEMENT, null, true, xmlElementWrapperName, required, originalMethodName));
            } else {
                xmlNameMap.put(setterVariable, new XmlElementData(namespace, name, name, defaultValue, Format.ELEMENT, null, true, xmlElementWrapperName, required, originalMethodName));
            }
        } else if (xmlAttribute != null) {
            String namespace = xmlAttribute.getStringValue("namespace");
            String name = xmlAttribute.getStringValue("name");
            boolean required = xmlAttribute.getBooleanValue("required");
            if (Generator.JAXB_DEFAULT_STRING.equals(name)) {
                xmlNameMap.put(setterVariable, new XmlElementData(namespace, setterVariable, setterVariable, Generator.JAXB_DEFAULT_DEFAULT, Format.ATTRIBUTE, null, true, xmlElementWrapperName, required, originalMethodName));
            } else {
                xmlNameMap.put(setterVariable, new XmlElementData(namespace, name, name, Generator.JAXB_DEFAULT_DEFAULT, Format.ATTRIBUTE, null, true, xmlElementWrapperName, required, originalMethodName));
            }
        } else if (xmlValue != null) {
            if (valueData != null) {
                throw new IllegalArgumentException("There may be only one XmlValue method on " + convertMe);
            }
            valueData = new XmlElementData(XmlService.DEFAULT_NAMESPACE, XML_VALUE_LOCAL_PART, XML_VALUE_LOCAL_PART, null, Format.VALUE, null, false, xmlElementWrapperName, true, originalMethodName);
            xmlNameMap.put(setterVariable, valueData);
        } else if (xmlAnyAttribute != null) {
            if (xmlAnyAttributeData != null) {
                throw new IllegalArgumentException("There may be only one XmlAnyAttribute method on " + convertMe);
            }
            xmlAnyAttributeData = new XmlElementData(XmlService.DEFAULT_NAMESPACE, XML_ANY_ATTRIBUTE_LOCAL_PART, XML_ANY_ATTRIBUTE_LOCAL_PART, null, Format.ATTRIBUTE, null, false, xmlElementWrapperName, false, originalMethodName);
            xmlNameMap.put(setterVariable, xmlAnyAttributeData);
        } else {
            unmappedNames.add(setterVariable);
        }
        if (pluralOf == null)
            pluralOf = new AnnotationAltAnnotationImpl(new PluralOfDefault(), null);
        String unDecapitalizedVariable = originalMethod.getName().substring(3);
        addMethodToVariableMap.put(getMethodName(MethodType.ADD, unDecapitalizedVariable, pluralOf), setterVariable);
        removeMethodToVariableMap.put(getMethodName(MethodType.REMOVE, unDecapitalizedVariable, pluralOf), setterVariable);
        lookupMethodToVariableMap.put(getMethodName(MethodType.LOOKUP, unDecapitalizedVariable, pluralOf), setterVariable);
    }
    if (valueData != null && hasAnElement) {
        throw new IllegalArgumentException("A bean cannot both have XmlElements and XmlValue methods in " + convertMe);
    }
    Set<String> noXmlElementNames = new LinkedHashSet<String>();
    for (String unmappedName : unmappedNames) {
        if (!xmlNameMap.containsKey(unmappedName)) {
            noXmlElementNames.add(unmappedName);
        }
    }
    return new NameInformation(xmlNameMap, noXmlElementNames, addMethodToVariableMap, removeMethodToVariableMap, lookupMethodToVariableMap, referenceSet, aliasMap, valueData);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PluralOf(org.glassfish.hk2.xml.api.annotations.PluralOf) XmlAttribute(jakarta.xml.bind.annotation.XmlAttribute) ArrayList(java.util.ArrayList) AltClass(org.glassfish.hk2.xml.internal.alt.AltClass) LinkedHashMap(java.util.LinkedHashMap) XmlElements(jakarta.xml.bind.annotation.XmlElements) XmlAnyAttribute(jakarta.xml.bind.annotation.XmlAnyAttribute) AltMethod(org.glassfish.hk2.xml.internal.alt.AltMethod) XmlValue(jakarta.xml.bind.annotation.XmlValue) ArrayList(java.util.ArrayList) List(java.util.List) XmlElementWrapper(jakarta.xml.bind.annotation.XmlElementWrapper) AltAnnotation(org.glassfish.hk2.xml.internal.alt.AltAnnotation) AnnotationAltAnnotationImpl(org.glassfish.hk2.xml.internal.alt.clazz.AnnotationAltAnnotationImpl) XmlElement(jakarta.xml.bind.annotation.XmlElement)

Example 4 with XmlElements

use of jakarta.xml.bind.annotation.XmlElements in project eclipselink by eclipse-ee4j.

the class AnnotationsProcessor method buildChoiceProperty.

/**
 * Build a new 'choice' property. Here, we flag a new property as a 'choice'
 * and create/set an XmlModel XmlElements object based on the @XmlElements
 * annotation.
 *
 * Validation and building of the XmlElement properties will be done during
 * finalizeProperties in the processChoiceProperty method.
 */
private Property buildChoiceProperty(JavaHasAnnotations javaHasAnnotations) {
    Property choiceProperty = new Property(helper);
    choiceProperty.setChoice(true);
    boolean isIdRef = helper.isAnnotationPresent(javaHasAnnotations, XmlIDREF.class);
    choiceProperty.setIsXmlIdRef(isIdRef);
    // build an XmlElement to set on the Property
    org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements();
    XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value();
    for (XmlElement next : elements) {
        org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement();
        xmlElement.setDefaultValue(next.defaultValue());
        xmlElement.setName(next.name());
        xmlElement.setNamespace(next.namespace());
        xmlElement.setNillable(next.nillable());
        xmlElement.setRequired(next.required());
        xmlElement.setType(next.type().getName());
        xmlElements.getXmlElement().add(xmlElement);
    }
    choiceProperty.setXmlElements(xmlElements);
    // handle XmlElementsJoinNodes
    if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementsJoinNodes.class)) {
        org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes;
        org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode;
        List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes> xmlJoinNodesList = new ArrayList<>();
        List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList = null;
        for (XmlJoinNodes xmlJNs : ((XmlElementsJoinNodes) helper.getAnnotation(javaHasAnnotations, XmlElementsJoinNodes.class)).value()) {
            xmlJoinNodeList = new ArrayList<>();
            for (XmlJoinNode xmlJN : xmlJNs.value()) {
                xmlJoinNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode();
                xmlJoinNode.setXmlPath(xmlJN.xmlPath());
                xmlJoinNode.setReferencedXmlPath(xmlJN.referencedXmlPath());
                xmlJoinNodeList.add(xmlJoinNode);
            }
            if (xmlJoinNodeList.size() > 0) {
                xmlJoinNodes = new org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes();
                xmlJoinNodes.setXmlJoinNode(xmlJoinNodeList);
                xmlJoinNodesList.add(xmlJoinNodes);
            }
        }
        choiceProperty.setXmlJoinNodesList(xmlJoinNodesList);
    }
    return choiceProperty;
}
Also used : XmlElementsJoinNodes(org.eclipse.persistence.oxm.annotations.XmlElementsJoinNodes) ArrayList(java.util.ArrayList) XmlJoinNodes(org.eclipse.persistence.oxm.annotations.XmlJoinNodes) XmlJoinNode(org.eclipse.persistence.oxm.annotations.XmlJoinNode) XmlElements(jakarta.xml.bind.annotation.XmlElements) XmlElement(jakarta.xml.bind.annotation.XmlElement) XmlProperty(org.eclipse.persistence.oxm.annotations.XmlProperty)

Aggregations

XmlElement (jakarta.xml.bind.annotation.XmlElement)4 XmlElements (jakarta.xml.bind.annotation.XmlElements)4 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 List (java.util.List)2 QName (javax.xml.namespace.QName)2 AltAnnotation (org.glassfish.hk2.xml.internal.alt.AltAnnotation)2 AltClass (org.glassfish.hk2.xml.internal.alt.AltClass)2 AltMethod (org.glassfish.hk2.xml.internal.alt.AltMethod)2 XmlAnyAttribute (jakarta.xml.bind.annotation.XmlAnyAttribute)1 XmlAttribute (jakarta.xml.bind.annotation.XmlAttribute)1 XmlElementWrapper (jakarta.xml.bind.annotation.XmlElementWrapper)1 XmlRootElement (jakarta.xml.bind.annotation.XmlRootElement)1 XmlType (jakarta.xml.bind.annotation.XmlType)1 XmlValue (jakarta.xml.bind.annotation.XmlValue)1 Map (java.util.Map)1 CannotCompileException (javassist.CannotCompileException)1 CtClass (javassist.CtClass)1 CtMethod (javassist.CtMethod)1