How to compile Freestyle/Simple Java Project in Jenkins?

Jenkins Freestyle Project Logo

We were testing certain features of Jenkins. We were trying to set-up simple Java Project with ANT. There ain't any simple article available over Internet and it took hours to set-up so I thought let me share my experience with you.

Step 1: Create Simple Java Project using Eclipse.

Step 2: Open Jenkins and Click "New Item", Provide Job name, Select "Freestyle Project" and Click OK to create new Jenkins Job. Follow the image.



Step 3: On next page click on "Advance" under Advanced Project Options. Follow the image.



Step 4: Select "Use custom workspace" and Provide Directory path and Display name. Follow the image.



Step 5: Under Build section select "Ant Version". Target is name of <target> tag in build.xml. You can choose it as per you convenient but it should be same in build.xml and here in Jenkins. Follow the image.



Step 6: Click on "Advanced" under Build section and write "Build File" name commonly used build.xml. Follow the image.



Step 7: Click on "Apply"

Step 8: Create "build.xml" under root directory of your project. Follow the image.


Step 9: Copy paste the following content in your build.xml. Change Project name and default value (*if applicable)
<?xml version="1.0" encoding="UTF-8"?>
<project name="JenkinsSampleProject" default="compile" basedir=".">
 <!-- ANT will start execution from here by finding target "compile"  -->
 <target name="compile" depends="clean">
  <!-- Java compile parameters here  -->
  <javac debug="true" debuglevel="lines,vars,source" srcdir="src" destdir="bin" />
 </target>

 <!-- "compile" target depends on "clean" so It'll delete "bin" folder if exists and 
   create new "bin" folder for compiles class file -->
 <target name="clean">
  <delete dir="bin" />
  <mkdir dir="bin" />
 </target>
</project>

Step 10: Go to Jenkins and click on "Build Now"


Unknown Source in Exception or Stacktrace of Java

Unknown Source in Exception or Stacktrace of Java

Its very rare situation when you face this issue in Java Programming. Possibly there are very few people have seen this error. This exception occur when you compile your Java code with no "debugging information" flag.

Why such provision in Java?
This option given by Java to prevent hacking. When you compile your code "without debugging information" then it won't show line number in exception instead it shows "Unknown Source".


Solution For any Integrated Development Environment (IDE)
I've not tested this setting with any IDE but find the code compilation settings in your IDE and set flag as per your requirement.

