Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Friday, June 17, 2016

Basic steps while dealing with application slowness due to database

In this blog I will share my experience of improving web application performance. Application slowness is often faced in large scale applications. Slowness can happen due to multiple factors and one of the major factor is because of bad database design.

Recently I got a chance to work on an application optimization task. The whole activity includes many areas that are focused and optimized. The main performance improvements are though after database optimizations are done. I am listing down some of the major activities that are performed and found very helpful in finding performance improvement areas.

Is it really a database problem?

Get web server traces and find if there is performance issue in the application itself. Before saying that DB is the only issue just double check by getting and comparing the web server traces and SQL-Profiler traces. Confirm that most of the time taken by request is through database and not something from application itself.

Execute and check SQL-Profilers

Execute the SQL-Profiler and check the queries/stored-procedures that are taking most of time. Notice both duration and read counts in causing application slowness.

Check proper indexes

From the profiler traces one can easily identify the queries or stored-procedures that are taking time. Once those are identified, first thing you have to look is to check your indexes on tables used in queries or stored-procedures. Add appropriate indexes on required columns.

Execute query execution plans

Before I was not very friendly with this feature of Microsoft SQL Server. The Actual Execution Plan of a particular query or SP is very helpful in finding out the specific area that is taking time. The execution plan also suggests the indexes that can fasten up the execution. The suggested indexes can be applied on tables and the impact can be re-checked by executing query/SP again.

Use JOIN instead of IN statements on large data

Other than indexes do go through the statements either those can be overwritten more efficiently. For example instead of using IN clause use JOINS if the data is too much for IN clause.

Check for LOCKS

Specifically taking about MSSQL, it has different pre-defined SP calls that can hep in identifying locking information. For example sp_who2 and sp_lock SPs can be called to get locking information. Statements can be locked due to synchronous Update/Read hits are made on a same table in database. One of the statements can be blocked/locked until other statement releases the table lock.

Use WITH (NOLOCK) where ever required

Do not use WITH(NOLOCK) everywhere. Use it where ever required. I am not going to mention the details of using/not-using WITH(NOLOCK) but I will suggest to read some helpful articles related to this.

Check database statistics

Database statistics can be find out from sys.stats system table. sp_updatestats command can be used to update database statistics. Index rebuilding can also happen statistics update. These activities are not mandatory but if for some reason your database indexes goes bad you have to update/rebuild them. Bad database indexes cannot only return false results but can also make the query/SPs very slow to execute.

rizzz86

Friday, September 26, 2014

Android Library Project and its usage

"Android Library projects contain shareable Android source code and resources that you can reference in Android projects. This is useful when you have common code that you want to reuse. Library projects cannot be installed onto a device, however, they are pulled into the .apk file at build time." 

When creating a new Android project you can mark a project as ‘Library’ project. This will create a project that can be shared/used in multiple projects. You cannot run/install the library project stand alone instead you have to reuse it in Android project.

How to mark a project as library:


Create a new Android project that will use the library project. Library project can be added as reference as follows:
  • Android Project > Properties > Android (left option) > Library (bottom right pane) > Add

  
                       

Click ‘Apply’ > ‘OK’

  • To use the library class activities in android project, 'import' the library references where ever you are using library files.
  • To launch the library activity you should have that activity listed in your Android project 'AndroidManifest.xml'.
  • Don’t make files (Layouts, Classes, XML’s) with the same name in main and library projects. This can cause problems at run time. What I have noticed is that if you have same name layouts in both projects the library layout got overridden and parent layout will be used.


rizzz86

Friday, May 30, 2014

Manipulating PDF document using iText library

There are several libraries that can be used to manipulate a PDF document like PDFBox, iText, PDFClows etc. I also have to do some PDF manipulation stuff and I decided to go with iText. I choose iText because it supports low level PDF manipulation, its community is very strong, lots of helping hands are available and it is also open source and available in both Java and C#.

iText allows you to create a PDF doument, add content in it, update content and save it. I have tried following basic features so far and found it really interesting:

  • With low level support one can add a text chunk, paragraph, phrase, link, chapter, section, image, set text color and other attributes into the document. 
  • You can also create a table/grid inside a PDF document and play with each cell of the table.
  • It is also easy to read an existing PDF document. You can retrieve existing information related to document and pages.
  • Using iText one can also fill up an empty PDF template.
  • It allows to set javascript in a PDF document to make a document interactive. Document can be also be navigated to a particular page. Creating bookmarks, annotations and triggering javascirpt from a button can also be done using iText.
  • Document can also be password encrypted to allow/disallow certain actions that can be done the document.
  • Whole PDF document can also be signed using a certificate to make the document secure.
