Results 1 to 3 of 3
  1. #1
    alexandra12 is offline Member
    Join Date
    Jul 2011
    Posts
    34
    Rep Power
    0

    Default Can someone please help me persist data to a database

    Can someone please help me persist data to a database-sax.pngHello,

    I am stuck and I am trying to work on this over the last couple of weeks and no matter what I do I am not able to get it to properly work.

    I am trying to persist data into a database via SaxParser and JPA. JPA is managed by an entity manager. I am not sure exactly where I should be putting the option to persist the data into the database. Depending on where I call the persist code - I either get null values for elements or I am getting multiple rows / duplicate rows of data. I basically want to load one object and it's element as 1 row in the database. So in the below xml document - 1 row will contain the object attributes, the label and the num. I also do not want the label's under the page element. I only want everything within the object elements opening and closing tags.

    Can anyone help ? I will provide the appropriate code below

    Java Code:
    <response result="ok">
    <page id="P1" status="comms">
    <label>Auto Refresh 1</label>
    <object id="P1O1" type="num" status="ok" updated="2012-08-20T23:48:12" logavailable="true">
    <label>B1</label>
    <num>1173171</num>
    </object>
    <object id="P1O2" type="num" status="ok" updated="2012-08-20T23:48:12" logavailable="true">
    <label>B3</label>
    <num>761415</num>
    </object></page>

    Here is the getters/setters [north]class code
    Java Code:
    @Entity
    @Table(name="north")
    public class north implements Serializable {
    	private static final long serialVersionUID = 1L;
    
    	//setting the default value for bool as null values is bringing back wrong data
    	@Column(length=10)
    	private String bool;
    
    	@Column(name="FLOAT")
    	private Float float_;
    
    	@Column(length=10)
    	@Id
    	private String id;
    
    	@Column(length=1)
    	private String label;
    	
    	//trying to set the nullable field to true to see if that helps with the empty element issue.
    	@Column(length=10, nullable = true)
    	private Double num;
    
    	@Column(length=10)
    	private String type;
    
    	//setting the default value for units as null values is bringing back wrong data
    	@Column(length=10)
    	private String units;
    	
    	@Column()
    	private Date updated;
    
        public north() {
        }
    
        public String getBool() {
    		return this.bool;
    	}
    
    	public void setBool(String bool) {
    		//setting the default value for BOOL as null values is bringing back wrong data
    		this.bool = bool;
    	
    	}
    
    	public Float getFloat_() {
    		return this.float_;
    	}
    
    	public void setFloat_(Float float_) {
    		this.float_ = float_== null ? 0 : float_;
    
    	}
    
    	public String getId() {
    		return this.id;
    	}
    
    	public void setId(String id) {
    	this.id = id==null ? null : id;
    		
    	}
    
    	public String getLabel() {
    		return this.label;
    	}
    
    	public void setLabel(String label) {
    		this.label = label==null ? null : label;
    		
    		
    	}
    
    	public Double getNum() {
    		return this.num;
    	
    	}
    
    	public void setNum(Double num) {
    	
    		//this.num = num == null ? 0.0 : num;
    		this.num = num == null ? Double.NaN : num;
    		
    	}
    
    	public String getType() {
    		return this.type;
    		
    	}
    
    	public void setType(String type) {
    		this.type = type==null ? null : type;
    		
    		
    	}
    
    	public String getUnits() {
    		return this.units;
    	}
    
    	public void setUnits(String units) {
    		//setting the default value for units as null values is bringing back wrong data
    		this.units = units==null ? null : units;
    		
    	}
    
    	public Date getUpdated() {
    		return this.updated;
    	}
    
    	public void setUpdated(Date updated) {
    		
    		this.updated = updated;
    		
    	}
    Here is the managed entity manager
    Java Code:
    @Action(Action.ACTION_TYPE.CREATE)
    	public String createnorth(North north)
    			throws Exception {
    		System.out.println("begining the transaction");
    		EntityManager em = getEntityManager();
    		
    		try {
    			
    			em.getTransaction().begin();
    			
    			em.persist(northRawData);
    			
    			em.getTransaction().commit();
    			
    			
    		} catch (Exception ex) {
    			try {
    				if (em.getTransaction().isActive()) {
    					em.getTransaction().rollback();
    				}
    			} catch (Exception e) {
    				ex.printStackTrace();
    				throw e;
    			}
    			throw ex;
    		} finally {
    			em.close();
    		}
    		return "";

    Here is the class file
    Java Code:
    public class north extends DefaultHandler {
    
    
    		private boolean inObject=false;
    		String elementName;
    		String tmpString;	
    		Date tmpTime;
    		StringBuffer textBuffer;
    		north Tmp;
    		saxParser saxParser;
    		static ErrorHandler ErrorHandler;
    		Toolkit toolkit;
    		Socket clientSocket;
    		float tmpFloat;
    		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		EntityManagerFactory entityManagerFactory;
    		NorthRawManager manager=null;
    		
    		
    	    	public northCommander() throws Exception{
    	    		
    			clientSocket = new Socket("localhost", 80);
    	 		Authenticator.setDefault(new MyAuthenticator());
    	 		this.entityManagerFactory =  Persistence.createEntityManagerFactory("Sax");
        		this.manager = new NorthManager(entityManagerFactory);
        		
        		
    			Tmp = new north();
    			
        		
    	    	}
    	   
    	   //this helps to tell where in the parsing the document is 	
    	    public void setDocumentLocator(Locator locator) {
    	    		System.out.println(" * setDocumentLocator() called");
    	    		// We save this for later use if desired.
    	    		Locator Locator = locator;
    	    		System.out.println(Locator.getLineNumber());
    	    		}
    	    	
    	    public void startDocument(){
    	    	
    	    
    	    	
    	    }
    	    	
    	    public void endDocument(){
    	    
    		}
    		
    	    	
    		public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
    		
    		
    		
    		
    		inObject=true;
    		
    		elementName=qName;
    		
    	
    		if(qName.equalsIgnoreCase("object")&&("ok".equalsIgnoreCase(attributes.getValue("status")))){
    			
    			
    			
    			
    				Tmp.setId(attributes.getValue("id"));
    				Tmp.setType(attributes.getValue("type"));
    				
    		/*		try {
    					Tmp.setUpdated(sdf.parse("updated"));
    				} catch (ParseException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				
    				*/
    				
        	} 
    	
    	
    			 
    	}
    
    		
    		
    
    		/*
    
    		
    	@Override
    		public void endElement(String uri, String localName,String qName) throws SAXException {
    		
    	
    		
    		inObject=false;
    	
    		
    		
    		
    		if(localName.equalsIgnoreCase("label")){
    			System.out.println("qname is " + qName);
    			System.out.println("localName is " + localName);
    			Tmp.setLabel(String.valueOf(tmpString));
    					}
    			
    		else if(localName.equalsIgnoreCase("num")){
    			Tmp.setNum(Double.valueOf(tmpString).doubleValue());
    			}
    			
    		else if(localName.equalsIgnoreCase("float")){
    			Tmp.setFloat_(Float.valueOf(tmpString).floatValue());
    			}
    		
    		else if(localName.equalsIgnoreCase("bool")){
    			Tmp.setBool(String.valueOf(tmpString));	
    		    	}
    		
    		else if(localName.equalsIgnoreCase("units")){
    			Tmp.setUnits(String.valueOf(tmpString));
    			
        	}
    		
    				
    		
    	try {
    			manager.createNorth(Tmp);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	
    			
    		
    	}
    		
    		
    	 
    	 @Override
    	 //this only prints out element values, it does not print out attr values
    		public void characters(char []ch, int start, int length) throws SAXException {
    		
    		 if(inObject){
    			 
    					
    		tmpString = new String(ch, start, length);
    	//	System.out.println(tmpString);
    			inObject=false;
    				
    			
    			
    		}
    	 }
    
    	
    	 	
    		
    		
    		 
    		public static void main(String[] args) throws Exception {
    		
    			URL aURL = null;
    			try {
    				aURL = new URL("httpURL");
    			} catch (MalformedURLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		    
    		    
    		//reading in the data from the url directly into the console to see all results returned
    			
    			new BufferedReader(
    			  new InputStreamReader((aURL.openStream())));
    			           
    			        /* Get a SAXParser from the SAXPArserFactory. */
    		            SAXParserFactory spf = SAXParserFactory.newInstance();
    		            try{
    		            //getting a new instance of parser
    		            SAXParser saxParser = spf.newSAXParser();
    //		          
    
    		            /* Get the XMLReader of the SAXParser we created. */
    		            XMLReader XMLReader = saxParser.getXMLReader();
    		           //setting the content handler              
    		            XMLReader.setContentHandler(new northCommander());
    		            XMLReader.setErrorHandler(ErrorHandler);
    		            XMLReader.parse(new InputSource(aURL.openStream()));
    		            
    		            
    		      
    		            //implementing error handler as I am getting errors on empty elements
    		            }catch (Throwable err){
    		            	err.printStackTrace();
    		            	 //closing the socket, so that it does not constantly remain open
    		            	
    		            }
    		            
    		     
    	                
    		}
    		
    		
    		}
    Please excuse any classes that are not named correctly. I have modified some of the names or personal purposes.
    Last edited by alexandra12; 08-21-2012 at 03:12 AM.

  2. #2
    alexandra12 is offline Member
    Join Date
    Jul 2011
    Posts
    34
    Rep Power
    0

    Default Re: Can someone please help me persist data to a database

    Anyone ?

  3. #3
    alexandra12 is offline Member
    Join Date
    Jul 2011
    Posts
    34
    Rep Power
    0

    Default Re: Can someone please help me persist data to a database

    I got this resolved !

Similar Threads

  1. Persist Emails in database using James
    By kumar11 in forum Apache Commons
    Replies: 0
    Last Post: 06-27-2012, 09:26 AM
  2. Persist data
    By eclectica in forum Spring
    Replies: 6
    Last Post: 06-19-2012, 12:01 PM
  3. Replies: 0
    Last Post: 02-14-2011, 03:24 PM
  4. Not able to data into database
    By nash1990 in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 08-11-2010, 05:01 PM
  5. data between dates in database.
    By mkkrkiran in forum New To Java
    Replies: 1
    Last Post: 09-22-2009, 10:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •