Translate

Friday 20 December 2013

How to set datasource in iReport using a JRDatasource Provider as well as custom JRDataSource - Along with sample and Video Tutorial

JRDataSource is interface that represents the abstract representation of a JasperReports data source. All data source types must implement this interface.

We could create   JRDatasource using java code, but there is a stipulation that the class made as the datasource needs to implement JRDataSource interface.

Now, in this article I will talk about:
1. Setting the datasource using custom JRDataSource.
2. Setting the datasource using JRDataSourceProvider.

To start with, 
Setting the datasource using custom JRDataSource.
The prerequisites for the creating a custom datasource are:
1. JRDataSource
2. Factory class setting the JRDataSource.



Setting the datasource using JRDataSourceProvider
The prerequisites for the creating a custom datasource are:
1. JRDataSource
2. JRDataSourceProvider implemented class.


For showing setting of each of the methods I have created a youtube video.
                                                ==VIDEO LINK==

In the sample I have created, what I intend to do is that I want to know the names, is directory(boolean true/false) and the size on disk, of the folder whose path is passed in the constructor of the datasource. Now in my datasource I have 3 columns NAME, SIZE and IS_DIRECTORY.

In both the cases we need to create a JRDatasource class .. that is the class which implements JRDataSource, so in the sample it looks like this 

/**
* JR DataSource Class
* @author Ankur Gupta
*/
public class JRFileSystemDataSource implements JRDataSource {
File[] files = null;
int index = -1;
public JRFileSystemDataSource(String path) {
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
files = dir.listFiles();
}
}

@Override
public boolean next() throws JRException {
index++;
if (files != null && index < files.length) {
return true;
}
return false;
}

@Override
public Object getFieldValue(JRField jrf) throws JRException {
File f = files[index];
if (f == null) {
return null;
}
if (jrf.getName().equals("name")) {
return f.getName();
} else if (jrf.getName().equals("IS_DIRECTORY")) {
return new Boolean(f.isDirectory());
} else if (jrf.getName().equals("totalSpace")) {
return new Long(f.length());
}
// Field not found...
return null;
}

/**
* This method is responsible for setting the field names in the provider.(Required for the provider)
* @return
*/
public static String[] fieldNames() {
String[] fieldNames = {"name", "IS_DIRECTORY", "totalSpace"};
return fieldNames;
}
}
CODE SCRIPTLET #1
The  fieldNames()  method is not required for custom JRDataSource , but is required for JRDataSource Provider.

Now for the custom JRDatasource
1. The JRDataSource as shown above.(Remove the last method not required.)
2. The Factory Class for the custom JRDataSource looks like.

/**
*
* @author Ankur Gupta
*/
public class FactoryClassDataSource {

/**
* Factory Class responsible for setting the JRdatasource.
* @return
*/
public static JRDataSource generateDS(){
return new JRFileSystemDataSource("Path of the desired folder");
}
}
CODE SCRIPTLET #2

This is it, now you can compile these two classes , and place the jar file in the class path.

Now for the  JRDatasource Provider.
1. The JRDataSource as shown as above in the code scriptet #1.
2. Next is the JRDataSourceProvider class shown as below.


/**
* JRDatasource Provider
* @author Ankur Gupta
*/
public class JRFileSystemDataSourceProvider implements JRDataSourceProvider{

@Override
public boolean supportsGetFieldsOperation() {
return false;
}

@Override
public JRField[] getFields(JasperReport jr) throws JRException, UnsupportedOperationException {

ArrayList fields = new ArrayList();
String [] fieldNames = JRFileSystemDataSource.fieldNames();
for (String s : fieldNames) {
JRDesignField field = new JRDesignField();
field.setName(s);
field.setValueClassName("java.lang.String");
fields.add(field);
}
return (JRField[]) fields.toArray(new JRField[fields.size()]);
}

@Override
public JRDataSource create(JasperReport jr) throws JRException {
return new JRFileSystemDataSource("Enter the path of folder");
}

@Override
public void dispose(JRDataSource jrds) throws JRException {
}

}
CODE SCRIPTLET #3

Now, you can compile the classes and get the jar and place it in the classpath of iReport.

This was the portion you need to complete in creating the JAR file, now we need to set the datasource in thr iReport .
For setting the datasource as custom JRDataSource, you need to enter the qualified path of the factory class. In iReport it looks like :

 
Custom JRDataSource

