Monday, 7 September 2015

Connecting to Oracle Database using Hibernate Framework

A basic hibernate mvc tutorial which connect to Oracle database 12c and do some DDL and DML operation using hibernate framework. I have used Oracle database 12c release 1 on Red Hat Linux 6.4 64 bit and used Eclipse Helios 64 bit and Hibernate Framework 3.6.4. I am uploading the project and sharing the link. 


The main contents of the project is 
1. hibernate.cfg.xml, 2. UserDetails.java and 3. OracleTest.java.

It is not possible to  show the details steps of creating the project for that you need to see the video on youtube.

Download Hibernate 3.6.4-final  

Goto project properties, select Java build path, Click on Add library, Select Add user library, Click on New, Give name to the library, click on add jar files. and select these jars.



Now download ojdbc6.jar.zip and extract it to your desired location. Click on Add external jars and select ojdbc.jar. This jar is required for the jdbc driver for oracle connection.


Hibernate.cfg.xml is required to setup the connection to the database, configuration which initiates the connection, build the session, transactional savepoint and commit DDL and DML operation.
Create this three files inside src folder. Put Hibernate.cfg.xml in src root and 2 java files into the package you create.

Sample Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@192.168.0.109:1521:orcl</property>
        <property name="connection.username">hrd</property>
        <property name="connection.password">hrd</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

           <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.use_outer_join">false</property>
<!--          <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property> -->
        <mapping class="org.subhro.hibernate.UserDetails"/>       
    </session-factory>
</hibernate-configuration>

UserDetails.java

package org.subhro.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int UserId;
    private String UserName;
    /**
     * @param userId the userId to set
     */
    public void setUserId(int userId) {
        UserId = userId;
    }
    /**
     * @return the userId
     */
    public int getUserId() {
        return UserId;
    }
    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        UserName = userName;
    }
    /**
     * @return the userName
     */
    public String getUserName() {
        return UserName;
    }   
}



OracleTest.java

package org.subhro.hibernate;

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


public class OracleTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        UserDetails usr = new UserDetails();
        usr.setUserId(5);
        usr.setUserName("Fourth Record");
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(usr);
        session.getTransaction().commit();
    }
}


Tuesday, 1 September 2015

Google Map with AngularJS and JSON data from Oracle database.

Google Map created with Javascript and AngularJS. Here we have a Oracle database table of data consisting of list of Countries, their respective cities and state and latitude and longitude. JSON data is retrieved from Oracle database 12c using a JSP module, get_oracle_Data.jsp. Data has been imported from a lat_long.csv file into Oracle database.
In this program you select one country, you get the list of cities and you select one city and the map will be generated of that country with the city at the center point of the map.




<html ng-app="app">
<head>
<script
  src="angular.min.js"></script>
<!--<script
  src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>-->
<script
  src="js?sensor=false&language=en"></script>
<script>

 app = angular.module('app',[]);

 app.controller('MyCtrl',function($scope,$http){

  $scope.jsonData = [];

  $http.get("get_oracle_data.jsp?sqlStr=select distinct country from citieslatlong order by country")
  .success(function(response) {
    $scope.country  = response; 
  })
  .error(function(){
  });


  $scope.getCities = function() {

    $http.get("get_oracle_data.jsp?sqlStr=select t.* from citieslatlong t where t.country = '" + $scope.country_name + "'")
    .success(function(response) {
      $scope.jsonData = response; 
    })
    .error(function(){
    });
  }

  $scope.getCityIndex = function() {
    for(i=0;i<$scope.jsonData.length;i++)
    {
      if($scope.jsonData[i].CITY == $scope.city_name)
        return   i; //$scope.jsonData[i].ROWNUM;
    }
    return 0;
  }
 
  $scope.latlong = function(lat,long) {
    var l = new google.maps.LatLng(lat, long);
    return l;
  }

  $scope.mapProp = function(city){
    return {
    center:city,
    zoom:5,
    mapTypeId:google.maps.MapTypeId.SATELLITE
   };   
  }

  $scope.city = function(lat,long) {
    return new google.maps.LatLng(lat, long);
  }

  $scope.gmap = function(dom){
    var gm = new google.maps.Map(document.getElementById(dom),
      $scope.mapProp($scope.latlong($scope.jsonData[$scope.getCityIndex()].LATITUDE,$scope.jsonData[$scope.getCityIndex()].LONGITUDE)));
    return gm;
  }

  $scope.marker = function(data){
      var m = new google.maps.Marker({
                Title:data.CITY,
                Name:data.CITY,
                position:$scope.city(data.LATITUDE,data.LONGITUDE),
                animation:google.maps.Animation.BOUNCE
              });
      return m;
    }

  $scope.infoWindow = function(marker) {
    var w = new google.maps.InfoWindow({
      content:marker.Name
    });
    return w;
  }

  $scope.CreateMap = function(dom){   


    var map = $scope.gmap(dom);

    for(i=0;i<$scope.jsonData.length;i++)
    {
      var marker = $scope.marker($scope.jsonData[i]);
      marker.setMap(map);
      var iw = $scope.infoWindow(marker);
      $scope.addMarkerListener(map,marker,iw);
    }
    //google.maps.event.addDomListener(window,'load',$scope.CreateMap(dom));
  }

  $scope.addMarkerListener = function(map,marker,iw){
    google.maps.event.addListener(marker,'mousedown',function(){
      iw.open(map,marker);
    });   
    google.maps.event.addListener(marker,'mouseup',function(){
      iw.close(map,marker);
    });   
  }

 });

