Friday, August 30, 2013

Generating the DDL of Oracle Schema Objects


set serveroutput on size unlimited
begin
dbms_output.put_line('--');
dbms_output.put_line('-- DROP TABLES --');
dbms_output.put_line('--');
    for rt in (select table_name tname from user_tables order by tname) loop
        dbms_output.put_line('DROP TABLE '||rt.tname||' CASCADE CONSTRAINTS;');
    end loop;
end;
/        

declare 
    v_tname  varchar2(30);
    v_cname  char(32);
    v_type     char(20);
    v_null   varchar2(10);
    v_maxcol number;
    v_virg     varchar2(1);
begin
dbms_output.put_line('--');
dbms_output.put_line('-- CREATE TABLES --');
dbms_output.put_line('--');
    for rt in (select table_name from user_tables order by 1) loop
        v_tname:=rt.table_name;
        v_virg:=',';
        dbms_output.put_line('CREATE TABLE '||v_tname||' (');
        for rc in (select table_name,column_name,data_type,data_length,
                            data_precision,data_scale,nullable,column_id
                from user_tab_columns tc
                where tc.table_name=rt.table_name
                order by table_name,column_id) loop
                    v_cname:=rc.column_name;
                    if rc.data_type='VARCHAR2' then
                        v_type:='VARCHAR2('||rc.data_length||')';
                    elsif rc.data_type='VARCHAR' THEN
                        v_type:='VARCHAR('||rc.data_length||')';
                    elsif rc.data_type='NVARCHAR2' THEN
                        v_type:='NVARCHAR2('||rc.data_length||')';
                    elsif rc.data_type='NUMBER' and rc.data_precision is null and
                                         rc.data_scale=0 then
                        v_type:='INTEGER';
                    elsif rc.data_type='NUMBER' and rc.data_precision is null and
                                     rc.data_scale is null then
                        v_type:='NUMBER';
                    elsif rc.data_type='NUMBER' and rc.data_scale='0' then
                        v_type:='NUMBER('||rc.data_precision||')';
                    elsif rc.data_type='NUMBER' and rc.data_scale<>'0' then
                        v_type:='NUMBER('||rc.data_precision||','||rc.data_scale||')';
                    elsif rc.data_type='CHAR' then
                         v_type:='CHAR('||rc.data_length||')';
                    else v_type:=rc.data_type;
                    end if;
                    
                    if rc.nullable='Y' then
                        v_null:='NULL';
                    else
                        v_null:='NOT NULL';
                    end if;
                    select max(column_id)
                        into v_maxcol
                        from user_tab_columns c
                        where c.table_name=rt.table_name;
                    if rc.column_id=v_maxcol then
                        v_virg:='';
                    end if;
                    dbms_output.put_line (v_cname||v_type||v_null||v_virg);
        end loop;
        dbms_output.put_line(');');
    end loop;
end;  
/

declare 
    v_virg        varchar2(1);
    v_maxcol    number;
begin
dbms_output.put_line('--');
dbms_output.put_line('-- PRIMARY KEYS --');
dbms_output.put_line('--');
    for rcn in (select table_name,constraint_name 
            from user_constraints 
            where constraint_type='P' 
            order by table_name) loop
        dbms_output.put_line ('ALTER TABLE '||rcn.table_name||' ADD (');
        dbms_output.put_line ('CONSTRAINT '||rcn.constraint_name);
        dbms_output.put_line ('PRIMARY KEY (');
        v_virg:=',';
        for rcl in (select column_name,position 
                from user_cons_columns cl 
                where cl.constraint_name=rcn.constraint_name
                order by position) loop
            select max(position)
                into v_maxcol
                from user_cons_columns c
                where c.constraint_name=rcn.constraint_name;
            if rcl.position=v_maxcol then
                v_virg:='';
            end if;
            dbms_output.put_line (rcl.column_name||v_virg);
        end loop;
        dbms_output.put_line(')');
        dbms_output.put_line('USING INDEX );');
    end loop;
end;
/

declare
    v_virg        varchar2(1);
    v_maxcol    number;
    v_tname        varchar2(30);
