Thursday, February 25, 2010

Oracle job scheduling

In my project, the requirement is inserting records into main database from child databases.

I have created one Job in Oracle. It automatically inserting record which is not yet inserted into main database.
The status of each record which is not yet inserted or already inserted is maintained in one table called “update status” .

If “updaterecord” column is “True” then that record is not yet inserted in main database.
Otherwise that record is already inserted.

I have created one procedure which will checks and inserting the record. Created one Job (Oracle scheduler) and set the interval as 1 minute. That’s it. This job will be executed the procedure for every minute.

Step I :
The following is the procedure for inserting pending registrations of main database
CREATE OR REPLACE PROCEDURE updatejobproc IS
CURSOR x_cur IS
SELECT registrationno FROM abc.updatestatus@Child_Database WHERE updaterecord ='true';
BEGIN
FOR x_rec IN x_cur
LOOP
Insert into abc.contactdetails@Main_Database(aliasname,password,
hintquestion,hintanswer)
select userid,password,hintquestion,hintanswer from contactinformation@Child_Database where
registrationno=x_rec.registrationno;
update abc.updatestatus@Child_Database set updaterecord='false' where registrationno=x_rec.registrationno;
END LOOP;
COMMIT;
END updatejobproc;
/

Steps included in above procedure:
1) Getting all the registration numbers from child database which has updaterecord = true;
2) For each registration number from child database, corresponding record will be inserted into main database
3) Updating updaterecord flag in child database to “FALSE”

Step II:
Compile and run the procedure.

Step III:
Created one Job internally in child database to insert the record which has “updaterecord “ flag is “TRUE” for every minute.
SQL> declare 
2 job integer; 
3 begin 
4 dbms_job.submit(job, ‘updatejobproc;',sysdate,'sysdate+1/1440');
5 commit; 
6 end; 
7 /

Step IV:
Execute following queries.
1)ALTER SYSTEM DISABLE RESTRICTED SESSION;
2)ALTER SYSTEM SET JOB_QUEUE_PROCESSES = 10;



Monday, February 22, 2010

Jasper Reports with pagination

Jasper Reports with pagination

I have added one more concept of adding pagination to Jasper Reports.
Adding pagination functionality to the jasper reports is very simple.
It has few steps to get it .
Have a look.
Following example is very simple.We can modify it as well for good UI.




IN MY jsp (reportview.jsp)
------------------------------
<% JRHtmlExporter export = (JRHtmlExporter)request.getAttribute("exportIndentObject"); session.setAttribute("exportIndentObject", export); JRHtmlExporter export1=(JRHtmlExporter)session.getAttribute("exportIndentObject"); Integer st1 = (Integer) request.getAttribute("repoprt.size"); %>
<head>
<script language="javascript">
var value=0;
function showpageview(val)
{

value=val;
var len=<%=st1%>;
if(val>=len){
value=len-1;
alert("No more pages");
} else if (val<0){
value=0;
alert("No Previous pages");
}else{
showPage(val);
}
}

function showPage(val)
{

xmlhttp = false;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
/* ========== AJAX Initializtion ========== */

if (xmlhttp!=null) {
url="<%=request.getContextPath()%>/report/view?pageNo="+val;
xmlhttp.onreadystatechange= function () { getReport(xmlhttp); };
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Cache-Control","no-cache, private, max-age=0");
xmlhttp.send(null);

} else {
alert("Your browser does not support XMLHTTP.");
}

}
function getReport(httpRequest1)
{
if(httpRequest1.readyState==4)
{
if(httpRequest1.status==200)
{
var result = httpRequest1.responseText;
document.getElementById("reportdiv").innerHTML=result;
}
}

}
</script>

</head>
<body onLoad="showPage(0)">
<html:form action="/export/action">
<%
Integer st = (Integer) request.getAttribute("repoprt.size");

if (st > 0) {
%>
<table>
<tr>
<td colspan="3">
<select id="exportName" name="exportName" class="select_box" >
<option value="PDF">PDF</option>
<option value="EXCEL">EXCEL</option>
<option value="TEXT">TEXT</option>
</select>

<html:submit value="Export" styleClass="button_submit"/>


<input type="button" class="button_submit" value="print" onClick="javascript:print();"/>

</td>
</tr>
<tr><td colspan="3" align="center">

<div id="reportdiv" style="display:block"></div>
</td> </tr>
</table>

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="pagintable3">
<tr>

<td width="17%" height="35" align="right" class="extreme"><a href="javascript:showpageview(value-1)"><b>< Prev</b> </a></td>
<td width="17%" align="left" class="extreme"><a href="javascript:showpageview(value+1)"> <b>Next ></b></a> </td>
</tr>
</table>



<%} else {
%>
<div class="warn"> <h3>No Records Found</h3></div>

<% }
%>
</html:form>


