Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Monday, February 22, 2016

Java Example For Generating Xml Through Xpath


Generating Xml  Through Xpath

PROGRAM

import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.Iterator;
import java.util.Vector;
import javax.naming.directory.Attribute;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Example {
   public static void main(String[] args) throws Exception {
      try {
    DocumentBuilderFactory docFactory = null;
 
  Document doc = null;
  String xmlForDislay = null;
  Element rootElement = null;
    docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
rootElement = doc.createElement("student");
  System.out.println("rootElement"+rootElement );
  doc.appendChild(rootElement);
Element student = doc.createElement("studentlist");
rootElement.appendChild(student);
Element rollno = doc.createElement("roollno");
Element name= doc.createElement("name");
Element fname = doc.createElement("fname");
Element lname = doc.createElement("lname");

   rollno.appendChild(doc.createTextNode(""));
name.appendChild(doc.createTextNode(""));
fname.appendChild(doc.createTextNode(""));
lname.appendChild(doc.createTextNode("No Name"));

student.appendChild(rollno);
student.appendChild(name);
student.appendChild(fname);
student.appendChild(lname);

xmlForDislay = getDatafromDocument(doc);
   } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
   } catch (IOException e) {
   e.printStackTrace();
   }
   }

public static String getDatafromDocument(Document doc)throws Exception {
String MED =": getDatafromDocument()";
System.out.println(" called :");
String output =  null;
TransformerFactory tf = null;
Transformer transformer = null;
StringWriter writer = null;
try {
tf = TransformerFactory.newInstance();
transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
output = writer.getBuffer().toString().replaceAll("\n|\r", "");
System.out.println("output"+output);
}catch(Exception e ){
e.printStackTrace();
System.out.println("message"+e.getMessage());
}finally {
tf = null;
writer = null;
transformer = null;
}
return output;
}
}

Output:

rootElement [student: null]
 called :
output<?xml version="1.0" encoding="UTF-8"?><student><studentlist><roollno></roollno><name></name><fname></fname><lname>No Name</lname></studentlist></student>

Wednesday, November 18, 2015

Hibernate Versioning Concept

Hibernate Versioning Concept


Once an object is saved in a database, we can modify that object any number of times right, If we want to know how many no of times that an object is modified then we need to apply this versioning concept.
When ever we use versioning then hibernate inserts version number as zero, when ever object is saved for the first time in the database.  Later hibernate increments that version no by one automatically when ever a modification is done on that particular object.
In order to use this versioning concept, we need the following two changes in our application
  • Add one property of type int in our pojo class
  • In hibernate mapping file, add an element called version soon after id element
Files required to execute this program..
  • Product.java (My POJO class)
  • Product.hbm.xml  (Xml mapping file )
  • hibernate.cfg.xml  (Xml configuration file)
  • ClientForSave_1.java (java file to write our hibernate logic)
  • ClientForUpdate_2.java

Product.java

Product.hbm.xml

Note:
  • In this above mapping file, find the <version> element, there i have given column name as version, actually you can write any name its not predefined.

hibernate.cfg.xml



















<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>


ClientForSave_1.java


Note:
  • Remember friends, first we must run the logic to save the object then hibernate will inset 0 (Zero) by default in the version column of the database, its very important point in the interview point of view also
  • First save logic to let the hibernate to insert zero in the version column, then any number of update logic’s (programs) we run, hibernate will increments +1 to the previous value
  • But if we run the update logic for the first time, hibernate will not insert zero..! it will try to increment the previous value which is NULL in the database so we will get the exception.

ClientForUpdate_2.java

First run the ClientForSave_1.java, then only ClientForUpdate_2.java
&

Eclipse Output

In the database


Note(Important..!!!)______
Guys your know some thing.., actually we can run any logic (Save or Update) :-) for the first time, but make sure the versioning column is a number (>=0), but save logic has ability to insert zero by default if there is no value, and update logic will directly tries to increments already existing value by 1, it wont insert any value by default if its null, hope you are clear about this point, and mates its the very important concept in the interview point of view, if you have any doubt just Ask a Question on this our team will respond ASAP

Hibernate Update Query

Hibernate Update Query

This is the program to update an object (1 complete row) in the database, which is already persisted in the database, then we have the following two approaches…

Approach 1

Load that object from the database, and modify its values, now hibernate automatically modifies the values on to database also, when ever the transaction is committed.

Approach 2:

If we want to modify object in the database, then create new object with same id and we must call update() given by session interface.
Files required to execute this program..
  • Product.java (My POJO class)
  • product.hbm.xml (Xml mapping file )
  • hibernate.cfg.xml (Xml configuration file)
  • ClientProgram.java(java file to write our hibernate logic)

Related to approach 1:

Product.java (POJO)



Product.hbm.xml



hibernate.cfg.xml



ClientProgram.java (* Recommended way)


Notes:
  • See line number 20, actually there i tried to update Stno(105), we should not do this, because we have loaded the object from the database with his id number only, see line number 16, if we update hibernate will rises the exception
  • See line number 24 once we call the commit(), automatically update method will be called by hibernate.
  • When ever an object is loaded from the database then hibernate stores the loaded object in cache-memory maintained by session-interface
  • Once an object is loaded, if we do any modifications on that object by calling its setter methods, then these modification are stored in the object maintained by cache-memory
  • if we modify the loaded object for multiple times then also the modifications will be stored in object maintained by the cache-memory only.
  • when ever we issue commit() operation then hibernate verify whether any changes are there between the object stored in the cache and object in the database, if changes exists then hibernate automatically updates the database by generating any update operation.
  • What am saying is hibernate automatically maintains synchronization between cache-memory object and database table objects (rows)

Related to approach 2:



Oracle DB, Before Run The Program

Oracle DB, After Run the program

Notes:
  • From line number 17 to 19, we created new object and modified, and in line number 22 we are calling update method explicitly
  • Here we no need to load an object from the database
  • we will create a new object, and we will assign same id no’s to it and we will call update() explicitly in order to make the changes on the object that is stored in the database

That’s it, actually first approach is  recommended always..   :-)

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...