There is also a book on how to play with PDFs using iText in Action. He is the author of iText in Action and is very supportive on stackoverflow. I also have some questions regarding iText on stackoverflow on this link.

rizzz86

Friday, August 30, 2013

My experience @ RIKSOF

In this post I am going to mention my experience at 'RIKSOF Private Limited' where I have worked for around 2 years as a 'Senior Java Developer'.

Before starting I would like to mention one thing i.e. all the points are solely based on my own working experience at RIKSOF, :)

Learning Curve: You can learn a lot of new technologies here. Most of the developers working here have hands-on experience on at least two different technologies. You can get a chance to work on multiple platforms (Java, .Net, iOS, Android) and use different operating systems (Ubuntu, Mac, Windows). Due to 'project based' nature of company you will also be learning different domains based on what type of project you will get.

Staff: From CEO to Peon you can find a really nice and cooperative staff in RIKSOF. All of them are very helpful and always ready to support you whenever needed.

Picnic and Parties: This is something very common in RIKSOF. There is a quarterly Picnic/Dinner from company (location decided by employees). Apart from that the staff members are very keen to arrange Lunch, Dinner, Refreshments etc whenever possible. A separate well maintained planner is also available for this called 'Mangaloo Planner'.

Physical Environment: Talk about the building first that will definitely attract any one who sees it first time. The interior designs and building architecture is very impressive as compared to other office buildings in overall Karachi. The office from inside is also nicely designed. It has been designed by the interior designers that gives the creative look of office. The sitting area is also good (though not have the cubicles) with nice view outside the building.

Two day weekend: This is something that is quite common now but I liked it because in my previous company I have to work on alternative Saturdays.

Timings: There is no restriction on timings in RIKSOF. You just have to complete your task and leave. Some people come at 7 am and leave at 4 pm. My timing is mostly from 11 am to 8 pm.

Yearly Bonus: At the end of each year you will get the yearly bonus equals your salary. This is the actual saving that you can make the whole year.

Fuel Card: PSO card is provided by company which has limit up to 3000 rupees. The limit is ok for those who travel on bikes but very low for them who are on cars. But I will count it as positive because something is better than nothing :)

Salary on Time: You will get your salary on time

Some Good Memories:



Distance: Its too far from my home. I have to drive 55 km daily to cover home-office-home.

Technology Switching: In software houses mostly a person hired on technology has to work on the same technology or may be switch to a different flavor of it (for example Java EE switching to Android development). But in RIKSOF it can be possible that your designation is Java developer but you work on iOS application and the same case is with me. Most of times it doesn't feels good that you have to work on technologies that you haven't work on previously and you have to meet all deadlines as well.

Very tight deadlines: Project deadlines are very tight and its quite tough to meet the timelines and complete project on time. In span of two years I can see only two projects that completes on time else all are delayed.

No Work-Life Balance: To meet tight deadlines it becomes quite difficult to balance the work with your daily life. Most of the developers in RIKSOF has to do late sitting.

Project Base Development: You will feel sometimes that your job is not safe when you see that company doesn't have a project on which you can work on. Same situation comes to me as well when there are no Java or Android projects in company and I have only one option to switch to iOS projects.

Timings: I have also mentioned this in GOOD part of RIKSOF but there is also bad in it. To balance work with daily life I have tried several times to come early in office and leave early from office but have failed in not more than two days. If I reach office at 9 am and still have to leave at 9 pm due to work then I think there should be some strictness on timing i.e. to come earlier than 10 am or not to stay at office more than 8 pm.


rizzz86

Wednesday, October 5, 2011

JAVA: Date and Calendar

This is not something new but something of very common use in most of the projects. In this post I am going to write some date, time and calendar functions that are commonly used as utility. From next time I will copy them from this post rather than code them again.

To get a Date in any Format the SimpleDateFormat Class is used. Following snippet will return current date in provided format in SimpleDateFormat argument.

Date date = new Date();    
DateFormat dateFormatter = new SimpleDateFormat("dd");    
String formattedDate = dateFormatter.format(date);


Format "dd" is used to get the date number from date

Format "yyyy" is used to get the year number from date

Format "MM" is used to get the month number from date

Format "MMMM" is used to get the month name from date

