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.

Sunday, July 28, 2013

Steps to install Tortoise svn plug-in for Eclipse

In this post, we are going to see how to install tortoise svn plugin for eclipse.

Steps to install Tortoise plug-in for Eclipse:

Requirement:

  1. JDK 1.5 or later
  2. Tortoise SVN [Download]
  3. Eclipse 3.x
Steps:
Install:
1.       Open Eclipse IDE.
2.       Open  plug-in folder.[ex: D:\eclipse-jee-juno\eclipse\plugins]
3.       Download and extract the plugin file.[download]
4.       Copy the "tortoisePlugin_1.0.9" folder into ": D:\eclipse-jee-juno\eclipse\plugins" folder.
Configure:
Open Eclipse IDEàWindows Ã  preferencesàtortoise
 
Path:                          C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe
SVNServer:                server URL
Shared Root folder: Folder created in local machine.
Reference:

Read and Display the Properties from a Properties File

In this post, we are going to see how to read a properties from a Properties file.

Project Structure:
=======================================================
ReadingProperties
  Src
       com.ranga
          ReadProperties.java
          login.properties
=======================================================

ReadProperties.java
package com.ranga;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class ReadProperties {
public static void main(String[] args) {
InputStream inputStream = null;
Properties properties = new Properties();
try {
inputStream = new FileInputStream("login.properties");
properties.load(inputStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("=========================================");
System.out.println("username: " + username + " : password: " + password);
System.out.println("=========================================");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
login.properties
=====================
username=ranga
password=reddy

Output:
=========================================
username: ranga : password: reddy
=========================================

Reading both Key and Values:
            // Reading the both key and values
Enumeration props = properties.propertyNames();
while (props.hasMoreElements()) {
String key = (String) props.nextElement();
String value = properties.getProperty(key);
System.out.println("Key: " + key + ", Value: " + value);
}

Saturday, July 27, 2013

10 Ways to Boost Up Your Coding Productivity with Eclipse

10 Ways to Boost Up Your Coding Productivity with Eclipse

1. Find

Human eyes can't be trusted, and prone to errors. To search strings always use the FIND feature.


In eclipse, this feature is even so powerful. Here what we can do in Eclipse:
  • search in the entire workspace, workset, project, or selected resources
  • search with regular expression
  • search within files with a defined pattern
2. Find and Replace

Imagine that you have to edit texts in some files at once with the same patterns. Eclipse provide a preview so you can first check whether all replacements are correct or not before doing it.

And there's the special feature which you might need:

use replace magic{1}Old with maggie{1}New
To replace something like:
magicLinesOld to maggieLinesNew,
magicHouseOld to maggieHouseNew
magicShoesOld to maggieShoesNew
magic{*}Old to to maggie{*}New




3. Code Highlighting

This feature can help to efficiently read the code. If you want to know in which lines the object is being used, just put the cursor on the object, and then every occurence of it will be highlighted.


4. Refactoring

With this feature, you can do these things with some clicks only:
  • rename an object, a class, a variable, or a field.
  • extract a literal string to a constant field.
  • change method's name and parameters.
  • move a method or a field.
  • etc



5. Generate Getters and Setters

Actually there are more generators, but this one is the one I use most of the time. This will be very helpful to create POJO.




6. Formatting

Pretend that you typed some lines of code like this:



Will you arrange that code manually? No!! Just press the shortcut for formatting, usually CTRL + Shift + F, and voila here what you got:

7. Compare

What is so good with Eclipse's file comparer is that:
  • You can compare it by left-right side.
  • You can show next or previous difference.
  • On the right side of the scrollbar there is a clickable link to every differences.
  • There is a menu to copy current or all change(s) from right to left or vice versa.


8. The Warning Icons

Your brain is not designed to be a code compiler, so stop using it to check syntax !!
What's nice about Eclipse is that it even provide warning for ugly codes. If you see some yellow lines on the source editor, it's not a decoration. It means that your code is ugly. Here are some things that can make the code ugly:
  • Local variable is never read, so why keep it ?
  • A serializable class does not declare a static final serialVersionUID field.
  • The imported class is never used, so why keep it? There is also a feature to organize imports, so you don't have to take care of importing classes at all.
  • Used a deprecated method / class.
  • Using raw types of objects which should be parameterized such as: List, Set, Comparator, Class, etc.
  • etc.


9. Local History

"But it worked a few hours ago", you said. With Eclipse, every saving of every files are being logged, so you can show the entire history of a file, and then compare, or rollback to the previous saved version. Amazing isn't it ??



10. The Integrated CVS / SVN Client

There is no other CVS /SVN client I could find which is such rich of features and luckily, it's integrated to the IDE !!

With Eclipse' CVS / SVN client you can:
  • Show the history of 1 file, CVS / SVN history and local history (read number 9).
  • Show the history of 1 project (SVN client only).
  • Compare current version with another tagged version. Or with SVN much better, with every commited version, because every commit will be assigned with a incremented version number.
  • Show all of the tags which are existed within a CVS repository.
  • Synchronize the source code with a less painful way

Source: http://www.glomelurus.com/

Saturday, July 20, 2013

org.apache.ibatis.exceptions.TooManyResultsException:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2

Example is : while fetching by name, name founds in two times.

ID          NAME                           DESCRIPTION

1            Test                              Test Desc...
2            Test                              Test Desc1...

How Connect to Oracle when you forgot your Password

Reset Oracle Password
 
Step1: Open SQL Command Line  and enter the following command:

SQL> conn sys/manager as sysdba;
Connected.

Step2: To reset the password of the SYSTEM password (or any other user password), run the following query:
 
SQL> alter user sys identified by manager;
User altered.

Or

Your password file should be under <orahome>\database\PWD<SID>.ora.

Delete it and run the Oracle password utility from the command prompt:

c\:Oracle\ora92\database>ORAPWD file=PWD<SID>.ora password={password} entries={however many}.

The <password> is your new sys password. After you log in as sys you can change it and create new passwords for system.

Friday, July 19, 2013

Singleton Design Pattern Example Program in Java


Definition:
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Implementation:


1. Private static variable of the same class that is the only instance of the class. 
2. Private constructor to restrict instantiation of the class from other classes. 
3. Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

/**
 * Singleton Program
 * @author Ranga Reddy
 * @date 19-Jul-2013
 *
 */

// Singleton.java

package com.ranga;

public class Singleton {
  // private static member
  private static Singleton singleton= null;

  // private constructor
  private Singleton() {

  }
  // public static method
  public static Singleton getSingletonInstance() {
    if(singleton == null){
      synchronized (Singleton.class) {
         if(singleton == null)
            singleton = new Singleton();
      }
    }
    return singleton;
  }
}
SingletonDemo.java

package com.ranga;

public class SingletonDemo {
  public static void main(String[] args) {
       Singleton singleton3 = Singleton.getSingletonInstance();
       Singleton singleton4 = Singleton.getSingletonInstance();
       if(singleton3 == singleton4){
          System.out.println("Single Instance");
       } else {
          System.out.println("Two Instances");
       }

  }
}

Output:
Single Instance
 
Some of the examples we can use in our applications.

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.


Wednesday, July 17, 2013

CRUD operations using JDBC

CRUD(Create, Read, Update and Delete)

operations using JDBC

===============================================

CRUD stands for Create, Read, Update, Delete.
Student Table
 
CREATE TABLE STUDENT(StudentID NUMBER PRIMARY KEY, StudentName VARCHAR2(30), Age NUMBER(3));


Create Statement: 
INSERT INTO STUDENT(StudentID, StudentName, Age) VALUES(1, 'Ranga', 24);
READ Statement:
SELECT * FROM STUDENT WHERE StudentID = 1;
UPDATE Statement:
UPDATE STUDENT SET StudentName='RangaReddy', Age=25 WHERE StudentID =1
DELETE Statement:
DELETE FROM STUDENT WHERE StudentID = 1
Generating the Primary Key Values
In Oracle, by using Sequence we can generate the Automatic Primary key values

Creating a Sequence:
CREATE SEQUENCE Student_Id_Seq START WITH 1 INCREMENT BY 1;
By using sequence, insert the Student data
INSERT INTO STUDENT(StudentID, StudentName, Age) VALUES(Student_Id_Seq.nextval, 'Ranga', 25);

We can also get the Primary key values by using Max() function
int studentID = "SELECT MAX(STUDENTID) FROM STUDENT";
then adding 1 to the studentID
finally the studentID is "SELECT MAX(STUDENTID) FROM STUDENT" + 1
============================================================================================ 
Now we can see the CRUD operations by using JDBC 

Student.java
=================================================
package com.ranga;

import java.io.Serializable;

@SuppressWarnings("serial")
public class Student implements Serializable {
    private long studentId;
    private String studentName;
    private int age;
      
    public Student(long studentId, String studentName, int age) {
        super();
        this.studentId = studentId;
        this.studentName = studentName;
        this.age = age;
    }
    public Student() {
        super();
    }
    public long getStudentId() {
        return studentId;
    }
    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName="
                + studentName + ", age=" + age + "]";
    }  
}

-----------------------------------------------------------------------------------------------------------------------------------
DBUtil.java
 ==================================================
package com.ranga;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    private static Connection con;
    private static String username ="ranga";
    private static String password = "ranga";
    private static String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private static String driverClass = "oracle.jdbc.driver.OracleDriver";
   
    static {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
   
    public static Connection getConnection() throws SQLException{                            
        return con = DriverManager.getConnection(url, username, password);
    }

    public static void beginTransaction(){
        if(con!=null){
            try {
                con.setAutoCommit(false);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void commit(){
        if(con!=null){
            try {
                con.commit();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void rollback(){
        if(con!=null){
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void closeDBUtil(ResultSet rs, Statement stmt, Connection con){
        try {
            if(rs!=null) {
                rs.close();
                rs =null;
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
       
        try {
            if(stmt!=null) {
                stmt.close();
                stmt =null;
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
       
        try {
            if(con!=null) {
                con.close();
                con =null;
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
       
    }    
}
--------------------------------------------------------------------------------------------------------------------------------

App1.java
=================================================

package com.ranga;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ranga
 * @date 16-Jul-2013
 */

public class App1 {
    public static void main(String args[]) throws Exception {
        // Creating a Student object and setting the values
        Student st = new Student();
        st.setStudentName("Ranga");
        st.setAge(20);
        // inserting Student object and getting the studentId
        long studentId = createStudent(st);
        // fetching the Student object by using studentId
        Student student = getStudent(studentId);
        // displaying student data before update
        System.out.println("Before Update : " + student.toString());
        // updating the student object values
        student.setStudentName("RangaReddy");
        student.setAge(25);
        // updating the modified student
        updateStudent(student);
        student = getStudent(studentId);
        // displaying the updated data
        System.out.println("After Update : " + student);
        // deleting the student
        deleteStudent(studentId);
    }

    private static void deleteStudent(long studentId) throws SQLException {
        Connection con = DBUtil.getConnection();
        String sql = "DELETE FROM STUDENT WHERE StudentID = ?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setLong(1, studentId);
        DBUtil.beginTransaction();
        int res = pstmt.executeUpdate();
        if (res != 0) {
            DBUtil.commit();
        } else {
            DBUtil.rollback();
        }
        DBUtil.closeDBUtil(null, pstmt, con);
    }

    private static void updateStudent(Student stu) throws SQLException {
        String sql = "UPDATE STUDENT SET StudentName=?, Age=? WHERE StudentID =?";
        Connection con = DBUtil.getConnection();
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, stu.getStudentName());
        pstmt.setInt(2, stu.getAge());
        pstmt.setLong(3, stu.getStudentId());
        DBUtil.beginTransaction();
        int result = pstmt.executeUpdate();
        if (result != 0) {
            DBUtil.commit();
        } else {
            DBUtil.rollback();
        }
        DBUtil.closeDBUtil(null, pstmt, con);
    }

    private static Student getStudent(long studentId) throws SQLException {
        String sql = "SELECT * FROM STUDENT WHERE StudentID = " + studentId;
        Connection con = DBUtil.getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        DBUtil.beginTransaction();
        Student student = null;
        if (rs.next()) {
            student = new Student();
            student.setStudentId(rs.getLong(1));
            student.setStudentName(rs.getString(2));
            student.setAge(rs.getInt(3));
            DBUtil.commit();
        } else {
            DBUtil.rollback();
        }
        DBUtil.closeDBUtil(rs, stmt, con);
        return student;
    }

    private static long createStudent(Student stu) throws Exception {
        long studentId = generateStudentId() + 1;
        String sql = "INSERT INTO STUDENT(StudentID, StudentName, Age) VALUES(?, ?, ?)";
        Connection con = DBUtil.getConnection();
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setLong(1, studentId);
        pstmt.setString(2, stu.getStudentName());
        pstmt.setInt(3, stu.getAge());
        DBUtil.beginTransaction();
        int result = pstmt.executeUpdate();
        if (result != 0) {
            DBUtil.commit();
        } else {
            DBUtil.rollback();
        }
        DBUtil.closeDBUtil(null, pstmt, con);
        return studentId;
    }

    private static long generateStudentId() {
        String query = "SELECT MAX(StudentID) from STUDENT";
        Connection con = null;
        Statement stmt = null;
        long res = 0;
        try {
            con = DBUtil.getConnection();
            stmt = con.createStatement();
            res = stmt.executeUpdate(query);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        DBUtil.closeDBUtil(null, stmt, con);
        return res;
    }
}
---------------------------------------------------------------------------------------------------------------------------
Output:

Before Update : Student [studentId=2, studentName=Ranga, age=20]
After Update : Student [studentId=2, studentName=RangaReddy, age=25]

Download 

Sunday, July 14, 2013

Write a Program to find the longest palindrome in a given String

Write a Program to find the longest palindrome in a given String

Program:
Output:
String: HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE
Longest Palindrome: 12345678987654321

Saturday, July 13, 2013

If given a 15 digit number whats the best way to find the next palindrome?

If given a 15 digit number what is the best way to find the next palindrome? for example what will be the next palindrome of: 134567329807541?

Algorithm:

Step1: Split the number into three parts, head, mid, tail

number = 134567329807541
count = no. of characters = 15
head = number.substring(0, count / 2) = number.substring(0,7) = 1345673
mid = number.substring((count / 2), (count / 2) + 1) = number.substring(7,8) = 2
tail = number.substring((count / 2) + 1) = number.substring(8) = 9807541

head   mid        tail
1345673     2                   9807541
Step2: Reverse head and compare it to tail 3765431
  • If reverse(head) <= tail ( if they are equal the initial input is a palindrome, and you want the next )
    • If mid < 9, increment mid
    • Else increment head part and set mid := 0
     
reverseHead = rev(head) = 3765431
if(reverseHead == tail) {
           if (m <= 9) {
                m++;
            } else {
                m = 0;
                h = h + 1;
            }
}

Step3: Result is head mid reverse(head). 
result = head + mid + rev(head)
           = 1345673+ 3 + reverseHead 
           = 134567333765431

Wednesday, July 10, 2013

Reset forgotten Linux Root Password

Reset forgotten Linux Root Password

Reset forgotten Linux Root Password
Reset forgotten Linux Root Password
Reset forgotten Linux Root Password

How to Setup DNS Server in Linux

 How to Setup DNS Server in Linux


Click Here

Saturday, July 6, 2013

Ten Technologies Every Java Developer Should Know

  1. At least one MVC Framework like JSF, Struts, or Spring MVC
  2. Hibernate or JPA
  3. Dependency Injection (as demonstrated in Spring or Java EE through @Resource)
  4. SOAP based Web Services (JAX-WS)
  5. Some build tool (Ant, Maven, etc.)
  6. JUnit (or other Unit Testing framework)
  7. Version control
  8. JSTL
  9. Application server/container configuration management and application deployment (whether it is WebSphere, Tomcat, JBoss, etc. you need to know where your application runs and how to improve its execution).
  10. AJAX