Java Code Examples for javax.xml.bind.annotation.XmlRootElement

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activemq-apollo, under directory /apollo-dto/src/main/java/org/apache/activemq/apollo/dto/.

Source file: ApolloTypeIdResolver.java

  17 
vote

public void init(JavaType baseType){
  this.baseType=baseType;
  ArrayList<Class<?>> classes=new ArrayList<Class<?>>();
  classes.add(baseType.getRawClass());
  classes.addAll(Arrays.asList(DtoModule$.MODULE$.extension_classes()));
  for (  Class<?> c : classes) {
    if (baseType.getRawClass().isAssignableFrom(c)) {
      JsonTypeName jsonAnnoation=c.getAnnotation(JsonTypeName.class);
      if (jsonAnnoation != null && jsonAnnoation.value() != null) {
        typeToId.put(c,jsonAnnoation.value());
        idToType.put(jsonAnnoation.value(),TypeFactory.specialize(baseType,c));
        idToType.put(c.getName(),TypeFactory.specialize(baseType,c));
      }
 else {
        XmlRootElement xmlAnnoation=c.getAnnotation(XmlRootElement.class);
        if (xmlAnnoation != null && xmlAnnoation.name() != null) {
          typeToId.put(c,xmlAnnoation.name());
          idToType.put(xmlAnnoation.name(),TypeFactory.specialize(baseType,c));
          idToType.put(c.getName(),TypeFactory.specialize(baseType,c));
        }
      }
    }
  }
}
 

Example 2

From project crest, under directory /entitywriter/src/main/java/org/codegist/crest/serializer/jaxb/.

Source file: JaxbParam.java

  17 
vote

public void setParams(List<Param> params){
  this.params=new ArrayList<JAXBElement<?>>();
  this.classes=new HashSet<Class<?>>();
  this.classes.add(getClass());
  for (  Param entry : params) {
    Class<?> cls=entry.getParamConfig().getValueClass();
    for (    Object value : entry.getValue()) {
      if (value == null)       continue;
      Object valueEl;
      if (isPrimitive(value)) {
        valueEl=value;
      }
 else {
        XmlRootElement root=cls.getAnnotation(XmlRootElement.class);
        String name;
        String ns;
        if (root != null) {
          name="##default".equals(root.name()) ? decapitalize(cls.getSimpleName()) : root.name();
          ns="##default".equals(root.namespace()) ? null : root.namespace();
        }
 else {
          name=decapitalize(cls.getSimpleName());
          ns=null;
        }
        valueEl=new JAXBElement(new QName(ns,name),cls,value);
      }
      JAXBElement entryEl=new JAXBElement(new QName(entry.getParamConfig().getName()),valueEl.getClass(),valueEl);
      this.params.add(entryEl);
    }
    this.classes.addAll(Types.getActors(entry.getParamConfig().getValueGenericType()));
  }
}
 

Example 3

From project gedcomx, under directory /gedcomx-rt-support/src/main/java/org/gedcomx/rt/.

Source file: GedcomNamespaceManager.java

  17 
vote

private static String getDefaultNamespace(Class<?> rootClass){
  DefaultNamespace defaultNs=rootClass.getAnnotation(DefaultNamespace.class);
  if (defaultNs == null && rootClass.getPackage() != null) {
    defaultNs=rootClass.getPackage().getAnnotation(DefaultNamespace.class);
  }
  String defaultNamespace="";
  if (defaultNs != null) {
    defaultNamespace=defaultNs.value();
  }
 else {
    XmlRootElement rootElement=rootClass.getAnnotation(XmlRootElement.class);
    if (rootElement != null) {
      if ("##default".equals(rootElement.namespace())) {
        if (rootClass.getPackage() != null) {
          XmlSchema xmlSchema=rootClass.getPackage().getAnnotation(XmlSchema.class);
          if (xmlSchema != null) {
            defaultNamespace=xmlSchema.namespace();
          }
        }
      }
 else {
        defaultNamespace=rootElement.namespace();
      }
    }
  }
  return defaultNamespace;
}
 

Example 4

From project gedcomx, under directory /gedcomx-rt-support/src/main/java/org/gedcomx/rt/.

Source file: GedcomNamespaceManager.java

  17 
vote

/** 
 * Get the JSON name for the specified type.
 * @param type The type.
 * @return The json name.
 */