This method will return the date of targeted format from source format.

    String dt = dateString;  // Start date
    SimpleDateFormat sdf = null;
    try {
            sdf = new SimpleDateFormat(sourceFormat);
            Date date = sdf.parse(dt);
    
            sdf  = new SimpleDateFormat(targetFormat);
            dt = sdf.format(date);  // dt is now in the new date format            
    } catch (ParseException e) {
        e.printStackTrace();
    }



To get Number of Days in a Month we will take help from Calendar Class here. Following method will be usd to get number of days in a month.

public static int getNumberOfDaysInMonth(int screenMonth){
      Calendar calendar = Calendar.getInstance();
      int year = Integer.valueOf(getYearNumber());
      int month = screenMonth;
      int date = 1;
      calendar.set(year, month, date);
      int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);        
      
      return days;
}


This method will return Month Name from month number. Calendar is used here as well.

public static String getMonthNameByMonthNumber(int currentMonthNumber) {
    String dt;
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, currentMonthNumber);
    c.add(Calendar.MONTH, 0);  // number of days to add
    
    SimpleDateFormat sdf  = new SimpleDateFormat("MMMM");
    dt = sdf.format(c.getTime());  // dt is now the new date        
    return dt;
}


To get the First Day of month following method can be used.

public static String getFirstDayOfMonth(int month) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DATE, 1);

    DateFormat f = new SimpleDateFormat("EEE");        
    return f.format(c.getTime());
}


Similarly to get the first date of week Calendar Class is used.

public static int getFirstDateOfWeek() {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());

    DateFormat f = new SimpleDateFormat("dd");
    String cc = f.format(c.getTime());

    // Plus 1 is done to get the Monday Date instead of Sunday
    return Integer.valueOf(cc) + 1;
}


There are many other methods that can be used commmonly. I will keep updating this post when ever I got something new. Also do comment If there is any method you want to add here or If any of them can be implemented in much better way.

rizzz86

Monday, February 28, 2011

Split a String with Dot "." in JAVA


In JAVA we can split a String with Dot "." using a split() function. But it can be done in a different way as compared to other characters. Dot "." is a reserved character in regular expression, hence it will not treat the split on dot the same way.

Following code can be used to split a string by dot.

String stringWithDot = "rizzz86.blogspot.com"; 
String[] stringArray = stringWithDot.split("\\.");

Double backslash will do the work where one slash is work as a escape character.

rizzz86

Thursday, January 13, 2011

Iterate over JAVA HashMap in FreeMarker

Java HashMap can be iterated in FreeMarker by using a <#list> tag as follows:

<#list hashMap?keys as key>
        ${key}=${hashMap[key]}
<#list>


If you are using the above code with default FreeMarker Configuration then there would be some different behavior during iteration. For example if the HashMap is:

HashMap hashMap = new HashMap();
hashMap.put("1","one");
hashMap.put("2","two"); 

By iterating on hashMap with default Configuration it will output following keys in result:

put
remove
entrySet
hashCode
productElement
clear
isEmpty
1
values
empty
underlying
productElements
copy
getClass
get
copy$default$1
equals
productPrefix
class
canEqual
keySet
size
2
containsKey
productArity
containsValue
productIterator
toString
putAll        


This result shows that the iteration is done on all the available hashMap properties.

To get rid of this you have to set the FreeMarker Configuration as follows:


Configuration configuration = new Configuration();
BeansWrapper wrapper = (BeansWrapper) this.configuration.getObjectWrapper();
wrapper.setSimpleMapWrapper(true);
this.configuration.setObjectWrapper(wrapper);

Here the BeanWrapper's simpleMapWrapper property is set as 'true'. After setting this configuration the results over iterating on hashMap will give only the defined key-value pair.

rizzz86

Wednesday, January 12, 2011

MD5 Hashing in J2ME

MD5 (Message Digest) is a hashing algorithm that can be used to ensure data integrity, save and protect passwords/codes, generate unique keys of limited length against a long literal etc. It takes input as String and generates the Hash of that string.

In JAVA there is a built-in MD5 support in its Standard Edition (J2SE). But if we talk about its Micro Edition (J2ME) their is no support for MD5. The package of JAVA Standard Edition can also be used in Micro Edition if and only if the platform supports the SATSA-Crypto Optional Package (How to know that your platform supports SATSA-Crypto).

I have found and tested the Third-Party implementation that can generate MD5 hash and can be used in JAVA Micro Edition. You can get the MD5 source files from here.