Now you need to create the fields in the iReport by doing a right click on the field node and remember that the name of the field should be same as in the datasource . In the sample we need to create 3 fields as  name, IS_DIRECRTORY,totalSpace. 
And then place these fields in the detail section of the report and then preview the report and then you could see the contents of the folder(In the sample the folder path is set to C drive.)

For setting the datasource as JRDataSourceProvider, you need to set datasource by selecting to create a new datasource of type JRDataSourceProvider. In the sample it looks like
JRDataSourceProvider

Now the difference in the custom JRDataSource and JRDataSource Provider is that in this function you will not be worried for creating the field  you could directly fetch it by going to the Report query, navigate to DataSource Provider tab and click on Get Fields from dataSource , it will display all the fields in case of this sample it look like :



You then use the fields in the report and you can obtain similar structure of folder.


Here is the sample ZIP file 

                                                              ==ZIP FILE==
This ZIP  file will contain
1, TestRun PDF
2. JRXMLs for both the custonm JRDataSource as well  as JRDataSource Provider
3, JAR file which is needed to be placed in the classpath of iReport.

You could follow the video and sample and learn how to set the datasource with JRDataSource easily.

Please put you questions or demands for clarification in the comments section below.

Happy Coding.,,,!!!

How to set JavaBean set as Datasource in iReports, along with a working sample.

Java beans are practically, classes that encapsulate many objects into a single object (the bean). This is pretty simple to create and could easily hold lots of data in them. They are serializable, have a 0-argument constructor, and allow access to properties using getter and setter methods.

In a nutshell, java bean is easy to use methodology to obtain data. Now the task in hand is that how to use this bean in our reports . For setting the bean in reports there are few prerequisites, 

  1. There should be a Bean class
  2. There should be a factory class which returns the collection/array of the beans
iReport provides two options, either it could read from collection of beans or array of beans. First of all we need a bean, so below is how the bean looks like.
/**
* Bean
*
* @author Ankur Gupta
*/
public class PersonBean {
private String name = "";
private int age = 0;
public PersonBean(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}

Now you need to create a factory class which contains the function which returns the bean.There are two ways to do that :
1. Collection of bean

/**
* Responsible for filling values in the Bean and return it as collection of bean.
*
* @author Ankur Gupta
*/
public class TestFactory {

public static java.util.Collection generateCollection() {
// Creates the collection
java.util.Vector collection = new java.util.Vector();

// Adds the values in the bean and adds it into the collection
collection.add(new PersonBean("Ted", 20));
collection.add(new PersonBean("Jack", 34));
collection.add(new PersonBean("Bob", 56));
collection.add(new PersonBean("Alice", 12));
collection.add(new PersonBean("Robin", 22));
collection.add(new PersonBean("Peter", 28));

// returns the collection of beans.
return collection;
}
}
2. Array of Beans

/**
* Responsible for filling values in the Bean and return it as collection of bean.
*
* @author Ankur Gupta
*/
public class TestFactory {

// Creates the Arraylist
PersonBean[] list = new PersonBean[6];

// Adds the values in the bean and adds it into the Array
list[0]= (new PersonBean("Ted", 20));
list[1]= (new PersonBean("Jack", 34));
list[2]= (new PersonBean("Bob", 56));
list[3]= (new PersonBean("Alice", 12));
list[4]= (new PersonBean("Robin", 22));
list[5]= (new PersonBean("Peter", 28));

// returns the Array of beans.
return list;
}
}

Now, we need to compile these files  and put the generated jar file in the classpath of the iReport.

Next we need to set the datasource, by adding datasource Java Bean set as datasource and fill in the Factory class as well as the function which generates the bean as array or collection, whichever suits our purpose.

In this case:
Factory class  :  javabeanset.TestFactory
Generating function: generateBeanArray/generateCollection (based upon collection or array)
Below are some screen shots.

Array of JavaBeans



Collection of JavaBeans

You can follow the video link for setting javabeans as datasource.  Here is the Youtube video made by me which gives a complete walkthrough to set the datasource as javabean with the help of a sample report also.

                                                                   ==The video link==



I have made a sample in the video itself here is zip file which contains:
1, Jar File (You need to place this in your classpath)
2. JRXML File
3. Set datasource as shown in the video and insert the values provided in the above screenshots.
4. Test Run PDF(PDF output of the Sample report)
                                                            == ZIP Sample File ==
Follow all the steps in order to get the sample working.


Hope this clears your doubt for this topic. Still if you face any issues or problems then you can add a comment below .

Happy Coding.!!

Thursday 12 December 2013

