For Showing a comboo by static value in Grails

17 Jan

Technique No-1:

If Value String (Key with cotation):

 <g:select id=”active” name=”active”  from=”${[‘Enabled’,’Disabled’]}”  keys=”${[‘A’,’B’]}” value=”${afmCalendarInstance?.calendarType}” /> 

If Value Integer (Key without cotation):

 <g:select id=”active” name=”active”  from=”${[‘Enabled’,’Disabled’]}”  keys=”${[1,2]}”  value=”${afmCalendarInstance?.calendarType}” />

Technique No-2 :

# In domain Class:

class Sponsorship {

String contributionType

static constraints = {
contributionType(inList:[“Other” , “Venue” , “A/V” , “Promotion” , “Cash”,”Maruf” ])
}

}
# In .gsp page

<g:fieldValue bean=”${tekEventInstance}” field=”venue”/>

It will show as comboo with value….
—————————————————————————————————————-

Technique No-3 :

–           ‘belongsTo’ is used to show that another class is the owning side of a relationship. It is
used for one-to-many and many-to-many relationships.

class Parent {

static hasMany = [children:Child]

}

class Child {

Parent parent

static belongsTo = Parent

}
========================Example====================
class Message {

String subject
TekEvent event

static constraints = {
subject(blank:false)
}

static belongsTo = TekEvent
}

class TekEvent {
String city
String name
String description
static hasMany = [ messages:Message]

static constraints = {
name()
city()
description(maxSize : 5000)
messages(nullable : true)
}

} 

# ‘toString()’ 

class Message {
String subject
String content
TekEvent event

String toString(){ subject }

static constraints = {
subject(blank:false)
content(blank:false, maxSize:2000)
}

static belongsTo = TekEvent
}

# class TekEvent {
String city
String name
String description

static hasMany = [ messages:Message]
static constraints = {
name()
city()
description(maxSize : 5000)
messages(nullable : true)
}

}

# <g:each in=”${tekEventInstance.volunteers}” var=”v”>

<g:link controller=”tekUser”     action=”show”   id=”${v.id}”>
${v?.
encodeAsHTML()}
</g:link>
</span>
</g:each>

NB.- For writing  the line  “String toString(){ subject }” in class Message  in .gsp page result will be against “${v?.encodeAsHTML()}” the line will be the value of  “subject”  column.
If 
the line  “String toString(){ subject }” in class Message  in .gsp page result will be against “${v?.encodeAsHTML()}” the line will be “tekdays.Message : 1” i.e.”parentClassName.childClassName:childClassId(PK)value”

//

How to show a Style on a element conditionally in iReport?

17 Jan

a) Create a style –
<style name=”alternateStyle” forecolor=”#000000″ fontName=”Arial”>

<conditionalStyle>
<conditionExpression>
                                                <![CDATA[new Boolean($F{IS_BOLD}== ‘Y’)]]>
</conditionExpression>
<style forecolor=”#000000″ isBold=”true”/>
</conditionalStyle>
</style>

Or , For more than one condition

<style name=”alternateStyle” forecolor=”#000000″ fontName=”Arial”>

<conditionalStyle>
<conditionExpression>
                                                <![CDATA[new Boolean($F{IS_BOLD}== ‘Y’)]]>
</conditionExpression>
<style forecolor=”#000000″ isBold=”true”/>
</conditionalStyle>

<conditionalStyle>
<conditionExpression>
<![CDATA[new Boolean($F{CASH_FLOW_HEAD}==null)]]>
</conditionExpression>
<style forecolor=”#FF0000″ isBold=”true”/>
</conditionalStyle>

</style>

b) put the style in the desired “textField”-
<textField isBlankWhenNull=”true”>
<reportElement uuid=”47d8dea6-067b-4ff9-b846-f73c1fdb7abe” style=”alternateStyle” x=”0″ y=”0″ width=”355″ height=”20″/>

<box>
                                                <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.0″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.0″/>
<rightPen lineWidth=”0.0″/>
</box>

