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

Keyboard Function keys Functionality

//Functionality of function keys

F1 - help
F2 - rename
F3 - search
F4 - closing the windows
F5 - refresh
F6 - cycle through the items
F7 - check spelling in word
F8 -
F9 -
F10 - activates the windows menu
F11 - Full screen
F12 - For inspect element in browser

How to add number of days to current date

//Add number of days to current date
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 15);
cal.getTime()

What is immutable?

Immutable class is a class which once created, it’s contents can not be changed.
Immutable objects are the objects whose state can not be changed once constructed.
e.g. String class

Count of Days, Months and Years

/*
 * @author Himabindu
 * When you pass start date & end date to the function, it returns a map which contain number of days,number of months
 * & years will return
 *
 */

def getDatesCountMap(startDate, endDate){

int[] monthDay = [ 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
Calendar fromDate
Calendar toDate
def increment = 0
def year
def int month
def int day

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

def p1 = startDate + " 00:00:00"
def p2 = endDate + " 00:00:00"

Date start = format.parse(p1)
Date end = format.parse(p2)

Calendar d1 = new GregorianCalendar().getInstance();
d1.setTime(start);

Calendar d2 = new GregorianCalendar().getInstance();
d2.setTime(end);

if (d1.getTime().getTime() > d2.getTime().getTime()) {
fromDate = d2;
toDate = d1;
} else {
fromDate = d1;
toDate = d2;
}

if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH)) {
increment = monthDay[fromDate.get(Calendar.MONTH)];
}

GregorianCalendar cal = new GregorianCalendar();
boolean isLeapYear = cal.isLeapYear(fromDate.get(Calendar.YEAR));

if (increment == -1) {
if (isLeapYear) {
increment = 29;
} else {
increment = 28;
}
}

// DAY CALCULATION
if (increment != 0) {
day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
increment = 1;
} else {
day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
}

// MONTH CALCULATION
if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
increment = 1;
} else {
month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
increment = 0;
}

// YEAR CALCULATION
year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);

def dateMap = [:]

dateMap.days = day
dateMap.month = month
dateMap.year = year
return dateMap
}

Tuesday, 23 December 2014

Message Properties use in struts2

in struts2.x we can access properties file properties in

jsp and action classes( which extends ActionSupport) very easily

the following step will help to access properties file in easy manner....

Step 1: Create struts.properties in src folder.
Step 2: Create any properties file in src folder (let suppose messages.proprerties).
Step 3: copy and past following line in struts.properties
struts.custom.i18n.resources=message
Step4: let suppose the following one are properties in message.properties
unAuthorize=Your not Eligible to Acess...!
exception= Exception is Raised.
sessionExpire= Your Session is Over ...!

Step 5: if u want those properites in Jsp page...
<s:property value="getText('sessionExpire')"/>
Step 6: if u want those properties in action class
getText("unAuthorize");

Message properties use in struts 2

Thursday, 18 December 2014

How to change author name in eclipse


First Goto windows -> preferences
Change the template patterns in eclips by sairam rajulapati

Tuesday, 16 December 2014

More than 100 Keyboard Shortcuts

