javax.xml.bind.annotation.XmlRootElement Java Examples

The following examples show how to use javax.xml.bind.annotation.XmlRootElement. 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: TypeInfoImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #2
Source File: TransactionBindTest.java    From staedi with Apache License 2.0 6 votes vote down vote up
QName getRootElementName(Class<?> type) {
    XmlRootElement rootElement = type.getAnnotation(XmlRootElement.class);
    String ns;
    String localName;

    if (rootElement != null) {
        if ("##default".equals(rootElement.name())) {
            localName = decapitalize(type.getSimpleName());
        } else {
            localName = rootElement.name();
        }
        if ("##default".equals(rootElement.namespace())) {
            ns = "";
        } else {
            ns = rootElement.namespace();
        }

        return new QName(ns, localName);
    }

    throw new IllegalStateException("Missing XmlRootElement annotation on root class");
}
 
Example #3
Source File: Jaxb2CollectionHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * {@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, @Nullable Class<?> contextClass, @Nullable 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);
}
 
Example #4
Source File: TypeInfoImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #5
Source File: JAXBManager.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
void initJaxbContext(final Method method) {
    Stream
            .concat(of(method.getGenericReturnType()),
                    of(method.getParameters())
                            .filter(p -> of(Path.class, Query.class, Header.class, QueryParams.class, Headers.class,
                                    HttpMethod.class, Url.class).noneMatch(p::isAnnotationPresent))
                            .map(Parameter::getParameterizedType))
            .map(RequestParser::toClassType)
            .filter(Objects::nonNull)
            .filter(cType -> cType.isAnnotationPresent(XmlRootElement.class)
                    || cType.isAnnotationPresent(XmlType.class))
            .forEach(rootElemType -> jaxbContexts.computeIfAbsent(rootElemType, k -> {
                try {
                    return JAXBContext.newInstance(k);
                } catch (final JAXBException e) {
                    throw new IllegalStateException(e);
                }
            }));
}
 
Example #6
Source File: Jaxb2CollectionHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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);
}
 
Example #7
Source File: Jaxb2CollectionHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * {@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);
}
 
Example #8
Source File: JaxbSerialization.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T deserialize(final InputStream is, final Type type) throws SerializerException {
    if (type == null || !(type instanceof Class)) {
        return null;
    }
    Class clazz = (Class) type;
    Annotation annotation = clazz.getAnnotation(XmlRootElement.class);
    if (annotation == null) {
        return null;
    }
    try {
        JAXBContext context = getJaxbContext(clazz);
        Unmarshaller marshaller = context.createUnmarshaller();
        return (T) marshaller.unmarshal(is);
    } catch (JAXBException e) {
        throw new SerializerException(String.format("Error occurs while deserializing %s", type), e);
    }
}
 
Example #9
Source File: ClassBeanInfoImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #10
Source File: ClassBeanInfoImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #11
Source File: ClassBeanInfoImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #12
Source File: Jaxb2CollectionHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * {@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, @Nullable Class<?> contextClass, @Nullable 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);
}
 
Example #13
Source File: GenericRequest.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public GenericRequest setPayload(Object payload, GenericFeature... features) {
   this.process(features);
   XOPFeature mtomFeature = (XOPFeature)this.getFeature(XOPFeature.class);
   Class<?> payloadClazz = payload.getClass();
   if (payloadClazz.isAnnotationPresent(XmlRootElement.class)) {
      MarshallerHelper helper = getHelper(payloadClazz, mtomFeature);
      this.payload = helper.toDocument(payload);
      this.handlers = helper.getDataHandlersMap();
   } else {
      if (!(payload instanceof JAXBElement)) {
         throw new IllegalArgumentException("PayLoadclass [" + payloadClazz + "] is not annotated with @XMLRootElement or is not a JAXBElement class.");
      }

      try {
         Document doc = DOC_BUILDER.newDocument();
         JAXBElement<?> jaxbElement = (JAXBElement)payload;
         Marshaller marshaller = JaxbContextFactory.getJaxbContextForClass(jaxbElement.getDeclaredType()).createMarshaller();
         marshaller.marshal(jaxbElement, doc);
         this.payload = doc;
      } catch (JAXBException var8) {
         throw new IllegalArgumentException("PayLoadclass [" + payloadClazz + "] is not annotated with @XMLRootElement or is not a JAXBElement class.", var8);
      }
   }

   return this;
}
 
Example #14
Source File: TypeInfoImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #15
Source File: ClassBeanInfoImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #16
Source File: GenericResponse.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T> T asObject(Class<T> clazz) throws SOAPException {
   if (!clazz.isAnnotationPresent(XmlRootElement.class)) {
      throw new IllegalArgumentException("Class [" + clazz + "] is not annotated with @XMLRootElement");
   } else {
      this.getSOAPException();
      MarshallerHelper<T, T> helper = new MarshallerHelper(clazz, clazz);
      helper.clearAttachmentPartMap();
      Iterator attachmentPartIterator = this.message.getAttachments();

      while(attachmentPartIterator.hasNext()) {
         AttachmentPart element = (AttachmentPart)attachmentPartIterator.next();
         helper.addAttachmentPart(this.getAttachmentPartId(element), element);
      }

      return helper.toObject((Node)this.getFirstChildElement());
   }
}
 