<textElement/>
                                <textFieldExpression>
                                   <![CDATA[($F{CASH_FLOW_HEAD}==null?” “:$F{CASH_FLOW_HEAD})+($F{HEAD_2}==null?””:$F{HEAD_2})]]>
                      </textFieldExpression>
</textField>

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-49304906-2’, ‘wordpress.com’);
ga(‘send’, ‘pageview’);

Some Useful Information For iReport…

17 Jan

How to fixed date format in a string date field  :

-“From “+new java.text.SimpleDateFormat(“dd/MM/yyyy”).format($P{P_FROM_DATE})+” to “+new java.text.SimpleDateFormat(“dd/MM/yyyy”).format($P{P_TO_DATE})

How to Check Negative value and replace with ‘()’ :
$F{DR_BALANCE}<0?”(“+(new DecimalFormat(‘#,##0.000’).format($F{DR_BALANCE}*-1))+”)”:(new DecimalFormat(‘#,##0.000’).format($F{DR_BALANCE}))

Ternary operator Multiple conditions:

$F{PARTICULARS}==”Income-Academic”?”Total Income (Academic)”:

($F{PARTICULARS}==”Expenditure-Academic”?”Total Expenses (Academic)”:

($F{PARTICULARS}==”Expenditure- Non Academic”?”Total Non Academic Expenses”:””))

 

( iReport )Ternary operator Single conditions:

$F{PARTICULARS}==”Income-Academic”?”Total Income (Academic)”:”A”
How to show a attribute or element conditionally?
in properties panel of the element => change “Print When Expression” value only Boolean value like that->                $F{IS_SUBSIDIARY}==0?true:false

How to Add Format in a number in a String?

“Taka “+(new DecimalFormat(‘#,##0.00’).format($F{PAYABLE_AMOUNT}))

SQL: Get Value IF A Parameter is not PASSES

SELECT STUDENT_ID,A.CREDIT_DATE,CREDIT_AMOUNT,RECONCILE_TYPE

FROM UPLOAD_STD_BANK_STATEMENT A

WHERE CREDIT_DATE BETWEEN $P{FDATE} AND $P{TDATE}

AND RECONCILE_TYPE=nvl($P{P_RECONCILE_TYPE},RECONCILE_TYPE)

ORDER BY STUDENT_ID ASC

SUB REPORT EXPRESSION IN SUBREPORT PROPERTIES WILL BE

$P{SUBREPORT_DIR}+File.separator+ “SLS_STOCK_SALES_REPORT_subreport1.jasper”

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-49304906-2’, ‘wordpress.com’);
ga(‘send’, ‘pageview’);

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-49304906-2’, ‘wordpress.com’);
ga(‘send’, ‘pageview’);

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-49304906-2’, ‘wordpress.com’);
ga(‘send’, ‘pageview’);

AJAX

21 Nov

 AJAX For Web Programming….

PostGRE Database Connection

19 Nov

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.*;

public class JDBCExample {

public static void main(String[] argv) {

System.out.println(“——– PostgreSQL ”
+ “JDBC Connection Testing ————“);

try {

Class.forName(“org.postgresql.Driver”);

} catch (ClassNotFoundException e) {

System.out.println(“Where is your PostgreSQL JDBC Driver? ”
+ “Include in your library path!”);
e.printStackTrace();
return;

}

System.out.println(“PostgreSQL JDBC Driver Registered!”);

Connection connection = null;

try {

connection = DriverManager.getConnection(
“jdbc:postgresql://localhost:5432/maruf”, “dbaUser”,”123″);
//Database Name=maruf ,User Name=dbaUser,Password=123
Statement stm = connection.createStatement();
String sql=”select * from e_rajuk.testing”;
// Schema Name=e_rajuk ,Table Name=testing
ResultSet rs =stm.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1)+”  “+ rs.getString(2));
}

} catch (SQLException e) {

System.out.println(“Connection Failed! Check output console”);
e.printStackTrace();
return;

}

if (connection != null) {
System.out.println(“You made it, take control your database now!”);
} else {
System.out.println(“Failed to make connection!”);
}
}

}