</script>
</head>
<body ng-controller="MyCtrl">
Select Country: <select width=30px ng-model="country_name" name="country_name" id="country_name" ng-options="data.COUNTRY as data.COUNTRY for data in country" ng-change="getCities()"></select><br><br>
Select City: <select width=30px ng-model="city_name" name="city_name" id="city_name" ng-options="data.CITY as data.CITY for data in jsonData" ng-change='CreateMap("googleMap")'"></select>
<div id="googleMap" style="width:100%; height:100%">
</div>
</body>
</html>


We are giving you the link of a zipped archive which contains three files. gmap2.html, get_oracle_Data.jsp and lat_long.csv.

Link : https://drive.google.com/file/d/0BznrW3lgX0ozMnd1U200RWxoNDA/view?usp=sharing

You can also look at our  youtube video :

Google Map with AngularJS and JSON data from Oracle database.

 

A PLSQL procedure to compile plsql object.


A plsql procedure written using dbms_ddl package and all_objects table from sys schema where we have used one procedure from dbms_ddl package known as alter_compile which takes four arguments. 
1. Object_type - Type of object (i.e. function, procedure, package)
2. Owner - User/ Schema name under which object exists
3. Object Name - Function / procedure name
4. Reuse settings (default false)

This program runs a loop navigation through all the objects and checking for whether it is
a function, procedure or package / package bodies, compiling it and error takes place printing error
to console.

Here is the program.

create or replace procedure CompileAllObjects is
    cursor rec is select OWNER,OBJECT_NAME,OBJECT_TYPE from all_objects
    where OBJECT_TYPE in ('PROCEDURE','FUNCTION','PACKAGE','PACKAGE             BODIES','TRIGGER')
    and owner like &<name="Object owner"
                   hint="The object owner (wildcards allowed)"
                   type="string"
                   default="select user from dual"
                   ifempty="%"
                   list="select username from all_users order by username">
    and OBJECT_TYPE like &<name="Object type"
                           hint="The object type"
                           type="string"
                           default="All"
                           ifempty="All"
                           list="%, All, PROCEDURE, Procedures, FUNCTION, Functions, PACKAGE%,     Packages, TYPE%, Types, TRIGGER, Triggers, TABLE, Tables, INDEX, Indexes, SEQUENCE, Sequences, SYNONYM, Synonyms"
                           description="yes">;
begin
  for i in rec loop
    begin
      dbms_ddl.alter_compile(i.OBJECT_TYPE,i.OWNER,i.OBJECT_NAME,false);
      exception
      when others then
          dbms_output.put_line('Error cannot compile : '||i.OBJECT_TYPE||' '||i.OBJECT_NAME||' Error - '||sqlerrm());
        end;
    end loop;
end CompileAllObjects;

Monday, 24 August 2015

Adding shapes and markers in Google Map.




Able to add shapes like Polyline, Circle in google map gives you the tool to add flight paths or locate specific location with circles. Using polylines can make you able to join multiple locations in a path specifically used to demonstrate flight path. In this program I have added three markers for three cities Delhi, Mumbai and Kolkata in the country India. And joined the three metropolitan with polyline and also added a circle for one of the city. I have also tried to add a click event listener for each cities though that part is still buggy and might not work properly. Also added info window for each markers. Here is the source code, you can try it.


<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
  function initialize()
  {
   var delhi = new google.maps.LatLng(28.38000, 77.12000);
   var kolkata = new google.maps.LatLng(22.572646,88.363895);
   var mumbai = new google.maps.LatLng(18.9750, 72.8258); 

   var mapProp = {
    center:delhi,
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
   };
   var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

   var marker = [
    new google.maps.Marker({
      Name:'Mumbai Business Center',
      position:mumbai,
      animation:google.maps.Animation.BOUNCE
    }),
    new google.maps.Marker({
      Name:'Delhi Capital of India',
      position:delhi,
      animation:google.maps.Animation.BOUNCE
    }),
    new google.maps.Marker({
      Name:'Kolkata Heritage City',
      position:kolkata,
      animation:google.maps.Animation.BOUNCE
    })
   ];

   var flightPath = new google.maps.Polyline({
      path:[mumbai,delhi,kolkata],
      strokeColor: "#FF0000",
      strokeOpacity:0.4 ,
      strokeWeight:2,
      fillColor:"#0000FF",
      fillOpacity:0.4     
   });

   flightPath.setMap(map);

   var myCity  = new google.maps.Circle({
    center:kolkata,
    radius:50000,
    strokeColor:"#FF0000",
    strokeOpacity:0.5,
    strokeWeight:2,
    fillColor:"#FF0000",
    fillOpacity:0.4
   });

   myCity.setMap(map);

   for(i=0;i<marker.length;i++)
   {
    var m = marker[i];
    m.setMap(map);
    var infoWindow = new google.maps.InfoWindow({
      content:m.Name
    });

    infoWindow.open(map,m);

    google.maps.event.addListener(m,'click',function(){
       map.setZoom(8);
       map.setCenter(m.getPosition());
    });
   }
  }
  google.maps.event.addDomListener(window,'load',initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:1200px; height:800px">
</div>
</body>
</html>