/** * {@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); }
/** * Parses an {@link XmlRootElement} annotation on a class * and determine the element name. * * @return null * if none was found. */ protected final QName parseElementName(ClassDeclT clazz) { XmlRootElement e = reader().getClassAnnotation(XmlRootElement.class,clazz,this); if(e==null) return null; String local = e.name(); if(local.equals("##default")) { // if defaulted... local = NameConverter.standard.toVariableName(nav().getClassShortName(clazz)); } String nsUri = e.namespace(); 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()); }
public void serializeRoot(BeanT bean, XMLSerializer target) throws SAXException, IOException, XMLStreamException { if(tagName==null) { Class beanClass = bean.getClass(); String message; if (beanClass.isAnnotationPresent(XmlRootElement.class)) { message = Messages.UNABLE_TO_MARSHAL_UNBOUND_CLASS.format(beanClass.getName()); } else { message = Messages.UNABLE_TO_MARSHAL_NON_ELEMENT.format(beanClass.getName()); } target.reportError(new ValidationEventImpl(ValidationEvent.ERROR,message,null, null)); } else { target.startElement(tagName,bean); target.childAsSoleContent(bean,null); target.endElement(); if (retainPropertyInfo) { target.currentProperty.remove(); } } }
/** Returns the contentType for the attachment. * The following algorithm is used * - If the input is an array of bytes, then "application/x-download" is returned. * - If the input is a String, then "text/plain" is returned. * - If the input is a File, then a null is returned. The file name should be used to determine the contentType. * - If the input carries the JAXB annotation, then "text/xml" is returned. * - If none of the above are satisfied, then "text/xml" is returned. * @param attachment the attachment. * @throws FrameworkException If any system error occurs. * @throws ApplicationExceptions If any application error occurs. * @return the contentType for the attachment. */ public static String createContentType(Object attachment) throws FrameworkException, ApplicationExceptions { String contentType = null; if (attachment.getClass().isArray() && attachment.getClass().getComponentType() == Byte.TYPE) { contentType = CONTENT_TYPE_BYTE_ARRAY; } else if (attachment instanceof String) { contentType = CONTENT_TYPE_STRING; } else if (attachment instanceof File) { // Do not set the contentType. It'll be determined based on the file name } else if (attachment.getClass().isAnnotationPresent(XmlRootElement.class)) { contentType = CONTENT_TYPE_JAXB; } else { contentType = CONTENT_TYPE_XML_ENCODER; } return contentType; }
@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(); }
@SuppressWarnings("unchecked") @Override public T read(HttpResponseMessage httpResponseMessage, Type expectedType) { Class<T> expectedClassType = (Class<T>) expectedType; JAXBContext context = contextOf(expectedClassType); try { Unmarshaller unmarshaller = context.createUnmarshaller(); StreamSource source = new StreamSource(httpResponseMessage.body()); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(source); return expectedClassType.isAnnotationPresent(XmlRootElement.class) ? (T) unmarshaller.unmarshal(reader) : unmarshaller.unmarshal(reader, expectedClassType).getValue(); } catch (JAXBException | XMLStreamException | FactoryConfigurationError e) { throw new RestifyHttpMessageReadException("Error on try read xml message", e); } }
/** * 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; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { if (roundEnv.processingOver()) { return true; } Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(XmlRootElement.class); for (Element element : elements) { if (element instanceof TypeElement) { processModelClass(roundEnv, (TypeElement) element); } } } catch (Throwable e) { dumpExceptionToErrorFile("camel-apt-error.log", "Error processing EIP model", e); } return true; }
protected void writeJSonSchemeDocumentation(PrintWriter writer, RoundEnvironment roundEnv, TypeElement classElement, XmlRootElement rootElement, String javaTypeName, String modelName) { // gather eip information EipModel eipModel = findEipModelProperties(roundEnv, classElement, javaTypeName, modelName); // get endpoint information which is divided into paths and options (though there should really only be one path) Set<EipOption> eipOptions = new TreeSet<EipOption>(new EipOptionComparator(eipModel)); findClassProperties(writer, roundEnv, eipOptions, classElement, classElement, "", modelName); // after we have found all the options then figure out if the model accepts input/output eipModel.setInput(hasInput(roundEnv, classElement)); eipModel.setOutput(hasOutput(eipModel, eipOptions)); String json = createParameterJsonSchema(eipModel, eipOptions); writer.println(json); }
/** * @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()); }
private void _processPackages(final Set<String> packages) { if (CollectionUtils.hasData(_packages)) { // [1] - Find all types annotated with @XmlRootElement Set<Class<?>> allPckgsTypes = Sets.newHashSet(); List<URL> urls = new ArrayList<URL>(); //urls.addAll(ClasspathHelper.forPackage("javax.xml.bind.annotation")); for (String p : packages) { //Reflections typeScanner = new Reflections(p); urls.addAll(ClasspathHelper.forPackage(p)); // see https://code.google.com/p/reflections/issues/detail?id=53 log.debug("Scanning package {} for @XmlRootElement annotated types",p); } Reflections typeScanner = new Reflections(new ConfigurationBuilder() .setUrls(urls)); Set<Class<?>> pckgTypes = typeScanner.getTypesAnnotatedWith(XmlRootElement.class); if (CollectionUtils.hasData(pckgTypes)) { for (Class<?> type : pckgTypes) log.trace(">Type {}",type); allPckgsTypes.addAll(pckgTypes); } else { log.debug("NO types annotated with @XmlRootElement"); } // [2] - Process... _processTypes(allPckgsTypes); } }
/** * Sets the main output directory. * If the directory does not exist, it will be created. */ public void testOutputDirectory() throws Exception { provide(); ClassLoader loader = getArtefactClassLoader(); Class<?> responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.AddResponse"); XmlRootElement rootElement = (XmlRootElement) responseWrapper.getAnnotation(XmlRootElement.class); assertNotNull("@XmlRootElement missing from response wrapper", rootElement); assertEquals("Wrong namespace", rootElement.namespace(), "http://foo.bar.com/calculator"); responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.ProcessListResponse"); XmlList xmlList = (XmlList) responseWrapper.getDeclaredField("_return").getAnnotation(XmlList.class); assertNotNull("@XmlList missing from response wrapper's _return field", xmlList); responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.ProcessCustomResponse"); XmlJavaTypeAdapter xmlJavaTypeAdapter = (XmlJavaTypeAdapter)responseWrapper.getDeclaredField("_return").getAnnotation(XmlJavaTypeAdapter.class); assertNotNull("@XmlJavaTypeAdapter missing from response wrapper's _return field", xmlJavaTypeAdapter); assertEquals("org.jboss.test.ws.jaxws.smoke.tools.CustomAdapter", xmlJavaTypeAdapter.value().getName()); }
/** * Constructor for read or delete * * @param entity a tellervo WS entity to perform an operation on * @param queryType one of read or delete */ public TellervoEntityAssociatedResource(WSIEntity entity, TellervoRequestType queryType) { super(entity.getClass().getAnnotation(XmlRootElement.class).name(), queryType); if(entity == null) throw new NullPointerException("Entity may not be null"); switch(queryType) { case READ: case DELETE: this.readDeleteOrMergeEntity = entity; break; default: throw new IllegalArgumentException("Invalid request type: must be one of READ or DELETE for this method"); } }
/** * Transform xml object to xml string. * * @param xmlObj xml object * @throws JAXBException * * @return */ public static String toXmlString(Object xmlObj) throws JAXBException { Class<?> clazz = xmlObj.getClass(); if (clazz.getAnnotation(XmlRootElement.class) == null) { throw new IllegalArgumentException("Object must be generate by jaxb."); } JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter w = new StringWriter(); jaxbMarshaller.marshal(xmlObj, w); return w.toString(); }
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); }
/** * {@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); }
public Object mapJavaToInternal(Object parameter) { ensureNotNull("Parameter", parameter); final Class<?> parameterClass = parameter.getClass(); final DOMResult domResult = new DOMResult(); try { Marshaller marshaller = getMarshaller(parameterClass); boolean isRootElement = parameterClass.getAnnotation(XmlRootElement.class) != null; if(isRootElement) { marshalRootElement(parameter, marshaller, domResult); } else { marshalNonRootElement(parameter, marshaller, domResult); } Node node = domResult.getNode(); return ((Document)node).getDocumentElement(); } catch (JAXBException e) { throw LOG.unableToMapInput(parameter, e); } }
/** * @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); } }
public static String serializeToString(Object obj) throws IOException { if(obj == null || !obj.getClass().isAnnotationPresent(XmlRootElement.class)) return null; try(StringWriter writer = new StringWriter()) { try { JAXBContext ctx = JAXBContext.newInstance(obj.getClass()); ctx.createMarshaller().marshal(obj, writer); return writer.toString(); } catch(JAXBException ex) {//let's just ignore. } } return null; }
private Object getPreparedJaxbObject() { final Object jaxbObject; if (object instanceof JAXBElement) { jaxbObject = object; } else { final Class<?> clazz = object.getClass(); final XmlRootElement r = clazz.getAnnotation(XmlRootElement.class); if (r == null) { if (userObjectFactory) { jaxbObject = createJAXBElement(object); } else { jaxbObject = createInferredJAXBElement(object); } } else { jaxbObject = object; } } return jaxbObject; }
public JAXBWriter(NamespacePrefixMapper mapper) { super(); this.mapper = mapper; try { List<Class<?>> clazz = new ArrayList<Class<?>>(); for (Class<?> each : ScanUtil.getClasses(this.protocol)) { if (each.getAnnotation(XmlRootElement.class) != null) { clazz.add(each); } } this.context = JAXBContext.newInstance(clazz.toArray(new Class[] {})); this.log.info("All classes in JAXB Context: " + clazz); } catch (Exception e) { this.log.error(e.toString()); Trace.trace(this.log, e); throw new RuntimeException("Can't init JAXB context", e); } }
@Test public void testRemotableChangeTest( ) { preloadEmptyObject( ); // tests the data object being marked as "remotable". // emulate that the legacy annotation @Remotable was set for whatever reason. e.g. a project generated in an // older WB version. context.getDataObject( ).addAnnotation( DataModelerEditorsTestHelper.createAnnotation( Remotable.class ) ); when( view.getRemotable( ) ).thenReturn( true ); objectEditor.onRemotableChange( ); // the new defined annotation XmlRootElement for marking the data object as "remotable should have been set assertNotNull( context.getDataObject( ).getAnnotation( XmlRootElement.class.getName( ) ) ); // the legacy annotation should have been removed. assertNull( context.getDataObject( ).getAnnotation( Remotable.class.getName( ) ) ); // emulate that the legacy annotation @Remotable was set for whatever reason. e.g. a project generated in an // older WB version. context.getDataObject( ).addAnnotation( DataModelerEditorsTestHelper.createAnnotation( Remotable.class ) ); // tests the data object being maked as non "remotable". when( view.getRemotable( ) ).thenReturn( false ); objectEditor.onRemotableChange( ); //the XmlRootElement annotation should have been removed. assertNull( context.getDataObject( ).getAnnotation( XmlRootElement.class.getName( ) ) ); // the legacy annotation should have been removed. assertNull( context.getDataObject( ).getAnnotation( Remotable.class.getName( ) ) ); }