Example #17
Source File: MarshallerHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String toString(Y data) {
   StringWriter writer = new StringWriter();

   try {
      if (!data.getClass().isAnnotationPresent(XmlRootElement.class) && !(data instanceof JAXBElement)) {
         JAXBElement<Y> jaxbElement = new JAXBElement(translate(data.getClass()), this.marshallClass, data);
         this.getMarshaller().marshal(jaxbElement, writer);
      } else {
         this.getMarshaller().marshal(data, writer);
      }
   } catch (JAXBException var4) {
      throw handleException(var4);
   }

   return writer.toString();
}
 
Example #18
Source File: GenericRequest.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public GenericRequest setPayload(Object payload, GenericFeature... features) {
   this.process(features);
   XOPFeature mtomFeature = (XOPFeature)this.getFeature(XOPFeature.class);
   Class<?> payloadClazz = payload.getClass();
   if (payloadClazz.isAnnotationPresent(XmlRootElement.class)) {
      MarshallerHelper helper = getHelper(payloadClazz, mtomFeature);
      this.payload = helper.toDocument(payload);
      this.handlers = helper.getDataHandlersMap();
   } else {
      if (!(payload instanceof JAXBElement)) {
         throw new IllegalArgumentException("PayLoadclass [" + payloadClazz + "] is not annotated with @XMLRootElement or is not a JAXBElement class.");
      }

      try {
         Document doc = DOC_BUILDER.newDocument();
         JAXBElement<?> jaxbElement = (JAXBElement)payload;
         Marshaller marshaller = JaxbContextFactory.getJaxbContextForClass(jaxbElement.getDeclaredType()).createMarshaller();
         marshaller.marshal(jaxbElement, doc);
         this.payload = doc;
      } catch (JAXBException var8) {
         throw new IllegalArgumentException("PayLoadclass [" + payloadClazz + "] is not annotated with @XMLRootElement or is not a JAXBElement class.", var8);
      }
   }

   return this;
}
 
Example #19
Source File: DomXmlDataFormatMapper.java    From camunda-spin with Apache License 2.0 6 votes vote down vote up
@Override
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);
  }
}
 
Example #20
Source File: TypeInfoImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #21
Source File: MarshallerHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String toString(Y data) {
   StringWriter writer = new StringWriter();

   try {
      if (!data.getClass().isAnnotationPresent(XmlRootElement.class) && !(data instanceof JAXBElement)) {
         JAXBElement<Y> jaxbElement = new JAXBElement(translate(data.getClass()), this.marshallClass, data);
         this.getMarshaller().marshal(jaxbElement, writer);
      } else {
         this.getMarshaller().marshal(data, writer);
      }
   } catch (JAXBException var4) {
      throw handleException(var4);
   }

   return writer.toString();
}
 
Example #22
Source File: GenericResponse.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T> T asObject(Class<T> clazz) throws SOAPException {
   if (!clazz.isAnnotationPresent(XmlRootElement.class)) {
      throw new IllegalArgumentException("Class [" + clazz + "] is not annotated with @XMLRootElement");
   } else {
      this.getSOAPException();
      MarshallerHelper<T, T> helper = new MarshallerHelper(clazz, clazz);
      helper.clearAttachmentPartMap();
      Iterator attachmentPartIterator = this.message.getAttachments();

      while(attachmentPartIterator.hasNext()) {
         AttachmentPart element = (AttachmentPart)attachmentPartIterator.next();
         helper.addAttachmentPart(this.getAttachmentPartId(element), element);
      }

      return helper.toObject((Node)this.getFirstChildElement());
   }
}
 
Example #23
Source File: XmlAsserter.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static String convert(Object obj) {
    try {
        Class clazz = obj.getClass();
        if (!jaxbContextMap.containsKey(clazz)) {
            jaxbContextMap.put(clazz, JAXBContext.newInstance(clazz));
        }
        JAXBContext context = jaxbContextMap.get(clazz);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
            marshaller.marshal(obj, writer);
        } else if (obj.getClass().isAnnotationPresent(XmlType.class)) {
            JAXBElement jaxbElement = new JAXBElement(new QName("", obj.getClass().getSimpleName()), clazz, obj);
            marshaller.marshal(jaxbElement, writer);
        }
        return writer.toString();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        Assert.fail(e.getMessage());
    }
    return null;
}
 
Example #24
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String toXml(Class<?> clazz, Object obj) throws GFDDPPException {
   StringWriter sw = new StringWriter();
   Marshaller marshaller = this.getMarshaller(clazz);

   try {
      marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
      if (clazz.getAnnotation(XmlRootElement.class) != null) {
         marshaller.marshal(obj, (Writer)sw);
      } else {
         JAXB.marshal(obj, (Writer)sw);
      }
   } catch (JAXBException var7) {
      LOG.error("", var7);
      String message = this.processJAXBException(var7);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_MARSHAL, new String[]{message, clazz.getName()});
   }

   return sw.toString();
}
 