Introduction to jasper Reports .

JasperReports is an open source Java reporting tool that can write to a variety of targets, such as: screen, a printer, into PDF,HTMLMicrosoft ExcelRTFODTComma-separated values or XML files.

It can be used in Java-enabled applications, including Java EE or web applications, to generate dynamic content. It reads its instructions from an XML or .jasper file.
JasperReports is part of the Lisog open source stack initiative.

Jasper Reports is quite handy , in huge projects which could summarize the whole project in form of few reports .


I have recently developed a great interest for jasper reports and , stay tuned to the blog and I would post some great tricks and solutions to the common problems.
To know more about this check out a video on this topic which I have created.
Introduction to jasper reports.



Please provide your suggestions and feedback.

Monday 9 December 2013

How to write conditional query in iReport using parameters

Inside iReport creating static query that is, writing a simple static query in the the Query executor and set it up running is quite simple and too monotonous.

The real challenge arrives in actually changing the query of the report dynamically based upon some condition, this could be achieved with a simple implementation of parameters.

Following are the steps to use the conditional SQL Statements.

1. Create a parameter if you want user triggered change of the SQL Query , if not user triggered then it must be based upon the field, so that can be used too.

2. Create a different parameter which will be responsible for triggering the changed query based upon the condition.

3. Now identify the condition which is responsible for changing the query,

4. The parameter which contains the conditional SQL switching should have the property "Used as prompt" turned off and the condition should be placed in the default value.

5. Then after setting this, move onto set the Report Query Expression. Now see the dynamism of the query could be provided to the whole query or a portion of query so accordingly place the expression .The parameter containing the conditional expression should be used as the expression and it should be denoted as $P!{name of the param containing expression}
Here is a little illustration
Suppose there is a parameter called $P{TestParamSQL}, the prompt should be turned off as we are setting the value at runtime checking the value of the $P{TEST_PARAM}. 
Set the default value of the parameter as:
For a single condition 
$P{TEST_PARAM}.equals("test")
? " select SQL query"
: " else SQL select query"
For a multiple condition 

$P{TEST_PARAM}.equals("test")
? " select SQL query"
: $P{TEST_PARAM}.equals("test1")
? " SQL select query"
: $P{TEST_PARAM}.equals("test2")
?" SQL Query"
: "else SQL Query"

Now in the iReport Query executor you should give the following expression$P!{TestParamSQL} 

Do take care that the dependent parameter $P{TEST_PARAM}. should be set before the $P{TestParamSQL} else would throw a null pointer exception.
Another thing which should be kept in mind is that the query given in the quotes in the expression should be syntactically correct, that is the SQL in as the string should be correct.

Here is a running sample-

Prerequesites-
1. JRXML File
2. PDF Export

Steps to set up this Sample Report.
1. Then you must choose Sample Database in the datasource
4. Then next you need to activate the the sample database from Help(in the iReport Menu bar)---> Samples---->Run Sample Database
5. Then Run the  Report

There is a PDF export also which would show exactly how the report looks(The input value is employeeId= 2).

Please put in you queries/suggestions, I will be more than happy to know.
Cheers .. Happy Coding!!

Friday 6 December 2013

How to add user defined function in iReport

In iReport it is very important to have a knowledge of integrating the Java code with the Jasper Report as the things do easier and provide lot of versatility to the report. Usage of Java Code in iReport is achieved by usage of scriptlets.

Scriptlets acts as bridge to get the Java Code in the iReport, scriptlet is a Java class which extends the JRDefaultScriptlet, and in this class we could write our user defined functions which later could be easily accessed in the report.


There are few simple steps which could be followed in order to run the User Defined Functions.

1. Tools(in the iReport Menu bar ) ----->  Options -----> Click on Claspath Tab ------> ADD Jar -----> choose the Jar file ( This JAR is made on building the project containing the scriptlet )
2. Then in the iReport there is a node called Scriptlet in the Report Inspector ( By Default on left ).
3. Go to the properties of the scriptlet , there is a property called 'Scriptlet Class'
4. Key in the the location of the scriptlet class where the user defined function is present  for instance:
com.jasper.scriptlet.TestScriptlet -- In this scenario TestScriptlet is my class where the user defined function is written.
(Remember the the class containing the user defined function needs to be extended by the JRDefaultScriptlet )
5. Now you are set to use it in the report, to use in the iReport you need to use the reference of a parameter called $P{REPORT_SCRIPTLET} , this is a predefined parameter which could come handy.
 6. In order to use the user defined in the iReport, in the the expression would be given as 
 $P{REPORT_SCRIPTLET} .userDefinedFun() -  This is a user defined function which returns values from the scriptlet.
