/** * PageBuilder can add correct annotations. * @throws Exception If there is some problem inside */ @Test public void addsCorrectAnnotations() throws Exception { final String xsl = "/some/path/test.xsl"; final Object page = new PageBuilder() .stylesheet(xsl) .build(PageBuilderTest.BarPage.class); MatcherAssert.assertThat( page.getClass().getAnnotation(XmlType.class).name(), Matchers.equalTo( "com.rexsl.page.PageBuilderTest$BarPage$somepathtestxsl" ) ); MatcherAssert.assertThat( page.getClass().getAnnotation(Stylesheet.class).value(), Matchers.equalTo(xsl) ); }
/** * {@inheritDoc} * <p>Jaxb2CollectionHttpMessageConverter can read a generic * {@link Collection} where the generic type is a JAXB type annotated with * {@link XmlRootElement} or {@link XmlType}. */ @Override public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { if (!(type instanceof ParameterizedType)) { return false; } ParameterizedType parameterizedType = (ParameterizedType) type; if (!(parameterizedType.getRawType() instanceof Class)) { return false; } Class<?> rawType = (Class<?>) parameterizedType.getRawType(); if (!(Collection.class.isAssignableFrom(rawType))) { return false; } if (parameterizedType.getActualTypeArguments().length != 1) { return false; } Type typeArgument = parameterizedType.getActualTypeArguments()[0]; if (!(typeArgument instanceof Class)) { return false; } Class<?> typeArgumentClass = (Class<?>) typeArgument; return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType); }
@SuppressWarnings("unchecked") public static String marshal(Object obj) { StringWriter stringWriter = new StringWriter(); try { JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); XmlRootElement xmlRootAnnotation = obj.getClass().getAnnotation(XmlRootElement.class); System.out.println(xmlRootAnnotation); if (xmlRootAnnotation == null) { XmlType xmlTypeAnnotation = obj.getClass().getAnnotation(XmlType.class); QName qname = new QName("", xmlTypeAnnotation.name()); JAXBElement<Object> jaxbElement = new JAXBElement<Object>(qname, (Class<Object>) obj.getClass(), null, obj); jaxbMarshaller.marshal(jaxbElement, stringWriter); } else { jaxbMarshaller.marshal(obj, stringWriter); } } catch (Exception e) { e.printStackTrace(); } return stringWriter.toString(); }
@Override @SuppressWarnings("unchecked") public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); for (Annotation annotation : annotations) { if (annotation instanceof XsiSchemaLocation) { XsiSchemaLocation schemaAnnotation = (XsiSchemaLocation) annotation; String schemaLocation = schemaAnnotation.schemaLocation(); jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation); } } XmlType xmlTypeAnnotation = object.getClass().getAnnotation(XmlType.class); QName qname = new QName("", xmlTypeAnnotation.name()); StringWriter stringWriter = new StringWriter(); JAXBElement<Object> jaxbElement = new JAXBElement<Object>(qname, (Class<Object>) object.getClass(), null, object); jaxbMarshaller.marshal(jaxbElement, stringWriter); entityStream.write(stringWriter.toString().getBytes()); } catch (Exception e) { throw new WebApplicationException(e); } }
private String determineNamespaceUncached(Class<? extends Object> beanClass) { XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { return null; } String namespace = xmlType.namespace(); if (BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { XmlSchema xmlSchema = beanClass.getPackage().getAnnotation(XmlSchema.class); namespace = xmlSchema.namespace(); } if (StringUtils.isBlank(namespace) || BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { return null; } return namespace; }
private QName determineTypeForClassUncached(Class<? extends Object> beanClass) { XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { return null; } String namespace = xmlType.namespace(); if (BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { XmlSchema xmlSchema = beanClass.getPackage().getAnnotation(XmlSchema.class); namespace = xmlSchema.namespace(); } if (StringUtils.isBlank(namespace) || BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { return null; } return new QName(namespace, xmlType.name()); }
/** * Returns a short name for this node which can be useful for ID generation or referring to related resources like images * * @return defaults to "node" but derived nodes should overload this to provide a unique name */ @Override public String getShortName() { if (shortName == null) { XmlRootElement root = getClass().getAnnotation(XmlRootElement.class); if (root != null) { shortName = root.name(); } if (shortName == null) { XmlType type = getClass().getAnnotation(XmlType.class); if (type != null) { shortName = type.name(); } } } return shortName; }
/** * @return determine element name by using the XmlType.name() of the type to * be marshalled and the XmlSchema.namespace() of the package-info */ public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) { XmlType xmlType = type.getAnnotation(XmlType.class); if (xmlType == null || xmlType.name() == null) { throw new RuntimeException("The type " + type.getName() + " needs to have an XmlType annotation with name"); } String nameSpace = xmlType.namespace(); if ("##default".equals(nameSpace)) { XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class); if (xmlSchema != null) { nameSpace = xmlSchema.namespace(); } } // prefer name from the XmlType, and fallback to XmlRootElement String localName = xmlType.name(); if (ObjectHelper.isEmpty(localName)) { XmlRootElement root = type.getAnnotation(XmlRootElement.class); if (root != null) { localName = root.name(); } } return new QName(nameSpace, localName); }
public static String getTagName(Class<?> handled) { if (TAG_NAMES.containsKey(handled)) { return TAG_NAMES.get(handled); } XmlType xmlType = handled.getAnnotation(XmlType.class); if (xmlType != null && xmlType.name() != null && xmlType.name().trim().length() > 0) { TAG_NAMES.put(handled, xmlType.name()); return xmlType.name(); } else { XmlRootElement xmlRoot = handled.getAnnotation(XmlRootElement.class); if (xmlRoot != null && xmlRoot.name() != null && xmlRoot.name().trim().length() > 0) { TAG_NAMES.put(handled, xmlRoot.name()); return xmlRoot.name(); } } throw new IllegalArgumentException("XML name not found for " + handled.getName()); }
public static Stub convertToStub(JavaLanguageVariable variable, Stub parentStub, StubTypeTreeRepository typeTreeRepository) { Stub stub = new Stub(); stub.setParentStubRelation(parentStub); stub.setStubName(variable.getVariableName()); stub.setRequired(variable.isRequired()); stub.setHeader(variable.isHeader()); stub.setMultiOccurs(variable.isMultiOccurs()); stub.setType(variable.getType()); if (variable.getType().isAnnotationPresent(XmlType.class) && !variable.getType().isEnum() && !stub.isSameTypeWithSomeAncestor()) { convertFieldsToChildStubs(stub, variable.getType(), typeTreeRepository); } return stub; }
private static List<Field> getFieldsIncludingAncestorTypes(Class<?> type) { List<Field> allFields = new ArrayList<Field>(); while (true) { Field[] fieldsArray = type.getDeclaredFields(); List<Field> fields = new ArrayList<Field>(); if (fieldsArray != null) { for (Field f : fieldsArray) { fields.add(f); } } allFields.addAll(0, fields); type = type.getSuperclass(); if (type == null) { break; } if (!type.isAnnotationPresent(XmlType.class)) { break; } } return allFields; }
private void validateCollection(Field f, Object obj) throws IllegalArgumentException, IllegalAccessException { XmlType xtype = obj.getClass().getAnnotation(XmlType.class); if (xtype == null) { return; } String elementName = xtype.name(); logger.debug(String.format("validating %s->%s", elementName, f.getName())); Collection l = (Collection) f.get(obj); XmlElement eat = f.getAnnotation(XmlElement.class); if (eat != null && (eat.required() && (l == null || l.isEmpty()))) { throw new IllegalArgumentException(String.format("field[%s] of element[%s] is mandatory, cannot be missed", f.getName(), elementName)); } XmlAttribute aat = f.getAnnotation(XmlAttribute.class); if (aat != null && (aat.required() && (l == null || l.isEmpty()))) { throw new IllegalArgumentException(String.format("field[%s] of element[%s] is mandatory, cannot be missed", aat.name(), elementName)); } if (l != null) { Object val = l.iterator().next(); if (val != null) { validateObject(val); } } }
private void validateField(Field f, Object obj) throws IllegalArgumentException, IllegalAccessException { XmlType xtype = obj.getClass().getAnnotation(XmlType.class); if (xtype == null) { return; } Object val = f.get(obj); String elementName = xtype.name(); logger.debug(String.format("validating %s->%s", elementName, f.getName())); XmlElement eat = f.getAnnotation(XmlElement.class); if (eat != null && eat.required() && val == null) { throw new IllegalArgumentException(String.format("field[%s] of element[%s] is mandatory, cannot be missed", f.getName(), elementName)); } XmlAttribute aat = f.getAnnotation(XmlAttribute.class); if (aat != null && aat.required() && val == null) { throw new IllegalArgumentException(String.format("field[%s] of element[%s] is mandatory, cannot be missed", aat.name(), elementName)); } if (val != null) { validateObject(val); } }
private static int getPropertyOrder(final Map<String, Integer> propMap, final Class<?> beanClass, final int offset) { int index = offset; if (beanClass.getSuperclass() != null) { index = getPropertyOrder(propMap, beanClass.getSuperclass(), offset); } final XmlType xmlTypeAnnotation = beanClass.getAnnotation(XmlType.class); if (xmlTypeAnnotation != null && xmlTypeAnnotation.propOrder() != null && !xmlTypeAnnotation.propOrder()[0].isEmpty()) { for (final String propName : xmlTypeAnnotation.propOrder()) { propMap.put(propName, index++); } } else { try { final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, beanClass.getSuperclass()); for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { propMap.put(propertyDescriptor.getName(), index++); } } catch (final IntrospectionException e) { throw new JXPathException(e); } } return index; }
public <T> void writeOut(T node, Class<T> declaredType) throws JAXBException { try { if (this.context == null) { init(); } Marshaller marshaller = this.context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, SCHEMA_LOCATION); marshaller.marshal(new JAXBElement( new QName(declaredType.getDeclaredAnnotation(XmlType.class).name()), declaredType, node), new File(xmlPath)); } catch (JAXBException ex) { getLogger(FlowProcessor.class.getName()).log(Level.SEVERE, "Fail to write configuration down to config file[{0}] due to error : \n{1}", new Object[]{this.xmlPath, ex}); throw ex; } }
private static String getType(Class<? extends ClientResource<?>> clientObjectClass) { String clientResourceType = null; XmlRootElement xmlRootElement = clientObjectClass.getAnnotation(XmlRootElement.class); if (xmlRootElement != null && !"##default".equals(xmlRootElement.name())) clientResourceType = xmlRootElement.name(); else { XmlType xmlType = clientObjectClass.getAnnotation(XmlType.class); if (xmlType != null && !"##default".equals(xmlType.name())) clientResourceType = xmlType.name(); } if (clientResourceType == null) { String classSimpleName = clientObjectClass.getSimpleName(); clientResourceType = classSimpleName.replaceFirst("^.", classSimpleName.substring(0, 1).toLowerCase()); } return clientResourceType; }
public static void main(String[] args) throws JsonMappingException { ObjectMapper jsonMapper = new ObjectMapper(); AnnotationIntrospector introspector = new AnnotationIntrospector.Pair(new JaxbAnnotationIntrospector(), new JacksonAnnotationIntrospector()); jsonMapper.setAnnotationIntrospector(introspector); JsonSchema schema = jsonMapper.generateJsonSchema(Testi.class); if(Testi.class.getAnnotation(XmlRootElement.class)!=null && !Testi.class.getAnnotation(XmlRootElement.class).name().equals("##default")) schema.getSchemaNode().put("name", Testi.class.getAnnotation(XmlRootElement.class).name()); else if(Testi.class.getAnnotation(XmlType.class)!=null && !Testi.class.getAnnotation(XmlType.class).name().equals("##default")) schema.getSchemaNode().put("name", Testi.class.getAnnotation(XmlType.class).name()); else schema.getSchemaNode().put("name", Testi.class.getSimpleName()); String schemaJson = schema.toString(); System.out.println(schemaJson); }
private String determineNamespaceUncached(Class<?> beanClass) { XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { return null; } String namespace = xmlType.namespace(); if (BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { XmlSchema xmlSchema = beanClass.getPackage().getAnnotation(XmlSchema.class); namespace = xmlSchema.namespace(); } if (StringUtils.isBlank(namespace) || BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { return null; } return namespace; }
private QName determineTypeForClassUncached(Class<?> beanClass) { XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { return null; } String namespace = xmlType.namespace(); if (BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { XmlSchema xmlSchema = beanClass.getPackage().getAnnotation(XmlSchema.class); namespace = xmlSchema.namespace(); } if (StringUtils.isBlank(namespace) || BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) { return null; } return new QName(namespace, xmlType.name()); }
public static void debugDumpValue(StringBuilder sb, int expectedIndent, Object value, PrismContext prismContext, QName elementName, String defaultLanguage) { if (value instanceof DebugDumpable) { sb.append(((DebugDumpable)value).debugDump(expectedIndent)); return; } String formatted; String language = DebugUtil.getPrettyPrintBeansAs() != null ? DebugUtil.getPrettyPrintBeansAs() : defaultLanguage; if (elementName == null) { elementName = new QName("value"); } if (language != null && value != null && !(value instanceof Enum) && prismContext != null && value.getClass().getAnnotation(XmlType.class) != null) { try { formatted = prismContext.serializerFor(language).serializeRealValue(value, elementName); } catch (SchemaException e) { formatted = PrettyPrinter.prettyPrint(value); } } else { formatted = PrettyPrinter.prettyPrint(value); } sb.append(DebugUtil.fixIndentInMultiline(expectedIndent, DebugDumpable.INDENT_STRING, formatted)); }
/** * {@inheritDoc} * <p>Jaxb2CollectionHttpMessageConverter can read a generic * {@link Collection} where the generic type is a JAXB type annotated with * {@link XmlRootElement} or {@link XmlType}. */ public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { if (!(type instanceof ParameterizedType)) { return false; } ParameterizedType parameterizedType = (ParameterizedType) type; if (!(parameterizedType.getRawType() instanceof Class)) { return false; } Class<?> rawType = (Class<?>) parameterizedType.getRawType(); if (!(Collection.class.isAssignableFrom(rawType))) { return false; } if (parameterizedType.getActualTypeArguments().length != 1) { return false; } Type typeArgument = parameterizedType.getActualTypeArguments()[0]; if (!(typeArgument instanceof Class)) { return false; } Class<?> typeArgumentClass = (Class<?>) typeArgument; return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType); }
/** * @param list * @param pkg */ private static void checkClasses(List<Class> list, String pkg) { // The installed classfinder or directory search may inadvertently add too many // classes. This rountine is a 'double check' to make sure that the classes // are acceptable. for (int i=0; i<list.size();) { Class cls = list.get(i); if (!cls.isInterface() && (cls.isEnum() || getAnnotation(cls, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(cls) != null) && !ClassUtils.isJAXWSClass(cls) && !isSkipClass(cls) && cls.getPackage().getName().equals(pkg)) { i++; // Acceptable class } else { if (log.isDebugEnabled()) { log.debug("Removing class " + cls + " from consideration because it is not in package " + pkg + " or is an interface or does not have a public constructor or is" + " a jaxws class"); } list.remove(i); } } }
/** * @param cls * @return true if cls appears to be a JAXB enabled class */ private static boolean isJAXB(Class cls) { // See if the object represents a root element XmlRootElement root = (XmlRootElement) getAnnotation(cls,XmlRootElement.class); if (root != null) { if (log.isDebugEnabled()) { log.debug("isJAXB returns true due to presence of @XmlRootElement on " + cls); } return true; } // See if the object represents an type XmlType type = (XmlType) getAnnotation(cls,XmlType.class); if (type != null) { if (log.isDebugEnabled()) { log.debug("isJAXB returns true due to presence of @XmlType on " + cls); } return true; } if (log.isDebugEnabled()) { log.debug("isJAXB returns false for" + cls); } return false; }
public static String toString(Object o) { if (!(o instanceof JAXBElement) && o.getClass().getAnnotation(XmlRootElement.class) == null && o.getClass().getAnnotation(XmlType.class)!= null) { o = new JAXBElement(new QName("uri:lens:cube:0.1", o.getClass().getAnnotation(XmlType.class).name()), o.getClass(), null, o); } try { StringWriter stringWriter = new StringWriter(); Class cl = null; if (o instanceof JAXBElement) { cl = ((JAXBElement) o).getDeclaredType(); } else { cl = o.getClass(); } Marshaller marshaller = getLensJAXBContext(cl).createMarshaller(); marshaller.marshal(o, stringWriter); return stringWriter.toString(); } catch (JAXBException e) { throw new RuntimeException(e); } }
private static void populateDefaultValues(Object object) { Object target = object instanceof JAXBElement ? ((JAXBElement)object).getValue() : object; if (target == null) { return; } else if (target instanceof Collection) { for (Object element : (Collection<?>)target) { populateDefaultValues(element); } } else if (target.getClass().getDeclaredAnnotation(XmlType.class) != null) { for (Field field : target.getClass().getDeclaredFields()) { XmlElement xmlElement = field.getAnnotation(XmlElement.class); if (xmlElement != null) { checkXmlElementFieldValue(target, field, xmlElement); } } } }
private void addObjectFactoryClass(Map<String, RmType> target, Class<?> rmClass, RmType child) { XmlType xmlType = rmClass.getAnnotation(XmlType.class); if (xmlType != null || rmClass == RmObject.class) { String rmType = xmlType != null ? xmlType.name() : RmTypes.RM_OBJECT; RmType node = target.get(rmType); if (node == null) { node = new RmType(rmType); rmTypeNameClasses.put(rmType, rmClass); target.put(rmType, node); } if (child != null && !node.getChildren().contains(child)) { node.addChild(child); } addObjectFactoryClass(target, rmClass.getSuperclass(), node); } }
/** * Get the id for the specified type. * * @param type The type. * @return The type id. */ public static String getTypeIdName(Class<?> type) { String ns = ""; if (type.getPackage() != null && type.getPackage().isAnnotationPresent(XmlSchema.class)) { ns = type.getPackage().getAnnotation(XmlSchema.class).namespace(); } String name = Introspector.decapitalize(type.getSimpleName()); if (type.isAnnotationPresent(XmlType.class)) { XmlType typeMeta = type.getAnnotation(XmlType.class); if (!"##default".equals(typeMeta.name())) { name = typeMeta.name(); } if (!"##default".equals(typeMeta.namespace())) { ns = typeMeta.namespace(); } } return ns + name; }
public static String getNamespace(Class<?> klass) { String namespace = null; XmlType xmlType = klass.getAnnotation(XmlType.class); if (xmlType != null) { String ns = xmlType.namespace(); if (!DEFAULT_NAMESPACE_VALUE.equals(ns)) { namespace = ns; } } if (namespace == null) { namespace = DEFAULT_NAMESPACE_VALUE; Package pkg = klass.getPackage(); XmlSchema xmlSchema = pkg.getAnnotation(XmlSchema.class); if (xmlSchema != null) { namespace = xmlSchema.namespace(); } } return namespace; }
/** * Parses a (potentially-null) {@link XmlType} annotation on a class * and determine the actual value. * * @param clazz * The class on which the XmlType annotation is checked. * @param t * The {@link XmlType} annotation on the clazz. This value * is taken as a parameter to improve the performance for the case where * 't' is pre-computed. */ protected final QName parseTypeName(ClassDeclT clazz, XmlType t) { String nsUri="##default"; String local="##default"; if(t!=null) { nsUri = t.namespace(); local = t.name(); } if(local.length()==0) return null; // anonymous if(local.equals("##default")) // if defaulted ... local = NameConverter.standard.toVariableName(nav().getClassShortName(clazz)); if(nsUri.equals("##default")) { // if defaulted ... XmlSchema xs = reader().getPackageAnnotation(XmlSchema.class,clazz,this); if(xs!=null) nsUri = xs.namespace(); else { nsUri = builder.defaultNsUri; } } return new QName(nsUri.intern(),local.intern()); }
/** * XmlType allows specification of factoryClass and * factoryMethod. There are to be used if no default * constructor is found. * * @return * true if the factory method was found. False if not. */ private boolean hasFactoryConstructor(XmlType t){ if (t == null) return false; String method = t.factoryMethod(); T fClass = reader().getClassValue(t, "factoryClass"); if (method.length() > 0){ if(nav().isSameType(fClass, nav().ref(XmlType.DEFAULT.class))){ fClass = nav().use(clazz); } for(M m: nav().getDeclaredMethods(nav().asDecl(fClass))){ //- Find the zero-arg public static method with the required return type if (nav().getMethodName(m).equals(method) && nav().isSameType(nav().getReturnType(m), nav().use(clazz)) && nav().getMethodParameters(m).length == 0 && nav().isStaticMethod(m)){ factoryMethod = m; break; } } if (factoryMethod == null){ builder.reportError(new IllegalAnnotationException( Messages.NO_FACTORY_METHOD.format(nav().getClassName(nav().asDecl(fClass)), method), this )); } } else if(!nav().isSameType(fClass, nav().ref(XmlType.DEFAULT.class))){ builder.reportError(new IllegalAnnotationException( Messages.FACTORY_CLASS_NEEDS_FACTORY_METHOD.format(nav().getClassName(nav().asDecl(fClass))), this )); } return factoryMethod != null; }
private void writeXmlTypeDeclaration(JDefinedClass cls, String typeName, String namespaceUri, Collection<MemberInfo> members) { if (cls == null) return; JAnnotationUse xmlTypeAnn = cls.annotate(cm.ref(XmlType.class)); xmlTypeAnn.param("name", typeName); xmlTypeAnn.param("namespace", namespaceUri); if (members.size() > 1) { JAnnotationArrayMember paramArray = xmlTypeAnn.paramArray("propOrder"); for (MemberInfo memInfo : members) { paramArray.param(memInfo.getParamName()); } } }