Keyboard Shortcuts (Microsoft Windows)
1. CTRL+C (Copy)
2. CTRL+X (Cut)
... 3. CTRL+V (Paste)
4. CTRL+Z (Undo)
5. DELETE (Delete)
6. SHIFT+DELETE (Delete the selected item permanently without placing the item in the Recycle Bin)
7. CTRL while dragging an item (Copy the selected item)
8. CTRL+SHIFT while dragging an item (Create a shortcut to the selected item)
9. F2 key (Rename the selected item)
10. CTRL+RIGHT ARROW (Move the insertion point to the beginning of the next word)
11. CTRL+LEFT ARROW (Move the insertion point to the beginning of the previous word)
12. CTRL+DOWN ARROW (Move the insertion point to the beginning of the next paragraph)
13. CTRL+UP ARROW (Move the insertion point to the beginning of the previous paragraph)
14. CTRL+SHIFT with any of the arrow keys (Highlight a block of text)
SHIFT with any of the arrow keys (Select more than one item in a window or on the desktop, or select text in a document)
15. CTRL+A (Select all)
16. F3 key (Search for a file or a folder)
17. ALT+ENTER (View the properties for the selected item)
18. ALT+F4 (Close the active item, or quit the active program)
19. ALT+ENTER (Display the properties of the selected object)
20. ALT+SPACEBAR (Open the shortcut menu for the active window)
21. CTRL+F4 (Close the active document in programs that enable you to have multiple documents opensimultaneously)
22. ALT+TAB (Switch between the open items)
23. ALT+ESC (Cycle through items in the order that they had been opened)
24. F6 key (Cycle through the screen elements in a window or on the desktop)
25. F4 key (Display the Address bar list in My Computer or Windows Explorer)
26. SHIFT+F10 (Display the shortcut menu for the selected item)
27. ALT+SPACEBAR (Display the System menu for the active window)
28. CTRL+ESC (Display the Start menu)
29. ALT+Underlined letter in a menu name (Display the corresponding menu) Underlined letter in a command name on an open menu (Perform the corresponding command)
30. F10 key (Activate the menu bar in the active program)
31. RIGHT ARROW (Open the next menu to the right, or open a submenu)
32. LEFT ARROW (Open the next menu to the left, or close a submenu)
33. F5 key (Update the active window)
34. BACKSPACE (View the folder onelevel up in My Computer or Windows Explorer)
35. ESC (Cancel the current task)
36. SHIFT when you insert a CD-ROMinto the CD-ROM drive (Prevent the CD-ROM from automatically playing)
Dialog Box - Keyboard Shortcuts
1. CTRL+TAB (Move forward through the tabs)
2. CTRL+SHIFT+TAB (Move backward through the tabs)
3. TAB (Move forward through the options)
4. SHIFT+TAB (Move backward through the options)
5. ALT+Underlined letter (Perform the corresponding command or select the corresponding option)
6. ENTER (Perform the command for the active option or button)
7. SPACEBAR (Select or clear the check box if the active option is a check box)
8. Arrow keys (Select a button if the active option is a group of option buttons)
9. F1 key (Display Help)
10. F4 key (Display the items in the active list)
11. BACKSPACE (Open a folder one level up if a folder is selected in the Save As or Open dialog box)
Microsoft Natural Keyboard Shortcuts
1. Windows Logo (Display or hide the Start menu)
2. Windows Logo+BREAK (Display the System Properties dialog box)
3. Windows Logo+D (Display the desktop)
4. Windows Logo+M (Minimize all of the windows)
5. Windows Logo+SHIFT+M (Restorethe minimized windows)
6. Windows Logo+E (Open My Computer)
7. Windows Logo+F (Search for a file or a folder)
8. CTRL+Windows Logo+F (Search for computers)
9. Windows Logo+F1 (Display Windows Help)
10. Windows Logo+ L (Lock the keyboard)
11. Windows Logo+R (Open the Run dialog box)
12. Windows Logo+U (Open Utility Manager)
13. Accessibility Keyboard Shortcuts
14. Right SHIFT for eight seconds (Switch FilterKeys either on or off)
15. Left ALT+left SHIFT+PRINT SCREEN (Switch High Contrast either on or off)
16. Left ALT+left SHIFT+NUM LOCK (Switch the MouseKeys either on or off)
17. SHIFT five times (Switch the StickyKeys either on or off)
18. NUM LOCK for five seconds (Switch the ToggleKeys either on or off)
19. Windows Logo +U (Open Utility Manager)
20. Windows Explorer Keyboard Shortcuts
21. END (Display the bottom of the active window)
22. HOME (Display the top of the active window)
23. NUM LOCK+Asterisk sign (*) (Display all of the subfolders that are under the selected folder)
24. NUM LOCK+Plus sign (+) (Display the contents of the selected folder)
MMC Console keyboard shortcuts
1. SHIFT+F10 (Display the Action shortcut menu for the selected item)
2. F1 key (Open the Help topic, if any, for the selected item)
3. F5 key (Update the content of all console windows)
4. CTRL+F10 (Maximize the active console window)
5. CTRL+F5 (Restore the active console window)
6. ALT+ENTER (Display the Properties dialog box, if any, for theselected item)
7. F2 key (Rename the selected item)
8. CTRL+F4 (Close the active console window. When a console has only one console window, this shortcut closes the console)
Remote Desktop Connection Navigation
1. CTRL+ALT+END (Open the Microsoft Windows NT Security dialog box)
2. ALT+PAGE UP (Switch between programs from left to right)
3. ALT+PAGE DOWN (Switch between programs from right to left)
4. ALT+INSERT (Cycle through the programs in most recently used order)
5. ALT+HOME (Display the Start menu)
6. CTRL+ALT+BREAK (Switch the client computer between a window and a full screen)
7. ALT+DELETE (Display the Windows menu)
8. CTRL+ALT+Minus sign (-) (Place a snapshot of the active window in the client on the Terminal server clipboard and provide the same functionality as pressing PRINT SCREEN on a local computer.)
9. CTRL+ALT+Plus sign (+) (Place asnapshot of the entire client window area on the Terminal server clipboardand provide the same functionality aspressing ALT+PRINT SCREEN on a local computer.)
Microsoft Internet Explorer Keyboard Shortcuts
1. CTRL+B (Open the Organize Favorites dialog box)
2. CTRL+E (Open the Search bar)
3. CTRL+F (Start the Find utility)
4. CTRL+H (Open the History bar)
5. CTRL+I (Open the Favorites bar)
6. CTRL+L (Open the Open dialog box)
7. CTRL+N (Start another instance of the browser with the same Web address)
8. CTRL+O (Open the Open dialog box,the same as CTRL+L)
9. CTRL+P (Open the Print dialog box)
10. CTRL+R (Update the current Web page)
11. CTRL+W (Close the current window)