$P{REPORT_SCRIPTLET} .userDefinedFun($F{field})  - This is also a user defined function which returns values from scriptlet, but has an input parameter from the field in the report. So this gives fluidity of the Java from Jasper to Java code.

Here is a running sample-

Prerequesites-
1. JRXML File
2. Jar File
3. PDF Export 

Steps to set up this Sample Report.
1. Tools(in the iReport Menu bar )-----> Options ----- > Click on Claspath Tab ------> ADD Jar -----> choose the Jar file
2.  Then navigate to Scriptlet node in the Report inspector, and then modify the property Scriptlet Class to 'pkg1.ConvertToWord'
3. Then you must choose Sample Database in the datasource
4. Then next you need to activate the the sample database from Help(in the iReport Menu bar)---->Samples---->Run Sample Database
5. Then Run the  Report
There is a PDF export also which would show exactly how the report looks.

Please put in you queries/suggestions, I will be more than happy to know.
Cheers .. Happy Coding!!

How to format number when running report from Java code in iReport

There is always ambiguity that how could you format the data conditionally or at runtime of the report based upon the data in the iReport.

iReport does provides a robust methodology to format the values of the textfield but sometime you require data to be formatted conditionally or needs to be formatted not at the design time but needs to be modified dynamically, that is, based upon the data coming from the datasource or upon the user choice. So this particular article is dedicated to cater this very problem.

The formatting done in the iReport is report specific it like extra utility , of providing the pattern provided by the iReport. When you run that in java code the formatting is removed. So what you can do for the java code is that you could use:
 new java.text.DecimalFormat("pattern").format(put the field here)

So to provide similarity in the report and in the Java code what can be done is that you could replace the expression of the text field with the same expression and the discrepancy could be easily taken care off.In that case the expression would look something like this
 new java.text.DecimalFormat("¤ #,##0").format($F{VALUE})   
Now here the in the field expression easily , any field or parameter could be put and same would work fine for java code too,
Here any pattern can be put, and formatting could be applied to any described field.


Cheers Happy Coding....!!

Thursday 3 October 2013

Women | The Mitochondria of Nation

The topic of the post might seem confusing, let me start with explaining 'Mitochondria' . Have you ever heard of this word? Think for a moment....
Yes of course, you must have studied about this in the elementary biology classes back in 6th grade or so. 'Mitochondria' is a organelle found in the cell , they are responsible for converting glucose into the form of energy which our body can use (that is ATP). These organelles are better known as the 'Powerhouse of the Cell' or 'Cellular Power Plants'.  
So , until now you would have definitely figured out what does 'Mitochondria' refers in the topic, it depicts the Women as the Powerhouse or Power Plant of the Nation. 

So proceeding with the discussion after getting the perception of the topic-- Everyone needs to understand role of women in all the domains. Even after 67 years of independence of India , majority of women have not been able to  free themselves from the dogmatic ideologies of the society. As our nation, India is on track to be a developed nation, as an obligatory measure  it must ensure development of  women simultaneously as, women are the integral part of the total population of the nation.

On the contrary, in current scenario,  there still prevails the discrimination based on sex . Still male children are more facilitated than the female children, providing better opportunities for males. The women in the rural areas( which contains the most of the female population ) are not treated equally, they have no or less say in the family affairs. Mentality of society is under influence of male chauvinism.Women are treated as an entity, and is assumed to be heartless and emotionless being meant to do all the household jobs without complaining. Women are restricted to their homes and they are taught right from their childhood that their ultimate goal of life is to overtake all the household responsibilities after marriage, and so they have to get trained from their childhood killing all other passions.

Looking at the brighter side, if we obliterate the above situation momentarily ( which is hard ) very few women who choose a harder path of fighting the odds and pursue their passions , become successful (no doubt) and excel in their respective domains. For instance, Hon'ble Smt. Pratibha Devisingh Patil is currently President of India, Sania Nehwal an Indian Badminton Player is the first person ever to win a medal in Badminton in Olympics, and many more. Women have proved that when given a chance, they prove their mettle and that is plausible. It is well known Russian Proverb --
                                           "Women can do everything; men can do the rest."
No matter what a woman's appearance may be, it will be used to undermine what she is saying and taken to individualize - as her personal problem - observations she makes about the beauty myth in society.

