Monday, 29 December 2014

Differences Between ArrayList And LinkedList In Java

ArrayList Vs LinkedList In Java :

Although both ArrayList and LinkedList implement List interface, they have some differences between them. The performance and internal working nature of both varies significantly. There are also some similarities between them. In this article, we will see both differences and similarities between ArrayList and LinkedList in Java.




Saturday, 27 December 2014

Grails : Rollback

/*
 *  @author Vamsi Krishna Grandhi
 *  if you want to insert morethan one table. any table insertion failed because of errors the remaining  *  tables data can be  rollback. for that purpose the following code useful.
 *
 */

// Add data Customer & PurchaseGoods domains
com.gb.vamsi.customer.Customer.withTransaction{
if(!(new Customer(name:'Vamsi').save() && new PurchaseGoods(name:'Fruits').save())) it.setRollbackOnly()
}

Grails : Project Setup, Spring Security, Loggers and Filters Setup

Create Grails Project:

I am using GGST. before going to IDE, create one folder for workspace in your drive. open IDE and switch workspace to IDE.

Step 1 : Integrate JDK for that workspace.

- Goto window -> Preferences -> Java -> Installed JREs -> Add JDK

Step 2 : Goto File -> New -> Grails Project

Open the project, it shows the project structure like domains,controllers,services etc..



In Grails, Provide Spring Security for an application follow these steps.

Step 1 : create grails project
Step 2 : after creation of project, we want to change three groovy files in Conf. they are
        1. BuildConfig
2. Config
3. DataSource

Step 3 : In BuildConfig,
         - comment the 'test' dependency in dependencies
         - uncomment mysql connector ( runtime 'mysql:mysql-connector-java:5.1.29' ) in dependencies
         - in plugins add ( compile ":spring-security-core:2.0-RC4" )

Step 4 : In config,

         // Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.gb.vamsi.Account'    //Create package with com.gb.vamsi Name in domain
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.gb.vamsi.AccountRole'
grails.plugin.springsecurity.authority.className = 'com.gb.vamsi.Role'
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/welcome'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/**':                              ['permitAll'],
'/index':                         ['permitAll'],
'/index.gsp':                     ['permitAll'],
'/assets/**':                     ['permitAll'],
'/**/js/**':                      ['permitAll'],
'/**/css/**':                     ['permitAll'],
'/**/images/**':                  ['permitAll'],
'/**/favicon.ico':                ['permitAll']
]
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
com.gb.ems.Activity.withTransaction {
// TO DO Login date & time saving actions here
}
}


Step 5 : In DataSource, the code like

         dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    username = "root"
    password = "root"

}

         In devlopment in environments,

         development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:mysql://localhost:3306/vamsi"              // Create database name with vamsi
// Optional
pooled = true
jmxExport = true
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "root"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
        }
    }


Step 6 : Create DB in mysql with name 'vamsi' as we given step 5
Step 7 : Create package as given in step 4
Step 8 : clean the project : click grails command history icon, type 'clean' and then click 'Enter'
         refresh the dependencies : Right click on project -> Grails Tools -> Refresh Dependencies
Step 9 : Execute command in grails command history as Like ( s2-quickstart com.gb.vamsi Account Role )
Step 10: In our package created Account, Role and AccountRole domain classes
step 11: run the project ( Right click on project -> Run as -> run-app )


// Steps to Spring security service

// In BootStrap,

// Login purpose

Step 1 : Create roles

// Mentions Roles Here

         def roles = [
"ROLE_ADMIN",
"ROLE_SCHOOL_ADMIN",
"ROLE_SCHOOL_SUB_ADMIN",
"ROLE_USER",
"ROLE_TEACHER",
"ROLE_WARDEN",
"ROLE_ACCOUNTANT",
"ROLE_DIRECTOR",
"ROLE_PARENT",
"ROLE_ADMISSION_USER",
"ROLE_FEE_USER"
    ]

         // create roles which are not existed in role table

def dbRoles = Role.findAll()*.authority
if(!dbRoles.containsAll(roles)){
roles.each{ def role = new Role(authority:it).save(flush:true) }
}

// create the admin account if it doesn't exists
def admin = Account.findByUsername("admin")
if(!admin){
//create an account
admin = new Account()
admin.username = "admin"
admin.password = "admin"
admin.save(flush:true)

roles.each{
def role = Role.findByAuthority(it)
AccountRole.create(admin, role)
}
                 }

Step 2 : run the project. main page will be displayed. click on login controller it renders login page.
Step 3 : give user name & password it checks those parameters in account table in database.
if login is valid it calls the controller what we given at defaultTargetUrl in config. otherwise it shows error
message

// Logout Purpose

Step 4 : For Logout, first we override the existing logout controller.
         with CTRL + SHIFT + R, first find out the logout controller. copy that code. create one new logout controller
in our package com.gb.vamsi and then paste the code. overriding is completed.

Step 5 : Create on button in gsp, call index of logout controller on clicking on that. you terminated from your
application and grails main page will be displayed. in this index, you want update logout time details.

Step 6 : after logout, you want to redirect your application to some other page. for that purpose, you make a change '/'
mapping in UrlMappings.groovy.

