Java Code Examples for javax.xml.bind.annotation.adapters.XmlAdapter

The following examples show how to use javax.xml.bind.annotation.adapters.XmlAdapter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hottub   Source File: TypeUseImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 2
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);
}
 
Example 3
Source Project: openjdk-8   Source File: BIConversion.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: springlets   Source File: SpringletsDataJaxb.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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, "[Assertion failed] - this argument is required; it must not be null");

  if (source == null) {
    return Collections.emptyList();
  }

  List<S> result = new ArrayList<S>();

  for (T element : source) {
    try {
      result.add(adapter.marshal(element));
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }

  return result;
}
 
Example 5
Source Project: openjdk-jdk8u   Source File: TypeUseImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 6
/**
 * 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);
}
 
Example 7
Source Project: openjdk-jdk9   Source File: BIConversion.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 8
Source Project: cxf   Source File: JAXBUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object useAdapter(Object obj,
                                XmlJavaTypeAdapter typeAdapter,
                                boolean marshal,
                                Object defaultValue) {
    if (typeAdapter != null) {
        try {
            @SuppressWarnings("rawtypes")
            XmlAdapter xmlAdapter = typeAdapter.value().newInstance();
            if (marshal) {
                return xmlAdapter.marshal(obj);
            }
            return xmlAdapter.unmarshal(obj);
        } catch (Exception ex) {
            LOG.log(Level.INFO, "(un)marshalling failed, using defaultValue", ex);
        }
    }
    return defaultValue;
}
 
Example 9
Source Project: cxf   Source File: JAXBDataBindingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConfiguredXmlAdapter() throws Exception {
    Language dutch = new Language("nl_NL", "Dutch");
    Language americanEnglish = new Language("en_US", "Americanish");

    Person person = new Person(dutch);
    JAXBDataBinding binding = new JAXBDataBinding(Person.class, Language.class);
    binding.setConfiguredXmlAdapters(Arrays.<XmlAdapter<?, ?>>asList(new LanguageAdapter(dutch, americanEnglish)));
    DataWriter<OutputStream> writer = binding.createWriter(OutputStream.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writer.write(person, baos);
    String output = baos.toString();
    String xml = "<person motherTongue=\"nl_NL\"/>";

    assertEquals(xml, output);

    DataReader<XMLStreamReader> reader = binding.createReader(XMLStreamReader.class);
    Person read = (Person) reader.read(XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)));

    assertEquals(dutch, read.getMotherTongue());

}
 
Example 10
Source Project: TencentKona-8   Source File: CAdapter.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 11
Source Project: openjdk-jdk9   Source File: TypeUseImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 12
Source Project: jdk8u60   Source File: PropertyInfoImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source Project: openjdk-8   Source File: AdaptedAccessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public OnWireValueT get(BeanT bean) throws AccessorException {
    InMemValueT v = core.get(bean);

    XmlAdapter<OnWireValueT,InMemValueT> a = getAdapter();
    try {
        return a.marshal(v);
    } catch (Exception e) {
        throw new AccessorException(e);
    }
}
 
Example 14
Source Project: hyperjaxb3   Source File: XmlAdapterUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <ValueType, BoundType> JAXBElement<BoundType> marshallJAXBElement(
		Class<? extends XmlAdapter<BoundType, ValueType>> xmlAdapterClass,
		Class<BoundType> declaredType, QName name, Class<?> scope, ValueType v) {
	try {
		if (v == null) {
			return null;
		} else {
			final XmlAdapter<BoundType, ValueType> xmlAdapter = getXmlAdapter(xmlAdapterClass);
			return new JAXBElement<BoundType>(name, declaredType, scope,
					xmlAdapter.marshal(v));
		}
	} catch (Exception ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 15
Source Project: hyperjaxb3   Source File: XmlAdapterUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <ValueType, BoundType> ValueType unmarshallJAXBElement(
		Class<? extends XmlAdapter<BoundType, ValueType>> xmlAdapterClass,
		JAXBElement<? extends BoundType> v) {
	try {
		if (v == null) {
			return null;
		} else {
			final XmlAdapter<BoundType, ValueType> xmlAdapter = getXmlAdapter(xmlAdapterClass);
			return xmlAdapter.unmarshal(v.getValue());
		}
	} catch (Exception ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 16
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();
    }
}
 
Example 17
Source Project: jackson-modules-base   Source File: AdapterConverter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public AdapterConverter(XmlAdapter<?,?> adapter,
        JavaType inType, JavaType outType, boolean ser)
{
    _adapter = (XmlAdapter<Object,Object>) adapter;
    _inputType = inType;
    _targetType = outType;
    _forSerialization = ser;
}
 
Example 18
Source Project: hyperjaxb3   Source File: DefaultTypeUse.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
	@SuppressWarnings("unchecked")
	Class<? extends XmlAdapter<?, ?>> atype = (Class<? extends XmlAdapter<?, ?>>) adapter
			.getAdapterIfKnown();

	// try to run the adapter now rather than later.
	if (cons instanceof JStringLiteral && atype != null) {
		JStringLiteral scons = (JStringLiteral) cons;
		@SuppressWarnings("unchecked")
		XmlAdapter<Object, String> a = (XmlAdapter<Object, String>) 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);
}
 
Example 19
Source Project: hottub   Source File: AdaptedLister.java    License: GNU General Public License v2.0 5 votes vote down vote up
AdaptedLister(
    Lister<BeanT,PropT,InMemItemT,PackT> core,
    Class<? extends XmlAdapter<OnWireItemT,InMemItemT>> adapter) {

    this.core = core;
    this.adapter = adapter;
}
 
Example 20
Source Project: TencentKona-8   Source File: BridgeAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 21
Source Project: openjdk-jdk9   Source File: MarshallerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <A extends XmlAdapter> A getAdapter(Class<A> type) {
    if(type==null)
        throw new IllegalArgumentException();
    if(serializer.containsAdapter(type))
        // so as not to create a new instance when this method is called
        return serializer.getAdapter(type);
    else
        return null;
}
 
Example 22
public OnWireValueT get(BeanT bean) throws AccessorException {
    InMemValueT v = core.get(bean);

    XmlAdapter<OnWireValueT,InMemValueT> a = getAdapter();
    try {
        return a.marshal(v);
    } catch (Exception e) {
        throw new AccessorException(e);
    }
}
 
Example 23
private XmlAdapter<OnWireValueT, InMemValueT> getAdapter() {
    Coordinator coordinator = Coordinator._getInstance();
    if(coordinator!=null)
        return coordinator.getAdapter(adapter);
    else {
        synchronized(this) {
            if(staticAdapter==null)
                staticAdapter = ClassFactory.create(adapter);
        }
        return staticAdapter;
    }
}
 
Example 24
Source Project: TencentKona-8   Source File: MarshallerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <A extends XmlAdapter> A getAdapter(Class<A> type) {
    if(type==null)
        throw new IllegalArgumentException();
    if(serializer.containsAdapter(type))
        // so as not to create a new instance when this method is called
        return serializer.getAdapter(type);
    else
        return null;
}
 
Example 25
Source Project: openjdk-8   Source File: Coordinator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 26
@Override
public <A extends XmlAdapter> A getAdapter(Class<A> type) {
    if(type==null) {
        throw new IllegalArgumentException();
    }
    if(coordinator.containsAdapter(type)) {
        return coordinator.getAdapter(type);
    } else {
        return null;
    }
}
 
Example 27
/**
 * 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;
}
 
Example 28
Source Project: openjdk-jdk8u   Source File: BridgeAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
    }
}
 
Example 29
@Override
public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) {
    if (type==null) {
        throw new IllegalArgumentException();
    }
    coordinator.putAdapter(type,adapter);
}
 
Example 30
public void set(BeanT bean, OnWireValueT o) throws AccessorException {
    XmlAdapter<OnWireValueT, InMemValueT> a = getAdapter();
    try {
        core.set(bean, (o == null ? null : a.unmarshal(o)));
    } catch (Exception e) {
        throw new AccessorException(e);
    }
}