Object to Xml in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • techbytes
    New Member
    • May 2010
    • 36

    Object to Xml in java

    In my project,Iam converting object into xml.Iam using jaxb marshal method to do the conversion.
    In running the program ,i got 1 counts of Illegal Annotation Exceptions.
    how to solve this problem .
    thanks in advance
    Code:
    //Method for converting
      public static ReturnObject getXmlValue(HttpServletRequest httpRequest)
    {
     ReturnObject  xRetObject = new ReturnObject();
            xRetObject.setReturnCode("0");
            xRetObject.setReturnMessage(null);
            xRetObject.setReturnObject(null);
            List<Widgets> widgetObjLists = null;
            Container thisContainer =new Container();
            System.out.println("Inside the Utilities for getting the XmlValue >>>>>>>>>>");
           try
            {
              List<Container> myContainer = (List<Container>) httpRequest.getSession().getAttribute(com.cmsapplication.utilities.StaticDefinitions.CONTAINER_OBJECT);
             //   List l1 =new ArrayList();
             //   l1.add(thisContainer);
                Iterator itr = myContainer.iterator();
             // System.out.println("List Size ::::::::::" + myContainer.size());
               
            // =============================================================================================================
            // Setup JAXB
            // =============================================================================================================
             System.out.println("11111111111111111111111");
           // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
                 final JAXBContext context = JAXBContext.newInstance(com.cmssuite.application.objects.Container.class);
          //     final JAXBContext context = JAXBContext.newInstance(com.cmssuite.application.objects.JavaObject.class);
    
            // =============================================================================================================
            // Marshalling OBJECT to XML
            // =============================================================================================================
    
            // Create the marshaller, this is the nifty little thing that will actually transform the object into XML
            final Marshaller marshaller = context.createMarshaller();
            System.out.println("222222222222222222222222");
            // Create a stringWriter to hold the XML
            final StringWriter stringWriter = new StringWriter();
    
            // Create the sample object we wish to transform into XML
                final Container javaObject = new Container();
            //  final JavaObject javaObject = new JavaObject();
                //javaObject.setName("Shanthi");
                //javaObject.setRole("CEO");
             while (itr.hasNext())
                {
                    Container conObj = (Container) itr.next();
                    System.out.println("WIDTH LIST SIZE :::::::::" + conObj.getWidgetObjectLists().size());
                    System.out.println("Container Code >>>>>>>>>>>>"+conObj.getContainerCode());
                    System.out.println("Container Name >>>>>>>>>>>>"+conObj.getContainerName());
                    //widgetObjLists = conObj.getWidgetObjectLists();
                    javaObject.setContainerCode(conObj.getContainerCode());
                    javaObject.setContainerName(conObj.getContainerName());
                    javaObject.setTotalContainer(conObj.getTotalContainer());
                    //Iterator widItr = widgetObjLists.iterator();
    //                while (widItr.hasNext())
    //                {
    //                    Widgets scrollTextObj = (Widgets) widItr.next();
    //                    System.out.println("Behaviour >>>>>>>>" + scrollTextObj.getBehaviour());
    //                    System.out.println("Direction >>>>>>>>>>>>" + scrollTextObj.getDirection());
    //                    System.out.println("Height >>>>>>>>>>>>>" + scrollTextObj.getHeight());
    //                    System.out.println("Scroll Amount >>>>>>>>>>" + scrollTextObj.getScrollAmount());
    //                    System.out.println("Scroll Delay >>>>>>>>>>>>" + scrollTextObj.getScrollDelay());
    //                    System.out.println("Text >>>>>>>>>>" + scrollTextObj.getText());
    //
    //
    //                }
    }
    
    //Container.Class
    
    
    @XmlRootElement
    public class Container extends com.cmssuite.businesslayer.core.DataObject
    {
    
           /// <summary>
        /// Default Constructor
        /// </summary>
        public Container() {
            super();
            System.out.println ("Inside the constructor");
            //
            // TODO: Add constructor logic here
            //
        }
    
    
    
        private String _containerName = null;
        public String getContainerName() {
            return _containerName;
        }
    
        public void setContainerName(String containerName) {
            this._containerName = containerName;
        }
    
    
        private String _containerCode = null;
        public String getContainerCode() {
            return _containerCode;
        }
    
        public void setContainerCode(String containerCode) {
            this._containerCode = containerCode;
        }
    
        private Integer _totalContainer = null;
    
        public Integer getTotalContainer() {
            return _totalContainer;
        }
    
        public void setTotalContainer(Integer totalContainer) {
            this._totalContainer = totalContainer;
        }
    
    
       /*
        * Getter and Setting method for Widgets Object Instance.
        */
    	private Vector _widgetLists = null;
    	public void setWidgetObjectLists(Vector widgetObject)
    	{
    		_widgetLists = widgetObject;
    	}
    	public Vector getWidgetObjectLists()
    	{
    		return _widgetLists;
    	}
    
        public void addWidgetObject(DataObject widgetObject)
    	{
            if ( (_widgetLists != null) && (_widgetLists.size() > 0) )
                this._widgetLists.add(widgetObject);
            else
            {
                _widgetLists = new Vector();
                this._widgetLists.add(widgetObject);
            }
        }
    
    
        /// <summary>
        /// Getter and Setting method for Instance Variable.
        /// </summary>
        /// <summary>
        /// Method for generateObjectLists:
        /// A Virtual method that is being implemented (overrided) by the sub class.
        /// This will generate all the respective object related table fields and its corresponding values.
        /// </summary>
        public void generateObjectLists() {
    
        }
    
        /// <summary>
        /// Method for generateUpdateObjectLists:
        /// A Virtual method that is being implemented (Overrided) by the sub class.
        /// This will generate all the respective object related table fields and its corresponding values.
        /// </summary>
        public void generateUpdateObjectLists() {
    
        }
    
    
        /// <summary>
        /// Method for validateObject:
        /// A Virtual method that must be implemented by the sub class.
        /// This will validate the respective object.
        /// </summary>
        public ReturnObject validateObject() {
            ReturnObject xRetObject = new ReturnObject("0", "", null);
            xRetObject.setReturnCode("0");
            xRetObject.setReturnMessage("");
            xRetObject.setReturnObject(null);
            return xRetObject;
        }
    
    
       
    
        /// <summary>
        /// Overrided Constructor
        /// </summary>
    
        public Container(String containerName,String containerCode,Integer totalContainer)
        {
          super();
           System.out.println("4444444444444444444444");
          this.setContainerName(containerName);
           System.out.println("555555555555555555555");
          this.setContainerCode(containerCode);
           System.out.println("666666666666666666666");
          this.setTotalContainer(totalContainer);
        }
    }
  • antonioatt
    New Member
    • Oct 2011
    • 2

    #2
    To try discover where is the problem I need at least 2 thinghs:

    1)Error stack trace
    2)Widgets implementation

    Better if you post the entire code

    Comment

    • techbytes
      New Member
      • May 2010
      • 36

      #3
      hi,
      Iam attaching error stack trace ,now don't consider the widget.
      Code:
      15:29:47,843 ERROR [STDERR] com.sun.xml.bind.v2.runtime.IllegalAnnotationsExcept
      ion: 1 counts of IllegalAnnotationExceptions
      java.sql.Date does not have a no-arg default constructor.
              this problem is related to the following location:
                      at java.sql.Date
                      at public java.sql.Date com.cmssuite.businesslayer.core.DataObje
      ct.getCreatedDate()
                      at com.cmssuite.businesslayer.core.DataObject
                      at com.cmssuite.application.objects.Container
      15:29:47,843 ERROR [STDERR]     at com.sun.xml.bind.v2.runtime.IllegalAnnotation
      sException$Builder.check(IllegalAnnotationsException.java:102)
      15:29:47,843 ERROR [STDERR]     at com.sun.xml.bind.v2.runtime.JAXBContextImpl.g
      etTypeInfoSet(JAXBContextImpl.java:448)
      15:29:47,843 ERROR [STDERR]     at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<
      init>(JAXBContextImpl.java:297)
      15:29:47,843 ERROR [STDERR]     at com.sun.xml.bind.v2.ContextFactory.createCont
      ext(ContextFactory.java:139)
      15:29:47,843 ERROR [STDERR]     at com.sun.xml.bind.v2.ContextFactory.createCont
      ext(ContextFactory.java:117)
      15:29:47,843 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke0(
      Native Method)
      15:29:47,843 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke(N
      ativeMethodAccessorImpl.java:39)
      15:29:47,843 ERROR [STDERR]     at sun.reflect.DelegatingMethodAccessorImpl.invo
      ke(DelegatingMethodAccessorImpl.java:25)
      15:29:47,843 ERROR [STDERR]     at java.lang.reflect.Method.invoke(Method.java:5
      97)
      15:29:47,843 ERROR [STDERR]     at javax.xml.bind.ContextFinder.newInstance(Cont
      extFinder.java:214)
      15:29:47,843 ERROR [STDERR]     at javax.xml.bind.ContextFinder.find(ContextFind
      er.java:375)
      15:29:47,843 ERROR [STDERR]     at javax.xml.bind.JAXBContext.newInstance(JAXBCo
      ntext.java:574)
      15:29:47,843 ERROR [STDERR]     at javax.xml.bind.JAXBContext.newInstance(JAXBCo
      ntext.java:522)
      15:29:47,843 ERROR [STDERR]     at com.cmsapplication.utilities.Utilities.getXml
      Value(Utilities.java:409)
      15:29:47,843 ERROR [STDERR]     at com.cmssuite.beans.PageLayoutBean.processFunc
      tion(PageLayoutBean.java:396)
      15:29:47,843 ERROR [STDERR]     at org.apache.jsp.suite.process.templates.test1_
      jsp._jspService(test1_jsp.java:219)
      15:29:47,843 ERROR [STDERR]     at org.apache.jasper.runtime.HttpJspBase.service
      (HttpJspBase.java:70)
      15:29:47,843 ERROR [STDERR]     at javax.servlet.http.HttpServlet.service(HttpSe
      rvlet.java:803)
      15:29:47,843 ERROR [STDERR]     at org.apache.jasper.servlet.JspServletWrapper.s
      ervice(JspServletWrapper.java:369)
      15:29:47,843 ERROR [STDERR]     at org.apache.jasper.servlet.JspServlet.serviceJ
      spFile(JspServlet.java:322)
      15:29:47,843 ERROR [STDERR]     at org.apache.jasper.servlet.JspServlet.service(
      JspServlet.java:249)
      15:29:47,843 ERROR [STDERR]     at javax.servlet.http.HttpServlet.service(HttpSe
      rvlet.java:803)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterCha
      in.internalDoFilter(ApplicationFilterChain.java:290)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterCha
      in.doFilter(ApplicationFilterChain.java:206)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.filters.ReplyHeaderFilte
      r.doFilter(ReplyHeaderFilter.java:96)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterCha
      in.internalDoFilter(ApplicationFilterChain.java:235)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterCha
      in.doFilter(ApplicationFilterChain.java:206)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.StandardWrapperValve
      .invoke(StandardWrapperValve.java:235)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.StandardContextValve
      .invoke(StandardContextValve.java:191)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityAssocia
      tionValve.invoke(SecurityAssociationValve.java:190)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.security.JaccContextValv
      e.invoke(JaccContextValve.java:92)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityContext
      EstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityContext
      EstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.StandardHostValve.in
      voke(StandardHostValve.java:127)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.valves.ErrorReportValve.i
      nvoke(ErrorReportValve.java:102)
      15:29:47,843 ERROR [STDERR]     at org.jboss.web.tomcat.service.jca.CachedConnec
      tionValve.invoke(CachedConnectionValve.java:158)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.core.StandardEngineValve.
      invoke(StandardEngineValve.java:109)
      15:29:47,843 ERROR [STDERR]     at org.apache.catalina.connector.CoyoteAdapter.s
      ervice(CoyoteAdapter.java:330)
      15:29:47,843 ERROR [STDERR]     at org.apache.coyote.http11.Http11Processor.proc
      ess(Http11Processor.java:828)
      15:29:47,843 ERROR [STDERR]     at org.apache.coyote.http11.Http11Protocol$Http1
      1ConnectionHandler.process(Http11Protocol.java:601)
      15:29:47,843 ERROR [STDERR]     at org.apache.tomcat.util.net.JIoEndpoint$Worker
      .run(JIoEndpoint.java:447)
      15:29:47,843 ERROR [STDERR]     at java.lang.Thread.run(Thread.java:619)
      15:29:47,843 INFO  [STDOUT] Exception Jaxb Exception :::::::::1 counts of Illega
      lAnnotationExceptions
      
      //DATAOBJECT CLASS
      
      public abstract class DataObject
      {
              public DataObject()
              {
                  _returnObjectLists = new Hashtable();
                  _returnUpdateObjectLists = new Hashtable();
              }
      
              public DataObject(String _objType)
              {
                  _returnObjectLists = new Hashtable();
                  _returnUpdateObjectLists = new Hashtable();
                  this._objectType = _objType;
              }
      
              private String _objectType;
              public String getObjectType()
              {
                  return _objectType;
              }
              public void setObjectType(String oType)
              {
                  this._objectType = oType;
              }
      
              
              private Hashtable _returnObjectLists;
              public Hashtable getReturnObjectLists()
              {
                  return _returnObjectLists;
              }
              public void setReturnObjectLists(Hashtable rObjectLists)
              {
                  this._returnObjectLists = rObjectLists;
              }
      
              private Hashtable _returnUpdateObjectLists;
              public Hashtable getReturnUpdateObjectLists()
              {
                  return _returnUpdateObjectLists;
              }
              public void setReturnUpdateObjectLists(Hashtable rUpdateObjectLists)
              {
                  this._returnUpdateObjectLists = rUpdateObjectLists;
              }
      
      
              /*
               * Method to addObjectLists for single mode or group mode select processing
               */
              public void addObjectLists(String _keyValue, Object _iObject)
              {
                  if (_iObject != null)
                      this._returnObjectLists.put(_keyValue, _iObject);
              }
      
              /*
               * Method to add UpdateObjectLists for Insert, Update, Delete functionality
               */
              public void addUpdateObjectLists(String _keyValue, String type, Object _iObject)
              {
                  if ( _iObject != null)
                  {
                      Hashtable dataTypeValue = new Hashtable();
                      dataTypeValue.put(type, _iObject);
                      this._returnUpdateObjectLists.put(_keyValue, dataTypeValue);
                  }
              }
      
              /*
               * Abstract methods to be implemented by the subclasses.
               */
              public abstract void generateObjectLists();
              public abstract void generateUpdateObjectLists();
              public abstract ReturnObject validateObject();
      
              /*
               * Common Utiltiy methods used by the insert, update functionality
               */
              private String _status = null;
              public String getStatus()
              {
                  if (_status == null)
                      _status = "A";
      
                  if(_status.equals(""))
                      _status = "A";
                  
                  return _status;
              }
              public void setStatus(String status)
              {
                  this._status = status;
              }
      
      
              private int _createdBy = 0;
              public int getCreatedBy()
              {
                  if (_createdBy == 0)
                      _createdBy = 0; // Need to modify the code
      
                  return _createdBy;
              }
              public void setCreatedBy(int value)
              {
                  this._createdBy = value;
              }
      
              private int _updatedBy = 0;
              public int getUpdatedBy()
              {
                  if (_updatedBy == 0)
                      _updatedBy = 0; // Need to modify the code
      
                  return _updatedBy;
              }
              public void setUpdatedBy(int value)
              {
                  this._updatedBy = value;
              }
      
              private java.sql.Date _createdDate = null;
              public java.sql.Date getCreatedDate()
              {
                  if (_createdDate == null)
                  {
                      _createdDate = Utilities.getDatabaseDate();
                  }
                  
                  return _createdDate;
              }
              public void setCreatedDate(java.sql.Date cDate)
              {
                  this._createdDate = cDate;
              }
      
              private java.sql.Date _updatedDate = null;
              public java.sql.Date getUpdatedDate()
              {
                  if (_updatedDate == null)
                  {
                      _updatedDate = Utilities.getDatabaseDate();
                  }
      
                  return _updatedDate;
              }
              public void setUpdatedDate(java.sql.Date cDate)
              {
                  this._updatedDate = cDate;
              }
      
      
              public void setWhoColumns(HttpServletRequest request)
              {
                  //Setting the Created by column
                  LoginObject currentUser =(LoginObject)request.getSession().getAttribute(StaticDefinitions.USER_OBJECT);
                  if(request.getSession().getAttribute(StaticDefinitions.USER_OBJECT) != null)
                      this.setCreatedBy(currentUser.getUserID());
                  else
                      this.setCreatedBy( Integer.parseInt(StaticDefinitions.GLOBAL_STANDARD_USER_ID) );
      
                  //Setting the Created by column
                  if(request.getSession().getAttribute(StaticDefinitions.USER_OBJECT) != null)
                      this.setUpdatedBy(currentUser.getUserID());
                  else
                      this.setUpdatedBy( Integer.parseInt(StaticDefinitions.GLOBAL_STANDARD_USER_ID) );
      
                  //Setting the Created & Updated Date column
                  this.setCreatedDate( Utilities.getDatabaseDate() );
                  this.setUpdatedDate( Utilities.getDatabaseDate() );
                  System.out.println("Set Who Columns");
              }
      }

      Comment

      • antonioatt
        New Member
        • Oct 2011
        • 2

        #4
        It seems to me your problem is similar to that(except you have java.sql.Date instead of Timestamp):http://redrata.com/2009/04/resolving...t-constructor/

        Like in example above you must define a SQLDateAdapter this way:
        1) annotate method public java.sql.Date getCreatedDate( ) with:
        @XmlJavaTypeAda pter( SQLDateAdapter. class)
        2)Define your SQLDateAdapter:
        Code:
        public class SQLDateAdapter extends XmlAdapter<java.util.Date, java.sql.Date> {
              public java.util.Date marshal(java.sql.Date v) {
                  return new java.util.Date(v.getTime());
              }
              public java.sql.Date unmarshal(java.util.Date v) {
                  return new java.sql.Date(v.getTime())
              }
          }
        The problem is like says exception java.sql.Date does not have a no-arg default constructor.
        An alternative is define getCreatedData with return type java.util.Date (java.util.Date has costructor with no-args)

        Comment

        Working...