Step 7 : Example, after logout i want to display login page. the code like as follows:
class UrlMappings {

static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(controller:"/login")          // Here we modify the code
        "500"(view:'/error')
}
      }


Steps to creation of loggers in grails:
// we inject the loggers in config.groovy

Step 1 : By default, loggers will be injected. For maintain of information in some file we will follow like this.
         Add these 3 steps in log4j.main as follows.

         // step 1
appenders {
console name: 'stdout', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')
file name:'file', maxFileSize: 1024, file:'/practice_project/greenbuds/logs/projectLog.log', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')
}

// By default, messages are logged at the error level to both the console and hibe.log
// step 2
root {
error 'stdout', 'file'
additivity = true
}

//step 3
info "grails.app.controllers.com.gb.vamsi"
debug "grails.app.controllers.com.gb.vamsi"
info "grails.app.services.com.gb.vamsi"
debug "grails.app.services.com.gb.vamsi"


Step 2 : After running the application, projectLog.log file created in project drive. the filename is given in step1 appenders -> filename

Step 3 : For every action, the information tracked in logs.




Filters:

Although Grails controllers support fine grained interceptors, these are only really useful when applied to a
few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied
across a whole group of controllers, a URI space or to a specific action. Filters are far easier to plugin and
maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns
such as security, logging, and so on.


To create a filter create a class that ends with the convention Filters in the grails-app/conf directory.

Filter Types:


Within the body of the filter you can then define one or several of the following interceptor types for the filter:

    before - Executed before the action. Return false to indicate that the response has been handled that that all
    future filters and the action should not execute

    after - Executed after an action. Takes a first argument as the view model to allow modification of the model
   before rendering the view

    afterView - Executed after view rendering. Takes an Exception as an argument which will be non-null if an exception
occurs during processing. Note: this Closure is called before the layout is applied.

Note : Every action comes under filter


Grails : How to access config file details in controller

// The config file is in the format as follows:

// SMS Settings IN Config
app{
sms{
senderId = "KRISHNA"
}
}

// senderId access as follows : grailsApplication.config.app.sms.senderId

Grails : Project exceptions maintained in text document

/*
 * This function useful to create exception text documents of the project. when any exception rises it
 * creates the text document and saves that exception in that file
 */

def exceptionHandler(){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy")
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy HH.mm.ss")
def folder = new File("D:\\Gimboard\\"+sdf.format(new Date()))
if( !folder.exists())  folder.mkdirs()
def fileName = "Exception "+sdf1.format(new Date())+".txt"
def  fileStore = new File(folder,fileName)
fileStore.createNewFile()
def data = request.exception
def ln = System.getProperty('line.separator')

                // Two methods are there. for print stack trace lines. use one method for printing in doc

                // Method 1 :

fileStore.withWriter{
it << "Exception : $ln$ln              "+data+" $ln$ln"
it << "Cause : $ln$ln"
data.getCause().getProperties().each{prop->
if(prop.getKey() == "stackTrace"){
it << "              "+prop.getKey()+" :  "
prop.getValue().each {stack->
it << "                            "+stack+"$ln$ln"
}
}
else it << "              "+prop.getKey()+" : "+prop.getValue().toString()+" $ln$ln"
}
//it << "Trace : $ln$ln              "+data.getStackTrace().toString()+"$ln$ln"
}

// Method 2 :

fileStore.withWriter{ request.exception.stackTraceLines.each{e -> it << e } }

render view:"/error", model:[cause:data.getCause().getProperties().toString(),exception:data]
}
}

Convert Date to Milliseconds in javascript

// convert date time to milli seconds; date is in the format of dd/mm/yyyy hh:mm a;
function convertDateTime(date){
var O_dateParts = date.split(' ');
var hours;
if(O_dateParts[2] == "AM" && parseInt(O_dateParts[1].split(':')[0]) == 12) hours = 0;
else if(O_dateParts[2] == "AM") hours = O_dateParts[1].split(':')[0];
else if(O_dateParts[2] == "PM") hours = parseInt(O_dateParts[1].split(':')[0]) + 12;
return (new Date(O_dateParts[0].split('/')[2],parseInt(O_dateParts[0].split('/')[1])-1,O_dateParts[0].split('/')[0],hours,O_dateParts[1].split(':')[1])).getTime();
}

Grails commands


Available commands:
  help      (\h ) Display this help message
  ?         (\? ) Alias to: help
  exit      (\x ) Exit the shell
  quit      (\q ) Alias to: exit
  import    (\i ) Import a class into the namespace
  display   (\d ) Display the current buffer
  clear     (\c ) Clear the buffer and reset the prompt counter.
  show      (\S ) Show variables, classes or imports
  inspect   (\n ) Inspect a variable or the last result with the GUI object browser
  purge     (\p ) Purge variables, classes, imports or preferences
  edit      (\e ) Edit the current buffer
  load      (\l ) Load a file or URL into the buffer
  .         (\. ) Alias to: load
  save      (\s ) Save the current buffer to a file
  record    (\r ) Record the current session to a file
  history   (\H ) Display, manage and recall edit-line history
  alias     (\a ) Create an alias
  set       (\= ) Set (or list) preferences
  register  (\rc) Registers a new command with the shell
  doc       (\D ) Opens a browser window displaying the doc for the argument