Jasper report with JDBC connection Of Java web Project

29 May

Write it in index.jsp  page :

<form action=”getUserDetails.jsp” method=”get” enctype=”application/x-www-form-urlencoded”>

<table width=”469″ border=”0″ align=”center”>
<tr>
<td colspan=”3″><div align=”center”><strong>User Details Report </strong></div></td>
</tr>
<tr>
<td width=”177″><div align=”right”><strong>User Login Key:</strong></div></td>
<td width=”8″><strong>:</strong></td>
<td width=”262″><input name=”userName” type=”text” /></td>
</tr>
<tr>
<td><div align=”right”><strong>User Name :</strong></div></td>
<td><strong>:</strong></td>
<td><input name=”userFullName” type=”text” /></td>
</tr>
<tr>
<td><input name=”filename” type=”hidden” value=”Report/TestReport1.jasper” /></td>
<td>&nbsp;</td>
<td><input name=”submit” type=”submit” value=”submit” />
<input name=”reset” type=”reset” id=”reset” value=”reset” /></td>
</tr>
</table>
</form>

——————————————————————————————————————————–

Create a TestReport1.jasper report by ireport3.7.5 or other version  (  you must change the jar version according to iReport tools version )

and put in a “Report” folder and put the folder in “web” folder in NetBeans project.

———————————————————————————————————————————

Write the below code in getUserDetails.jsp page :

<%@page import= “java.util.*”%>
<%@page import= “javax.swing.JOptionPane”%>
<%@page language= “java” import= “net.sf.jasperreports.engine.*,net.sf.jasperreports.engine.export.*”%>
<%@page import= “java.sql.*,java.io.*” %>
<%@page import=”com.allClass.action.DatabaseConnection” %>

<%
String filename =request.getParameter(“filename”);
String userName=request.getParameter(“userName”);
String userFullName=request.getParameter(“userFullName”);
Map parameters = new HashMap();
parameters.put(“userName”, userName);
parameters.put(“userFullName”, userFullName);
String reporttype = “pdf”;//request.getParameter(“reporttype”);
DatabaseConnection connectionClass = new DatabaseConnection();

Connection conn = connectionClass.connectOracleDB();
System.out.println(“OracleDB Connection Established”);

String path = application.getRealPath(“/”);

JasperPrint jasperPrint = JasperFillManager.fillReport(path + “/” + filename,parameters, conn);
System.out.println(“Report Created…”);

OutputStream ouputStream = response.getOutputStream();

JRExporter exporter = null;