begin
dbms_output.put_line('--');
dbms_output.put_line('-- FOREIGN KEYS --');
dbms_output.put_line('--');
    for rcn in (select table_name,constraint_name,r_constraint_name 
            from user_constraints 
            where constraint_type='R'
            order by table_name) loop
        dbms_output.put_line ('ALTER TABLE '||rcn.table_name||' ADD (');
        dbms_output.put_line ('CONSTRAINT '||rcn.constraint_name);
        dbms_output.put_line ('FOREIGN KEY (');
        v_virg:=',';
        for rcl in (select column_name,position 
                from user_cons_columns cl 
                where cl.constraint_name=rcn.constraint_name
                order by position) loop
            select max(position)
                into v_maxcol
                from user_cons_columns c
                where c.constraint_name=rcn.constraint_name;
            if rcl.position=v_maxcol then
                v_virg:='';
            end if;
            dbms_output.put_line (rcl.column_name||v_virg);
        end loop;
        select table_name 
            into v_tname
            from user_constraints c
            where c.constraint_name=rcn.r_constraint_name;
        dbms_output.put_line(') REFERENCES '||v_tname||' (');

        select max(position)
                into v_maxcol
                from user_cons_columns c
                where c.constraint_name=rcn.r_constraint_name;
        v_virg:=',';
        select max(position)
            into v_maxcol
            from user_cons_columns c
            where c.constraint_name=rcn.r_constraint_name;
        for rcr in (select column_name,position 
                from user_cons_columns cl
                where rcn.r_constraint_name=cl.constraint_name
                order by position) loop
            if rcr.position=v_maxcol then
                v_virg:='';
            end if;
            dbms_output.put_line (rcr.column_name||v_virg);
        end loop;
        dbms_output.put_line(') );');
    end loop;
end;
/
        
begin
dbms_output.put_line('--');
dbms_output.put_line('-- DROP SEQUENCES --');
dbms_output.put_line('--');
    for rs in (select sequence_name 
            from user_sequences
            where sequence_name like 'SQ%'
            order by sequence_name) loop
        dbms_output.put_line('DROP SEQUENCE '||rs.sequence_name||';');
    end loop;
dbms_output.put_line('--');
dbms_output.put_line('-- CREATE SEQUENCES --');
dbms_output.put_line('--');
    for rs in (select sequence_name 
            from user_sequences
            where sequence_name like 'SQ%'
            order by sequence_name) loop
        dbms_output.put_line('CREATE SEQUENCE '||rs.sequence_name||' NOCYCLE;');
    end loop;
end;
/

declare
    v_virg        varchar2(1);
    v_maxcol    number;
begin
dbms_output.put_line('--');
dbms_output.put_line('-- INDEXES --');
dbms_output.put_line('--');
    for rid in (select index_name, table_name 
            from user_indexes
            where index_name not in (select constraint_name from user_constraints) 
                and index_type<>'LOB'
            order by index_name) loop
        v_virg:=',';
        dbms_output.put_line('CREATE INDEX '||rid.index_name||' ON '||rid.table_name||' (');    
        for rcl in (select column_name,column_position 
                from user_ind_columns cl 
                where cl.index_name=rid.index_name
                order by column_position) loop
            select max(column_position)
                into v_maxcol
                from user_ind_columns c
                where c.index_name=rid.index_name;
            if rcl.column_position=v_maxcol then
                v_virg:='';
            end if;
            dbms_output.put_line (rcl.column_name||v_virg);
        end loop;
        dbms_output.put_line(');');
    end loop;
end;
/



http://www.dba-oracle.com/art_builder_get_schema_syntax.htm
http://docs.oracle.com/cd/E17781_01/server.112/e18804/impexp.htm
http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_metada.htm
http://docs.oracle.com/cd/E11882_01/server.112/e22490/original_import.htm

Saturday, July 20, 2013

Preparing environment for Andiod Development

While thinking about Android application development, first question comes into our mind, that how can we get the android environment into our laptop or desktop.

There are two ways, we could deal with this challenge one installing an android simulator and another installing android operating system in the laptop. 

The example of some android simulators are as follows -
  1. BlueStacks
  2. Youwave
Installation of Android operating system directly needs vm virtual box. The steps of same can be accessed from here

Monday, May 13, 2013

Various tool and their benefits


JSHint - JSHint is a community-driven tool to detect errors and potential problems in JavaScript code and to enforce your team’s coding conventions.JSHint can be used in eclipse via it's eclipse plugin  as well as in qunit to develop test cases which will consider each validation failure as test case failure.

W3c Markup validator - This validator checks the markup validity  of Web documents in HTML, XHTML, SMIL, MathML, etc.
Stripe Generator -This is a tool to generate stripe images by few clicks, in few seconds. These images can be used as background of a web page. 
SpriteMe -Sprite me is a javascript utility, whcih can be executed from any browser. During execution, it scans all the background images in current page and suggest possible spriting. The suggestion also include the number of request reduction happening on sptiring implementation. We can export the final spriting image along with corresponding CSS to be used for applying spriting in the page, from this tool. 
Trang - Tool to generate xsd from xml file

Various techniques & their benefit


CSS Sprites:CSS sprites are a way to reduce the number of images by combining several images into one. This technique is useful in reducing the all images load time.
Regular Expression - Regular Expression - Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data. In java regular expression evaluation engine's evaluation process can be tweaked in any of three possible flavors using quantifiers ie Greedy, Reluctant & Possessive

Wednesday, May 8, 2013

Various frameworks and their purposes

DWR (Direct Web Remoting) -DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.

Display tag -Display tag library can just... display tables! Give it a list of objects and it will handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table in a customizable XHTML style.

JQuery - jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

BlazeDS - BlazeDS is a server-based Java remoting and web messaging technology that allows you to connect to back-end distributed data and push data to Adobe Flex and Adobe Integrated Runtime (AIR) Rich Internet applications (RIA).