-g ~ This will compile code with debugging information [Shows line number in exception]
-g:none ~ This will compile code without debugging information [Won't show line number/Unknown Source]


Source Code
/**
 * ------------------------------------------
 * This will shows line number in exception
 * ------------------------------------------
 * javac -g UnknownSourceExample.java 
 * java UnknownSourceExample
 * 
 * ------------------------------------------
 * This won't shows line number in exception
 * ------------------------------------------
 * javac -g:none UnknownSourceExample.java 
 * java UnknownSourceExample
 */
public class UnknownSourceExample{
 public static void main(String args[]){
  System.out.println(10/0);
 }
}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at UnknownSourceExample.main(UnknownSourceExample.java:3)
------------------------------------------  
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at UnknownSourceExample.main(Unknown Source)

Jenkins / ANT Compilation
We've just setup Jenkins for scheduled war compilation and on exception we face UnknownSource issue. We are still in learning phase and didn't know that we've to set debug attribute in build.xml of ANT. If you are also facing same issue then here is the solution that may help you.

Find code compilation tag <javac> in your build.xml, add debug and debuglevel attribute in it and now build your project through Jenkins so it'll show line number in exception instead Unknown Source. Your tag will look like as follow...
<javac debug="true" debuglevel="lines,vars,source" destdir="bin" srcdir="src"/>

Hibernate Disjunction with Example

Hibernate Disjunction with Example

Hibernate Disjunction, is used to add multiple condition in SQL query separated by OR clause within brackets. To generate following query using Hibernate Criteria we need to use Disjunction.

Query
select
 this_.id as id0_0_,
 this_.username as username0_0_,
 this_.email as email0_0_ 
from
 user_master this_ 
where
(
 this_.username=? 
 or this_.username=?
)

Source Code
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate Conjunction with Example
 * @author javaQuery
 */
public class HibernateDisjunctionExample {

    public static void main(String[] args) {
 /* Create hibernate configuration. */
        Configuration objConfiguration = new Configuration();
        objConfiguration.configure("com\\hibernateassist\\hbm\\hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory objSessionFactory = objConfiguration.buildSessionFactory();
        Session session = objSessionFactory.openSession();
        
        /* Create criteria */
        Criteria criteria = session.createCriteria(User.class);
        
        /* Create object of Disjunction */
        Disjunction objDisjunction = Restrictions.disjunction();
        /* Add multiple condition separated by OR clause within brackets. */
        objDisjunction.add(Restrictions.eq("Username", "vicky"));
        objDisjunction.add(Restrictions.eq("Username", "thakor"));
        
        /* Attach Disjunction in Criteria */
        criteria.add(objDisjunction);
        
        /* Execute criteria */
        criteria.list();
    }
}

Hibernate Conjunction with Example

Hibernate Conjunction

Hibernate Conjunction, is used to add multiple condition in SQL query separated by AND clause  within brackets. To generate following query using Hibernate Criteria we need to use Conjunction.

Query
select
 this_.id as id0_0_,
 this_.username as username0_0_,
 this_.email as email0_0_ 
from
 user_master this_ 
where
(  
 this_.username=? 
 and this_.username=? 
)

Source Code
Following code will generate above given query.
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate Conjunction with Example
 * @author javaQuery
 */
public class HibernateConjunctionExample {

    public static void main(String[] args) {
        /* Create hibernate configuration. */
        Configuration objConfiguration = new Configuration();
        objConfiguration.configure("hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory objSessionFactory = objConfiguration.buildSessionFactory();
        Session session = objSessionFactory.openSession();
        
        /* Create criteria */
        Criteria criteria = session.createCriteria(User.class);
        
        /* Create object of Conjunction */
        Conjunction objConjunction = Restrictions.conjunction();
        /* Add multiple condition separated by AND clause within brackets. */
        objConjunction.add(Restrictions.eq("Username", "vicky"));
        objConjunction.add(Restrictions.eq("Username", "thakor"));
        
        /* Attach Conjunction in Criteria */
        criteria.add(objConjunction);
        
        /* Execute criteria */
        criteria.list();
    }
}

Lock wait timeout exceeded; try restarting transaction

Lock wait timeout exceeded; try restarting transaction


MySQL is always painful for developer when its comes to Stored Procedures, Function, PL/SQL, etc... This may be different for you and may not resolve problem however if you've situation similar to mine than it might help you.

Error
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Scenario
We've Stored Procedure that performs Insert/Update/Delete in about 45 tables. This Stored Procedure working fine in local databases with windows environment. It was not working on production server with Linux environment. I've followed below steps to find out the culprit query.

Steps
Find out the query that executing for long time. This information also contains process_id.
SHOW ENGINE INNODB STATUS

You can also execute following query to find out the process_id(id column) and query on particular database schema.
SHOW PROCESSLIST;

Now if the query is still executing you'll have to kill the process.
KILL process_id;

Culprit Query
INSERT INTO ...
SELECT 
FROM mytable
WHERE column_name
IN(SELECT mytable2_col_name 
   FROM mytable2 
   WHERE id IN(SELECT mytable3_col_name
               FROM mytable3 
        WHERE type = 'GRID' and m_id IN(SELECT DISTINCT column_name
                                               FROM mytable 
            WHERE nt_id = NewNtID)) 
   AND fk_col IS NOT NULL)
The query contains long inner query plus I'm using IN for column and same column I used as last inner query.

Solution
I chopped all inner queries and used temporary table to store records of each query and I used final output of all inner query in main query and it worked for me. 

Top 10 String interview question in Java

Top 10 String interview question in Java

What is String pool in Java?
Its the special area in Java heap to store the String literals like "javaQuery". When you create new String JVM first checks String in Pool, Its its available in Pool then it'll return the same object from Pool. If you create String using
new String("javaQuery") then it'll create the same object in Java heap not in String pool.


Why String is immutable or final in Java?
String objects are cached in String Pool and shared between multiple thread so it will lead to risk of value changed by one thread will affect value of other thread. This is one of the popular question in asked in Java interviews. This is explained with example and diagram Read more >>


What is the difference between str.equals("Vicky") and "Vicky".equals(str) in Java?
- name.equals("Vicky") Compare unknown value(name) with known value("Vicky").
- "Vicky".equals(name) Compare known value("Vicky") with unknown value(name) and its null safe. This is used to avoid java.lang.NullPointerException. Read more >>


What will be the output of following program? or Comparing two Strings in Java.
String str = "abc";
String str1 = "abc";
String str2 = new String("abc");

/**
 * '==' will compare the reference of two String.
 * str == str1 both points to same String in String Pool.
 */
System.out.println(str == str1); // true

/**
 * When we create String object using new String("abc"); then object will be created in Heap.
 * str belongs to String Pool and str2 belongs to Heap and they are not equal.
 */
System.out.println(str == str2); // false

/**
 * .equals() used with String compare the value of both String and they are equal.
 */
System.out.println(str.equals(str2)); //true

String vs StringBuilder vs StringBuffer
- String: When we have String that keeps changing then we have to use StringBuilder or StringBuffer and String is immutable.
- StringBuilder: Its fast compare to String and StringBuffer. However its not thread safe. StringBuilder is mutable.
- StringBuffer: Its slow compare to StringBuilder as its thread safe. StringBuffer is mutable.


How to reverse the String in Java? or How to check String is Palindrome or not in Java?
We can use StringBuilder.reverse() or StringBuffer.reverse() to reverse the String. Read more >>


How to convert String to char[] array and char[] array to String in Java?
- String to char[]: String.toCharArray()
- char[] to String:  String.valueOf(char[] data)
Read more >>


Why String is not good choice to store the password?
String is immutable, It means once you create the String it'll be available in memory for a long time. If one has access to memory dump then he/she can read the password from memory. char[] array is good choice for storing the password because you can wipe out the character array from memory.


How to move String object from Heap to String Pool?
String.intern() is used to move String object from Heap to String Pool.


Does String is thread-safe in Java?
Yes it it. String is immutable and we can't change value of String so it can be used in multi-threaded environment.


How to convert String to char[] array and char[] array to String in Java?

String to char array in Java

One of the rare question asked in Java interview however its worth knowing the basics of String.

Source Code
public class StringCharArray {
    public static void main(String[] args) {
        String str = "javaQuery";
        
        /* Conver String to char[] array */
        char[] charArray = str.toCharArray();
        
        /* Print the char[] array */
        System.out.println("String to char[]:");
        for(char ch : charArray){
            System.out.println(ch);
        }
        
        /* Convert char[] array to String */
        String strFromCharArray = String.valueOf(charArray);
        
        System.out.println("------------------------");
        
        /* Print the String */
        System.out.println("char[] to String: "+strFromCharArray);
    }
}

Output
String to char[]:
j
a
v
a
Q
u
e
r
y
------------------------
char[] to String: javaQuery