public static String getJsonName(Class<?> type){
  if (type.isAnnotationPresent(JsonElementWrapper.class)) {
    JsonElementWrapper ext=type.getAnnotation(JsonElementWrapper.class);
    return nameFromQName(ext.namespace(),ext.name());
  }
 else   if (type.isAnnotationPresent(XmlRootElement.class)) {
    XmlRootElement rootElement=type.getAnnotation(XmlRootElement.class);
    if (rootElement != null) {
      String localPart=rootElement.name();
      if ("##default".equals(localPart)) {
        localPart=Introspector.decapitalize(type.getSimpleName());
      }
      String namespaceURI=rootElement.namespace();
      if ("##default".equals(namespaceURI)) {
        Package pkg=type.getPackage();
        if (pkg != null && pkg.isAnnotationPresent(XmlSchema.class)) {
          namespaceURI=pkg.getAnnotation(XmlSchema.class).namespace();
        }
 else {
          namespaceURI="";
        }
      }
      return nameFromQName(namespaceURI,localPart);
    }
  }
  return null;
}
 

Example 5

From project servicemix4-specs, under directory /jaxb-api-2.1/src/main/java/javax/xml/bind/.

Source file: JAXB.java

  17 
vote

public static void marshal(Object object,Result result){
  try {
    JAXBContext context;
    if (object instanceof JAXBElement) {
      context=getContext(((JAXBElement<?>)object).getDeclaredType());
    }
 else {
      Class<?> clazz=object.getClass();
      XmlRootElement r=clazz.getAnnotation(XmlRootElement.class);
      if (r == null) {
        object=new JAXBElement(new QName(Introspector.decapitalize(clazz.getSimpleName())),clazz,object);
      }
      context=getContext(clazz);
    }
    Marshaller m=context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
    m.marshal(object,result);
  }
 catch (  JAXBException e) {
    throw new DataBindingException(e);
  }
}
 

Example 6

From project Core_2, under directory /javaee-impl/src/test/java/org/jboss/forge/spec/plugin/.

Source file: RestPluginTest.java

  15 
vote

@Test public void testCreateEndpoint() throws Exception {
  Project project=getProject();
  JavaClass entity=generateEntity(project,null,"User");
  assertFalse(entity.hasAnnotation(XmlRootElement.class));
  setupRest();
  queueInputLines("");
  getShell().execute("rest endpoint-from-entity");
  JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  JavaResource resource=java.getJavaResource(java.getBasePackage() + ".rest.UserEndpoint");
  JavaClass endpoint=(JavaClass)resource.getJavaSource();
  assertEquals("/users",endpoint.getAnnotation(Path.class).getStringValue());
  assertEquals("java.util.List",endpoint.getMethod("listAll").getQualifiedReturnType());
  Method<JavaClass> method=endpoint.getMethod("findById",Long.class);
  Type<JavaClass> returnTypeInspector=method.getReturnTypeInspector();
  assertEquals("javax.ws.rs.core.Response",returnTypeInspector.getQualifiedName());
  assertTrue(java.getJavaResource(entity).getJavaSource().hasAnnotation(XmlRootElement.class));
  getShell().execute("build");
}
 

Example 7

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/utils/.

Source file: JaxbSerializer.java

  15 
vote

/** 
 * Convert Object to XML.
 * @param obj Object to be converted to a XML-String
 * @return XML String XML-String derived out of Object
 * @throws JAXBException A JAXBException
 */
@Override @SuppressWarnings("unchecked") public String objectToXml(final Object obj) throws JAXBException {
  final ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  final StreamResult result=new StreamResult(outputStream);
  try {
    if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
      this.marshaller.marshal(obj,result);
    }
 else {
      final Class<?> objClass=obj.getClass();
      this.marshaller.marshal(new JAXBElement(new QName(objClass.getName()),objClass,obj),result);
    }
  }
 catch (  final NullPointerException npe) {
    throw new JAXBException(npe.getMessage() + "\n\nMay be caused by an invalid XMLGregorianCalendar.\n" + "Please make shure to use the generateXMLCalendar"+ " method from Helpers to create new Calendars to"+ " avoid illegal calendar states",npe);
  }
  return (outputStream.toString());
}
 

Example 8

From project harmony, under directory /phosphorus-gmpls/src/main/java/org/opennaas/extensions/gmpls/serviceinterface/databinding/utils/.

Source file: JaxbSerializer.java

  15 
vote

/** 
 * Convert Object to XML.
 * @param obj Object to be converted to a XML-String
 * @return XML String XML-String derived out of Object
 * @throws JAXBException A JAXBException
 */
@Override @SuppressWarnings("unchecked") public String objectToXml(final Object obj) throws JAXBException {
  final ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  final StreamResult result=new StreamResult(outputStream);
  try {
    if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
      this.marshaller.marshal(obj,result);
    }
 else {
      final Class<?> objClass=obj.getClass();
      this.marshaller.marshal(new JAXBElement(new QName(objClass.getName()),objClass,obj),result);
    }
  }
 catch (  NullPointerException npe) {
    throw new JAXBException(npe.getMessage() + "\n\nMay be caused by an invalid XMLGregorianCalendar.\n" + "Please make shure to use the generateXMLCalendar"+ " method from Helpers to create new Calendars to"+ " avoid illegal calendar states",npe);
  }
  return (outputStream.toString());
}
 

