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

The following examples show how to use javax.xml.bind.annotation.adapters.XmlAdapter. 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 File: TypeUseImpl.java    From openjdk-jdk9 with 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
Source File: PropertyInfoImpl.java    From jdk8u60 with 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 #3
Source File: CAdapter.java    From TencentKona-8 with 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 #4
Source File: JAXBDataBindingTest.java    From cxf with 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 #5
Source File: JAXBUtils.java    From cxf with 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 #6
Source File: BIConversion.java    From openjdk-jdk9 with 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 #7
Source File: PropertyInfoImpl.java    From TencentKona-8 with 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 #8
Source File: TypeUseImpl.java    From openjdk-jdk8u with 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 #9
Source File: TypeUseImpl.java    From openjdk-jdk8u-backup with 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 #10
Source File: SpringletsDataJaxb.java    From springlets with 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 #11
Source File: TypeUseImpl.java    From hottub with 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 File: BIConversion.java    From openjdk-8 with 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 #13
Source File: Coordinator.java    From openjdk-jdk8u with 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 #14
Source File: BridgeAdapter.java    From openjdk-8-source with 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 #15
Source File: UnmarshallerImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) {
    if (type==null) {
        throw new IllegalArgumentException();
    }
    coordinator.putAdapter(type,adapter);
}
 
Example #16
Source File: XmlAdapterUtils.java    From hyperjaxb3 with 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 #17
Source File: Coordinator.java    From hottub with 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 #18
Source File: DefaultTypeUse.java    From hyperjaxb3 with 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 File: AdaptedLister.java    From openjdk-jdk8u-backup with 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 File: AdaptedLister.java    From hottub with 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 #21
Source File: BridgeAdapter.java    From openjdk-jdk8u-backup with 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 #22
Source File: UnmarshallerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) {
    if (type==null) {
        throw new IllegalArgumentException();
    }
    coordinator.putAdapter(type,adapter);
}
 
Example #23
Source File: MarshallerImpl.java    From TencentKona-8 with 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 #24
Source File: Coordinator.java    From openjdk-8 with 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 #25
Source File: BridgeAdapter.java    From jdk8u60 with 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 #26
Source File: AdaptedAccessor.java    From openjdk-8 with 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 #27
Source File: UnmarshallerImpl.java    From openjdk-jdk8u with 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(coordinator.containsAdapter(type)) {
        return coordinator.getAdapter(type);
    } else {
        return null;
    }
}
 
Example #28
Source File: AdaptedAccessor.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source File: Coordinator.java    From openjdk-jdk8u-backup with 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 #30
Source File: UnmarshallerImpl.java    From jdk8u60 with 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(coordinator.containsAdapter(type)) {
        return coordinator.getAdapter(type);
    } else {
        return null;
    }
}