Lets share love

How ? copy url of this blog and share in your social network :) simple

Lets share love

How ? copy url of this blog and share in your social network :) simple

Monday, January 20, 2014

html table to JavaScript array

you can put data of HTML table to a array and then send it to PHP or JAVA or GROOVY for any use with following code. 
      

      var myTableArray = [];
            $("#dataTableList tr").each(function() {
                var arrayOfThisRow = [];
                var tableData = $(this).find('td');
                if (tableData.length > 0) {
                    tableData.each(function() { arrayOfThisRow.push($(this).text()); });
                    myTableArray.push(arrayOfThisRow);
                }
            });
            alert(myTableArray)

note here dataTableList is my table id

Tuesday, January 14, 2014

 Use of CASE Expressions in SQL query is sometimes extremely useful.For example Using CASE in SELECT statement provides developer the power to manipulates the data at presentaion layer without changing data at backend.So there are various use of CASE Expressions and it can be used in, including in
statements like [SELECT, UPDATE, DELETE, SET ]
and clauses like [ WHERE, ORDER BY, HAVING, GROUP BY ]
Here is some more information on CASE expressions
Type of CASE Expression:
  • Simple Case Expression
  • Searched Case Expression
Basic SYNTAX for CASE experession :
 
#Type-I(Simple Case Expression)
   
 CASE InputValue
       WHEN WhenValue THEN ReturnValue
       WHEN WhenValue THEN ReturnValue
 ELSE DefaultReturnValue
  
Functionality :
1.In Simple CASE Expression, one value is checked against multiple values [ Each value at WHEN clause ]
2.Simple CASE Expression only allows equality check.
3.Returns ReturnValue of the first match i.s when InputValue = WhenValue.
4.If no matches is found returns NULL if ELSE clause is not specified otherwise DefaultReturnValue will be returned.
  
Note:
1.The DataType of InputValue and WhenValue must be same.
2.The DataType of ReturnValue and DeafaultReturnValue must be same.
3.Simple Case Expression can be nested up to three levels.

#Type-II(Searched Case Expression)
  
 CASE 
      WHEN BooleanExpression THEN ReturnValue
      WHEN BooleanExpression THEN ReturnValue
 ELSE DefaultReturnValue
  
Functionality :
1.In Searched CASE Expression,BooleanExpression will be evaluted for each WHEN clause specified .
2.Returns ReturnValue of the first BooleanExpression evalutes to True.
3.Simple CASE Expression allows comparision using [AND OR] between boolean expression. 
4.If no BooleanExpression is evaluted to True then returns NULL if ELSE clause is not specified otherwise 
DefaultReturnValue will be returned.
  
Note :
1.The DataType of ReturnValye and DeafaultReturnValue must be same
2.Searched Case Expression have no limit to the number of nesting levels.
 
Example : Use of CASE with SELECT statement.
 
Simple Case Expression with SELECT statement.
SELECT
    Name, UserType = CASE TypeID
     WHEN '0' THEN 'Anonymous'
     WHEN '1' THEN 'Registered'
     WHEN '2' THEN 'Admin'
     ELSE NULL
    END
FROM
   User;
 
Searched CASE expression with SELECT statement
 SELECT
   Name, Marks, 'Division' =
   CASE
    WHEN Marks < 350 THEN 'Fail'
    WHEN Marks >= 350 AND Marks < 450 THEN ' THIRD'
    WHEN Marks >=450 AND Marks < 550 THEN 'SECOND'
    WHEN Marks >=550 AND Marks < 650 THEN 'FIRST'
    ELSE 'Excelent'
   END
 FROM
     Student; 

Monday, January 13, 2014

Groovy Sql queries

1. For selecting from database::


import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr",
                      "oracle.jdbc.pool.OracleDataSource")
sql.eachRow("SELECT employee_id, last_name, first_name FROM employees")
{
   println "The employee's name is ${it.first_name} ${it.last_name}."

}

2. INSERT into 


employeeId = 2000
firstName = "Fred"
lastName = "Flintstone"
eMail = "fred@slaterockngravel.com"
jobId = "QU_OPER"
hireDate = new java.sql.Date(System.currentTimeMillis())
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr",
                      "oracle.jdbc.pool.OracleDataSource")
sql.execute(
   """INSERT INTO employees(employee_id, first_name, last_name, email, job_id, hire_date)
   VALUES(?, ?, ?, ?, ?, ?)""", [employeeId, firstName, lastName, eMail, jobId, hireDate])

3. Remove ::


import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr",
                      "oracle.jdbc.pool.OracleDataSource")
sql.execute("DELETE FROM employees WHERE employee_id = 2000")

sql.execute("DELETE FROM jobs WHERE job_id = ?", ["QU_OPER"])


Groovy SQL

Okay today i am going to discuss about Groovy SQL .

1. First of you will have to import sql to your controller :

                                    import groovy.sql.Sql;

2. Then you have to define datasource globally  :
class controllerClass  {
           def dataSource
}

3. Now in you action 
def action (){
                def sql = Sql.newInstance(dataSource)
                def persons = []
sql.eachRow('Select * from Person') { persons << it.toRowResult() }
sql.close() println persons

}

