How to auto generate unit testing code in Java

Written by ben on May 9, 2013 Categories: eclipse, Java Tags: , , , , ,

How to auto generate unit testing code in Java

General Description :

We all familiar with the unit testing phrase.

In the continuous integration world this phrase became a must.

Although sometimes , to write quality unit testings takes more time than to write the real code.

Code Coverage is a well known phrase in the software developing world.

Some will say that Code Coverage should allways be 100%, I really don’t think so , it takes a lot of work to maintain the 100% , and it doesn’t worth it.

According to some continuous integration development articles written by team leaders probably ,

The optimized ratio of code Coverage is about 80%.

In order to achive this ratio you need some discipline from your developers , or you can use the CodePro eclipse plugin ! :)

CodePro’s solution :

Google have published a new Eclipse plugin which can auto generate unit testing classes and methods based on your buisness logic !

all you have to do is install the plugin , adjust the settings (or use the default ones , it doesn’t matter) and run the Auto Generate command right from eclipse!

So , How to Auto Generate the JUnit classes  ?

  1. in Eclipse -> go to help->install new software (how to install new plugins from Eclipse’s update manager) and insert the link (http://dl.google.com/eclipse/inst/codepro/latest/3.7).
  2. Right click on your project , CodePro Tools->Generate Test Cases.unit testing - CodePro tutorial
  3. And that’s it !

of course , if you like to change the package of you test cases from the default (as default it creates a new project with a “Test” suffix) you can do it by clicking CodePro->Preferences->JUnit->Auto Generation and change the settings there.

No Comments

Unable to resolve target android-8

Written by ben on January 7, 2013 Categories: Android, eclipse, Java Tags: , , , ,

Android – Unable to resolve target android-8

Description :

When importing android project or creating/changing the resource file (R) the “unable to resolve target android-8′” problem can pop out.

I’m familiar with two solutions for this problem.

The first solution should work for everyone.

The reason I shared the second solution was because I was new to android at that time so I made a lot of newbie mistakes , so this was the creative solution I found :) .

My Solutions :

The first solution is :

  • Rebuild the project in eclipse:
    1. make sure there are no other problems instead of ‘unable to resolve target android-x’
    2. Uncheck the Build Automatically under the Project menu.
    3. Hit Clean under the Project menu.
    4. Hit Build Project under the Project menu.

unable to resolve target android-8 - build automatically

unable to resolve target android-8 - clean project

unable to resolve target android-8 - build project

This solution didn’t work for me because I imported my Android project in another way.

The second solution is :

  • Reimport the android project using the :
    • File -> Import ->Existing Android Code Into Workspace

 

thanks to this post on stackoverflow

a short post but I hope it helped some of you :)

2 Comments

Oracle – How to optimize insert performance ? #2

Written by ben on January 1, 2013 Categories: Oracle, Performance Tuning Tags: , , , ,

Oracle – optimizing insert performance

Dropping indexes before inserting and recreating after

Description :

There are many ways to optimize mass insert operation performance , I will summerize some of them shortly :

In this article I’m going to discuss the Dropping indexes before and recreate them after way.

When inserting a row into a table , the relevant indexes also need to “know” about this.

Some of the indexes are unique indexes and they need to validate that there are no duplications , some of them are bitmap like indexes and some of them are normal indexes.

My solutions :

without optimizing example :

insert into some_table
select * from other_table;

After dropping unique indexes example;

begin
execute immediate 'alter table some_table drop constraint unique_constraint';

execute immediate 'drop index unique_constraint';

insert into some_table
select * from other_table;
commit;

execute immediate 'create unique index unique_constraint on some_table (unique_constraint_column)';
end;

After dropping and recreating indexes parallel example;

begin
drop_unique_constraint('some_table' , 'unique_constraint');

insert into some_table
select * from other_table;
commit;