QUnit -QUnit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself!

Junit - JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

JUnitParamsIts a library, which acts as an extension to write parametric test cases in an easier fashion than conventional JUnit parametric test case writing and execution.It works on JUnit version greater than 4.6. Its change log and java doc can be accessed from  git and javadocslinks respectively.

Tuesday, May 7, 2013

Challenges while developing test for spring beans

Spring provides us options to test beans in application contexts using spring-test module. The detailed explanation of the way to use it can be accessed from the following link

I had maven based application. During the development and running of these test cases, I came accross few challenges. The key ones along with their resolutions are as mentioned below.

Issue - Compilation failure - SpringJUnit4ClassRunner.class and @ContextConfiguration not found
Solution - Included below mentioned maven dependency in the project and executed mvn eclipse:eclipse

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
            <version>3.1.2.RELEASE</version>
        </dependency>

Issue - IDE displying error - The type org.junit.runners.BlockJUnit4ClassRunner cannot be resolved. It is indirectly referenced from required .class files
Solution - BlockJUnit4ClassRunner was included in Junit4.5 so added below mentioned dependency of junit4.5 and executed mvn eclipse:eclipse

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
        </dependency>

Friday, January 18, 2013

Eliminating hibernate boiler plate code


While using Hibernate, we use below mentioned code each time, we perform any database operation.
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
 // your purposefull code goes here

 session.getTransaction().commit();
 return object;
} catch (Exception exception) {
 session.getTransaction().rollback();
 throw new RuntimeException(exception);
} finally {

 session.disconnect();
}
 We can eliminate the duplicity of this code by using the strategy, where this code will reside only  in HibernateUtil and while performing database operation, we will focus only on database operation, we want to perform.
The infrastructure code is as mentioned below - 
HibernateStrategy.java
package hibernate;

import org.hibernate.Session;

public interface HibernateStrategy {
 Object execute(Session session);
}
HibernateUtil.java
package hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

 private static SessionFactory sessionFactory;

 static {

  sessionFactory = new AnnotationConfiguration().configure()
    .buildSessionFactory();
 }

 public static Object performAction(final HibernateStrategy strategy) {
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  try {
   Object object = strategy.execute(session);
   session.getTransaction().commit();
   return object;
  } catch (Exception exception) {
   session.getTransaction().rollback();
   throw new RuntimeException(exception);
  } finally {

   session.disconnect();
  }
 }
}

The sample code using HibernateUtil is as mentioned below - 
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="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
  <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
  <property name="hibernate.connection.url">jdbc:hsqldb:mem:InMemoryDatabase</property>
  <property name="hibernate.connection.username">sa</property>
  <property name="hibernate.connection.password"></property>


  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">2</property>

  <property name="hibernate.hbm2ddl.auto">create-drop</property>
  <property name="hibernate.show_sql">true</property>

  <mapping class="hibernate.Student"></mapping>
 </session-factory>
</hibernate-configuration> 
Student.java
package hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Student")
public class Student {

 @Id
 @GeneratedValue
 private int studentId;
 private String name;
 private int age;

 public Student(final String name, final int age) {
  this.name = name;
  this.age = age;
 }

 public Student() {
 }

 @Override
 public String toString() {
  return "Student [studentId=" + studentId + ", name=" + name + ", age="
    + age + "]";
 }
}

Maven dependency
<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate</artifactId>
 <version>3.2.7.ga</version>
</dependency>
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> 
 <version>3.2.1.ga</version> </dependency> -->
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-annotations</artifactId>
 <version>3.2.1.ga</version>
 <exclusions>
  <exclusion>
   <artifactId>javax.transaction</artifactId>
   <groupId>jta</groupId>
  </exclusion>
 </exclusions>
</dependency>
<dependency>
 <groupId>javax.transaction</groupId>
 <artifactId>jta</artifactId>
 <version>1.1</version>
</dependency>
<dependency>
 <groupId>org.hsqldb</groupId>
 <artifactId>hsqldb</artifactId>
 <version>2.2.9</version>
</dependency>
HibernateUtilTest.java  (code to test above infrastructure)
package hibernate;

import java.util.List;
import junit.framework.TestCase;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class HibernateUtilTest extends TestCase {

 @Test
 public void testHibernateUtil2() {

  HibernateUtil.performAction(new HibernateStrategy() {
   @Override
   public Object execute(Session session) {
    Student student = new Student("Salil Verma-Test1", 20);
    session.saveOrUpdate(student);
    return new Object();
   }
  });

  List studentList = (List) HibernateUtil
    .performAction(new HibernateStrategy() {
     @Override
     public Object execute(Session session) {
      Criteria criteria = session.createCriteria(
        Student.class).add(
        Restrictions.eq("name", "Salil Verma-Test1"));

      return criteria.list();
     }
    });

  assertNotNull(studentList);
  assertEquals(1, studentList.size());
 }
}