third step will print you all the details of person domain/table.

okay lets explain all these one by one ::

1. Imported Sql class.

2. You need to define dataSource outside of your controller action. Otherwise spring cannot do the required dependency injection . Spring will auto wire this dependency for us by name and with that we are ready to go. After we create a new instance of the sql class we can call a method on it called rows that can take a SQL statement.

3. Now in the action: Define a new instance using the current datasource. Actually new instance make connection with database. 

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver")


but here in Grails this job done by datasource.groovy as follows::


dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost/yourDB"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "yourUser"
    password = "yourPassword"
}

Docs recommends to close the Sql connection after opening it .

Constructs an SQL instance using the given Connection. It is the caller's responsibility to close the Connection after the Sql instance has been used. Depending on which features you are using, you may be able to do this on the connection object directly but the preferred approach is to call the close() method which will close the connection but also free any caches resources.

for some queries click here

Thursday, January 9, 2014

Using map for jasper reports datasource

i used this for map-based datsource in jasper reports.


def action()
{
HashMap[] reportRows = new HashMap[2];

        HashMap row1Map = new HashMap();
        HashMap row2Map = new HashMap();


        row1Map.put("name", "aaditya");
        row1Map.put("lastname", "bhatta");
        row1Map.put("phone", "9848782444");
        row1Map.put("gender", "male");

        row2Map.put("name", "aaditya");
        row2Map.put("lastname", "bhatta");
        row2Map.put("phone", "9848782444");
        row2Map.put("gender", "male");

        reportRows[0] = row1Map;
        reportRows[1] = row2Map;

}

now you can use map reportRows for the datasouce in you jasper reports .
as ::

        chain(controller:'jasper', action:'index', model:[data:reportRows],params:params)

Visit to Chisapani , Nepal

Deepak Bhatta, Prithu Sharma, Bharat Ghatal, Munna Gupta, Deepak Padal and me planned to go Namobuddha for trekking. We searched in Google, printed Google map to Namobuddha, searched for hotels and other details of Namobuddha. Finally we met in Koteshwor at 11am. We suddenly changed plan to Namobuddha we all agreed to go to Chisapaani. Everybody wanted a kick in this trek. Now we had no map and no details. We are dwellers of mountains we will find our own way and if there is no way we would make it ourselves. And we headed towards it. From Koteshwor to Chawel we took a bus and from Chawel to Sundarijal we had another bus.


I had been to Sundarijal with my college friends on one of my birthday, I guess 2 years back. Now it’s time to walk and I believe I can walk a lot and a lot. We bought some fast food to eat on the way because we are not going to get anything except trees and leaves on the way. At least we know this. We started our real journey from Sundarijal there is a there is a straight up steps ladder to go up. After 30-40 minutes of walk we reached entry point of Shivapuri wildlife reserves. We had to get ticket of Rs 10 to enter the jungle. I gave my number and my address and I told guys  " guys now I am the official leader of this tour and everybody shall follow my orders. " everybody there was senior then me except Deepak Padal who is my friend since school . One is a business man in far west of Nepal , another is doing his MBA from Tribhuwan University , another is expert of derivative market and one is engaged in foreign job. I feel privileged to walk with them, and the way they treat juniors like me equally it makes it more comfortable and enjoyable.

Yeah we reached entry point of Shivapuri, got ticket and entered the jungle the kingdom of dangerous animals and beautiful birds and butterflies. In 10 minutes we reached a water reservoir that was small but you will get stuck there at least for 15 minutes to take photos and kiss your girlfriend (of course if you are together). Unfortunately I am alone: p. We walked ahead and reached BP jail. Where our great visionary and politician was imprisoned. It was a good place he must have felt awesome for at least six months to be there. Being imprisoned in a heaven like place is not a bad experience. Yeah of course there may be no angels. Now one of our member was having difficulty in walking. However he made it to the last point. Deepak dai stared his own modified theories of Bipasana . Everything in this world is temporary. He said Munna dai that this pain is also temporary it will get ways very soon. You just have to get no feeling about this pain. That is neither love this pain, nor hates this pain, just think this pain as pain nothing more than that. Bipasna teaches us very good things. Once I went to 10 days camp to Bipasana and learned many things. And at home people thought I am going to be a sage or priest but I got chance to unfold a small part of life there. I recommend everyone to go there once at least once there.

We were tired and thirsty and wanted to have some water. And got Fanta . Thanks to these multinational companies there are everywhere. You would get no pain killer in mountains but I guarantee you will get coca cola, wai wai chau chau, Beer, cigarettes’ everywhere in Nepal. And if you have reached this far and not having, chaynga (Locally made liquor) is like you Are insulting Himalayas culture. We sat on a small shop. That place was called Deurali. And we were seeing everything as a small part of heaven. Yeah I learned why people from that far come to our mountains. Yeah the reason was in front of me. Mountains with green trees, Himalayas with snow caps as they are calling you. And everything looks so awesome. People are so friendly. I forgot to tell you about the range of Himalayas. I cannot explain them with my poor words. You go there and watch it with your own eyes. With my iphone 3g I took some photos. It was almost dark and finally we reached Chisapaani.  Chisa = Cold and Paani = Water. As name says the water was cold and let’s says ice was cold. So I recommend to name it "ChisaHeu"  Heu is snow in Nepali.