</body>

In my Struts-Config file
----------------------------

<action
path="/report/view"
name="IndentReportForm"
type="com.jsperReports.ReportViewAction">
<forward name="success" path="reports.view"/>
<forward name="success1" path="/WEB-INF/jsp/jasperReports/reportshow.jsp"/>
</action>


In my struts Action class(ReportViewAction.java)
--------------------------------------------------

String pg=request.getParameter("pageNo");
if(pg!=null)
{
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(JRHtmlExporterParameter.PAGE_INDEX, new Integer(pg));
HashMap fontMap = new HashMap();
exporter.setParameter(JRHtmlExporterParameter.FONT_MAP, fontMap);
exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD,Boolean.TRUE);
JasperExportManager.exportReportToHtmlFile(jasperPrint,request.getRealPath("/reports") + "/" + "Report.html");
request.setAttribute("exportPrintObject", exporter);
List sizeList=(ArrayList)jasperPrint.getPages();
Integer repoerSize=sizeList.size();
if(repoerSize==0){
request.setAttribute("repoprt.size",repoerSize);
map="success1";
}
try{
//closing connection
SDB.close(con);
}catch(Exception e){e.printStackTrace();}



In my reportshow.jsp
---------------------
<% JRHtmlExporter export = (JRHtmlExporter) request.getAttribute("exportPrintObject"); export.exportReport(); %>


See the following screen shot(We can do modification as we require)




Thursday, February 11, 2010

Design Japser Report in Net beans

Design Jasper Report in Net beans IDE

We can design the jasper report in Netbeans IDE. So, at one place(IDE) we can design Java, PHP, Reports and etc..

The following JAR files needed to add the plugin of Jasper Reports

1) iReport-nb-3.5.2.nbm
2) jasperreports-components-plugin-nb-3.5.2.nbm
3) jasperreports-extensions-plugin-nb-3.5.2.nbm
4) jasperserver-plugin-nb-3.5.2.nbm

You just add these jar files to the Netbeans like this
Tools--->Plugins--->downloaded--->Add Plugins-- Browse and give the path of jar files located.

See the screen shot.



Monday, February 8, 2010

Exporting Jasper Reports into Pdf,Excel(.xls) and Text (.txt) format with Save As dialog box

Hi friends,

Way of exporting jasper Reports into .pdf, .xls and .txt format with "Save As" dialog to download at client side

my .jrxml file is like this.( ListOfItems.jrxml)


<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="null" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<queryString language="SQL">
<![CDATA[select inventory_id,
item_no,
(select item_name from bp_items where item_no= bp_inventory.item_no) as item_name,
quantity,
shelf_time,
optimum_shelf_time
from
bp_inventory
order by item_name]]>
</queryString>
<field name="inventory_id" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="item_no" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="item_name" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="quantity" class="java.math.BigDecimal">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="shelf_time" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="optimum_shelf_time" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
<band/>
</background>
<title>
<band height="55">
<staticText>
<reportElement x="65" y="13" width="424" height="35" backcolor="#0000FF"/>
<textElement textAlignment="Center">
<font size="16" isBold="true"/>
</textElement>
<text><![CDATA[Items Report]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band/>
</pageHeader>
<columnHeader>
<band height="18">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="79" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Inventory No]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="79" y="0" width="68" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Item No]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="147" y="0" width="79" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Item Name]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="226" y="0" width="77" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Quantity]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="303" y="0" width="103" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Shelf Time]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="406" y="0" width="147" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement>
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[OptimumShelfTime]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20">
<textField>
<reportElement x="0" y="0" width="79" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[$F{inventory_id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="79" y="0" width="68" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[$F{item_no}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="147" y="0" width="79" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{item_name}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="226" y="0" width="77" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{quantity}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="303" y="0" width="103" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{shelf_time}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="406" y="0" width="147" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{optimum_shelf_time}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band/>
</columnFooter>
<pageFooter>
<band height="54">
<textField>
<reportElement x="410" y="15" width="80" height="20"/>
<textElement textAlignment="Right"/>
<textFieldExpression class="java.lang.String"><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
<reportElement x="490" y="15" width="40" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band/>
</summary>
</jasperReport>




Code in Action class


//filename is the .jrxml file ( ListOfItems.jrxml)
String filename=request.getParameter("file");
// title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
String title=request.getParameter("title");
Connection con = MMSDB.getConnection();
String jrept = filename;
String reportFileName = JasperCompileManager.compileReportToFile(request.getRealPath("/reports") + "/" + jrept);

java.util.Map parameters = new java.util.HashMap();
parameters.put("ReportTitle", title);

File reportFile = new File(reportFileName);
if (!reportFile.exists()) {
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}
JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);



//Maintaining request.----


JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
HashMap fontMap = new HashMap();
exporter.setParameter(JRHtmlExporterParameter.FONT_MAP, fontMap);
exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD, Boolean.TRUE);

request.setAttribute("exportObject", exporter);

if (!reportFile.exists()) {
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}

if (fileType.equals("PDF"))
{
response.setContentType("application/pdf");

JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/reports") + "/" +title+".pdf");
File f=new File(request.getRealPath("/reports") + "/" +title+".pdf");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/pdf");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename='"+title+"'.pdf");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

}
else
if (fileType.equals("EXCEL"))
{
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterXLS.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, request.getRealPath("/reports") + "/" +title+".xls");
exporterXLS.exportReport();
File f=new File(request.getRealPath("/reports") + "/" +title+".xls");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/vnd.ms-excel");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename="+title+".xls");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

}
else
if (fileType.equals("TEXT"))
{


JRTextExporter exporterTxt = new JRTextExporter();
exporterTxt.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporterTxt.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, request.getRealPath("/reports") + "/" +title+".txt");
exporterTxt.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(7));