create_uk_parallel('some_table' , 'unique_constraint' , 'unique_constraint_columns);
end;

drop_unique_constraint code :

CREATE OR REPLACE PROCEDURE drop_unique_constraint(p_table_name varchar2 , p_con varchar2) IS
BEGIN
execute immediate 'alter table ' || p_table_name || ' drop constraint ' || p_con;

execute immediate 'drop index' || p_con;

END drop_unique_constraint;

create_uk_parallel (parallel mode) code :

CREATE OR REPLACE PROCEDURE create_uk_parallel(p_table_name varchar2 , p_con varchar2 , p_cols varchar2) IS
BEGIN
-- create the uk without enabling and validating it

execute immediate 'create unique index ' || pcon || ' on ' || p_table || ' (' || p_cols || ') parrallel 8';

execute immediate 'alter table ' || p_table || ' add constraint ' || p_con || ' unique (' || p_cols || ') disable';

execute immediate 'alter table ' || p_table || ' enable novalidate constraint ' || p_con;

execute immediate 'alter session force parallel ddl parallel 8';

execute immediate 'alter table ' || p_table || ' parallel 8';

-- perform the validate part , which is the most difficult one in parallel mode

execute immediate 'alter table ' || p_table || ' enable validate constraint';

-- back to the original state

execute immediate 'alter session disable parallel ddl';

execute immediate 'alter table ' || p_table || ' noparallel';

execute immediate 'alter index ' || p_con || ' noparallel';

END create_uk_parallel;

1 Comment

Oracle – How to optimize insert performance ? #1

Written by ben on December 31, 2012 Categories: Oracle, Performance Tuning Tags: , , , ,

Oracle – optimizing insert performance

Enable/Disable foreign keys before inserting

Description :

There are many ways to optimize mass insert operation performance , I will summerize some of them shortly :

In this article I’m going to discuss the Disable/Enable foreign keys way.

When inserting a row into a table , the row has to be checked and that is done by the table’s constraints.

some of the constraints are Foreign Keys to other table’s Primary Keys and that means that you have to scan the other table’s Primary Key’s index and to validate the value that is going to be inserted.

When you want to insert many rows at once or in a loop or in another way .. those Indexes scans are Significant.

If you don’t want to disable all of the table’s Foreign Keys and still you want to optimize the insert statement using that method , you can disable only the heaviest Foreign Key (the heaviest Foreign Key is the one pointing to the table that contains the highest number of rows) , by doing that you saved n times index scans.

My solutions :

without optimizing example :

<pre class=”brush:sql”>

insert into some_table
select * from other_table;

</pre>

After disabling the largest Foreign key example;

begin
execute immediate 'alter table some_table disable constraint large_table_fk';

insert into some_table
select * from other_table;
commit;

execute immediate 'alter table some_table enableconstraint large_table_fk';
end;

After disabling all Foreign keys example;

begin
disable_table_fks('some_table');

insert into some_table
select * from other_table;
commit;

enable_table_fks('some_table');
end;

disable_table_fks code :

</pre>
CREATE OR REPLACE PROCEDURE disable_table_fks(p_table_name varchar2) IS
BEGIN
for a in (select t.CONSTRAINT_NAME
from user_constraints t
where lower(t.TABLE_NAME) = lower(p_table_name)
and t.CONSTRAINT_TYPE = 'R'
and t.status = 'ENABLED') loop

execute immediate 'alter table ' || p_table_name || ' disable constraint ' || a.constraint_name;
end loop;

END disable_table_fks;
<pre>

enable_table_fks (parallel mode) code :

</pre>
CREATE OR REPLACE PROCEDURE enable_table_fks(p_table_name varchar2) IS
BEGIN
-- alter the session and the table's mode to parallel
execute immediate 'alter session force parallel ddl parallel 8';
execute immediate 'alter table ' || p_table_name || ' parallel 8';

for a in (select t.CONSTRAINT_NAME
from user_constraints t
where lower(t.TABLE_NAME) = lower(p_table_name)
and t.CONSTRAINT_TYPE = 'R'
and t.status = 'DISABLED') loop

-- first enable without validating and then validate
execute immediate 'alter table ' || p_table_name ||' enable novalidate constraint ' || a.constraint_name;
execute immediate 'alter table ' || p_table_name ||' enable validate constraint ' || a.constraint_name;
end loop;

-- alter the session and the table's mode to no parallel
execute immediate 'alter session disable parallel ddl';
execute immediate 'alter table ' || p_table_name || ' noparallel';

END enable_table_fks;
<pre>
1 Comment

ProjectEuler – Problem 10 Solution

Project Euler – Problem 10 Solution

This is my solution for Problem 10 in Project Euler :

Problem 10 in Project Euler description :

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

My Solution :

</pre>
public Problem10()
 {
long sum = 0;
     int n = 2000000;
     for (int i=2;i<n;i++)
     {
         if (isPrime(i))
         {
             sum += i;
         }
     }
     System.out.println(sum);
 }

 public static boolean isPrime(long n)
 {
     boolean isPrime = true;
     for (int i=2; i<= Math.round(Math.sqrt(n)) && isPrime; i++)
     {
         isPrime = !(n % i == 0);
     }
     return isPrime;
 }
<pre>

Final Answer : 142913828922

No Comments

ProjectEuler – Problem 9 Solution

Project Euler – Problem 9 Solution

This is my solution for Problem 9 in Project Euler :

Thanks to this post : http://www.mathblog.dk/pythagorean-triplets/

Problem 9 in Project Euler description :

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

My Solution :

public problem9()
 {
double a = 0, b = 0, c = 0;
     double sum = 1000;
     boolean found = false;
     for (a = 1; a < sum / 3 && !found; a++)
     {
         for (b = a; b < sum / 2 && !found; b++)
         {
             c = sum - a - b;

             if (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2) )
             {
                 found = true;
                 System.out.println("product of a,b,c = " + a*b*c);
                 break;
             }
         }
     }
 }

