Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Monday, December 29, 2014

Explain about System.out.println()

System.out.println()

System is a final class available in java.lang package. It is a system related class and most of times make native calls.

Structure of System class:

public final class System {

public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;

private System() {

}

   public static void setIn(InputStream in) {
      
checkIO();
      
setIn0(in);
   }


  public static void setOut(PrintStream out) {
   
checkIO();
 setOut0(out);
}

   public static void exit(int status) {
      
Runtime.getRuntime().exit(status);
 
}

   public static void gc() {
      
Runtime.getRuntime().gc();
 
}
}

In the above System class, both err and out are instances of PrintStream class (java.io.PrintStream). System class has setters for all the three mentioned above but no getters. InputStream is again from java.io package.

out is a static field in a System class which is of type PrintStream ( a built in class available in java.io package, which contains several methods to print the different data values). In order to acess any static methods or static members we are using class name. So System.out

Structure of PrintStream:

public class PrintStream extends FilterOutputStream implements Appendable, Closeable {
  public PrntStream(OutputStream out) {    
       this(out, false);
  
}

    // Different arguments with print() and println() methods
      public void print() {
       
  
}
    
 public void println() {
       
  
}

    // printf() and format() methods

}

println - is a method of PrintStream class. println method prints the arguments passed to standard console and a new line. There are several print() and println() methods with different arguments. Every println() method makes a call to print() method and adds newline.



System is class in java.lang package and out is the instance of PrintStream class from java.io package and println() is a method from the PrintStream class.

Compiling and Running Java program by using another Java program.



package com.ranga;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
Program: Compiling and Running Java program by using another Java program.
java.lang.Runtime.exec()
*/
public class Main {
public static void main(String[] args) {
System.out.println("I am in Main class begin.");
Process process = null;
try {
process = Runtime.getRuntime().exec("javac Test.java");
System.out.println("Test class successfully compiled.");
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}

try {
process = Runtime.getRuntime().exec("java Test");
printMessage(" stdout:", process.getInputStream());
System.out.println("Test class successfully runned.");
} catch (IOException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("I am in Main class end.");
} // end main()

private static void printMessage(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
} // end printMessage()
} // end Main class



class Test {
public static void main(String a[]) {
System.out.println("I am in Test class");
}
}

Sunday, December 28, 2014

Different ways to get the Connection object using Hibernate

Getting the java.sql.Connection object using Session:
---------------------------------------------------------------------------

org.hibernate.Session is nothing but get the one physical connection from the database. 

By using Session we can get the Connection object several ways.

1) session.connection() - this method is deprecated. it is not available on Hibernate4.

2) session.doWork() - this method doesn't return Connection object, but inside what ever operation we want to do using connection object we can do. 

3) session.doReturningWork() - this method returns dynamic type value. In the below example i am return Connection object. 

4) SessionImpl.connection() - Down casting the Session object to SessionImpl. By using SessionImpl we will get the Connection object.

5) ConnectionProvider.getConnection() - Using ConnectionProvider getConnection() method.


Full Example:

package com.varasofttech.client;

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.SessionImpl;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;

import com.varasofttech.util.HibernateUtil;

public class Application {

public static void main(String[] args) {

// Different ways to get the Connection object using Session

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

// Way1 - using doWork method
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do your work using connection
}

});

// Way2 - using doReturningWork method
Connection connection = session.doReturningWork(new ReturningWork<Connection>() {
@Override
public Connection execute(Connection conn) throws SQLException {
return conn;
}
});

// Way3 - using Session Impl
SessionImpl sessionImpl = (SessionImpl) session;
connection = sessionImpl.connection();
// do your work using connection