Monday, 15 December 2014

How to read from properties file

in java projects reading properties files are common thing
but we fee littel bit inconvenient for write a code for reading properties files
but apache provide one util class for reading properties file in very easy manner than regular reading process.....
the following pic will show u how can i read properties file by using
org.apache.commons.resources.message.MessageResources;

Example : How to read from properties file

Friday, 12 December 2014

Why Java

Reason for platform independent

Basics

Popular java editors
Java supports fundamental concepts
Variable Types

Singleton Purpose:
The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.
Singleton Example
Access modifiers

Non - Access Modifiers
Abstract Class
Difference between throw & throws

Create Your Own Exceptions



Monday, 8 December 2014

Jquery Alphabet Validation

//In text fields enter only alphabets if status is true; otherwise it enters alpha-numeric
function alphabetsValidation(fieldId,status) { $(fieldId).keyup(function(){ var regExp = /^[a-zA-Z]/; // allow only letters var iChars = ""; if(status) iChars = "0123456789!@#$%^&*()+=-_[]\\\';,./{}|\":<>?"; else iChars = "!@#$%^&*()+=-_[]\\\';,./{}|\":<>?"; if (!regExp.test($(fieldId).val())) { $(fieldId).val(''); return false; } else for ( var i = 0; i < $(fieldId).val().length; i++) { if (iChars.indexOf($(fieldId).val().charAt(i)) != -1) { $(fieldId).val(''); return false; } } }); }

Thursday, 4 December 2014

Difference between PATH and CLASSPATH in Java


PATH and CLASSPATH are operating system level environment variables. PATH is used to define where the system can find the executables (.exe) files whereas CLASSPATH is used to specify the location of .class files.

                                                                                                             - By Sairam Rajulapati

Tuesday, 2 December 2014

Best Javascript frameworks

Use of Javascript Objects

The javascript objects acts as java beans. which is useful to store information & retrieve the information as easy without any objects.

Creation of javascript object:

var ob = new Object();

ob is an object. present i have to add some properties to this object like name & nickname.

ob.name = "Vamsi";
ob.nickname = "Krishna"

if you print these object properties like this:

console.log(ob.name);
console.log(ob.nickname);

How to maintain number of objects / records. let us see..

Take one empty arraylist add these objects to that array. simple..

var recordsList = [];
for(var i=0;i < 5;i++){
           // Here for every time created a new Object.
           var record = new Object();
           // Decide your properties
          record.uniqueRow = i;
          record.name = "Vamsi "+i;
          // Add this to arraylist
        recordsList.push(record);
}

//Print final arraylist
console.log(recordsList);  // Those are in object format

It reduces lot of java coding. the data easily prepared..

Happy Coding.. Dont do hardwork.. do smart work..