exporterTxt.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(11));

exporterTxt.exportReport();

File f=new File(request.getRealPath("/reports") + "/" + title+".txt");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/text");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename="+title+".txt");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

Thursday, February 4, 2010

Way of printing Jasper Report at client side

Hi friends,

I have developed one project which is customised Jasper Reports with export and print options.
I haven't get any problem for export options.
Coming to Print, i found that it is printing at server end.
So to eliminate that problem i found one solution that will be printing at client side.

For this solution i have used Jasper Report object and Ajax functionality.
The code is like this:
1) In my JSP



<input type="button" class="button_submit" value="print" onclick="javascript:print();">


Handler: For a "Print" Button you need to add onclick listener function print();


function print()
{
/* ========== AJAX Initializtion ========== */
xmlhttp = false;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
/* ========== AJAX Initializtion ========== */

if (xmlhttp!=null) {
url = "/mms/reports";
xmlhttp.onreadystatechange= function () { getWorkReqDivs(xmlhttp); };
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Cache-Control","no-cache, private, max-age=0");
xmlhttp.send(null);

} else {
alert("Your browser does not support XMLHTTP.");
}
}
function getWorkReqDivs(httpRequest1)
{
if(httpRequest1.readyState==4)
{
if(httpRequest1.status==200)
{
var result = httpRequest1.responseText;
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var content_vlue=result;
var docprint= window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write(&lthtml>);
docprint.document.write(<body onLoad="self.print()">&lt

/body>
&lt
/html>);

docprint.document.write(content_vlue);

docprint.document.close();
docprint.focus();

}
}
}

This script is used to get the Jasper Report in HTML format as responseText. So this text is added in window.open().It looks like print preview.In onload itself print dialog box will come to ask print.


Struts-config.xml


<action path="/mms/reports" type="com.km.bp.mms.jsperReports.printAction"> 
<forward name="print" path="/WEB-INF/jsp/jasperReports/print.jsp"/>
</action>


Java Class: (printAction.java)


JRHtmlExporter exporter = new JRHtmlExporter();

String jrept = "indentReport.jrxml";

String reportFileName = JasperCompileManager.compileReportToFile(request.getRealPath("/reports") + "/" + jrept);

java.util.Map parameters = new java.util.HashMap();

Connection con = MMSDB.getConnection();String fromDatet="01/01/2010";String toDate="28/02/2010";

parameters.put("fromDate", fromDatet);parameters.put("toDate", toDate);

File reportFile = new File(reportFileName);if (!reportFile.exists()) {throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}

JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);

PrintWriter out = response.getWriter();response.setContentType("text/html");

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER, out);

HashMap fontMap = new HashMap();

exporter.setParameter(JRHtmlExporterParameter.FONT_MAP, fontMap);

exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);

exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);

exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD, Boolean.TRUE);

request.setAttribute("exportIndentObject", exporter);

return mapping.findForward("print");}

}


  



Jsp File :(print.jsp)( The following Jsp is the responseText of the Ajax Call)


<%@page import="net.sf.jasperreports.engine.export.JRHtmlExporter" %>

< % JRHtmlExporter export = (JRHtmlExporter) request.getAttribute("exportIndentObject"); session.setAttribute("exportIndentObject", export); JRHtmlExporter export1 = (JRHtmlExporter) session.getAttribute("exportIndentObject"); export.exportReport(); %>