Rudimentary measures have been taken by Government to reform awful condition of women, but they have to understand , that these measures help small number of women who have already crossed the primary hurdle , but what about the majority of women who are not able to clear the primary hurdle due to several reasons like-- lack of resources, family refusal for studies, etc. So what I suggest is that Government should focus more on the families which have a girl child , educate them regarding the development of women and also support them financially  to facilitate the cause.

So I will end on the note that every person irrespective of their sex , is entitled to exercise their Fundamental Rights as mentioned in Constitution Of India. If anybody tries to deprive a woman of her rights he is doing a crime. As a matter of fact that women excel in all the fields they set their foot, suppose if the majority of women does then our nation could reach to new heights.This could be compared to a engine running on coal, and suddenly fuel is replaced with gasoline, which takes the train to new highs. So, indeed women are the powerhouse of the Nation.

Please put in your thoughts and concerns in the comments below.
Cheers.!!

Monday 30 September 2013

Java FX | A Powerful Platform

Today, in the age of Web 2.0, AJAX, and the iPhone, users have come to expect their applications to provide a dynamic and engaging user interface that delivers rich graphical content, audio, and video, all wrapped in GUI controls with animated cinematic-like interactions. They want their applications to be connected to the web of information and social networks available on the Internet. Developers, on the other hand, have become accustomed to tools such as AJAX/HTML5 toolkits, Flex/Flash, Google Web Toolkit, Eclipse/NetBeans RCP, and others that allow them to build and deploy rich and web-connected client applications quickly. They expect their development languages to be expressive with features that liberate them from the tyranny of verbosity and empower them with the ability to express their intents declaratively.
During the early days of the Web, the Java platform was the first to introduce rich content and interactivity in the browser using the applet technology (predating JavaScript and even Flash). Not too long after applets appeared, Swing was introduced as the unifying framework to create feature-rich applications for the desktop and the browser. Over the years, Swing matured into an amazingly robust GUI technology used to create rich desktop applications. However powerful Swing is, its massive API stack lacks the lightweight higher abstractions that application and content developers have been using in other development environments. Furthermore, the applet's plugin technology was (as admitted by Sun) neglected and failed in the browser-hosted rich applications against similar technologies such as Flash.
 The JavaFX is Sun's (now part of Oracle) answer to the next generation of rich, web-enabled, deeply interactive applications. JavaFX is a complete platform that includes a new language, development tools, build tools, deployment tools, and new runtimes to target desktop, browser, mobile, and entertainment devices such as televisions. While JavaFX is built on the Java platform, that is where the commonalities end. The new JavaFX scripting language is designed as a lightweight, expressive, and a dynamic language to create web-connected, engaging, visually appealing, and content-rich applications.
The JavaFX platform will appeal to both technical designers and developers alike. Designers will find JavaFX Script to be a simple, yet expressive language, perfectly suited for the integration of graphical assets when creating visually-rich client applications. Application developers, on the other hand, will find its lightweight, dynamic type inference system, and script-like feel a productivity booster, allowing them to express GUI layout, object relationship, and powerful two-way data bindings all using a declarative and easy syntax. Since JavaFX runs on the Java Platform, developers are able to reuse existing Java libraries directly from within JavaFX, tapping into the vast community of existing Java developers, vendors, and libraries.


The most fascinating thing about JavaFX is that we  need not take pain to install any third party plugins or include any external libraries, as it comes bundled with JRE, from Java7 onwards, in turn JavaFX leverages the extreme ubiquity, power, performance and security of the JRE. So we just need to install Java and you are ready to build FX applications with inbuilt library with utmost ease.

JavaFX provides a vivid range of functionality like animation, support for Canvas API, Multi-Touch Support and many more.JavaFX offers a dramatically shortened production cycle for designers and developers through its designer–developer workflow. JavaFX allows you to incorporate multimedia assets from popular third-party design tools such as Adobe Illustrator and Photoshop using the JavaFX Production Suite.

One other thing which I personally like in JavaFX is that , the FX application which is made is directly available as an executable JAR file as soon as the code is compiled , so it becomes pretty easy for distribution purposes . 

Feel free to post any queries in the the comments section I will be more than happy to answer them . I will be posting a basic FX game , FX Movie maker and FX Video player soon with the complete description of the code. So stay tuned , key in your email in 'Follow By Email' to get the notification as soon as I post .

Cheers!!

Friday 27 September 2013

Google Search | The Guardian Angel