// Way4 - using connection provider
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
try {
connection = connectionProvider.getConnection();
// do your work using connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}


How to Create Custom Dialect class in Hibernate?

Creating a Custom Dialect in Hibernate:

In order to create any new Dialect class we need to extends org.hibernate.dialect.Dialect class. Dialect class is a abstract class.

If you look at the Dialect class,

public abstract class Dialect implements ConversionContext {
protected Dialect() {
// here we are registering the functions, ColumnType, HibernateTypes
// for registering function's we can use registerFunction() method.
// for registering columntype's we can use registerColumnType() method.
// for registering hibernatetype's we can use registerHibernateType() method.
}
// some others methods
}

For connecting MySQL database, Hibernate people created a dialect class called 'org.hibernate.dialect.MySQLDialect'.

public class MySQLDialect extends MySQLDialect {
      public MySQLDialect() {
  // here they resisted mysql functions, column types
}
// some other methods
}

In the same way, in order to connect with Oracle database, hibernate people developed a 5 dialect classes based on Oracle Version.

org.hibernate.dialect.OracleDialect
org.hibernate.dialect.Oracle8iDialect
org.hibernate.dialect.Oracle9Dialect
org.hibernate.dialect.Oracle9iDialect
org.hibernate.dialect.Oracle10gDialect

if you see the OracleDialect class signature

public class OracleDialect extends Oracle9Dialect {
public OracleDialect() {
// here they resisted oracle functions, column types
}
}

Now we can see how to create Custom Dialect classes.

My requirement is, based on current time, i want to display greeting message say for example if time is 10:01:59 AM then i need to display "Morning" other time is 14:12:15 PM then i need to display "Afternoon". So for this one there is no function exists in any database. 

so for this one what i did is, i created one function in mysql database i.e say_gretting and i am using that function. In order to use that function i need to one new class and extends MySQLDialect class. Finally i need to register say_greeting function in Custom dialect class.

package com.varasofttech.dialect;

import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;

public class VaraSoftTechMySQLDialect extends MySQL5Dialect {
public VaraSoftTechMySQLDialect() {
super();
// here i am registring custom function to display greeting message.
registerFunction("say_greeting", new StandardSQLFunction("say_greeting"));
}
}

Finally this dialect class, we need to register in hiberante.cfg.xml file.


<!-- Dialect class -->
<property name="hibernate.dialect">com.varasofttech.dialect.VaraSoftTechMySQLDialect</property>

Now lets see how to create 'say_greeting' function in mysql.


DROP FUNCTION IF EXISTS say_greeting;
DELIMITER $$
CREATE FUNCTION say_greeting(name TEXT)
RETURNS TEXT
BEGIN
DECLARE greetingMessage CHAR(10);
SET greetingMessage = (SELECT IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 12,'Morning', IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 15,'Afternoon','Evening')));
RETURN CONCAT('Hello ', name, ', Good ', greetingMessage, '!');
END;
$$
DELIMITER ;

SELECT say_greeting('ranga') from DUAL;

Now write client application in order to use say_greeting function. Here i am using NativeSQLQuery.


        Configuration configuration = new Configuration();
configuration.configure(
"hibernate.cfg.xml");

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();


SQLQuery query = session.createSQLQuery("SELECT say_greeting('ranga') from DUAL");

String greetingMessage = (String) query.list().get(0);
System.out.println(greetingMessage);

session.close();

sessionFactory.close();

Output:

Dec 29, 2014 6:45:09 AM org.hibernate.dialect.Dialect <init>

INFO: HHH000400: Using dialect: com.varasofttech.dialect.VaraSoftTechMySQLDialect

Hibernate: 
    SELECT
        say_greeting('ranga') 
    from

        DUAL

Hello ranga, Good Evening!

Reference:
http://myjourneyonjava.blogspot.in/2014/12/displaying-greeting-message-based-on.html

Happy Coding!!!!

Displaying the Greeting Message based on Time in MySQL


Hi, My requirement is based on Current time i want to display Greeting message.

For example, if time is less than 12PM then i need to display "Morning" and if time is less than 5PM then i need to display "Afternoon" and if time is above 5 PM i need to display "Evening".

Step1: Selecting the Current time.
SELECT now() from DUAL;
Output:
 '2014-12-28 17:35:46'

Step2: In the Current time getting the hours.
SELECT TIME_FORMAT(now(),'%H') from DUAL;
Output: 
17

Step3: Now based on hours we need to display greeting message. So we need to use if condition.
SELECT IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 12,'Morning', IF((SELECT TIME_FORMAT(now(), 
'%H') from DUAL) < 17,'Afternoon','Evening'));
Output:
'Evening'

Happy coding!