if (“pdf”.equalsIgnoreCase(reporttype)) {
response.setContentType(“application/pdf”);

exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if (“rtf”.equalsIgnoreCase(reporttype)) {
response.setContentType(“application/rtf”);
response.setHeader(“Content-Disposition”, “inline; filename=\”file.rtf\””);

exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if (“html”.equalsIgnoreCase(reporttype)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if (“xls”.equalsIgnoreCase(reporttype)) {
response.setContentType(“application/xls”);
response.setHeader(“Content-Disposition”, “inline; filename=\”file.xls\””);

exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if (“csv”.equalsIgnoreCase(reporttype)) {
response.setContentType(“application/csv”);
response.setHeader(“Content-Disposition”, “inline; filename=\”file.csv\””);

exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
}

try {
exporter.exportReport();

} catch (JRException e) {
throw new ServletException(e);
} finally {
if (ouputStream != null) {
try {
ouputStream.close();
} catch (IOException ex) {
}
}
}
%>
————————————————————————————————————————————–

Create a connection class name like  DatabaseConnection.java :(If you want to use ORACLE as a database then use connectOracleDB() method and just comment out the connectMySqlDB() method and according to that main method  and jar should be changed.)

package com.allClass.action;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
*
* @author Kazi Mohammad Marufur Rashid
* @email maruf.rashid.du@gmail.com
*/
public class DatabaseConnection {

/**
* This final variable for fixed connection. This is not changeable.
* Please double check carefully before update this final variable.
*/
/*        Oracle connection information             */

private final String oracleDbURL = “jdbc:oracle:thin:@//localhost:1521/xe”;
private final String oracleDriver = “oracle.jdbc.OracleDriver”;
private final String oracleDbUser = “banb”;
private final String oraclePassword = “banb”;

/*        Mysql connection information             */

private final String mySqlDbURL = “jdbc:mysql://localhost:3309/erp”;
private final String mySqlDriver = “com.mysql.jdbc.Driver”;
//    private final String mySqlDbUser = “erp”;
//    private final String mySqlPassword = “erp”;
private final String mySqlDbUser = “root”;
private final String mySqlPassword = “123”;

public Connection connectMySqlDB() {
Connection mySqlConnection = null;
try {
Class.forName(mySqlDriver);
mySqlConnection = DriverManager.getConnection(mySqlDbURL, mySqlDbUser, mySqlPassword);
} catch (ClassNotFoundException ex) {
mySqlConnection = null;
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
mySqlConnection = null;
}
return mySqlConnection;
}

//    public Connection connectOracleDB() {
//        Connection oracleConnection = null;
//        try {
//            Class.forName(oracleDriver);
//            oracleConnection = DriverManager.getConnection(oracleDbURL, oracleDbUser, oraclePassword);
//        } catch (ClassNotFoundException ex) {
//            oracleConnection = null;
//            ex.printStackTrace();
//        } catch (SQLException ex) {
//            ex.printStackTrace();
//            oracleConnection = null;
//        }
//        return oracleConnection;
//    }

public static void main(String[] args) throws SQLException, ClassNotFoundException {
DatabaseConnection mySqlDb = new DatabaseConnection();
Connection mySqlCon = mySqlDb.connectMySqlDB();

if (mySqlCon != null) {
System.out.println(“MySql Connection Success “);
} else {
System.out.println(“MySql Connection Fail”);
}
//        DatabaseConnection oracleDb = new DatabaseConnection();
//        Connection oracleCon = oracleDb.connectOracleDB();
//
//        if (oracleCon != null) {
//            System.out.println(“Oracle Connection Success “);
//        } else {
//            System.out.println(“Oracle Connection Fail”);
//        }

}
}
———————————————————————————————————————————————-

Use Following Jar in lib folder of your project :

  1. classes12.jar
  2. commons-beanutils-1.5.jar
  3. commons-collections-2.1.jar
  4. commons-digester-1.7.jar
  5. commons-javaflow-20060411.jar
  6. commons-logging-1.0.2.jar
  7. iText-2.1.7.jar
  8. jasperreports-3.7.5.jar
  9. mysql-connector-java-5.1.6-bin.jar—————————————————————————–

Using Jasper Report in Grails Project

28 May

At first  create a Grails project

Install jasper plugin as below-

–          Ctrl+Alt+G

–          install-plugin jasper

–          Enter

write it in view page-

<g:form controller=”payrollReport”  action=”yearlySalaryRegister” >
<table id=”ySalReg” style=”display:none” width=”415″ border=”0″ >
<tr>
<td width=”96″> </td>
<td width=”19″></td>
<td width=”286″></td>
<td></td>
</tr>
<tr>
<td>Year</td>
<td>:</td>
<td>

<g:textField name=”year” id=”year”  value=”” required=”” maxlength=”4″ style=”width:85px;”></g:textField>

</td>
<td style=”width:175px;color: red;” id=”year5MsgTd” align=”left”></td>
</tr>
<tr>
<td>Department</td>
<td>:</td>
<td>

<g:textField name=”P_DEPARTMENT_ID” id=”P_DEPARTMENT_ID”  value=”” required=””  style=”width:130px;”>

</td>
<td id=”P_DEPARTMENT_ID5MsgTd” style=”color: red” align=”left”></td>
</tr>
<tr>
<td colspan=”4″ align=”center”>&nbsp;</td>
</tr>
<tr>
<td colspan=”4″ align=”center”>
<g:submitButton name=”View Report”  style=”width: 250px” onmouseover=”this.style.color = ‘#E6443C’;this.style.cursor=’pointer’;” onmouseout=”this.style.color = ‘#024697’;this.style.cursor=’pointer'”></g:submitButton>

</td>
</tr>
</table>
</g:form>
—————————————————————————————————————————————————–

write the below code in controller –

import grails.converters.JSON
import org.codehaus.groovy.grails.plugins.jasper.JasperExportFormat
import org.codehaus.groovy.grails.plugins.jasper.JasperReportDef
import org.codehaus.groovy.grails.plugins.jasper.JasperService
import org.springframework.beans.factory.annotation.Autowired

@Autowired
JasperService jasperService

private static final String REPORT_FILE_FORMAT = ‘pdf’
private static final String REPORT_NAME_FIELD = ‘REPORT_NAME’
/*private static final String REPORT_FOLDER = ‘storeInFromSite’*/
private static final String SUB_REPORT_FOLDER = ‘subReport’
private static final String OUTPUT_FILE_NAME = ‘roleReport’
private static final String REPORT_TITLE = ‘Company Name’
private static final String REPORT_DIR = ‘REPORT_DIR’
private static final String SUBREPORT_DIR = ‘SUBREPORT_DIR’
private static final String JASPER_FILE = ‘userRoleDetails.jasper’
private static final String PDF_EXTENSION = “.pdf”
private static final String REPORT = “report”

def yearlySalaryRegister() {
println params

String P_DEPARTMENT_ID= params.P_DEPARTMENT_ID
String P_YEAR= params.year
String P_SALARY_YEAR=P_YEAR
String P_SALARY_AND_ALLOWANCE_MONTH=P_YEAR

String reportDir = Util.getReportDirectory()
String outputFileName = ‘YEARLY_SALARY_REGISTER’ + PDF_EXTENSION

String subReportDir = Util.getReportDirectory()   //+ File.separator + SUB_REPORT_FOLDER
Map reportParams = new LinkedHashMap()
reportParams.put(REPORT_DIR, reportDir)
reportParams.put(SUBREPORT_DIR, reportDir)

reportParams.put(‘P_DEPARTMENT_ID’, P_DEPARTMENT_ID.trim())
reportParams.put(‘P_SALARY_YEAR’, P_SALARY_YEAR.trim())
reportParams.put(‘P_SALARY_AND_ALLOWANCE_MONTH’, P_SALARY_AND_ALLOWANCE_MONTH)

JasperReportDef reportDef = new JasperReportDef(name: ‘YEARLY_SALARY_REGISTER.jasper’, fileFormat: JasperExportFormat.PDF_FORMAT,
parameters: reportParams, folder: reportDir)

ByteArrayOutputStream report = jasperService.generateReport(reportDef)
response.contentType = “application/pdf”
response.setHeader(“Content-disposition”, “attachment;filename=”+outputFileName)   //OUTPUT_FILE_NAME+PDF_EXTENSION)
response.outputStream << report.toByteArray()
}

————————————————————————————————————————————————————–

create a Util class as below-

package accounts

import java.text.ParseException
import java.text.SimpleDateFormat
import org.codehaus.groovy.grails.commons.ApplicationHolder

class Util {
private static String REPORT_DIRECTORY = null;
public static String getReportDirectory() {
if (!REPORT_DIRECTORY) {
File reportFolder = ApplicationHolder.application.parentContext.getResource(‘/reports’).file;
REPORT_DIRECTORY = reportFolder.absolutePath;
}
return REPORT_DIRECTORY;
}

}

———————————————————————–

put all report in “report” folder and put the report folder in “\web-app” folder

Passing Parameters to Report (Jasper) in Struts2 Framework Project

26 May

you can make a report  by following the link  http://marufurrashidbd.blogspot.com/p/ireport-jasper-report-related.html

After that you can pass parameter to that report by the below method –

All Import are as below-

import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import java.sql.*;
import java.io.*;

Method is as below-

public void showReport() throws JRException, ServletException, IOException{

HttpServletResponse response=ServletActionContext.getResponse();
HttpServletRequest request=ServletActionContext.getRequest();

String filename =”AFM_BANK_INFO.jasper”;//request.getParameter(“filename”);
String outputFileName =”AFM_BANK_INFO”;
String reportType = request.getParameter(“reportType”);

String P_AFM_BANK_ID=request.getParameter(“P_AFM_BANK_ID”);
System.out.println(“P_AFM_BANK_ID”+P_AFM_BANK_ID);

Map parameters = new HashMap();

//All the parameter you want to pass to report write below way..
parameters.put(“P_AFM_BANK_ID”, P_AFM_BANK_ID);
//parameters.put(“userFullName”, userFullName);

Connection conn = databaseConnection.connectOracleDB();
System.out.println(“OracleDB Connection Established”);

ServletContext context = ServletActionContext.getServletContext();
String path = context.getRealPath(“/”);//.getContextPath();
System.out.println(“path ” + path);

JasperPrint jasperPrint = JasperFillManager.fillReport(path +”/report”+ “/” +filename,parameters, conn);
System.out.println(“Report Created…”);

OutputStream ouputStream = response.getOutputStream();

JRExporter exporter = null;

if (“pdf”.equalsIgnoreCase(reportType)) {

response.setContentType(“application/pdf”);
// If you want show the report in the browser then write “inline”
response.setHeader(“Content-disposition”, “inline;filename=”+outputFileName+”.”+reportType);
// If you want show the report out of the browser as a .pdf format then write “attachment”
//response.setHeader(“Content-disposition”, “attachment;filename=”+outputFileName+”.”+reportType);
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

} else if (“rtf”.equalsIgnoreCase(reportType)) {

response.setContentType(“application/rtf”);
response.setHeader(“Content-Disposition”, “inline; filename=”+outputFileName+”.”+reportType);
exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

} else if (“html”.equalsIgnoreCase(reportType)) {

exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

} else if (“xls”.equalsIgnoreCase(reportType)) {

response.setContentType(“application/xls”);
response.setHeader(“Content-Disposition”, “inline; filename=”+outputFileName+”.”+reportType);
exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);

} else if (“csv”.equalsIgnoreCase(reportType)) {

response.setContentType(“application/csv”);
response.setHeader(“Content-Disposition”, “inline; filename=”+outputFileName+”.”+reportType);
exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
}

try {
exporter.exportReport();

} catch (JRException e) {
throw new ServletException(e);
} finally {
if (ouputStream != null) {
try {
ouputStream.close();
} catch (IOException ex) {
}
}
}
}

————————————–

Below jar will be needed for the project

1) commons-beanutils-1.8.3.jar ,
2) commons-collections-3.1.jar ,
3) commons-digester-2.0.jar ,
4) commons-logging-1.1.jar ,
5) freemarker-2.3.8.jar ,
6) iText-2.1.7.jar ,
7) jasperreports-3.7.5.jar ,
8) ognl-2.6.11.jar ,
9) ojdbc14.jar ,
10) struts2-core-2.0.6.jar ,
11) struts2-jasperreports-plugin-2.1.6.jar ,
12) xwork-2.0.1.jar