Google  has become integral part of all the working professionals , as it is the ultimate solution to all the questions whatever may be the field , subject . It is basically the solution bank to all the questions which people have around the world.

Google is the most used search engine , among the other dozens of search engines available. Google makes life easy as you find all the possible links to the question keyed in . Frankly speaking to search on google is an art , not everyone can find desired results , as you should be really very sure what keywords should find the required content, as Google takes each of the word keyed in the search as the keys to search for and then it runs the search and drives the pages which have maximum number of keyword matches.

For the people who are in software development field, google acts as a boon for them. By profession I am also an Software Developer , Google really serves well in the crunch time , or just for casual searching. Be it preparation of Seminar , making of a Project, or preparation of a presentation. Even you could find several explanations for the technical questions you might come across . You could really anything in the technical field , as there are several online forums for various technologies , which have tags so that they be visible in searches made on Google.

 Google makes you aware of things which might be completely alien , and at some point of time you need to know about that alien object. One of my experiences, when I joined the company my lead assigned me a technology called 'SERVOY' , and I really didn't have idea if such a platform exist basically never heard of , so after the assignment of the technology I did a Google search and at least got that basic idea as what we can do on this platform .

Google Search in true terms is the saviour for people of all the age group , starting from small kids who may use it to search photos for their science projects ,or the professional people-- be it at work or be it for show timings of the shows in the city .Even  old people could use google for remedies of the diseases , or could be for casual reading or for reading news and lots more .

What a day for writing about the Google Search , today is the 15th Anniversary of Google (Might have noticed the doodle and the little game there .. ) .In order to help people search in a productive manner and to attain the closest match to the queries keyed in the Google Search , you can go through the courses offered on Power Searching by Google

I really want to thank Google for being my side always when  I needed any solution . Please do post you experience I will be more than happy to know them.
Cheers...!!

Thursday 26 September 2013

Being Amongst the Crowd or An Individual?

 
   The people in world could be categorized , as an individual or as  a someone among the 7 billion people in the world. The people be an individual , or be amongst the crowd , completely based on traits . I am not demarcating this on the basis of degree of greatness of a person , or popularity or any other aspects which are not common to all the people in the world , I am simply demarcating on the basis of their mentality and decisiveness .

To start with : What is a crowd
Crowd is basically a group of individuals which do not have their personal identity ( but a collective identification as a general mob ) or are a bit shy taking lead or stand in a cause , and they all have a common thinking that someone takes a stand in their group, hiding themselves behind each other. Being a part of crowd person's individuality subside, and even it deprives the individual of his power of expression  have fear or hesitation , that what will other think of their doing , will it be appreciated or condemned .

What is an Individual?
Individual is a person who weighs each and every situation reasonably and act accordingly surpassing all the reasons which might withdraw his decision. The reasons here is not change of mind , reasons are being influenced by what others might think , how would others react ,or will anyone support or not etc. But an individual being does not care about the noise (Reasons stated earlier ) in the environment he/she just goes on. An Individual always have an edge over the crowd because the wonderful gift which comes in blessing as a disguise is high level of confidence. In today's scenario one thing which is a direct  requirement for all the jobs be it any field is confidence. In other words confidence is the currency in the industry one person belongs to , because interviewers are looking for the level of confidence which is in the candidate. It is rightly said by a noted Physician, Bernard M. Baruch that ----

                                        “Be who you are and say what you feel, because those who mind don't matter,and those who matter don't mind.” 