We stayed in Milan hotel. Ate food, played cards and many more. We slept; we got up at 6:30 in morning and drank tea. And again headed towards somewhere. Where we would get bus to return to Kathmandu. We walked for 5-6 hours to get a bus. We went to roof of the bus and it was like a real roller coaster unless you do not fall down. Fortunately we are safe and writing a post here. and we reached home . This trip was awesome. I reached home at night with my all bones and muscles useless. And at this time I am writing this on my bed. I can only move my fingers. So I need to bunk my classes and my office. Thank god people are awesome there.

 If you do not feel this great it is me and my poor words that could not explain those great mountains and Himalayas clearly. You got to go yourself if you want to feel it. There are many other moments that were awesome.

HOPE YOU ARE FEELING JEALOUS BY NOW. :P  

Monday, January 6, 2014

short-cut for new tab

CTRL + ( CLICK on a link ) ===>  opens a new tab in browser :) simple but useful 

Thursday, January 2, 2014

To change port in grails

You may need to run more than one apps at the same time in grails. You cannot run two apps in same port so you need to change port for running next app. here is the command for changing port in grails.

                                                           -Dserver.port=8081 run-app

this will run your app in 8081 port if you default 8080 port s busy. 

How to Subtotals in groups in iReport

Okay if you are reading this blog you must have learned to create groups in ireport. so lets continue to sum integers in groups. Here is what we want at the end.

here this is a group that is ordered by district name "Gorkha" . so we will add the middle column. Okay lets get started. 

1. create a variable. and go to its property. 
here district wise is my group name. and $F{id} is the field that i want to SUM.
now drag that varisble to footer of the group . as following image.
now preview the report. you get the desired result. 

thank hope that helps. 

Wednesday, January 1, 2014

Jasper reports and its features

Jasper Report is an open source java reporting engine, which unlike other reporting tools, for example, Crystal Reports, is Java based and doesn't have its own expression syntax. JasperReports has the ability to deliver rich content onto the screen, to the printer, or into PDF, HTML, XLS, RTF, ODT, CSV, TXT and XML files. As it is not a standalone tool, it cannot be installed on its own. Instead, it is embedded into Java applications by including its library in the application's CLASSPATH. JasperReports is a Java class library, and is not meant for end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications.

Features of JasperReports

Some of the main JasperReport features include:
  • Has flexible report layout.
  • It can present data textually or graphically.
  • Developers can supply data in multiple ways.
  • It can accept data from multiple datasources.
  • It can generate watermarks.(A watermark is like a secondary image that is laid over the primary image)
  • It can generate subreports.
  • It is capable of exporting reports to a variety of formats.

using jasper report for Grails

Jasper reporting library is very popular in JAVA community. And it can be used with Grails. You can install plugin with  

                                                            grails install-plugin jasper

in command prompt of Grails. and get a coffee because its going to take time. after jasper is installed in your project. you have to create a .jrxml file or .jasper file. you can create these files with tools like iReport or some other are there. you can download iReport here http://sourceforge.net/projects/ireport/files/iReport/iReport-5.1.0/ and there you can design your .jrxml file or .jasper file very easily. i will be writing more blogs about designing reports in iReport. 

from there you will have jrxml file . you have to put the file that you create in dir ==> your_app\web-app\reports. you have to create a reports folder in web-app and paste it there. Okay now we go back to our grails project. 

now in your gsp copy and paste following code

<g:jasperReport
          jasper="file name without extension"
          format="PDF,HTML,XML,CSV,XLS,RTF,TEXT,ODT,ODS,DOCX,XLSX,PPTX"
          name="name of the report">
    Your name: <input type="text" name="name"/>
  </g:jasperReport>

here name parameter is sent to the .jasper file. this is like if you send "aaditya" as name in gsp you can print this name in report. 

and you will see a icon on the page you located the above code to get the report. 
Attributes:
  • jasper - filepath, relative to your configured report folder, of the report, no file extension needed (Required)
  • format - supply the file formats you want to use in a simple list (Required)
  • name - name of the report
  • delimiter - delimiter between the icons representing the file formats.
  • delimiterBefore - delimiter in front of the icons
  • delimiterAfter - delimiter at the end of the icons
  • description - description of the report
  • buttonPosition - position of the icons (top or below)
with jasperButton and jasperForm you can get more control in you data to be reported:
<g:jasperForm controller="report"
    action="jasper"
    id="1498"
    jasper="w_iReport" >
..form contents..
<g:jasperButton format="pdf" jasper="jasper-test" text="PDF" />
.. other html..
</g:jasperForm>

okay you need a action code . here is a sample that i used. :

 def jasper () {
          def emp = Employee.findAll()
        chain(controller:'jasper', action:'index', model:[data:emp],params:params)
    }

here controller is report and action is jasper. here emp stores all the data that i need to report.