Example #25
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public <X> X toObject(Class<X> clazz, byte[] data) throws GFDDPPException {
   try {
      ByteArrayInputStream bis = new ByteArrayInputStream(data);
      Object result;
      if (clazz.getAnnotation(XmlRootElement.class) != null) {
         result = this.getUnmarshaller(clazz).unmarshal((InputStream)bis);
      } else {
         try {
            JAXBElement<X> jax = this.getUnmarshaller(clazz).unmarshal(this.xmlInputFactory.createXMLStreamReader((InputStream)bis, (String)"UTF-8"), clazz);
            result = jax.getValue();
         } catch (XMLStreamException var6) {
            LOG.error("Incorrect xml : " + var6);
            throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALL, new String[]{var6.getMessage(), clazz.getName()});
         }
      }

      return (X) result;
   } catch (JAXBException var7) {
      LOG.error("", var7);
      String message = this.processJAXBException(var7);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALL, new String[]{message, clazz.getName()});
   }
}
 
Example #26
Source File: XmlAsserter.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String convert(Object obj) {
   try {
      Class clazz = obj.getClass();
      if (!jaxbContextMap.containsKey(clazz)) {
         jaxbContextMap.put(clazz, JAXBContext.newInstance(clazz));
      }

      JAXBContext context = (JAXBContext)jaxbContextMap.get(clazz);
      Marshaller marshaller = context.createMarshaller();
      StringWriter writer = new StringWriter();
      if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
         marshaller.marshal(obj, (Writer)writer);
      } else if (obj.getClass().isAnnotationPresent(XmlType.class)) {
         JAXBElement jaxbElement = new JAXBElement(new QName("", obj.getClass().getSimpleName()), clazz, obj);
         marshaller.marshal(jaxbElement, (Writer)writer);
      }

      return writer.toString();
   } catch (Exception var6) {
      LOG.error(var6.getMessage(), var6);
      Assert.fail(var6.getMessage());
      return null;
   }
}
 
Example #27
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public <X> X toObject(Class<X> clazz, byte[] data) throws GFDDPPException {
   try {
      ByteArrayInputStream bis = new ByteArrayInputStream(data);
      Object result;
      if (clazz.getAnnotation(XmlRootElement.class) != null) {
         result = this.getUnmarshaller(clazz).unmarshal((InputStream)bis);
      } else {
         try {
            JAXBElement<X> jax = this.getUnmarshaller(clazz).unmarshal(this.xmlInputFactory.createXMLStreamReader((InputStream)bis, (String)"UTF-8"), clazz);
            result = jax.getValue();
         } catch (XMLStreamException var6) {
            LOG.error("Incorrect xml : " + var6);
            throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALL, new String[]{var6.getMessage(), clazz.getName()});
         }
      }

      return result;
   } catch (JAXBException var7) {
      LOG.error("", var7);
      String message = this.processJAXBException(var7);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALL, new String[]{message, clazz.getName()});
   }
}
 
Example #28
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String toXml(Class<?> clazz, Object obj) throws GFDDPPException {
   StringWriter sw = new StringWriter();
   Marshaller marshaller = this.getMarshaller(clazz);

   try {
      marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
      if (clazz.getAnnotation(XmlRootElement.class) != null) {
         marshaller.marshal(obj, (Writer)sw);
      } else {
         JAXB.marshal(obj, (Writer)sw);
      }
   } catch (JAXBException var7) {
      LOG.error("", var7);
      String message = this.processJAXBException(var7);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_MARSHAL, new String[]{message, clazz.getName()});
   }

   return sw.toString();
}
 
Example #29
Source File: GenericResponse.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T> T asObject(Class<T> clazz) throws SOAPException {
   if (!clazz.isAnnotationPresent(XmlRootElement.class)) {
      throw new IllegalArgumentException("Class [" + clazz + "] is not annotated with @XMLRootElement");
   } else {
      this.getSOAPException();
      MarshallerHelper<T, T> helper = new MarshallerHelper(clazz, clazz);
      helper.clearAttachmentPartMap();
      Iterator attachmentPartIterator = this.message.getAttachments();

      while(attachmentPartIterator.hasNext()) {
         AttachmentPart element = (AttachmentPart)attachmentPartIterator.next();
         helper.addAttachmentPart(this.getAttachmentPartId(element), element);
      }

      return helper.toObject((Node)this.getFirstChildElement());
   }
}
 
Example #30
Source File: WebServiceWrapperGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void writeXmlElementDeclaration(JDefinedClass cls, String elementName, String namespaceUri) {

       if (cls == null)
            return;
        JAnnotationUse xmlRootElementAnn = cls.annotate(XmlRootElement.class);
        xmlRootElementAnn.param("name", elementName);
        if (namespaceUri.length() > 0) {
            xmlRootElementAnn.param("namespace", namespaceUri);
        }
        JAnnotationUse xmlAccessorTypeAnn = cls.annotate(cm.ref(XmlAccessorType.class));
        xmlAccessorTypeAnn.param("value", XmlAccessType.FIELD);
    }