It is frequently said that there are consequences and latter effects of a thing,as a Crowd(or mob) there comes mob mentality as the consequence(as human in a rational being , and humans constitute mob-- though the catch is that they don't think that rationally) , this is basically the collective decision of group of people. This kind of mentality can be seen among the herd and cattle where all of them do a common thing,like walking in group one after the other ,etc.   An instance which would give a better perception-- Everyone would have heard about the communal riots , what happens in it one person turns outlaw and huge crowd of people simply follow because of witty talks of single person without giving it a second thought,  and unknowingly they become part of the anti-social activity. See how does this mentality has a magnification effect starting with a one outlaw person, it raised the whole crowd of outlaws.

Now, lets see another less intense or rather general instance , I can bet that everyone must have  seen a place where it is written that 'No Spitting Here' and to much surprise that particular place is stained all over with spits. 
What do you think people can't see or they just feel happy breaking code of conduct?
 Here  mob mentality plays its part , suppose a person when sees the sign of 'No Spitting Here' ,notices the spits all over, looking that ,his confidence soars up to spit ,thinking that already the place is dirty let me add to the attributes , instead he could obviously not clean it but at least could have refrained form spitting.


It does not takes much to be a face in the crowd and take rightful decisions , but in turn it acts as a foundation to individuality, which in its true essence, is responsible for molding a human into a person who is master of his intellect.

So think wisely which group are you into , as your decision could be crucial. Do post your views/suggestions as I would love to hear from you about the topic, as views vary from person to person .
Cheers!! 

Wednesday 25 September 2013

How to decorate reports in Jasper Reports , and how can we produce certificates with Jasper reports?

What you need to do is add a property to the fields you are wanting referenced. To add the class name you need to add net.sf.jasperreports.export.html.class and to include an id you need to addnet.sf.jasperreports.export.html.id as a property. As an example, below is a Text field that sets both:
<textField>
    <reportElement uuid="2399e4ef-633c-4d17-b964-3e093ece1936" x="0" y="22" width="100" height="20">
        <property name="net.sf.jasperreports.export.html.class" value="TEST"/>
        <property name="net.sf.jasperreports.export.html.id" value="ID"/>
    </reportElement>
    <textElement markup="html"/>
    <textFieldExpression><![CDATA[($F{field1}]]></textFieldExpression>
</textField>
In iReport you add these by selecting the field, and then in the properties window clicking the ellipses button next to Properties expressions. enter image description here
To include the link to the css file in the exported report, you need to set the value for theJRHtmlExporterParameter.HTML_HEADER parameter before exporting. Note the parameter is not the header in the sense of HTML (the contents of the head tag), but the header of the exported HTML report. Meaning it is what is first placed in the exported report to begin with, before including the report. The default that Jasper Reports uses is:
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <style type="text/css">
    a {text-decoration: none}
  </style>
</head>
<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td width="50%">&nbsp;</td><td align="center">
So you will need to modify this to include the link to your stylesheet by adding:
<link rel="stylesheet" type="text/css" href="<cssfile you want to point to>" />
to that in the appropriate place, which I think is inside the head tag, but if not move to appropriate area. So the java code would end looking something like:
<span style="font-size:11px;"><strong>JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, 
    "<html>"+
    "<head>"+
    "  <title></title>"+
    "  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>"+
    "  <link rel=\"stylesheet\" type=\"text/css\" href=\"css/jasper.css\" />"+
    "  <style type="text/css">"+
    "    a {text-decoration: none}"+
    "  </style>"+
    "</head>"+
    "<body text="#000000" link="#000000" alink="#000000" vlink="#000000">"+
    "<table width="100%" cellpadding="0" cellspacing="0" border="0">"+
    "<tr><td width="50%">&nbsp;</td><td align="center">");
exporter.exportReport();</strong></span>
Hope that it helps

How to make global header and footer in Jasper Reports?

Hi,
Suppose there are reports ABX,BNC and KLM  which have a same header and footer Then what you can do is create a master Report suppose mainReport, in there you add 3 subreports in the details section and then  and give the path of the the three reports ABX,BNC and KLM.  
You will have to specify the input control in the mainReport which user will have to enter suppose REPORT_SELECTION. Now you will have to decide the disctinct codes for each of the subreports . Suppose in this case I assign codes as :
ABX-1
BNC-2
KLM-3 
It  would accept the 1,2,3 from the user as input from the user in the parameter $P{REPORT_SELECTION} on the basis of this very choice of user it will trigger the presence or absence of the subreport.(Here 1,2,3 are just the cases could be anything like A,B,C or name itself like "ABX","BNC","KLM" )
Now to trigger the appearance of the subreport on the basis of this parameter $P{REPORT_SELECTION} ,which is entered by user we need to write the print when expression. The printwhen expression(which you would find in the property of the subreport element) you need to specify it as  : $P{REPORT_SELECTION}  ==1 (This will be for the report ABX ). So in this way the expression will vary. and you will get the desired subreport.
Please keep in mind that in the subreports header and footer is removed .
Here the input control REPORT_SELECTION is included on the mainReport so would be global too, and even you could accept the values of other parameters required by the reports and then pass it on to the subreports.So the parameters or input controls would be turned global too.
Hope that above explanation helps .


Happy Coding!!

How to execute Jasper Report through Java?

I found a way for that by parsing the xml and then extracting the tags with parameter and retrieving the attribute name and class keeping in mind the check attribute  isForPrompting is blank or not present for the parameters , In this way I got the Hashmap of all the parameters with their types and I put that in the parameterMap and hence fulfilling the parameters in the jrxml dynamically


The jars need to be included are-
1.commons-beanutils-x.x.x.jar
2.commons-collections-x.x.x.jar
3.commons-digester-x.x.jar
4.commons-logging-x.x.jar
5.groovy-all-x.x.x.jar
6.iText-x.x.x.jar
7.jasperreports-x.x.x.jar
8.poi-x.x.jar(for excel export)
9.jfreechart-x.x.x.jar


Happy Coding!!

What is MONGO DB?

MongoDB is a cross-platform document based system. Classified as a "NoSQL"database, MongoDB eschews the traditional relational database structure in favor of JSON-like documents with dynamic schemas , making the integration of data in certain types of applications easier and faster.

It is very interesting to work on a system which does not follow the conventional tantrums of relational DB, and curbing the obligation of maintaining  a perfect table structure and keeping the relations intact. Now you need not worry for the same with MongoDB , you just have to create the collections to much of a surprise the collections here are dimensionless , what I mean is that there could be a scenario where in the first row you have 3 records and next you have 2, wherein the SQL table you need to specify all the fields for all the rows. For Instance :
As the data stored is in a form of a document so all the documents are like a JSON  Document
{a:1,b:1,c:3},
{a:1},
{a:2,b:3},
{a:1,b:4,c:3,d:4}

As you could see above , its dimensionless. Now the next question which would haunt you would be that how would the sorting, grouping and other aggregations can be done , so the answer is that MongoDB has an inbuilt feature which skips the rows which does not contain the queried field to sort.


One might question that if there is no relational arrangement then how come the relations are maintained, but joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.So the catch is you can put as much data in the parent document which has high frequency of access , but is required to be updated less . And the documents which needs lots of updates or require increments it could be placed in a small document. So in that way the data is arranged and that data is only accessed which needs to be retrieved.



'mongod' This is a command line command to run the database instance , 'mongo' is a command to run the mongo shell where in you could access you data ,'mongos' this command keeps the track of shard keys. When you have to access the data you have to run the database instance and then access the mongo shell .

MongoDB provides a number of features that allow application developers and database administrators to customize the behavior of a sharded cluster or replica set deployment so that MongoDB may be more “data center aware,” or allow operational and location-based separation.


MongoDB uses write ahead logging to an on-disk journal to guarantee write operation durability and to

provide crash resiliency. Before applying a change to the data files, MongoDB writes the change operation to the
journal. If MongoDB should terminate or encounter an error before it can write the changes from the journal to the 
data files, MongoDB can re-apply the write operation and maintain a consistent state.

The MongoDB aggregation framework provides a means to calculate aggregated values without having to use mapreduce.While map-reduce is powerful, it is often more difficult than necessary for many simple aggregation tasks,such as totaling or averaging field values.

If you’re familiar with SQL, the aggregation framework provides similar functionality to GROUP BY and related
SQL operators as well as simple forms of “self joins.” Additionally, the aggregation framework provides projection
capabilities to reshape the returned data. Using the projections in the aggregation framework, you can add computed fields, create new virtual sub-objects, and extract sub-fields into the top-level of results.

MongoDB supports unique replication feature which increases data availability with multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup



This feature gives and edge in the case when the primary DB fails, because mongoDB supports a unique feature , wherein it grants  the secondary databases to perform an election amongst them to elect the primary database and then carry on the further transactions from that instance.



Another great feature of MongoDB is Sharding, or horizontal scaling which divides the data set and distributes the data over multiple servers, or shards. Each shard is an independent database, and collectively, the shards make up a single logical database. 

MongoDB also supports segregation based on functional parameters, to ensure that certain mongod instances are only used for reporting workloads or that certain high-frequency portions of a sharded collection only exist on specific shards. 

There is a limitation of MongoDB that it can have a document of maximum 16mb ,not greater than that , but to cater that 'GridFS' is there- This breaks the document in several small chunks and index it accordingly . This proves handy when you have to store huge data like photos,etc.

In my views it really fascinating to work on MongoDB ,to experience the NOSQL environment , it really great to provide flexibility in the database structure as the structure, relations have been the prime concern  for the developers . I would certainly recommend the usage in order to provide wings to the application.

Well one of the courses which I would recommend everyone is MongoDB for Developers M101J-   MongoDB for Developers M101J. In the course nicely all the features are covered and explained , I will recommend everyone to complete this.

Don't hesitate to add comments and questions if you have any doubts in the content , I will try to answer as soon as possible.
Cheers!!