Final Answer : 31875000

No Comments

ProjectEuler – Problem 8 Solution

Written by ben on September 17, 2012 Categories: Java, project Euler Tags: , , , ,

Project Euler – Problem 8 Solution

This is my solution for Problem 8 in Project Euler :

Problem 8 in Project Euler description :

Find the greatest product of five consecutive digits in the 1000-digit number.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

My Solution :

public problem8()
 {
String s =
     "73167176531330624919225119674426574742355349194934" +
     "96983520312774506326239578318016984801869478851843" +
     "85861560789112949495459501737958331952853208805511" +
     "12540698747158523863050715693290963295227443043557" +
     "66896648950445244523161731856403098711121722383113" +
     "62229893423380308135336276614282806444486645238749" +
     "30358907296290491560440772390713810515859307960866" +
     "70172427121883998797908792274921901699720888093776" +
     "65727333001053367881220235421809751254540594752243" +
     "52584907711670556013604839586446706324415722155397" +
     "53697817977846174064955149290862569321978468622482" +
     "83972241375657056057490261407972968652414535100474" +
     "82166370484403199890008895243450658541227588666881" +
     "16427171479924442928230863465674813919123162824586" +
     "17866458359124566529476545682848912883142607690042" +
     "24219022671055626321111109370544217506941658960408" +
     "07198403850962455444362981230987879927244284909188" +
     "84580156166097919133875499200524063689912560717606" +
     "05886116467109405077541002256983155200055935729725" +
     "71636269561882670428252483600823257530420752963450";
     List<Long> lResultList = Collections.max(divideToLists(s) , new Comparator<List<Long>>()
     {
         @Override
         public int compare(List<Long> o1, List<Long> o2)
         {
             if (productOfCollection(o1) < productOfCollection(o2))
             {
                 return -1;
             }
             else
             {
                 return 1;
             }
         }
     });
     System.out.println(productOfCollection(lResultList));
 }

 private long productOfCollection(List<Long> list)
 {
     long product = 1;

     for (Long lLong : list)
     {
         product *= lLong;
     }

     if (list.isEmpty())
     {
         return 0;
     }
     else
     {
         return product;
     }
 }

 private List<List<Long>> divideToLists(String hugeString)
 {
     long curr;
     List<List<Long>> lLargeList = new ArrayList<List<Long>>();
     List<Long> lConsecutiveList = new ArrayList<Long>();
     List<Long> lTempList = new ArrayList<Long>();
     for (int i=0; i <= hugeString.length() - 5 ; i+=4)
     {
         // 1
         curr = Long.valueOf(String.valueOf(hugeString.charAt(i))).longValue();
         lConsecutiveList.add(curr);

         // 2
         curr = Long.valueOf(String.valueOf(hugeString.charAt(i + 1))).longValue();
         lConsecutiveList.add(curr);

         // 3
         curr = Long.valueOf(String.valueOf(hugeString.charAt(i + 2))).longValue();
         lConsecutiveList.add(curr);

         // 4
         curr = Long.valueOf(String.valueOf(hugeString.charAt(i + 3))).longValue();
         lConsecutiveList.add(curr);

         // 5
         curr = Long.valueOf(String.valueOf(hugeString.charAt(i + 4))).longValue();
         lConsecutiveList.add(curr);
         lTempList.addAll(lConsecutiveList);
         lLargeList.add(lTempList);

         lConsecutiveList = new ArrayList<Long>();
         lTempList = new ArrayList<Long>();
     }

     return lLargeList;
 }