rizzz86

Wednesday, December 29, 2010

J2ME Default Emulator without asking for Permission

While running J2ME project with Default Emulator it will ask for Permissions in case of File Read/Write, HTTP Connectivity etc. To get rid of this Permission on every access you have to change the Security options of Emulator. In my case I am using NetBeans IDE, so to change these options I will go through following steps:
  1. Open Project Properties
  2. Click on Manage Emulators Button
  3. Go to Tools & Extension Tab and Click Open Preferences Option
  4. On Preferences Window click on Security option
  5. Select Security Policy to 'JTWI'
  6. Select Security Domain as 'trusted'
  7. Now run the project it will not ask for access Permissions

 rizzz86

Friday, September 10, 2010

Unit Testing for J2ME - JMUnit

In professional development environment it is a common practice to create Unit Tests. On Java platform there are lots of research and development done on Unit Tests for Enterprise Edition. As far as Java Micro Edition is concerned one of the framework available is JMUnit.

Creating and executing a test case using jmunit is quite simple and can be done without wasting much time to explore it. Following steps will guide you how to work with jmunit:

  •  In your mobile application right click on package (where you want to create a unit test) and select option 'New > Empty JMUnit Test'.
  • It will create a unit test class for you that will look like this:
    /*
     * ABCTest.java
     * JMUnit based test
     *
     */
    
    package hello;
    
    
    import jmunit.framework.cldc10.*;
    
    /**
     * @author rizwan
     */
    public class ABCTest extends TestCase {
        
        public ABCTest() {
            //The first parameter of inherited constructor is the number of test cases
            super(0,"ABCTest");
        }            
    
        public void test(int testNumber) throws Throwable {
        }    
    }  

    • Next you will create a test method in same class and call it in test() using switch cases.
    • Total count of test cases will also be mentioned in unit class constructor.
    • Now the code will look like this:

    /*
     * ABCTest.java
     * JMUnit based test
     *
     */
    
    package hello;
    
    
    import jmunit.framework.cldc10.*;
    
    /**
     * @author rizwan
     */
    public class ABCTest extends TestCase {
        
        public ABCTest() {
            //The first parameter of inherited constructor is the number of test cases
            super(1,"ABCTest");
        }            
    
        public void test(int testNumber) throws Throwable {
            switch(testNumber){
                case 0: 
                    testOne();
                    break;
            }
        }    
    
        private void testOne() throws Exception{
            String tmp = "Hello Rizwan";
            assertEquals(tmp, "Hello Rizwan");
        }
    } 

    • After that you have to mention 'ABCTest' as your Midlet.
    • Go into 'project properties > Application Descriptor > MIDlets' and define unit test name and package here.
    • Run application and you will also get Test option on screen:  
    • Test the project and it will show you the results




    Your mobile test case is ready !

    rizzz86

    Friday, May 7, 2010

    Add External JAR in j2me-polish Project


    To use any external jar in a j2me-polish project following steps need to be taken:

    • Copy jar file in j2me-polish/import/ folder
    • Add jar file in project libraries
    • Update build.xml file by adding attribute 'binarylibraries="jarname1.jar;jarname2.jar"' inside < build > tag. (Multiple jars can be defined by placing semi-colon between jars)

    rizzz86


    Tuesday, May 4, 2010

    Class.forName("classname").newInstance()

    Don't do this foolish mistake again :|

    I was trying to get the class instance using Class.forname(...) but continuosly getting IllegalAccessException.

    At the end I found that the class I am trying to call has a private constructor in it. So it cannot be possible to create an instance of class with private constructor.


    rizzz86

    Thursday, April 22, 2010

    Maven j2me-Archetype

    I am using Netbeans6.7 for mobile project development and want to make that project a 'maven project'. I have maven configured on my machine.

    To make maven based j2me project I have created a new project from File > New Project > Maven > Maven Project > j2me Archetype (2.0.4). The project created successfully and showing the properties of maven as well . . .  BUT !!

    I cannot able to view the properties of mobile project (i.e. Platform Type, Device Profile and Configuration, Midlet Information etc). To execute that project it requires a class with main() method. So I have posted all that on forum and finally got the following answer:

    j2me development is not supported for maven projects in netbeans :(

    rizzz86

    Thursday, April 15, 2010

    JSON source for J2ME (mobile applications)


    Javascript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. I am trying to use it in for mobile application development.

    Today I was looking for a JSON source code for Java Micro Edition (J2ME). After lots of googling I have found it from the following link:


    https://meapplicationdevelopers.dev.java.net/source/browse/meapplicationdevelopers/demobox/mobileajax/lib/json/src/org/json/me/



    rizzz86

    Wednesday, April 7, 2010

    Share Common Code Between J2ME and J2SE Project -- Problem/Solution


    Statement:

    If you are creating a client/server project on Java, where client is a mobile device and server is a web application. Also if there is a common code between client and server then where do you place that common code ?

    I also faces the same and go through the following phases before deciding what to do. The two points that came in mind right away are:

    • Create a J2SE Project and place common code there. Make your client and server project dependant on that common project.
    • Create a J2ME Project and place common code there. Make your client and server project dependant on that common project.

    First I have created J2SE as a Common Project:

    When I execute the client (J2ME) project with a dependency of common project (J2SE), I got the following error:

    Running with storage root DefaultColorPhone
    Method............: 100d2aa8 'com/sun/midp/midlet/MIDletState.createMIDlet (stat
    ic)'
    Stack Chunk.......: e58cd4
    Frame Pointer.....: e58d30
    Current IP........: 10128592 = 10128584 + offset 14
    Previous Frame....: e58cf4
    Previous IP.......: 1012052b (offset 22)
    Frame size........: 8 (1 arguments, 7 local variables)
    Argument[0].......: e59a9c
    Local[1]..........: 0
    Local[2]..........: e58cf4
    Local[3]..........: e68858
    Local[4]..........: e58d08
    Local[5]..........: 100dcdd0
    Local[6]..........: e58cd4
    Local[7]..........: 1015f0a0
    Operand[1]........: e59a9c
    
    Method............: 100cd0e4 'com/sun/midp/midlet/Selector.run (virtual)'
    Stack Chunk.......: e58cd4
    Frame Pointer.....: e58cf4
    Current IP........: 1012052b = 10120515 + offset 22
    Previous Frame....: 0
    Previous IP.......: 1
    Frame size........: 6 (1 arguments, 5 local variables)
    Argument[0].......: e59d10
    Local[1]..........: e68a68
    Local[2]..........: e59a9c
    Local[3]..........: 0
    Local[4]..........: 0
    Local[5]..........: 0
    Operand[1]........: e68a68
    
    VM status:
    Instruction pointer.: 10128592 (offset within invoking method: 14)
    Next instruction....: 0x4c
    Frame pointer.......: e58d30
    Local pointer.......: e58d10
    Stack size..........: 128; sp: e58d48; ranges: e58cdc-e58edc;
    Contents of the current stack frame:
    e58d10: e59a9c (lp)
    e58d14: 0
    e58d18: e58cf4
    e58d1c: e68858
    e58d20: e58d08
    e58d24: 100dcdd0
    e58d28: e58cd4
    e58d2c: 1015f0a0
    e58d30: e58cf4 (fp)
    e58d34: 1012052b
    e58d38: e58d0c
    e58d3c: 100d2aa8
    e58d40: e58cd4
    e58d44: 0 (end of frame)
    e58d48: e59a9c (sp)
    Execution stack contains 112 items:
    e59d10
    e68a68
    e59a9c
    0
    0
    0
    0
    1
    e58cd8
    100cd0e4
    e58cd4
    0
    e68a68
    e59a9c
    0
    e58cf4
    e68858
    e58d08
    100dcdd0
    e58cd4
    1015f0a0
    e58cf4
    1012052b
    e58d0c
    100d2aa8
    e58cd4
    0
    e59a9c
    
    Execution completed.
    429584 bytecodes executed
    10 thread switches
    486 classes in the system (including system classes)
    2380 dynamic objects allocated (72064 bytes)
    1 garbage collections (0 bytes collected)
    ALERT: java/lang/ClassFormatError: Bad version information.
    Execution completed.
    429584 bytecodes executed
    10 thread switches
    486 classes in the system (including system classes)
    2380 dynamic objects allocated (72064 bytes)
    1 garbage collections (0 bytes collected)
    


    After reading some forums I recompile my common project (J2SE) on jdk1.4 and add it as a dependency in client project (J2ME) again (previously I have compiled it on jdk1.5). This time the client (J2ME) executes and works successfully.


    ISSUES:

    In Java the development toolkit for mobile (J2ME) contains limited features as compared to the standard edition (J2SE). If you are creating your project on J2SE then you must not use any feature of J2SE in project that is not provided by J2ME (mobile edition have limited features).

    In jdk1.5 there are some major specification changes due to which it generates different byte-code number that results in "ALERT: java/lang/ClassFormatError: Bad version information". So you need to run/compile your common (J2SE) project on jdk1.3/1.4




    Next I have created J2ME as a Common Project:

    I am using Netbeans 6.7 for development, so I have created 'Java ME > Mobile Class Library' project for common code. The Mobile Class Library is a mobile project but does not contain any Midlets. It uses IDE-generated Ant build scripts and special tasks to pre-process, build, obfuscate, preverify, debug, run and depoly your library in JAVA ME Environment.

    I moved all my common code in this mobile project and then use it as a dependency for both client (J2ME) and server (J2SE) projects and it works properly for both editions. Doing this ensures the compatability of both versions because mobile edition features are already supported by standard edition. Also you will be free from jdk-versioning issue that was faced in previously.

    Conclusion:
    So create 3 different projects, one is a client (J2ME), another is a server (J2SE) and a common project (J2ME) that will be used by client and server.



    rizzz86

    Sunday, October 18, 2009

    FreeMarker: Functions & Macros

    FreeMarker allows you to define Functions and Macros in ftl's as well.

    Functions <#function>:

    Syntax:

    • In FM you can define a function using a simple syntax as follows:
    <#function functionName param1 param2>

    • Here "functionName" is the name of a function and param* shows the parameters that can be passed into the function
    Calling Function:
    • To call a function in ftl's following syntax is used: (Consider the same function definition as define in the 'Syntax')
    ${functionName(param1Val, param2Val)}


    <#return>:
    • The <#return> directive is not mandatory in functions. You can use <#return> any where in the function. Calling a <#return> exits from a function. If no such directive is used it will executes the whole function.

    Macros <#macro>:

    Syntax:
    • Syntax for <#macro> is almost same as <#function>. The name & parameters of macro are define in the same way as in the functions:
    <#macro macroName param1 param2>


    Calling Macro:
    • Calling a <#macro> is done by using "@" directive. Macro is itself a user-defined directive.
    <@macroName param1=param1Val param2=param2Val/>

    Recursion:
    • Macros can perform recursion (calling Macro inside Macro).
    • The recursion is same as done in normal functions.
    • Recursion Syntax:
    <#macro macroName param1 param2>

    <@macroName param1=param1Val param2=param2Val/>

    < /#macro>


    rizzz86

    Saturday, October 10, 2009

    Development Using FreeMarker

    If you are developing your application using freemarker, it is necessary for you to learn its syntax - to create FM templates.

    I have faced some issues while building templates using FM and also learned the right way to use freemarker syntax.

    Following are some points that I have go through while using freemarker:

    Passing Beans to Templates instead of Lists:

    In my case it is suitable for be to create a Java Bean and pass its object to templates. I was sending my data in the form of Lists previously but it is causing some problems as well as making things complex.

    The structure in which the data is stored in the list is the biggest issue. What I have to do is to create a menu that can have n-numbers of sub-menus and each sub-menu can have n-numbers of their sub-menus. Getting really mixed up using lists. Now I have created a bean to handle my menus. Bean looks like as follows:



    class MenuBean {

    String title;
    String url;
    List children;
    etc..
    }



    If condition and null object identification:

    To handle conditional statements it is quite easy in freemarker. The "IF" condition can easily be applied any where with <#if> clause. One thing to remember here is that the closing tags are must for most of freemarker tags. So when the conditional tag ends also has to placed. Just like brackets open and closed.

    Identification of empty list or null can also if done by <#if> tag. The syntax is a bit cheeky but it works. The statement "<#if yourList??>" verifies that their exists some element inside "yourList" and is not null, so it enter into the condition.


    foreach tag:

    Iterating through a list can also be done in freemarker. A simple <#foreach> tag is provided to iterate a list.

    The sytax for foreach tag is also simple:

    <#foreach element in yourList>


    Here element is just an alias of your list that can be used to access the properties or values inside youList.

    yourList is the name of list.


    list tag:

    List tag is also used to iterate any list. It can also be used as a "for loop".

    To iterate a list using <#list> following syntax is used:

    <#list yourList as x>


    If you want to used <#list> to work as a for loop, you have to use it as follows:

    <#list 1..10 as x>


    The <#list> will loop from 1 to 10 and ends.


    Click this Link for FreeMarker #Functions and #Macros


    rizzz86