———————————————

N.B.  – here we need to keep in mind about the version of  iReport software .I use iReport-3.7.5 for that I use  jasperreports-3.7.5.jar.If you use different or upper or lower version iReport then you must be provide same version jar in lib folder of your project .Other wise you will face exception or error message.

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-49304906-2’, ‘wordpress.com’);
ga(‘send’, ‘pageview’);

How to Create a jar from a java application by Ant ?

27 Apr

1)    First create the top-level directory called “HelloWorldJavaPro”. The HelloWorldJavaPro directory will contain the Ant build file (build.xml).

2)    Then create one sub-directories of the “helloworld” directory – “src”.

3)    Then create one sub-directories of the “src” directory – “com”.

4)    Then create one sub-directories of the “com” directory – “allClass”.

5)    Then create one sub-directories of the “allClass” directory – “action”.

6)    Here “action” directorie will contain the Java source file for the HelloWorldJavaPro project

7)    Create the Ant build file (build.xml) and put it in “HelloWorldJavaPro” directory.

8)     Compile and package the HelloWorldJavaPro java application by opening a command window and execute “ant ” command.For that I put my “helloworld” project in G:\workspaceForEclipse directory.So I go to run=> I write “cmd” and I press enter button=>Then the followings-

Microsoft Windows XP [Version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Tushi>g:

G:\>cd workspaceForEclipse\ HelloWorldJavaPro
G:\workspaceForEclipse\ HelloWorldJavaPro >ant

9)    In the “HelloWorldJavaPro” project you will see two new directories –a) dist ,b)build. In “dist” directory you will get the jar file.