Final Answer : 40824

No Comments

Java optimization – JIT Compilation – use of -XX:+PrintCompilation argument

JIT – Java optimization – JIT Compilation – use of -XX:+PrintCompilation argument

  • JIT Background :

JIT Compilation definition : Just In Time Compilation :

Java does not compile the source code into the native machine language.

It transforms the code into byte code (the Class object).

In order to maximize performance the JVM collects and analyzes the runtime performance , one of the concrete things it does is counting the methods invocations.

Sun decides that a method will get compiled into the machine “native op code” in Runtime if it got invoked 10,000 times in Server Side and 1,500 times in Client Side.

compiling the method into native op code causes the method to run 75% of it’s original execution time.

Description :

I’m not going to explain here how to optimize your java code (thing I will do in other posts :) ) , I’m only going to show you how to track and profile your highly invoked methods.

If you will improve your highly invoked methods your application will run much faster , although the 80/20 rule applies only for the heaviest methods , the highly invoked methods will provide an excellent performance tuning because of the fact that they are invoked many times.

Java developers actualy getting “Free” performance tuning while they are not aware of that :)  .

Solution :

In your DEBUG mode , add the argument : -XX:+PrintCompilation , this will show you the highly invoked methods (default server side threshold : 10,000 , default client side threshold : 1,500)

No Comments

ProjectEuler – Problem 7 Solution

Written by ben on August 16, 2012 Categories: General Tags: , ,

Project Euler – Problem 7 Solution

This is my solution for Problem 7 in Project Euler :

Problem 7 in Project Euler description :

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

My Solution :

int n = 10001;
 int count = 0;
 long i = 2;

 while (count <= n)
 {
if (Methods.isPrime(i))
     {
         count++;
         if (count == n)
         {
             System.out.println("i:" + i);
         }
     }
     i++;
 }

Final Answer : 104743

No Comments

Oracle – how to filter varchar2 columns by nullable parameter ?

Written by ben on August 1, 2012 Categories: Oracle Tags: , , , , , ,

Oracle – how to filter varchar2 columns by nullable parameter ?

Description :

Sometimes when we have a search form which creates a dynamic query we want to support all of the cases , also the case of a nullable parameters.

When filtering a table by some varchar2 columns we need to consider the fact that the given parameter may be null.

Sometimes the null means that the client didn’t set this parameter so he doesn’t care about it , or in some cases it means something different in the buisness logic of the current service..

I will show here an example of how to consider the nullable parameter by avoiding it using the nvl() oracle function.

My Solution :

In my workplace I’ve met a case like this , in my case it was inside a view which it got filtered by the outside using WHERE clause , this example can be implemented also in PROCEDURES , FUNCTIONS and etc..

I’m gonna swap the nullable parameter with nvl and the highest / lowest ascii values known to the keyboard :)

For example I’m taking the employee table and filter it by the first_name column , by both upper and lower boundry.


-- both from and to are set
select *
 from employees e
 where e.first_name between nvl('FROM', chr(0))�
                        and nvl('TO', chr(127))
 order by e.first_name;

As you can see , the returned values are between ‘FROM’ and ‘TO’.

In this example I’m taking the employee table and filter it by the first_name column ,only by lower boundry.


-- only from is set
select *
 from employees e
 where e.first_name between nvl('FROM', chr(0))�
                        and nvl(null, chr(127))
 order by e.first_name;

As you can see , the returned values are only higher than ‘FROM’ .

In this example I’m taking the employee table and filter it by the first_name column ,only by upper boundry.


-- only to is set
select *
 from employees e
 where e.first_name between nvl(null, chr(0))�
                        and nvl('TO', chr(127))
 order by e.first_name;

As you can see , the returned values are only lower than ‘TO’ .

In this example I’m taking the employee table and filter it by the first_name column with none boundries.


-- nothing is set
select *
 from employees e
 where e.first_name between nvl(null, chr(0))�
                        and nvl(null, chr(127))
 order by e.first_name;

As you can see , the returned values are ALL.

No Comments