Search in sources :

Example 6 with XmlAttribute

use of javax.xml.bind.annotation.XmlAttribute in project winery by eclipse.

the class ReflectionUtil method getFieldName.

/**
 * Checks a field for XmlElement or XmlAttribute annotations
 *
 * @return a pair of name and field
 */
@NonNull
private Pair<String, Field> getFieldName(Field field) {
    XmlAttribute xmlAttribute = field.getAnnotation(XmlAttribute.class);
    XmlElement xmlElement = field.getAnnotation(XmlElement.class);
    String name = field.getName();
    if (Objects.nonNull(xmlAttribute) && !xmlAttribute.name().equals("##default")) {
        name = xmlAttribute.name();
    } else if (Objects.nonNull(xmlElement) && !xmlElement.name().equals("##default")) {
        name = xmlElement.name();
    }
    return Tuples.pair(name, field);
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlElement(javax.xml.bind.annotation.XmlElement) NonNull(org.eclipse.jdt.annotation.NonNull)

Example 7 with XmlAttribute

use of javax.xml.bind.annotation.XmlAttribute in project groovity by disney.

the class ModelXmlWriter method writeTag.

protected void writeTag(String name, Object value, Consumer<Object> body) throws Exception {
    delimit();
    writer.write('<');
    writer.write(name);
    List<String> removeNamespaces = null;
    Object xmlValue = null;
    boolean foundXmlValue = false;
    if (value != null) {
        MetaProperty[] props = MetaPropertyLookup.getOrderedGettableProperties(value);
        AtomicInteger pos = new AtomicInteger(0);
        positions.push(pos);
        for (int i = 0; i < props.length; i++) {
            MetaProperty mp = props[i];
            XmlAttribute xa = getAnnotation(mp, XmlAttribute.class);
            if (xa != null) {
                String attName = xa.name();
                Object attValue = transformField(mp, mp.getProperty(value));
                if ("##default".equals(attName)) {
                    attName = mp.getName();
                }
                attName = getTagName(xa.namespace(), attName);
                inAttribute = true;
                handleField(attName, attValue);
                inAttribute = false;
            }
            XmlValue xv = getAnnotation(mp, XmlValue.class);
            if (xv != null) {
                if (foundXmlValue) {
                    log.warning("Found more than one @XmlValue on " + value.getClass().getName());
                } else {
                    foundXmlValue = true;
                    xmlValue = transformField(mp, mp.getProperty(value));
                }
            }
            XmlElement xe = getAnnotation(mp, XmlElement.class);
            if (xe != null && !"##default".equals(xe.namespace())) {
                getNamespacePrefix(xe.namespace());
            }
            XmlElementWrapper xew = getAnnotation(mp, XmlElementWrapper.class);
            if (xew != null && !"##default".equals(xew.namespace())) {
                getNamespacePrefix(xew.namespace());
            }
        }
        positions.pop();
    }
    if (declareNamespaces != null && !declareNamespaces.isEmpty()) {
        removeNamespaces = new ArrayList<>();
        for (Iterator<Entry<String, String>> iter = declareNamespaces.entrySet().iterator(); iter.hasNext(); ) {
            Entry<String, String> ns = iter.next();
            writer.write(" xmlns:");
            writer.write(ns.getValue());
            writer.write("=\"");
            escape.write(ns.getKey());
            writer.write("\"");
            iter.remove();
            removeNamespaces.add(ns.getKey());
        }
    }
    writer.write('>');
    if (foundXmlValue) {
        value = xmlValue;
    }
    if (indent >= 0) {
        indent++;
    }
    body.accept(value);
    if (indent >= 0) {
        indent--;
    }
    delimit();
    writer.write("</");
    writer.write(name);
    writer.write('>');
    doDelimit = true;
    if (removeNamespaces != null) {
        for (int i = 0; i < removeNamespaces.size(); i++) {
            namespacePrefixes.remove(removeNamespaces.get(i));
        }
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) Entry(java.util.Map.Entry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) XmlValue(javax.xml.bind.annotation.XmlValue) XmlElement(javax.xml.bind.annotation.XmlElement) MetaProperty(groovy.lang.MetaProperty) XmlElementWrapper(javax.xml.bind.annotation.XmlElementWrapper)

Example 8 with XmlAttribute

use of javax.xml.bind.annotation.XmlAttribute in project sis by apache.

the class XLink method getType.

/**
 * Returns the type of link. May have one of the following values:
 *
 * <ul>
 *   <li><b>simple:</b>   a simple link</li>
 *   <li><b>extended:</b> an extended, possibly multi-resource, link</li>
 *   <li><b>locator:</b>  a pointer to an external resource</li>
 *   <li><b>resource:</b> an internal resource</li>
 *   <li><b>arc:</b>      a traversal rule between resources</li>
 *   <li><b>title:</b>    a descriptive title for another linking element</li>
 * </ul>
 *
 * The default value is {@code null}. If the {@link #setType(XLink.Type)} method has been
 * invoked with the {@link org.apache.sis.xml.XLink.Type#AUTO AUTO} enum, then this method
 * will infer a type from the attributes having a non-null value.
 *
 * @return the type of link, or {@code null}.
 */
@XmlAttribute(name = "type", namespace = Namespaces.XLINK, required = true)
public Type getType() {
    if (type != Type.AUTO) {
        return type;
    }
    Type best = null;
    int min = Integer.SIZE;
    final int defined = fieldMask();
    final int undefined = ~(defined | 0x1);
    for (final Type candidate : Type.values()) {
        final int forbidden = ~candidate.fieldMask;
        if (forbidden == 0) {
            // Skip the AUTO enum.
            continue;
        }
        // Test if this XLink instance defines only values allowed by the candidate type.
        if ((defined & forbidden) != 0) {
            continue;
        }
        // Test if this XLink instance defines all mandatory fields.
        if ((undefined & candidate.mandatory) != 0) {
            continue;
        }
        // Select the type requerying the smallest amount of fields.
        final int n = Integer.bitCount(undefined & candidate.fieldMask);
        if (n < min) {
            min = n;
            best = candidate;
        }
    }
    // May still null.
    return best;
}
Also used : XmlSchemaType(javax.xml.bind.annotation.XmlSchemaType) XmlAttribute(javax.xml.bind.annotation.XmlAttribute)

Example 9 with XmlAttribute

use of javax.xml.bind.annotation.XmlAttribute in project winery by eclipse.

the class FieldValidator method setDeclaredFields.

private void setDeclaredFields(Class base, Class parent) {
    if (!this.declaredFields.containsKey(base)) {
        this.declaredFields.put(base, new HashSet<>());
    }
    if (parent.equals(YTArtifactDefinition.class)) {
        this.declaredFields.get(base).add("file");
    }
    if (!parent.equals(Object.class)) {
        this.declaredFields.get(base).addAll(Arrays.stream(parent.getDeclaredFields()).map(field -> {
            XmlAttribute xmlAttribute = field.getAnnotation(XmlAttribute.class);
            XmlElement xmlElement = field.getAnnotation(XmlElement.class);
            if (Objects.nonNull(xmlAttribute) && !xmlAttribute.name().equals("##default")) {
                return xmlAttribute.name();
            } else if (Objects.nonNull(xmlElement) && !xmlElement.name().equals("##default")) {
                return xmlElement.name();
            }
            Annotations.FieldName override = field.getAnnotation(Annotations.FieldName.class);
            if (Objects.nonNull(override)) {
                return override.value();
            }
            final String camelCaseFieldName = field.getName();
            Matcher matches = UPPERCASE_LETTERS.matcher(camelCaseFieldName);
            final String snakeCaseFieldName = matches.replaceAll("_$0").toLowerCase();
            return snakeCaseFieldName;
        }).collect(Collectors.toList()));
        setDeclaredFields(base, parent.getSuperclass());
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) Annotations(org.eclipse.winery.model.tosca.yaml.support.Annotations) Matcher(java.util.regex.Matcher) XmlElement(javax.xml.bind.annotation.XmlElement)

Example 10 with XmlAttribute

use of javax.xml.bind.annotation.XmlAttribute in project cxf by apache.

the class JAXBEncoderDecoder method marshallException.

public static void marshallException(Marshaller marshaller, Exception elValue, MessagePartInfo part, Object source) {
    XMLStreamWriter writer = getStreamWriter(source);
    QName qn = part.getElementQName();
    try {
        writer.writeStartElement("ns1", qn.getLocalPart(), qn.getNamespaceURI());
        Class<?> cls = part.getTypeClass();
        XmlAccessType accessType = Utils.getXmlAccessType(cls);
        String namespace = part.getElementQName().getNamespaceURI();
        String attNs = namespace;
        SchemaInfo sch = part.getMessageInfo().getOperation().getInterface().getService().getSchema(namespace);
        if (sch == null) {
            LOG.warning("Schema associated with " + namespace + " is null");
            namespace = null;
            attNs = null;
        } else {
            if (!sch.isElementFormQualified()) {
                namespace = null;
            }
            if (!sch.isAttributeFormQualified()) {
                attNs = null;
            }
        }
        List<Member> combinedMembers = new ArrayList<>();
        for (Field f : Utils.getFields(cls, accessType)) {
            XmlAttribute at = f.getAnnotation(XmlAttribute.class);
            if (at == null) {
                combinedMembers.add(f);
            } else {
                QName fname = new QName(attNs, StringUtils.isEmpty(at.name()) ? f.getName() : at.name());
                ReflectionUtil.setAccessible(f);
                Object o = Utils.getFieldValue(f, elValue);
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                writeObject(marshaller, frag, newJAXBElement(fname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, fname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(fname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        for (Method m : Utils.getGetters(cls, accessType)) {
            if (!m.isAnnotationPresent(XmlAttribute.class)) {
                combinedMembers.add(m);
            } else {
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                XmlAttribute at = m.getAnnotation(XmlAttribute.class);
                QName mname = new QName(namespace, StringUtils.isEmpty(at.name()) ? name : at.name());
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                Object o = Utils.getMethodValue(m, elValue);
                writeObject(marshaller, frag, newJAXBElement(mname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, mname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(mname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        XmlAccessorOrder xmlAccessorOrder = cls.getAnnotation(XmlAccessorOrder.class);
        if (xmlAccessorOrder != null && xmlAccessorOrder.value().equals(XmlAccessOrder.ALPHABETICAL)) {
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    return m1.getName().compareTo(m2.getName());
                }
            });
        }
        XmlType xmlType = cls.getAnnotation(XmlType.class);
        if (xmlType != null && xmlType.propOrder().length > 1 && !xmlType.propOrder()[0].isEmpty()) {
            final List<String> orderList = Arrays.asList(xmlType.propOrder());
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    String m1Name = getName(m1);
                    String m2Name = getName(m2);
                    int m1Index = orderList.indexOf(m1Name);
                    int m2Index = orderList.indexOf(m2Name);
                    if (m1Index != -1 && m2Index != -1) {
                        return m1Index - m2Index;
                    }
                    if (m1Index == -1 && m2Index != -1) {
                        return 1;
                    }
                    if (m1Index != -1 && m2Index == -1) {
                        return -1;
                    }
                    return 0;
                }
            });
        }
        for (Member member : combinedMembers) {
            if (member instanceof Field) {
                Field f = (Field) member;
                QName fname = new QName(namespace, f.getName());
                ReflectionUtil.setAccessible(f);
                if (JAXBSchemaInitializer.isArray(f.getGenericType())) {
                    writeArrayObject(marshaller, writer, fname, f.get(elValue));
                } else {
                    Object o = Utils.getFieldValue(f, elValue);
                    writeObject(marshaller, writer, newJAXBElement(fname, String.class, o));
                }
            } else {
                // it's a Method
                Method m = (Method) member;
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                QName mname = new QName(namespace, name);
                if (JAXBSchemaInitializer.isArray(m.getGenericReturnType())) {
                    writeArrayObject(marshaller, writer, mname, m.invoke(elValue));
                } else {
                    Object o = Utils.getMethodValue(m, elValue);
                    writeObject(marshaller, writer, newJAXBElement(mname, String.class, o));
                }
            }
        }
        writer.writeEndElement();
        writer.flush();
    } catch (Exception e) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
    } finally {
        StaxUtils.close(writer);
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessorOrder) Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) PrivilegedActionException(java.security.PrivilegedActionException) XmlType(javax.xml.bind.annotation.XmlType) Field(java.lang.reflect.Field) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Member(java.lang.reflect.Member) DocumentFragment(org.w3c.dom.DocumentFragment) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Aggregations

XmlAttribute (javax.xml.bind.annotation.XmlAttribute)20 XmlElement (javax.xml.bind.annotation.XmlElement)12 Field (java.lang.reflect.Field)4 XmlElementRef (javax.xml.bind.annotation.XmlElementRef)4 XmlElementWrapper (javax.xml.bind.annotation.XmlElementWrapper)4 XmlElements (javax.xml.bind.annotation.XmlElements)4 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 XmlValue (javax.xml.bind.annotation.XmlValue)3 MetaProperty (groovy.lang.MetaProperty)2 Xml (io.swagger.models.Xml)2 Member (java.lang.reflect.Member)2 PrivilegedActionException (java.security.PrivilegedActionException)2 TypeElement (javax.lang.model.element.TypeElement)2 VariableElement (javax.lang.model.element.VariableElement)2 TypeMirror (javax.lang.model.type.TypeMirror)2 JAXBException (javax.xml.bind.JAXBException)2 XmlAccessType (javax.xml.bind.annotation.XmlAccessType)2 XmlAccessorOrder (javax.xml.bind.annotation.XmlAccessorOrder)2 XmlType (javax.xml.bind.annotation.XmlType)2