To run the jar file open a command window and execute “ant execute” or “ant clean execute” command. (G:\workspaceForEclipse\ HelloWorldJavaPro > ant execute)

10) Then you will see the result………..

11)  A sample build.xml are given below-

<?xml version=”1.0″ ?>

<project name=”HelloWorldJavaPro” default=”compress”>

<target name=”init”>

<mkdir dir=”build/classes” />

<mkdir dir=”dist” />

</target>

<target name=”compile” depends=”init”>

<javac srcdir=”src” destdir=”build/classes” />

</target>

<target name=”compress” depends=”compile”>

<jar destfile=”dist/newJar.jar” basedir=”build/classes” />

</target>

<target name=”execute” depends=”compile”>

<!–java classname=”HelloWorld” classpath=”build/classes” /–>
<java classname=”com.allClass.action.HelloWorld” classpath=”build/classes” />

</target>

<target name=”clean”>

<delete dir=”build” />

<delete dir=”dist” />

</target>

</project>

How to Create a war from a web application by Ant ?

27 Apr

1)    At First create the top-level directory called “helloworld”. The helloworld directory will contain the Ant build file (build.xml).

2)    Then create two sub-directories of the “helloworld” directory – a) src , b)web.

Here “src” directorie will contain the Java source file for the HelloWorld servlet and “web”  will contain the JSP file, static HTML file, images, and deployment descriptor.

