public static <T> String marshal(final JAXBContext context, final T obj, final XmlAdapter<?, ?>... adapters) { if (obj == null) { return null; } try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Marshaller marshaller = context.createMarshaller(); if (adapters != null) { for (final XmlAdapter<?, ?> adapter : adapters) { marshaller.setAdapter(adapter); } } final TransformerHandler transformerHandler = XMLUtil.createTransformerHandler(true); transformerHandler.setResult(new StreamResult(out)); marshaller.marshal(obj, transformerHandler); return out.toString(String.valueOf(StandardCharsets.UTF_8)); } catch (final Throwable t) { throw new RuntimeException(t.getMessage(), t); } }
public static <T> T unmarshal(final JAXBContext context, final Class<T> clazz, final String data, final XmlAdapter<?, ?>... adapters) { if (data != null) { final String trimmed = data.trim(); if (trimmed.length() > 0) { try { final Unmarshaller unmarshaller = context.createUnmarshaller(); if (adapters != null) { for (final XmlAdapter<?, ?> adapter : adapters) { unmarshaller.setAdapter(adapter); } } final JAXBElement<T> jaxbElement = unmarshaller.unmarshal( new StreamSource(new ByteArrayInputStream(trimmed.getBytes(StandardCharsets.UTF_8))), clazz); return jaxbElement.getValue(); } catch (final JAXBException e) { throw new RuntimeException("Invalid XML " + trimmed, e); } } } return null; }
/** * Checks if the given adapter is applicable to the declared property type. */ private boolean isApplicable(XmlJavaTypeAdapter jta, T declaredType ) { if(jta==null) return false; T type = reader().getClassValue(jta,"type"); if(nav().isSameType(declaredType, type)) return true; // for types explicitly marked in XmlJavaTypeAdapter.type() T ad = reader().getClassValue(jta,"value"); T ba = nav().getBaseClass(ad, nav().asDecl(XmlAdapter.class)); if(!nav().isParameterizedType(ba)) return true; // can't check type applicability. assume Object, which means applicable to any. T inMemType = nav().getTypeArgument(ba, 1); return nav().isSubClassOf(declaredType,inMemType); }
public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; }
public JExpression createConstant(Outline outline, XmlString lexical) { if(isCollection()) return null; if(adapter==null) return coreType.createConstant(outline, lexical); // [RESULT] new Adapter().unmarshal(CONSTANT); JExpression cons = coreType.createConstant(outline, lexical); Class<? extends XmlAdapter> atype = adapter.getAdapterIfKnown(); // try to run the adapter now rather than later. if(cons instanceof JStringLiteral && atype!=null) { JStringLiteral scons = (JStringLiteral) cons; XmlAdapter a = ClassFactory.create(atype); try { Object value = a.unmarshal(scons.str); if(value instanceof String) { return JExpr.lit((String)value); } } catch (Exception e) { // assume that we can't eagerly bind this } } return JExpr._new(adapter.getAdapterClass(outline)).invoke("unmarshal").arg(cons); }
static NClass getRef( final Class<? extends XmlAdapter> adapter, boolean copy ) { if(copy) { // TODO: this is a hack. the code generation should be defered until // the backend. (right now constant generation happens in the front-end) return new EagerNClass(adapter) { @Override public JClass toType(Outline o, Aspect aspect) { return o.addRuntime(adapter); } public String fullName() { // TODO: implement this method later throw new UnsupportedOperationException(); } }; } else { return NavigatorImpl.theInstance.ref(adapter); } }
/** * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set. * <p>The default implementation sets the {@link #setMarshallerProperties(Map) defined properties}, the {@link * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[]) * schemas}, {@link #setMarshallerListener(javax.xml.bind.Marshaller.Listener) listener}, and * {@link #setAdapters(XmlAdapter[]) adapters}. */ protected void initJaxbMarshaller(Marshaller marshaller) throws JAXBException { if (this.marshallerProperties != null) { for (String name : this.marshallerProperties.keySet()) { marshaller.setProperty(name, this.marshallerProperties.get(name)); } } if (this.marshallerListener != null) { marshaller.setListener(this.marshallerListener); } if (this.validationEventHandler != null) { marshaller.setEventHandler(this.validationEventHandler); } if (this.adapters != null) { for (XmlAdapter<?, ?> adapter : this.adapters) { marshaller.setAdapter(adapter); } } if (this.schema != null) { marshaller.setSchema(this.schema); } }
/** * Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. * Gets called after creation of JAXB {@code Marshaller}, and after the respective properties have been set. * <p>The default implementation sets the {@link #setUnmarshallerProperties(Map) defined properties}, the {@link * #setValidationEventHandler(ValidationEventHandler) validation event handler}, the {@link #setSchemas(Resource[]) * schemas}, {@link #setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener) listener}, and * {@link #setAdapters(XmlAdapter[]) adapters}. */ protected void initJaxbUnmarshaller(Unmarshaller unmarshaller) throws JAXBException { if (this.unmarshallerProperties != null) { for (String name : this.unmarshallerProperties.keySet()) { unmarshaller.setProperty(name, this.unmarshallerProperties.get(name)); } } if (this.unmarshallerListener != null) { unmarshaller.setListener(this.unmarshallerListener); } if (this.validationEventHandler != null) { unmarshaller.setEventHandler(this.validationEventHandler); } if (this.adapters != null) { for (XmlAdapter<?, ?> adapter : this.adapters) { unmarshaller.setAdapter(adapter); } } if (this.schema != null) { unmarshaller.setSchema(this.schema); } }
/** * Marshals each of the elements of the given {@link Iterable} using the given {@link XmlAdapter}. * * @param source * @param adapter must not be {@literal null}. * @return * @throws Exception */ public static <T, S> List<S> marshal(Iterable<T> source, XmlAdapter<S, T> adapter) { Assert.notNull(adapter); if (source == null) { return Collections.emptyList(); } List<S> result = new ArrayList<S>(); for (T element : source) { try { result.add(adapter.marshal(element)); } catch (Exception o_O) { throw new RuntimeException(o_O); } } return result; }
/** * Checks if the given adapter is applicable to the declared property type. */ private boolean isApplicable(XmlJavaTypeAdapter jta, T declaredType) { if (jta == null) return false; T type = reader().getClassValue(jta, "type"); if (declaredType.equals(type)) return true; // for types explicitly marked in // XmlJavaTypeAdapter.type() T ad = reader().getClassValue(jta, "value"); T ba = nav().getBaseClass(ad, nav().asDecl(XmlAdapter.class)); if (!nav().isParameterizedType(ba)) return true; // can't check type applicability. assume Object, which // means applicable to any. T inMemType = nav().getTypeArgument(ba, 1); return nav().isSubClassOf(declaredType, inMemType); }
private void init(Method getter, Method setter, URI propUri, XmlAdapter<?, ?> adapter, XsdTypeMapper typeMapper){ this.typeMapper = typeMapper; this.setter = setter; this.getter = getter; this.collection = Collection.class.isAssignableFrom(getter.getReturnType()); this.array = getter.getReturnType().isArray(); this.propUri = propUri; this.declaringClass = getter.getDeclaringClass(); extractDataTypes(); if(getter.getDeclaringClass() != getter.getDeclaringClass()){ log.warn("Setter and getter defined in different classes {}, {}",getter.toGenericString(),setter.toGenericString()); } this.functional = getter.isAnnotationPresent(OwlFunctionalDataProperty.class) || getter.isAnnotationPresent(OwlFunctionalObjectProperty.class); }
/** * Checks if the given adapter is applicable to the declared property type. */ private boolean isApplicable(XmlJavaTypeAdapter jta, T declaredType ) { if(jta==null) return false; T type = reader().getClassValue(jta,"type"); if(declaredType.equals(type)) return true; // for types explicitly marked in XmlJavaTypeAdapter.type() T ad = reader().getClassValue(jta,"value"); T ba = nav().getBaseClass(ad, nav().asDecl(XmlAdapter.class)); if(!nav().isParameterizedType(ba)) return true; // can't check type applicability. assume Object, which means applicable to any. T inMemType = nav().getTypeArgument(ba, 1); return nav().isSubClassOf(declaredType,inMemType); }
/** * Gets the instance of the adapter. * * @return * always non-null. */ public final <T extends XmlAdapter> T getAdapter(Class<T> key) { T v = key.cast(adapters.get(key)); if(v==null) { v = ClassFactory.create(key); putAdapter(key,v); } return v; }
private OnWire _adaptM(XMLSerializer serializer, InMemory v) throws MarshalException { XmlAdapter<OnWire,InMemory> a = serializer.getAdapter(adapter); try { return a.marshal(v); } catch (Exception e) { serializer.handleError(e,v,null); throw new MarshalException(e); } }
private @NotNull InMemory adaptU(Unmarshaller _u, OnWire v) throws JAXBException { UnmarshallerImpl u = (UnmarshallerImpl) _u; XmlAdapter<OnWire,InMemory> a = u.coordinator.getAdapter(adapter); u.coordinator.pushCoordinator(); try { return a.unmarshal(v); } catch (Exception e) { throw new UnmarshalException(e); } finally { u.coordinator.popCoordinator(); } }