Example 9

From project play-module-resteasycrud, under directory /src/play/modules/resteasy/crud/.

Source file: CRUDEnhancer.java

  15 
vote

private void makeDataTable(CtClass ctClass,Signature makeDataTableSignature,Class<? extends Model> modelClass) throws Exception {
  CtClass dataTableClass=ctClass.makeNestedClass("__DataTable",true);
  ClassPool cp=ctClass.getClassPool();
  dataTableClass.setSuperclass(cp.get(DataTable.class.getName()));
  CtClass[] parameters=new CtClass[makeDataTableSignature.parameters.size()];
  for (int i=0; i < parameters.length; i++) {
    parameters[i]=cp.get(makeDataTableSignature.parameters.get(i).type.getName());
  }
  CtConstructor dataTableConstructor=CtNewConstructor.make(parameters,null,CtNewConstructor.PASS_PARAMS,null,null,dataTableClass);
  ConstPool constPool=dataTableClass.getClassFile().getConstPool();
  AnnotationsAttribute annotations=getAnnotations(dataTableClass);
  createAnnotation(annotations,XmlType.class,map(constPool,"namespace",dataTableClass.getName()));
  createAnnotation(annotations,XmlRootElement.class,map(constPool,"name","dataTable"));
  createAnnotation(annotations,XmlSeeAlso.class,map(constPool,new Object[]{modelClass}));
  createAnnotation(annotations,Mapped.class,map(constPool,"namespaceMap",new Object[]{createAnnotation(XmlNsMap.class,map(constPool,"namespace","http://www.w3.org/2001/XMLSchema-instance").add("jsonName","xsi"),constPool),createAnnotation(XmlNsMap.class,map(constPool,"namespace","http://www.w3.org/2005/Atom").add("jsonName","atom"),constPool)}));
  dataTableClass.addConstructor(dataTableConstructor);
  ApplicationClass dataTableApplicationClass=new ApplicationClass(dataTableClass.getName());
  dataTableApplicationClass.compiled(dataTableClass.toBytecode());
  dataTableClass.defrost();
  Play.classes.add(dataTableApplicationClass);
  StringBuilder ret=new StringBuilder(makeDataTableSignature.decl());
  ret.append("{ return new ").append(dataTableClass.getName()).append("(");
  boolean once=false;
  for (  Param param : makeDataTableSignature.parameters) {
    if (once)     ret.append(", ");
 else     once=true;
    ret.append(param.name);
  }
  ret.append("); }");
  CtMethod method=CtMethod.make(ret.toString(),ctClass);
  ctClass.addMethod(method);
}
 

Example 10

From project tools4j, under directory /support/support-jse/src/test/java/org/deephacks/tools4j/support/.

Source file: ClassIntrospectorTest.java

  15 
vote

@Test public void test1(){
  ClassIntrospector i=new ClassIntrospector(Test1.class);
  assertThat(i.getName(),is(Test1.class.getName()));
  assertThat(i.getAnnotation(XmlRootElement.class).name(),is("name"));
  Map<String,FieldWrap<XmlElement>> fields=i.getFieldMap(XmlElement.class);
  FieldWrap<XmlElement> f=fields.get("var1");
  assertThat(f.getFieldName(),is("var1"));
  assertEquals(f.getType(),String.class);
  assertNull(f.getDefaultValue());
  f=fields.get("var2");
  assertThat(f.getFieldName(),is("var2"));
  assertEquals(f.getType(),Boolean.class);
  assertNull(f.getDefaultValue());
  f=fields.get("var3");
  assertThat(f.getFieldName(),is("var3"));
  assertTrue(f.isCollection());
  assertEquals(f.getCollRawType(),List.class);
  assertEquals(f.getType(),String.class);
  assertNull(f.getDefaultValues());
  f=fields.get("var4");
  assertThat(f.getFieldName(),is("var4"));
  assertTrue(f.isCollection());
  assertEquals(f.getCollRawType(),List.class);
  assertEquals(f.getType(),Test2.class);
  Collection<?> values=f.getDefaultValues();
  Test2 value=(Test2)values.iterator().next();
  assertThat(1.0,is(value.var1));
  assertThat(2,is(value.var2));
  assertThat(2,is(value.units.size()));
  f=fields.get("var5");
  assertThat(f.getFieldName(),is("var5"));
  assertTrue(f.isCollection());
  assertEquals(f.getCollRawType(),Set.class);
  assertEquals(f.getType(),Double.class);
  assertNull(f.getDefaultValue());
}