3)    In the “src” directory, create an “examples” sub-directory. This directory corresponds to the package that the HelloWorld servlet is in.

4)    In the web directory, create two sub-directories:- a)images,b) WEB-INF
Here “images” directorie will obviously contain any images and “WEB-INF”  the standard directory will contains the Web application deployment descriptor file “web.xml”

5)    Create the Hello.java servlet Java source file and put it in the helloworld/src/examples directory.

6)    Create the hello.jsp JSP file and put it in the helloworld/web directory.

7)    Create the web.xml Web application deployment descriptor and put it in the helloworld/web/WEB-INF directory.

8)    Create the default index.html page and put it in the helloworld/web directory.

9)    Create the Ant build file (build.xml) that includes targets for compiling and packaging the Web application and put it in the helloworld directory.

10) In your own build file, be sure you update the tcserver(Tom cat server).home property to fit your environment; it should point to the CATALINA_HOME of your tc Server installation.

<property name=”tcserver.home” value=”/home/tcserver/tcServer-6.0/tomcat-6.0.20.C” />

I changed the above line just like below-

<property name=”tcserver.home” value=”C:/Program Files/Apache Software Foundation/Tomcat 6.0″ />

11)  Put a springsource.png named image to the helloworld/web/images directory.

12)  Compile and package the Helloworld Web application by opening a command window and execute “ant all” command.For that I put my “helloworld” project in G:\workspaceForEclipse directory.So I go to run=> I write “cmd” and I press enter button=>Then the followings-
Microsoft Windows XP [Version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Tushi>g:

G:\>cd workspaceForEclipse\helloworld
G:\workspaceForEclipse\helloworld>ant all 

At last I see BUILD SUCCESSFUL

Total time: 0 seconds

13)  In the “helloworld” project you will see two new directories –a) dist ,b)work
In “dist” directory you will get the war file.

Take the war file and deploy it in tomcat server .see it url-“ http://localhost:8084/helloWorld-0.1-dev/index.html”

%d bloggers like this: