jreport designer - user's guide · table of contents editing a report by inserting...

581
JReport Designer - User's Guide

Upload: others

Post on 25-Mar-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Designer − User's Guide

Page 2: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsJReport Designer − User's Guide: Structure .....................................................................................................................1

Installing and Launching JReport Designer ......................................................................................................................3System Requirements...............................................................................................................................................3Installing JReport Designer on Windows...................................................................................................................3Uninstalling JReport Designer on Windows..............................................................................................................4Running JReport Designer On Windows...................................................................................................................4Installing, Running and Uninstalling JReport Designer on Unix................................................................................4Setting up the ODBC/JDBC Driver............................................................................................................................5

Data Source.................................................................................................................................................5Setting up JDBC Driver if Necessary............................................................................................................5

Launchers Under JReport Designer..........................................................................................................................6Command−line Startup.................................................................................................................................8

Starting a Catalog.................................................................................................................................................................9Catalog......................................................................................................................................................................9

Catalog Overview.........................................................................................................................................9Using Catalog Browser to Manage Resources ..........................................................................................10Using Cross−reference Table to Clarify Resource Relationships..............................................................12Setting Default Values for Objects..............................................................................................................13Creating Catalog and Connections.............................................................................................................14Operating a Catalog...................................................................................................................................14Catalog in XML format................................................................................................................................16

Connection..............................................................................................................................................................16What's a Connection..................................................................................................................................16Creating a New Connection........................................................................................................................16Adding Tables/Views to Connection...........................................................................................................22Modifying an Existing Connection..............................................................................................................23

Pre−join...................................................................................................................................................................24Pre−join Overview......................................................................................................................................24Pre−join Definition......................................................................................................................................25Pre−join Editor............................................................................................................................................25Use Pre−joins In Your Query......................................................................................................................28

Merging Catalogs....................................................................................................................................................29Specifying the Checking Level...................................................................................................................29Merging Catalogs.......................................................................................................................................30

Using and Managing Cached Query Results..........................................................................................................31Introduction.................................................................................................................................................31Creating a Cached Query Result for a Query.............................................................................................31Using Cached Query Results to Run Reports............................................................................................32Managing the Cached Query Results with the Data Source Driver Manager............................................32

Developing Reports with Report Wizard..........................................................................................................................33Selecting a Report Template...................................................................................................................................33Creating a Report with Report Wizard.....................................................................................................................35

Working Set................................................................................................................................................35Data Tab.....................................................................................................................................................35Joins Tab....................................................................................................................................................37Conditions Tab...........................................................................................................................................40Display Tab................................................................................................................................................43Group Tab..................................................................................................................................................45Sort Tab......................................................................................................................................................47Summary Tab.............................................................................................................................................56Graph Tab..................................................................................................................................................58Cross−Tab Tab...........................................................................................................................................58Subreport Tab............................................................................................................................................60

I

Page 3: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsOther Tab...................................................................................................................................................62Style Tab....................................................................................................................................................64

Multiple Data Sources.............................................................................................................................................65

Previewing a Report...........................................................................................................................................................70Work Area...............................................................................................................................................................70Design Mode...........................................................................................................................................................70

Section.......................................................................................................................................................70Ruler, Grid and Guideline...........................................................................................................................71

View Mode...............................................................................................................................................................72The Toolbar of View Tab............................................................................................................................73Dynamic Sort..............................................................................................................................................73Drill−down...................................................................................................................................................73

JReport Designer Window.................................................................................................................................................75JReport Designer Window.......................................................................................................................................75Main Menu...............................................................................................................................................................75

File..............................................................................................................................................................75Edit.............................................................................................................................................................78View............................................................................................................................................................80Insert..........................................................................................................................................................81Format........................................................................................................................................................81Window.......................................................................................................................................................82

Resource Viewer.....................................................................................................................................................82Toolbars..................................................................................................................................................................83

Standard Toolbar........................................................................................................................................83Edit Toolbar................................................................................................................................................84

Hot keys..................................................................................................................................................................84Work Area...............................................................................................................................................................85

Refining the Report Layout ...............................................................................................................................................86Introduction..............................................................................................................................................................86Selecting, Moving and Resizing Objects.................................................................................................................86

Single Object..............................................................................................................................................86Multiple Objects and Fields: ......................................................................................................................86

Overlapping.............................................................................................................................................................87Single Object..............................................................................................................................................87Multiple Objects..........................................................................................................................................88

Font.........................................................................................................................................................................90Deleting, Copying, Cutting and Pasting...................................................................................................................91Report Inspector......................................................................................................................................................91

Introduction.................................................................................................................................................91Launching Report Inspector.......................................................................................................................91Report Inspector.........................................................................................................................................91Editing Objects in Report Inspector............................................................................................................93

Using Styles in Your Report..............................................................................................................................................96Introduction..............................................................................................................................................................96Setting up Styles in JReport Designer.....................................................................................................................97Modifying the XML Style Files...............................................................................................................................101Deploying Reports to Enterprise Server...............................................................................................................103Viewing Reports on JReport Enterprise Server.....................................................................................................103Using Styles in Your Report..................................................................................................................................104Limitations.............................................................................................................................................................107

Editing a Report................................................................................................................................................................108

II

Page 4: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsEditing a Report by Inserting Objects....................................................................................................................108

DB Field....................................................................................................................................................108Formula....................................................................................................................................................108Parameters...............................................................................................................................................109Draw Objects............................................................................................................................................112Special Field.............................................................................................................................................113Section.....................................................................................................................................................115Group/Sort................................................................................................................................................115Summary..................................................................................................................................................116Sub−report................................................................................................................................................118Embedded Sub−report.............................................................................................................................118Map..........................................................................................................................................................122Barcode....................................................................................................................................................128Cross−tab.................................................................................................................................................129Text..........................................................................................................................................................131Data Objects ...........................................................................................................................................132

Query Editor..........................................................................................................................................................136Query........................................................................................................................................................136Creating a New Query..............................................................................................................................136Editing a Query.........................................................................................................................................136Previewing a Query..................................................................................................................................142Creating Subquery in Query Editor...........................................................................................................144Changing the Query Name in Report Inspector.......................................................................................145Showing SQL Statement of a Query........................................................................................................146Showing Properties of a Query.................................................................................................................147Removing a Query...................................................................................................................................147

Dynamic Query......................................................................................................................................................147Instruction.................................................................................................................................................147Dynamic Query Interface..........................................................................................................................147Using Dynamic Query Interface................................................................................................................149

Editing a Report For DHTML Use....................................................................................................................................153Switching on/off the drilling feature of the summaries for DHTML........................................................................153Showing detailed information for comprehensive data using master/detail reports..............................................153

Setting up a pair of master−detail reports................................................................................................153Setting display names for DHTML sort/filter/drill functions....................................................................................156

Why display names? ...............................................................................................................................156Customize display names.........................................................................................................................157NLS on Display Names............................................................................................................................158

Pre−defining DHTML sort & filter conditions.........................................................................................................159Define sort conditions...............................................................................................................................159Define filter conditions..............................................................................................................................161

Using DHTML control objects in your reports........................................................................................................162

Charts................................................................................................................................................................................164About Chart...........................................................................................................................................................164Creating a Chart....................................................................................................................................................164Changing the Type of a Chart...............................................................................................................................166Changing the Display, View, or Placement of a Chart ........................................................................................167Formatting Axes, Legends, and Other Chart Elements.........................................................................................169Filtering Chart Data Source...................................................................................................................................171Reference Links....................................................................................................................................................172

Printing a Report ..............................................................................................................................................................173Introduction............................................................................................................................................................173Specifying Printing Methods..................................................................................................................................173

III

Page 5: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsPrinting a Report with JDK1.1 Printing Method.....................................................................................................173Printing a Report with JDK1.2 Printing Method.....................................................................................................174Printing a Report with JDK1.4 Printing Method.....................................................................................................175

Report Manager and Data Manager................................................................................................................................177About the Report Manager....................................................................................................................................177Working with the Report Manager.........................................................................................................................177

Adding Folder...........................................................................................................................................177Adding Reports.........................................................................................................................................178Renaming Item.........................................................................................................................................178Moving Item..............................................................................................................................................178Deleting Item............................................................................................................................................178Searching Item.........................................................................................................................................178Exporting to a Table.................................................................................................................................179

Data Manager........................................................................................................................................................179Introduction...............................................................................................................................................179Showing Temporary Data.........................................................................................................................179Max Rows and Max Duration...................................................................................................................180Viewing the Query History Information.....................................................................................................181Server−Side Run History..........................................................................................................................181

Tuning Runtime Performance .........................................................................................................................................183

Problem Diagnosis Tool − Catalog Doctor ....................................................................................................................185What are in a Catalog............................................................................................................................................185

Connection...............................................................................................................................................185Table/View................................................................................................................................................185Field in a Table/View................................................................................................................................186Parameter.................................................................................................................................................186Formula and Summary.............................................................................................................................186Mapping Field...........................................................................................................................................186Query........................................................................................................................................................186Relationship among Data Objects............................................................................................................186

What errors can Catalog Doctor Detect................................................................................................................186Errors are Diagnosed Independently........................................................................................................186Mapped Table/View and DB−Field...........................................................................................................187Formulas and Summaries........................................................................................................................187Queries.....................................................................................................................................................187

Using Catalog Doctor............................................................................................................................................187Starting Catalog Doctor............................................................................................................................187Loading a Catalog....................................................................................................................................187Saving a Catalog......................................................................................................................................187Merging Catalogs.....................................................................................................................................188Diagnosing and Fixing..............................................................................................................................190

Developing a Report from a Query File..........................................................................................................................199SQL in Connection................................................................................................................................................199Creating a Report from a Query File.....................................................................................................................199

Editing a File Containing an SQL Statement............................................................................................199Linking the SQL File with the Catalog Browser........................................................................................200Creating a Report Using the Query File...................................................................................................201

Developing Reports from Stored Procedures ...............................................................................................................203Stored Procedure..................................................................................................................................................203

Introduction...............................................................................................................................................203How does a Stored Procedure Work with JReport...................................................................................203

IV

Page 6: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsDeveloping Reports from Stored Procedures........................................................................................................203

Adding a Procedure to the Catalog..........................................................................................................203Editing Parameter Values.........................................................................................................................204Creating a Report Using a Stored Procedure...........................................................................................205Running a Report Which Uses a Stored Procedure.................................................................................205

Stored Procedure for Oracle Database.................................................................................................................206Adding UDS class....................................................................................................................................206Examples..................................................................................................................................................208Trouble Shooting Guides for Importing Oracle Stored Procedure............................................................211

Developing Reports from User Data Source .................................................................................................................212Introduction............................................................................................................................................................212Case 1: Address Data Source...............................................................................................................................212

Introduction...............................................................................................................................................212Compiling and Running Address UDS.....................................................................................................213Adding Address UDS into JReport Catalog..............................................................................................213Making a Report with Address UDS.........................................................................................................216

Case 2: SQL Data Source.....................................................................................................................................217Introduction...............................................................................................................................................217Compiling and Running SQL Data Source...............................................................................................218Adding SQLDataSource UDS into JReport Catalog.................................................................................218Add Dynamic SQLDataSource UDS into JReport Catalog.......................................................................223

Case 3: Applying UDS for Stored Procedure in Oracle.........................................................................................226Case 4: Creating Reports from Java Object Data Sources...................................................................................227

Introduction...............................................................................................................................................227Demo 1: Creating Reports from Simple Java Object Data Sources.........................................................228Demo 2: Creating Reports from Java Objects with Multi−levels of Collections........................................231

Developing Reports from Hierarchical Data Source.....................................................................................................234Introduction............................................................................................................................................................234XML Data Source..................................................................................................................................................234

XML HDS Overview .................................................................................................................................234Importing XML format HDS into JReport Catalog.....................................................................................235Making a Report with Hierarchical Data Source.......................................................................................238 Viewing Reports with Dynamic XML URI................................................................................................239Running Reports on JReport Enterprise Server.......................................................................................239

General Hierarchical Data Source.........................................................................................................................239General HDS Overview............................................................................................................................239Compiling and Running Hierarchical Data Source...................................................................................240Adding SQLDataSource HDS into JReport Catalog.................................................................................240

Parallel Hierarchical Data Source.........................................................................................................................243Parallel HDS Overview ............................................................................................................................243Using Parallel HDS...................................................................................................................................244

Developing Reports with OOJDBC.................................................................................................................................249Introduction............................................................................................................................................................249Case 1: XML..........................................................................................................................................................250

Importing XML Files..................................................................................................................................250Importing the XML.odf to JReport Catalog...............................................................................................257

Case 2: Direct XML File Import.............................................................................................................................259Importing XML Files..................................................................................................................................259Importing orgchart.odf to JReport Catalog...............................................................................................261

Case 3: Importing XML with Dynamic Parameters................................................................................................263Importing XML File...................................................................................................................................263Importing odf File to JReport Catalog.......................................................................................................264Modifying the Dynamic Parameters in Catalog Browser..........................................................................266

V

Page 7: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsHow does OOJDBC Work with Java Objects?......................................................................................................268Case 4: Importing the Product Table via Model Wizard........................................................................................268

Installation................................................................................................................................................268Importing Product Table...........................................................................................................................268Importing demo.odf to JReport Catalog....................................................................................................270

Optimization of OOJDBC......................................................................................................................................272Case 5: Importing com.jinfonet.jdbc.demo.common.RecordResult via Model Wizard..........................................272

Installation................................................................................................................................................272Importing com.jinfonet.jdbc.demo.common.RecordResult via Model Wizard..........................................272

Supporting EJB via OOJDBC in JReport..............................................................................................................276Introduction...............................................................................................................................................276

Case 6: Supporting EJB Deployed in J2EE ........................................................................................................277Installation ...............................................................................................................................................277Importing EJB with ModelWizard..............................................................................................................277Importing ejb.odf to JReport Catalog........................................................................................................282

Case 7: Supporting EJB Deployed in BEA Weblogic Server...............................................................................284Installation................................................................................................................................................284Deploying your EJB..................................................................................................................................285Importing EJB via OOJDBC.....................................................................................................................286Using Imported EJB in JReport................................................................................................................290

Case 8: Supporting EJB 2.0 Deployed in BEA Weblogic's Server 6.1..................................................................292Installation................................................................................................................................................292Modifying and Rebuilding EJB..................................................................................................................293Setting up Demo Data Source..................................................................................................................295Importing EJB via Model Wizard..............................................................................................................298Using Imported EJB in JReport................................................................................................................304

Deploying Resources From JReport Designer..............................................................................................................308Introduction............................................................................................................................................................308Deploying Resources From JReport Designer......................................................................................................308

Deploying Resources Locally...................................................................................................................308Deploying Resources to JReport Enterprise Server.................................................................................309

Executing Reports from JReport Beans Or APIs..........................................................................................................311Introduction............................................................................................................................................................311JReport Engine Bean............................................................................................................................................312

Installation................................................................................................................................................312Properties.................................................................................................................................................313Programming with JReport Engine Bean.................................................................................................315Showing Information.................................................................................................................................316Returning Code........................................................................................................................................316Exporting To HTML, Mail, PDF, TEXT, XLS, PS, RTF, XML and Fax.....................................................316Printing Reports........................................................................................................................................317WHERE Portion........................................................................................................................................319Data Driver...............................................................................................................................................319Cached Query Result...............................................................................................................................320National Language Support (NLS)...........................................................................................................320Getting the Communicator of this report...................................................................................................320Modifying User Information.......................................................................................................................320Setting Connection Information................................................................................................................320Setting Result Set.....................................................................................................................................321Getting the Version Number of JReport Engine Bean..............................................................................321Getting Page Orientation..........................................................................................................................322Getting DBField Information.....................................................................................................................322Getting Report Information.......................................................................................................................322Single Thread...........................................................................................................................................322

VI

Page 8: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsRun−time Key...........................................................................................................................................322The Illustrative Example...........................................................................................................................323

JReport Result Viewer Bean.................................................................................................................................324Installation................................................................................................................................................324Properties.................................................................................................................................................324Programming with JReport Result Viewer Bean......................................................................................325Exporting To HTML, PDF, TEXT, XLS, PS, RTF and XML......................................................................325Printing Reports........................................................................................................................................327Getting Page Orientation..........................................................................................................................328Browsing Report Pages............................................................................................................................328Zooming the Report..................................................................................................................................329ClickActionListener...................................................................................................................................329Setting the Communicator of this report...................................................................................................330Set User Input Stream..............................................................................................................................330Exiting the Bean.......................................................................................................................................330Illustrative Examples.................................................................................................................................330

Using JReport Catalog Bean.................................................................................................................................331Introduction...............................................................................................................................................331Installation................................................................................................................................................331Classes.....................................................................................................................................................331Programming with JReport Catalog Bean................................................................................................332

JReport Designer API............................................................................................................................................337About JReport Designer API....................................................................................................................337 Designer API & Server Designer API......................................................................................................337License.....................................................................................................................................................337Installation................................................................................................................................................338Getting Started.........................................................................................................................................339Programming with Designer API..............................................................................................................339Illustrative Examples for Using Designer API...........................................................................................346

Catalog API...........................................................................................................................................................351Introduction...............................................................................................................................................351Installation................................................................................................................................................351Programming with Catalog API................................................................................................................351Creating a Designer Object......................................................................................................................352Getting a Catalog API Instance................................................................................................................352Creating a Connection..............................................................................................................................352Inserting an Object...................................................................................................................................353Inserting a Table/View..............................................................................................................................353Inserting a Stored Procedure...................................................................................................................353Importing an SQL File..............................................................................................................................353Inserting a UDS........................................................................................................................................353Inserting a Query......................................................................................................................................354Inserting a Formula, Summary, Parameter or a WherePortion................................................................354Deleting an Object....................................................................................................................................355Modifying a Query....................................................................................................................................355Getting objects in Catalog........................................................................................................................356Saving......................................................................................................................................................358An Illustrative Example.............................................................................................................................358

Using JReport Beans in Java IDE...................................................................................................................................360Using JReport Beans in Forte for Java.................................................................................................................360

Installing JReport Software.......................................................................................................................360Adding JReport Beans into Component Palette of Forte for Java............................................................360Using JReport Beans in Forte for Java....................................................................................................363

Integrating JReport Beans with JBuilder 5............................................................................................................369Integrating JReport Design Bean.............................................................................................................369

VII

Page 9: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsIntegrating JReport Run−time..................................................................................................................373

Integrating JReport Beans with IBM VisualAge 3.0...............................................................................................374Installing JReport Beans..........................................................................................................................374Integrating JReport Beans with IBM VisaulAge 3.0..................................................................................375

Deploying JReport Engine Bean as EJB to WebLogic 8.1 on Windows/Linux......................................................378Introduction...............................................................................................................................................378Installation................................................................................................................................................379Wrapping JReport Engine Bean into Session Bean.................................................................................379Creating and Building EJB.......................................................................................................................380Running Client Application ......................................................................................................................382

Deploying JReport Engine Bean as EJB to Weblogic 6.1.....................................................................................382Installation................................................................................................................................................382Wrapping JReport Engine Bean into Session Bean...............................................................................382Creating and building EJB........................................................................................................................383Running JREngineClient.class.................................................................................................................386

Deploying JReport Engine Bean as EJB to WebSphere 5.1 on Windows/Linux...................................................387Introduction...............................................................................................................................................387Installation................................................................................................................................................388Developing EJB Session Bean and Servlet Calling EJB..........................................................................388Deploying EAR and Starting the Servlet...................................................................................................390

Deploying JReport Engine Bean as EJB to J2EE 1.2...........................................................................................391Preparation...............................................................................................................................................391Wrapping JReport Engine Bean.............................................................................................................391Deploying JReport Engine Bean as EJB to J2EE 1.2..............................................................................392Compiling and Running the Client............................................................................................................399

Supporting EJB Deployed in JBoss 3.0.7.............................................................................................................399Preparation...............................................................................................................................................399ant_jreport_ejb.zip....................................................................................................................................400Build and Deploy the JReport Demo Program.........................................................................................400Run JREngineClient Application...............................................................................................................401Manage Entity Beans...............................................................................................................................402

Using JReport Beans in Novell ConsoleOne.........................................................................................................402Preparation...............................................................................................................................................402Generating Reports..................................................................................................................................403

Exporting Report Result to Multiple File Formats.........................................................................................................410Introduction............................................................................................................................................................410Exporting to JReport Result..................................................................................................................................410Exporting to Text...................................................................................................................................................411Exporting to HTML................................................................................................................................................415Exporting to PDF...................................................................................................................................................421Exporting to Fax....................................................................................................................................................423Exporting to PostScript File...................................................................................................................................427Exporting to Mail....................................................................................................................................................428Exporting to Applet................................................................................................................................................431Exporting to RTF File............................................................................................................................................433Exporting to Excel File...........................................................................................................................................433Exporting to XML...................................................................................................................................................438

User Defined Objects (UDO)............................................................................................................................................441Introduction............................................................................................................................................................441Creating a UDO.....................................................................................................................................................441

Creating a UDO Manually.........................................................................................................................441Creating UDO with UDO Maker................................................................................................................450

Case: Chart API....................................................................................................................................................454Generating Frame Code with UDO maker...............................................................................................454

VIII

Page 10: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsInserting the UDO.....................................................................................................................................457JReport Enterprise Chart API Definition...................................................................................................460

Adding a UDO to a Report....................................................................................................................................464Inserting a UDO.......................................................................................................................................464Building Hyperlinks by Inserting Built−in UDOs........................................................................................464Example: Using JHyperlink to Link Reports as Master−Detail Reports....................................................466

True Type Font .................................................................................................................................................................470JReport Font System.............................................................................................................................................470Designing Reports with TTF..................................................................................................................................470Deploying TTF to Production Environment...........................................................................................................470Delivering the Result in Excel/RTF/HTML/Txt.......................................................................................................470Delivering the Result in PDF.................................................................................................................................470

Report Template...............................................................................................................................................................472Introduction............................................................................................................................................................472How does a Template Work..................................................................................................................................472Saving a Report as a Template.............................................................................................................................473Managing Templates.............................................................................................................................................474Modifying a Template File.....................................................................................................................................475

Writing and Using Formulas ...........................................................................................................................................478Introduction............................................................................................................................................................478Operations on a Formula.......................................................................................................................................478

Creating and Modifying a Formula...........................................................................................................478Formula Examples................................................................................................................................................478Using Formulas.....................................................................................................................................................480

Inserting a Formula into a Report.............................................................................................................480Controlling the Property Values................................................................................................................480

User−defined Formula Functions (UDF)...............................................................................................................483

JReport Parameter and its Applications ........................................................................................................................486Introduction............................................................................................................................................................486Operations on a Parameter...................................................................................................................................486Creating or Modifying a Parameter.......................................................................................................................486Sorting Parameters...............................................................................................................................................489Parameter Application Cases................................................................................................................................490

Inserting a Parameter Directly into a Report............................................................................................491Referencing a Parameter in a Formula....................................................................................................491Dynamic Group........................................................................................................................................493Dynamic Sort............................................................................................................................................495Using Parameter(s) to Filter Data Set......................................................................................................497Using Parameters to Filter Records (also fetch all records if no parameter value is entered).................498Supplementing Where Portion..................................................................................................................499Supplement Where Portion (also for a sub−report)..................................................................................500Parameter Binding....................................................................................................................................501Group Parameters....................................................................................................................................503

Importing Parameter Values..................................................................................................................................506Introduction...............................................................................................................................................506Importing Parameter Values.....................................................................................................................506

Exit Functions ...................................................................................................................................................................510Exit Functions........................................................................................................................................................510Using Exit Functions..............................................................................................................................................511Running the Exit Function Report on JReport Enterprise Server..........................................................................512

IX

Page 11: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsNational Language Support ............................................................................................................................................514

Introduction............................................................................................................................................................514Using National Language Support.......................................................................................................................514NLS for JREntServer.............................................................................................................................................516Appendix I: Language...........................................................................................................................................518Appendix II: Region...............................................................................................................................................522

Page Level Security .........................................................................................................................................................529Introduction............................................................................................................................................................529Setting Page Level Security.................................................................................................................................529Viewing a Report in JReport Enterprise Server....................................................................................................530Scheduling a Report in JReport Enterprise Sever................................................................................................531Example: Email Billing Reports.............................................................................................................................532

Record Level Security and Column Level Security .....................................................................................................536Introduction............................................................................................................................................................536Catalog Scope Security.........................................................................................................................................536

Setting up Security Policy.........................................................................................................................538Applying a Security Policy to the Report..................................................................................................546Deploying to JReport Enterprise Server...................................................................................................546

Report Scope Security..........................................................................................................................................547Setting up Record Level Security.............................................................................................................547Running Reports with RLS on Server......................................................................................................552

Security Context .............................................................................................................................................................553

Security Context Overview..............................................................................................................................................554

Configuration ....................................................................................................................................................................555 Designer...............................................................................................................................................................555 Server...................................................................................................................................................................555

Security Context APIs......................................................................................................................................................556 JReport Designer API...........................................................................................................................................556

JRSecurityContextFactory........................................................................................................................556JRSecurityUserDataSource......................................................................................................................556JRSecurityHierarchicalDataSource..........................................................................................................556

JReport Enterprise Server API.............................................................................................................................557SecurityContextFactory............................................................................................................................557SecurityContext........................................................................................................................................557

JReport Designer .............................................................................................................................................................558 Formula Editor......................................................................................................................................................558 Deployment..........................................................................................................................................................558

DeploymentWizard...................................................................................................................................558DeploymentWizardFactory.......................................................................................................................558Working Principle......................................................................................................................................559

View Report..........................................................................................................................................................559

Converting Crystal Reports to JReport Reports ...........................................................................................................560Introduction............................................................................................................................................................560Installing Crystal Converter...................................................................................................................................560

Installation................................................................................................................................................560System Properties....................................................................................................................................560

Converting Crystal Reports to JReport Reports....................................................................................................561Converting More Than One Crystal Reports At One Time.......................................................................561

X

Page 12: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table of ContentsConverting One Crystal Report At One Time...........................................................................................563Converting a Report with Sub−report.......................................................................................................563Converting Formulas................................................................................................................................564References...............................................................................................................................................565

Tips........................................................................................................................................................................566Trouble Shootings.................................................................................................................................................566Connecting to the Databases................................................................................................................................567

XI

Page 13: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Designer − User's Guide: StructureUser's Guide provides an in−depth coverage on JReport Designer's features, and it generally explains how to performdifferent tasks with the product. Browse the pages to find the chapters you are interested in for step−by−step instructions.The User's Guide includes the following chapters, and along with new features, further chapters added in future:

Installing and Launching JReport Designer• Starting a Catalog• Developing Reports with Report Wizard• Previewing a Report• JReport Designer Window• Refining the Report Layout• Using Styles in Your Report• Editing a Report • Charts • Report Manager and Data Manager• Problem Diagnosis − Catalog Doctor• Developing Reports from a Query/SQL File• Developing Reports from Stored Procedures• Developing Reports from User Data Source (UDS)• Developing Reports from Hierarchical Data Source• Developing Reports with OOJDBC• Deploying Reports• Executing Reports from JReport Beans or APIs• Using JReport Beans in Java IDE• Exporting Report Result• User Defined Objects (UDO)• True Type Font• Report Template• Writing and Using Formulas• JReport Parameter and its Applications• Exit Functions• National Language Support• Page Level Security• Record Level Security•

JReport manual roadmap

The following diagram lists other books in the JReport Designer manual, JReport Enterprise Server manual andJREntViewer manual and shows the relationship among them. We recommend you to start with the JReport DesignerManual. After you have some knowledge about designing reports, it will then be easy to learn JReport Enterprise Serverin the client/server architecture.

JReport Designer manual includes four books: Getting Started, Tutorial, User's Guide, and User Reference.

JReport Enterprise Server (JREntServer) manual contains three books: Getting Started, Tutorial, and User's Guide. Inaddition, the JREntViewer manual is for using JREntViewer with JREntServer.

1

Page 14: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For a complete coverage of the features, operations and other information, please refer to the specific book.

JReport Designer Getting StartedAn introduction to JReport. It covers issues associated with installation, setup and configuration of JReport. It is acombination of informational topics and strategic references to various topics in the User's Guide and User Referencebooks.

JReport Designer TutorialBasic report building instructions. It includes useful reporting features. After walking through this tutorial, you will be ableto build your own reports. For in−depth coverage of features such as building reports on XML, EJB, stored procedure,and SQL file, please refer to the User's Guide.

JReport Designer User ReferenceThis book contains technical and systematical reference information on JReport built−in objects, built−in formulafunctions and APIs.

JREntServer Getting StartedAn introduction to JReport. It covers issues associated with installation, setup, and configuration of JReport EnterpriseServer. It briefly describes most informational topics and references in the server User's Guide.

JREntServer TutorialBasic server configuration, administration and accessing instructions. After walking though this tutorial, you will be able touse the server to manage interactions between client and server, which enable activities such as scheduling and runningreports.

JREntServer User's GuideAn in−depth coverage of the features of JReport Enterprise Server, including advanced server features such as JSP,National Language Support (NLS), Server API, application server integration, and JReport (Client) Viewer Bean.

JREntViewer ManualA complete coverage of the features and instructions of using JREntViewer with JREntServer. Client API usage has alsobeen covered in this book.

JReport Designer − User's Guide: Structure

2

Page 15: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Installing and Launching JReport Designer

System Requirements

JReport Designer

Minimum Workstation Requirements

OS:Microsoft Windows 2000, XP,2003

Solaris, Linux

CPU: PIII − 450MHz PIII 450 or sunSPARC 400

Memory: 128 MB 128 MB

Disk: 128 MB free 128 MB free

JDK: 1.3.0 or above 1.3.0 or above

Recommended Workstation Requirements

OS:Microsoft Windows 2000, XP,2003

Solaris, Linux

CPU: P4 − 1.5GHz P4 1.5G or sunSPARC 1G

Memory: 256 MB 256 MB

Disk: 256 MB free 256 MB free

JDK: 1.4.1_02 or above 1.4.1_02 or above

Note: JReport supports Java VMs from Sun and IBM. Other vendor's Java VMs may cause unexpected errors. Jinfonettechnical support welcomes any feedback on the use of other Java VMs.

Installing JReport Designer on Windows

Please follow the steps listed below to install JReport Designer:

Download the JReport install program jrpsetup.exe from the Jinfonet website: http://www.jinfonet.com.1. Run jrpsetup.exe and follow the default prompts to install.2.

During installation, please note that:

The InstallShield will first find a JVM to get started. If no JVM is found, the installer will fail to launch. To solve thisissue, you can install JReport from a DOS command by specifying −is:javahome option for the InstallShield asbelow:

jrpsetup.exe −is:javahome d:\j2sdk1.4.1_06

The InstallShield will generate temp files during installation. You can specify the temp directory with −is:tempdiroption as below. Otherwise, system temp directory will be used. Temp files will automatically be removed oncethe installation is complete.

jrpsetup.exe −is:tempdir c:\temp

You are recommended to use JDK version 1.4.1 or above. We have encountered certain issues, such asdesigning problems with JDK 1.4.0.x.

The installer provides a chance for you to add additional classpaths. Also, after installation, you can choose toadd them manually into the JReport.bat or setenv.bat file under %install_root%\bin.

If you select to install JReport Designer in a folder that contains a copy of JReport Designer, the installer willreplace the packages and create new batch/script files. Meanwhile, a copy of the old batch/shell files will be keptfor your reference. You are recommended to use the batch/script files that come with the installer to make surethat all new packages are added into the classpath.

3

Page 16: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Uninstalling JReport Designer on Windows

Use one of the following ways to uninstall JReport Designer:

From the Start menu, select JReport Designer XXX (version number), and then click Uninstall JReportDesigner.

From the Control Panel, open Add/Remove Programs, and then select JReport Designer XXX to remove it.• Run uninstaller.exe under %install_root%\_uninst.•

Note: The uninstaller will remove all files generated by the installer, while the files that are created later by the programwill be retained. You can remove these manually.

Running JReport Designer On Windows

Use one of the following ways to run JReport Designer:

Double−click the shortcut of JReport Designer on the desktop.• From the Start menu, select JReport Designer XXX (version number), and click JReport Designer.• Run the batch file from a MS−DOS command prompt. Please type the following commands (Assuming thatJReport Designer has been installed under C:\JReport):

C:\>cd JReport\binC:\JReport\bin>jreport.bat

Installing, Running and Uninstalling JReport Designer on Unix

To install JReport Designer on Unix, please follow the steps below:

Download the JReport Designer install program for Unix jrpsetup.sh (JReport also providesjrpsetup_linux.bin for the Linux users) from the Jinfonet web site: http://www.jinfonet.com.

1.

Click the executable file jrpsetup.sh to launch the InstallShield wizard. Or, open a console window. Change thedirectory to the location of the jrpsetup.sh file. The following are the examples of the commands that can beused:

$ cd thepathTo make jrpsetup.sh executable, type the command: $ chmod +x jrpsetup.shRun jrpsetup.sh: $ ./jrpsetup.sh

Note: The InstallShield will first find a JVM to get started. If no JVM is found, the installer is failed to launch. Tosolve this issue you can specify a JVM for the InstallShield with the option −is:javahome like below.

$ ./jrpsetup.sh −is:javahome /home/j2sdk1.4.1_06

For the Linux users, if the InstallShield still cannot find the JVM, you can use jrpsetup_linux.bin instead ofjrpsetup.sh.

You are recommended to use JDK version 1.4.1 or above. We have found some known issues like designingproblems with JDK 1.4.0.x.

In addition, The InstallShield will generate temp files during installation. You can specify the temp directory with−is:tempdir option like below. Otherwise, system temp directory will be used. Temp files will be automaticallyremoved once the installation is complete.

2.

Installing and Launching JReport Designer

4

Page 17: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

$ ./jrpsetup.sh −is:tempdir /home/temp Once InstallShield has been successfully loaded, you can follow the default prompt to install JReport Designer.3.

To run JReport Designer on Unix, run the script file JReport.sh under %install_root%/bin.

$ ./JReport.sh

Note: you can modify this script file to add additional classes before launching JReport Designer.

To uninstall JReport Designer on Unix, execute uninstaller.sh under %install_root%/_uninst, or open a consolewindow. Change the directory to the location of the uninstaller.sh file. The following show examples of the commandsthat can be used:

$ cd thepathRun uninstaller.sh: $ ./uninstaller.sh

Setting up the ODBC/JDBC Driver

Data Source

You need to create a data source before you can start designing reports with JReport Designer. JReport Designer isrelational database oriented reporting software. That is, the data for reporting is a relational table such as atwo−dimension data sheet. Java Database Connectivity (JDBC) or Java Database Connectivity − Open DatabaseConnectivity (JDBC−ODBC) connection are the basic approaches for connecting to a database for data. Additionalmethods have also been provided to access data stored in various ways.

Currently, there are four approaches with which you can connect to data:

JDBC Connection: Allows you to connect to a database via a JDBC Driver. • JDBC – ODBC Bridge: Allows you to connect to a database via JDBC – ODBC Bridge. • OOJDBC Driver: Allows you to use XML and EJB as a data source, and import the data to JReport. • User Defined Source (UDS) API: Through User Data Source (UDS) API, JReport Designer can also accessdata from an external data source, such as a text file, Lotus Notes, which is not stored in a database or whenthere is no JDBC driver available.

Setting up JDBC Driver if Necessary

To connect to a database via a JDBC driver,

Install the JDBC driver according to the instructions provided by the JDBC driver provider.1. Edit JReport.bat/JReport.sh or setenv.bat, which are contained in the bin folder under %install_root%, byappending the classpath for the JDBC driver. %install_root% is the path where you installed JReport Designer.

Note: This step is very important, missing JDBC driver for JReport start−up batch or command line will result inthe "ClassNotFoundError" message when you try to run a report.

2.

Here we will show you two examples for setting up JDBC Driver.

Example 1: Installing a Sybase JDBC Driver:

Install Sybase JDBC driver Jconnect.class, run the SQL file sql_server.sql to create the JDBC metadatatables. (Please refer to the user's guide of Sybase installation for further details.)

1.

Modify the setenv.bat by appending the archive file path of the driver to the set ADDCLASSPATH systemvariable:

2.

Installing and Launching JReport Designer

5

Page 18: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

set REPORTHOME=C:\JReportset JAVAHOME=C:\j2sdk1.4.2_01set ADDCLASSPATH=c:\jconnect\classes

Or edit JReport\bin\JReport.bat/JReport.sh by appending the archive file path of the driver to the classpath:

Change: ... −classpath"%REPORTHOME%\lib\SwingDesigner.zip;%REPORTHOME%\lib\resources.zip;..."To : ... −classpath"%REPORTHOME%\lib\SwingDesigner.zip;c:\jconnect\classes;%REPORTHOME%\lib\resources.zip;..."

Example 2: Installing an Oracle JDBC Driver:

Install Oracle JDBC driver classes12.zip/Classes12.jar (for Oracle 8i or 9i) or ojdbc14.jar (for Oracle 9i). 1. Modify the setenv.bat by appending the archive file path of the driver to the set ADDCLASSPATH systemvariable:

set REPORTHOME=C:\JReportset JAVAHOME=C:\j2sdk1.4.2_01set ADDCLASSPATH=c:\orc\thin\lib\classes111.zip

Or edit JReport\bin\JReport.bat JReport.sh by appending the archive file of Oracle thin driver to classpath:

Change: ... −classpath"%REPORTHOME%\lib\SwingDesigner.zip;%REPORTHOME%\lib\resources.zip;..."To : ... −classpath"%REPORTHOME%\lib\SwingDesigner.zip;c:\orc\thin\lib\classes111.zip;%REPORTHOME%\lib\resources.zip;..."

2.

Launchers Under JReport Designer

The information in this topic was current at the time of release. However, it may no longer be valid due to changes duringthe release cycle. The most current information can be found in the readme.txt with each version under the path%installroot%.

You can find a set of utilities in the directory %installroot%\bin\. All of these batch files (Win)/script files (Unix) can beedited to suit different circumstances. However, always do this before making sure of their functions.

setenv.bat: Set JReport Designer environment variables, and is called by JReport.bat, DJReport.bat andNJReport.bat when running JReport Designer. The following are descriptions for items in the file:

set REPORTHOME=: The directory where you installed JReport Designer. Please do not modify thisvariable.

set JAVAHOME=: The directory where the JDK that is currently used by JReport Designer is located.Change it if you want to switch a different JDK version.

set ADDCLASSPATH=: Please add your necessary classpaths here. You can also add them in theclasspath of JReport.bat/JReport.sh, NJReport.bat/NJReport.sh, or DJReport.bat/DJReport.sh files.

JReport.bat/JReport.sh: Batch file/Script file for starting JReport Designer. • NJReport.bat/NJReport.sh: Batch file/Script file for starting JReport Designer without the JIT option. • DJReport.bat/DJReport.sh: Batch file/Script file for starting JReport Designer in logging mode. Usually in caseof problems, we allow users to launch JReport Designer with this batch file/script file to track the detailed loginformation. Running this batch file/script file will generate the log file JReport.log in the current directory.

CatDr.bat/CatDr.sh: Batch file/Script file for starting Catalog Doctor to make changes of the resources in thecatalog.

EConvert.bat/EConvert.sh: Batch file for removing the evaluation mark from reports. If you purchased ourproduct and was successful in running JReport Designer with the new key, but the evaluation watermarks are stillleft. You need to run this batch file to remove the evaluation watermarks. Run the batch file with the reportname(s) to be converted with the full path as parameter.

Installing and Launching JReport Designer

6

Page 19: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Econvert.bat [ReportName.cls]Example: Econvert.bat c:\JReport\Demo\reports\*.cls jrenv.bat/jrenv.sh: Batch file/Script file for generating the report environment file − report.env. In case ofproblem, this file can help the Jinfonet support staff to assist you.

PropConvert.bat: You can use this tool to modify report object properties without using JReport Designer. Thisis useful when you want to modify several properties using the same value at one time. For example, a Labeland several DBFields may share the same background as blue, but now you want to change them all totransparent, you can simply use this tool. To use this tool, do one of the following:

Double click to run this tool, on the JReport Property Converter dialog, type the file name (use *.cls if youwant to apply the change to all the catalog reports), enter object name (leave this field blank if you wantto apply the change to all objects), select the property name from the drop down list, provide the oldvalue (leave this field blank if you want to apply the change to all the objects that have this property) andnew value respectively, and then click Convert. The property of the report object(s) that meets therequirements will be changed to the new value that you specified.

Use the command line to execute this tool as:

PropConvert [−vdebug] [−verror] −f:FilePathName −p:PropName −ov:[OldValue]−nv:NewValue

For example:

C:\JReport\bin>propconvert −vdebug −verror −f:C:\JReport\Demo\Reports\*.cls−p:FontFace −ov:Serif −nv:Dialog

Note: You can use wildcards for report file name. Leave the −ov: empty if you want to apply the changeto all the objects that have this property, for exampel, −ov: −nv:Dialog.

rp.bat/rp.sh: Batch file/Script file for installing a new key without reinstalling the product. You can run thisprogram using the following command:

For Windowsrp.bat [ID] [Password]

For Unix ./rp.sh [ID] [Password]

UDOMaker.bat: User Defined Object maker to import beans. • ModelWizard.bat: ObjectDataSource importer. • ConvertUnit.bat/ConvertUnit.sh: Batch file/Script file for converting a report with resolution errors to use correctresolutions. Before using this file, you should first modify the property value as below:

1. When you edit the file, you will find a property named −Dresolution. This property is used to set the originalresolution the report used. The default value we set this property is 72. You should modify it according to thefollowing rules:a. If the report file was saved before build 472 (not including 472), you can remove this resolution option.b. If the report file was saved before build 495 (not including 495), you should set the resolution to 72.c. If the report file was saved before build 501 (not including 501), you should remove this resolution option.d. If the report file was saved after build 501, please do not use this batch.

2. After you have modified this property, you can run the batch file using the following command:ConvertUnit [drive:] [path] [filename]For example, if you want to convert the report namedLesson2.cls located at c:\JReport\demo\Reports\SunVMDemo,you should key in:ConvertUnit c:\JReport\demo\Reports\SunVMDemo\Lesson2.cls

upName.bat/upName.sh: Update the name of DBField in the report using the field name in catalog for exporting•

Installing and Launching JReport Designer

7

Page 20: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

to XML file.JRTutorial.bat: Run this batch file to display the tutorial help.•

Command−line Startup

You can launch JReport Designer from the Command Prompt window. This method is optional on some platforms(Windows for example) and preferred on others. Using command−line startup enables you to use command−line syntaxoptions.

java −Dreporthome=path −classpath path jet.builder.JReport −vError −vDebug −hideBrs −log[:<file>] −help

The command line arguments for JReport Designer are described below. Please note that the setup process createsseveral startup batch files which may contain additional parameters.

−DreporthomeSpecifiesthe directory where JReport Designer has been installed. This parameter is required. When you set thereport home, upon launching, JReport will try to find jslc.dat and report.ini files under %ReportHome%\bin andcheck whether they are valid. jslc.dat is the License control file. Open report.ini, you will find configurationinformation, including the temp path, template path and the help path. JReport will use the temp path to exportthe temporary files. Therefore, make sure the temp folder specified in report.ini actually exists.

If JReport Designer has been installed under c:\JReport, then this parameter should be: −Dreporthome=c:\JReport

−classpath pathTells the Java interpreter the classpath. Usually append the JReport Designer lib path to the Java classpath, ifJReport Designer was installed to c:\JReport and Java (JDK1.x.x) has been installed at c:\java, then thisparameter should look like:−classpath c:\java\lib\classes.zip;c:\jreport\lib\report.zip;

−Djava.compiler=NONETurns off just in time compiling which sometimes creates problems.

−Djrpt.outer=trueEnables JReport Engine to generate SQL statement with full outer join syntax instead of an abbreviated one.

−mx200mSets the maximum Java heap size.

Logging and debugging switchesYou can use the following three command switches together to track debug and error information to console orlog file.

You can specify the log file format, such as Text, or HTML. You can decide whether to append the log files to theexisting file, or create a new file. You can even specify the log layout using the abundant options that JReportprovides.

To do this, you need to edit the %REPORTHOME%\bin\LogConfig.properties file. For detailed informationon how to configure logging and debugging information, please read the LogConfig.properites file.

−vErrorEnables JReport Designer to output error messages to Console or log file (when used together with−log).

−vDebugEnables JReport Designer to output debug messages to Console or log file (when used together with−log).

−log[:<file>]Tells JReport Designer to output debug, error or other messages to the specified file. If no file specified,the file JReport.log will be used.

−helpPrint the help message.

Installing and Launching JReport Designer

8

Page 21: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Starting a Catalog

Catalog

Topics covered in this section:

Catalog OverviewUsing Catalog Browser to Manage Resources Using Reference Table to Clarify Resource RelationshipsSetting Default Values for ObjectsCreating Catalog and ConnectionsCatalog in XML format

Catalog Overview

A catalog is a report repository (a logical container of reports). A catalog file (.cat, .cat.xml) is a physical file that recordsdata sources and object definitions used by the reports in the catalog. There are two kinds of objects defined in a catalog:data objects and customized classes. Data objects include data sources, connections, tables/views, and queries.Customized classes include text− fields, cross tabs, styles, and various shapes, such as boxes, lines.

The reports cannot run properly unless they are saved under the same directory together with the catalog file they belongto. In addition, you are recommended to store only one catalog under one directory. If you migrate a report to a differentdirectory using the Save To command on the File menu, the catalog that contains the objects that the report refers to willalso be taken to that directory. If there is no other catalog file in the destination folder, a new copy will be generated, orelse it will be merged into the catalog file that already exists in that directory.

Advantages of Catalog

Similar to having cabinets in your kitchen to hold your plates, cups and saucers, JReport Designer has a catalog file tohold reports, queries and other resources. The advantages of introducing Catalog to JReport Designer lie in the followingaspects:

Visual Database − Working Off−lineJReport Designer provides a friendly tool for you to be clear of your resources any time − Catalog Browser.When you are offline from your database, you can still see the architecture of your database (includingtables/views, queries, parameters).

Sharing Defined Data Field Among ReportsMultiple reports can use the same defined data field already defined and saved in the catalog.

Cross Reference TableYou can use the cross−reference table to view the object referencing relationships. For example, informationsuch as what other resources are using the current resource can help you to manage your catalog resourcesmore conveniently. The most important, when you rename a catalog resource, JReport can help you update thechanges in the resources using this resource.

Setting Default Values for ObjectsUsers can set the default values for some catalog level objects in the property sheet of catalog browser. Oncethe user set the default value, you will not need to set it individually in the report after you've inserted it.

What is in a Catalog?

There are two kinds of objects defined in a catalog:

9

Page 22: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Data Objects: including connections, tables/views, queries, formulas.•

As shown in the figure above,

Tables/Views & Columns, Queries, Stored Procedures, Imported Queries are based on JDBC/ODBC connection.• Tables/Views & Columns are from the database. They outline the table structure in your raw database. A queryis built based on Tables/Views & Columns from the database. So, only after you add the Tables/Views to thecatalog can you build a query. We provide the interactive query editor, where you can create a query in a snap.

A stored procedure is one from the raw database. It can be used directly to build reports like a query.• Instead of using the interactive Query Editor for building a query, you can write your own SQL statements, andthen import them into a catalog.

Query, Stored Procedure, and Imported Query are functionally the same. Query depends on the Table/Viewsadded while Stored Procedure and Imported Query need only connect with your database. After you set up theconnection, they can be created or imported. However, to build a query, you should have database tables/viewsadded.

UDS is also like a query, but it is up to the user to write the code for fetching the records. It is independent of theJDBC/ODBC connection.

Parameters can be used in a report for users to enter the parameter value at report run time.• Formulas (summaries) are the objects to be computed at run time.•

Using Catalog Browser to Manage Resources

Catalog Browser is a useful JReport Designer interface which simplifies the work of report design and the managementof the actual resources you use. It consists of three tabs: Data, Reports and Styles. All the data objects are organized inData and Reports tabs, which are most often used.

To launch Catalog Browser:

Start JReport Designer.1. On the View menu, click to check Catalog Browser or on the toolbar, click the Catalog Browser button if the2.

Starting a Catalog

10

Page 23: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Catalog Browser window is not currently visible.

See the three tabs:

DataThe most important feature of Catalog Browser is the quick access to tables and fields on the Data tab. You caneasily create or edit fields using the working set which contains queries, formulas, summaries and parameters.

Resources Description

ConnectionA list of database tables, views and stored procedures from the JDBCor JDBC−ODBC connection as well as user defined SQL files in thecatalog.

QueriesInclude all the SQL queries used by the reports in the catalog. Onereport is based on only one query.

Formulas Creates and edit formulas in a catalog.

Summaries Creates and edit summaries in a catalog.

Parameters Creates and edit parameters in a catalog.ReportsManage your reports in folder view. You can divide the reports into different types. In this way, you can managethem just like processing files in a file system. You can add, delete, move, rename and search items.

StylesFrom the Styles tab, you can create and edit JReport styles.

Style Groups: Containers that hold a set of style elements or style groups. You can create, add, remove or editstyle groups from this tab.Styles: Style elements that hold a set of properties, which can be applied to specified report objects. You cancreate, add, remove or edit styles from this tab.

Catalog Browser Toolbar

NewThe first button on the toolbar which changes according to the object currently selected. Usually, this icon imagecontains a plus sign. Click this button to create a new object of the selected type. For example, if a query iscurrently selected, you can click this button to create a new query.

Copy and PasteApplies to queries, formulas and summaries on the Data tab. When copying an object, all the properties of thecopied object are the same as the original except for the object name. If an original object is named docstatus,the first copy will be named Copy of docstatus, the second copy will be named Copy(2) of docstatus, etc. Youcan also rename after paste by single−clicking the object twice.

Configure ReferenceAllows you to select data sources and resource types that you want JReport Designer to monitor.

Refresh ReferenceRefreshes the cross−reference relationship information to make it consistent with the catalog resources.

Export ReferenceExports the cross−reference relationship information to a text file.

OptionBrings out the Report Option dialog where you can set the options for editing a catalog or reports.

Data Source ManagerInserts a user data source into the catalog.

Per−joinBrings out the Per−join Editor to define the pre−join paths formed by the relationships among the tables in thedata source you specified.

Expand/FoldExpands or folds the Properties sheet of Catalog Browser. Note: You can access to the commands alternatively by right−clicking any item.

Starting a Catalog

11

Page 24: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using Cross−reference Table to Clarify Resource Relationships

Along with the development of the reports and catalog, the relationships among the catalog resources may becomeincreasingly complicated. You might be wondering if and where a SQL or a formula is used by a resource in catalog orreport. You might even hesitate to rename a resource because you don't exactly know what other resources are currentlyusing it and, if you rename it, what result it would cause. To help you manage catalog resources, we provide a tool foryou − cross−reference table.

JReport monitors the resource cross−reference information in the catalog and stores this information in thecross−reference table. You can select the resource types that can be registered in the cross−reference table.

With cross−reference table, when you rename a resource object, JReport Designer will scan the reference relationshipsbetween it and other resource objects. It will then prompt you to update the changes in the resources that are referencingthe object, helping you reduce risk of resource not applicable.

Most resources in the catalog can be included in the reference table, such as connections (tables, views, procedures,and SQLs), user data sources, hierarchical data sources, queries, formulas, summaries, parameters, and reports.

Configure cross−reference table

Before JReport starts to monitor and record the resource cross−reference information in the cross−reference table, youmust have the reference table configured. In the Reference Configuration dialog, you can choose the resource types thatare to be added to the table. Then, JReport will monitor the reference relationships among the objects of these resourcetypes and store the relationship information into the database.

To configure the cross−reference table,

On the Catalog Browser toolbar, click the Configure Reference button.1. Check the data sources that you want JReport to monitor in the Data Source list. 2. In the Resource Types list, check the resource types that are to be added to the cross−reference table.

In order to improve the product performance and provide you with more flexibility, JReport allows you to choosethe resource types that you want to monitor by yourself. Please note that JReport will only monitor thereferencing relationships among the resource types that you have selected. The resource types that have notbeen selected will not be monitored, though they may have referencing relationships to the selected resourcetypes. Therefore, if you are not sure that the resource types you have selected hold all the possible referencerelationships within themselves, you are recommended to select as many resource types as possible to avoidincomplete information caused by pretermission.

For example, in the Reference Configuration dialog, selecting only the formula resource type means that for aformula, only the formulas referencing this formula will be recorded in the reference table. Although otherresources, such as queries, summaries, and reports, may also be using this formula, they will not be shown inthe reference table. Also if you rename this formula, you will only be prompted to update the change in theformulas using it, ignoring other resources using it.

3.

Click OK. Referencing relationships among the objects of the checked resource types will then be monitoredafter you click the OK button.

4.

View the object reference relationships

After you have configured the cross−reference table, you can view the referencing relationships for an object. To do this,

On the Catalog Browser, browse to the object whose reference relationship you want to view.1. Right−click this object, and then click Reference Entities.2.

Starting a Catalog

12

Page 25: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Update the related resources when you rename an object

One great benefit the cross−reference table provides is when you manage your catalog resources, such as renaming anobject, you don't need to worry about the resources that are currently using that object. JReport automatically updatesthis information in those resources, after you have checked the Apply to all and save catalog option on the Warningmessage box of renaming an object.

Refresh reference table

The reference table information is stored in a database, which provides reliable stability. However, in somecircumstances you may need to refresh the reference table to retrieve the correct reference relationship information. Torefresh reference table, on the toolbar of Catalog Browser, click the Refresh Reference button.

Export reference table to a text file

You can export the reference table information to a text file. To do this, on the toolbar of Catalog Browser, click theExport Reference button.

Setting Default Values for Objects

If you are tired of changing the properties for the objects every time you insert them into your report, you can set thedefault values for them in the catalog browser. Just simply select the object you want to set, click the Expand icon toshow its properties, and then change the values of the properties to suit your requirements.

The properties listed in the property sheet are the default value for the selected object. You can change the propertyvalues here, and the next time you insert that object, the value you specified here will be used as a default value.

The objects that can have default values are fields in Table/View fields, Formulae, Parameters, Summaries, SQL fields,Procedure fields and User Data Source fields.

Note: Query field does not support this feature.

Starting a Catalog

13

Page 26: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating Catalog and Connections

The first thing you should do before you can start developing reports is to create a catalog. After which, you are thenrequired to set up the connections to your data sources (for JDBC/ODBC).

As mentioned in the preceding chapter on installing and running JReport Designer, make sure that you haveadded the class path for your database driver in the batch file with which you start JReport Designer. Start upyour JReport Designer, then click the Cancel button on the Open Report dialog.

1.

On the Data tab in Catalog Browser, make sure the Connection node is selected, right−click and on thepop−up menu click New Connection.

2.

For JDBC connection, type in the JDBC driver class name, the JDBC URL and the user name and password (ifnecessary), and then click OK.

3.

In the Add Table dialog, select and add required tables to the catalog, and then click Done.4. On the File menu, click Save Catalog to save your catalog file. 5. Then, in the Catalog Browser, Data tab, expand Connection. You will see the tables have already been added.The data source you have just created connection to is named Default.

6.

From JReport Designer version 6, the Multiple Data Sources feature has been supported. If you want to connectanother data source to your catalog, add the class path for the database driver to the batch file with which youstart JReport Designer, go to Catalog Browser and select the Default node, and then click the NewDataSource button on the toolbar. The Input Data Source Name dialog will then be displayed.

Give a name for the data source and click OK. You can then add the new data source with the method justdetailed. Please note that no space is allowed in the data source name.

7.

If you want to build reports on a stored procedure or an imported query file, expand the Connection node andclick Procedures or SQLs, and then on the File menu, click Save Catalog to save your catalog.

8.

To develop new reports, on the File menu, click New, or on the standard toolbar, click the New button.9.

Operating a Catalog

New CatalogCreate a new catalog file by choosing New Catalog on the File menu. The dialog will prompt you to typein the name and location of the catalog file (do NOT forget to add the extension .cat, or .cat.xml). Onceyou have created a new catalog file, in most cases you need to establish a new connection (UDS doesnot depend on a connection).

Open a CatalogOpen a catalog by choosing Open Catalog on the File menu, or open a catalog with a report from theOpen Report dialog.

Starting a Catalog

14

Page 27: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

When you start JReport Designer, the Open Report dialog appears. In the Catalog field you will find apath with a file named with a .cat or .cat.xml extension. This is the catalog file that will be loaded. Youcan click the Browse button next to it to browse for another catalog file. When you have selected acatalog file, the reports in that catalog are listed. Choose one of them and click the Open button to openit. If you click Cancel, the last opened catalog will be loaded.Save a CatalogClick Save Catalog on the File menu to save the current loaded catalog.

Save a Catalog AsClick Save Catalog As on the File menu to save the catalog to another location. You can save thecatalog in .cat file, or .cat.xml file, which is in XML format. The .cat.xml file can be in the same directoryas the .cat file.

Keep a Universal Catalog FileAll the resources for reports are shared in a catalog file. If you have different developers develop reportsat the same time, you may want to share all the resources. You can do this by using the Saveto command on the File menu. It will save your report into a target catalog file, which means:

The reports and the relevant files alike will be copied to the directory where the target catalog fileis located.

The resources (query, formulas, parameters, and so on) that are referenced by this report incurrent catalog will be merged to the target catalog.

So even though you work with your own catalog file, you still can publish your report and resources aliketo the target "Universal" catalog file. However, please note, we do not handle the concurrent issue. It'snot allowed to update the universal copy at the same time by more than one user.

Note: Only catalogs that with the same names can be merged.

Modify Object Properties in Catalog BrowserWhen you click the Expand button on Catalog Browser toolbar, the property list of the selected objectwill be displayed. By default, the properties in Catalog Browser are not editable.

To edit the properties in Catalog Browser: On Catalog Browser toolbar, click the Option button, or on the File menu, select Options.1. On the Advanced tab, uncheck Forbid editing data object properties.2. In Catalog Browser, highlight the column name that you want to edit.3. Change the property values.4.

Example: Specifying the display width of a field

You can define the default width of a field (DBField, formula, summary or parameter) by setting theDisplayWidth property in Catalog Browser.

To do this,

Highlight the column name and list its property.1. Make sure that the property values are editable in Catalog Browser.2. Set the value for DisplayWidth.3.

Notes:

If the DisplayWidth value is not set in Catalog Browser, it will be inserted with the width definedin the template, which you selected when creating the report.

Assume that you have set DisplayWidth of a field, and you insert the field using Report Wizard,its width may be adjusted according to the paper size. However, if you insert the field in thedesign mode, the defined width will not change.

Starting a Catalog

15

Page 28: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Catalog in XML format

JReport Designer supports two formats of catalog files. One is .cat file, which is in binary, and the other is .cat.xml file,which is in XML format. The .cat format catalog can be manipulated (Open, save, and edit, for instance) only by JReportDesigner since it is a binary file. On the other hand, the XML format catalog has many advantages. It has morereadability and controllability. You can modify the catalog freely, according to your requirements, without using any otherspecial editor.

The operation of .cat.xml format catalog in JReport Designer is the same as that of .cat format catalog. The differencebetween these two is the underlying structure in which they are organized.

Note: When you save a catalog to the XML format (*.cat.xml), a special key is needed. If you want, please contactJinfonet support ([email protected]).

Index

Connection

What's a Connection

A connection is a listing of the database objects which are accessible through JDBC or JDBC−ODBC Bridge. If you wantto use tables, views, procedures and other objects stored in a database, you need to connect them to the catalogBrowser.

Creating a New Connection

To create a new connection,

In Catalog Browser, select a data source node, such as Default, and then click New DataSource on the toolbar. 1. The Input Data Source Name dialog appears. Type a name in the text box for the data source and click OK.2. Select the Connection node of the newly created data source, right−click it and on the pop−up menu click newConnection, or click New Connection on the toolbar. The Get JDBC Connection Information dialog will thenappear.

Connection ListThis contains information of successful connections added previously with JReport Designer. The format of theconnection information is:JDBC URL / (JDBC Driver Name)

3.

Starting a Catalog

16

Page 29: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For example:"jdbc:odbc:jinfonet / (sun.jdbc.odbc.JdbcOdbcDriver)

If you choose one of the items from the Connection List drop−down list, the JDBC URL and JDBC driver namewill appear in the corresponding text box.

Use ODBC Data SourceBy default, this check box is checked. It indicates that the name you input in the DSN Name field is the ODBCdata source name. Input your user ID and password into the User Name and Password fields to access thedatabase through the ODBC data source. Uncheck the User ODBC Data Source option, the Get JDBC Connection Information dialog will shown asbelow:

Use Connection PoolConnect the database using WebLogic connection pool.

JDBC DriverIf you check this option, the class name you input next to it will be the JDBC driver name this connection will use.Otherwise, JReport will try all the JDBC drivers specified in %installroot%/bin/jdbcdrivers.properties file for thegiven JDBC URL when it tries to setup database connection. That is to say, you also can add your JDBCdriver's names into the jdbcdrivers.properties file.

JDBC URLIf you do not use ODBC data source, you need to input a valid JDBC URL which can establish a connection toyour database. The valid format of the URL should be provided by your JDBC Driver.

4.

Click the Option button, options for special requirements will be displayed.

QualifiedUsers can decide if Catalog or Schema is used when JReport sends a SQL statement to your database.

Unqualified Name − Neither Catalog nor Schema is included in data manipulation.2−part Names − Use Schema in data manipulation.3−part Names − Use both Catalog and Schema in data manipulation.

This is very useful when you have same table name in different catalog and schema. If you only use unqualifiedname, the SQL statement generated by JReport will not contain the catalog and schema name, and the resultwill be unpredictable.

Date FormatDifferent database systems have different Date and Time formats for Date and Time value. This is for you to

5.

Starting a Catalog

17

Page 30: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

specify the format, so that when JReport sends the SQL statement with Date or Time parameters, it can becorrectly translated to the format of your database system.

y year number

m month in year number

d day in month number

h hour in day (0~23) number

m minute in hour number

s second in minute number

S millisecond number

For example, in the Oracle database, the Date format is 'dd−MMM−yy', but in a Sybase system, the date formatis 'yyyy−MM−dd'. You need to correct the Date format in the connection object so that the SQL statementsgenerated by JReport will work with your database.

Quote QualifierYou can specify the characters, then qualifier name which contains the characters that will not be quoted.

In JReport, we need to quote them with the character defined by DBMS, the default character is double quotationmarks ("). There are two properties of Quote Qualifier:

Default (JDBC) − The program will get the extra name characters from JDBC.User Defined − You can modify the Quote Characters by themselves according to the database system they areusing.

EncodingThis property is used to decide whether the data fetched from the database is encoded.

Auto − Whether or not data is fetched from the database is decided by this statementYes − Data fetched from the database will be encodedNo − Data fetched from the database will not be encoded

When manipulating the data, you can determine which encoding format will be used.

TransactionIf you set the Read Only to be Read Only and Transaction Isolation to be Read Uncommitted, it will speed up thetransaction of the catalog.

Pre−joinUsed to specify whether to enable the Pre−join feature.

JDBC Connection Demo

Example 1: Oracle

The following example illustrates how to create a connection that connects a database with the Oracle JDBC driver.

Assuming that you have installed Oracle JDBC driver, appended the archive file of the thin driver to file classpath in thefile JReport\bin\JReport.bat, the Oracle database server with the name p02_wuhb, port No. 1521, database orcl, user IDscott, and password tiger:

Start up JReport Designer. Click the Cancel button on the Open Report Dialog. Click New Catalog on theFile menu. Provide the name and path for the new catalog. The Catalog Browser will now pop up.

1.

Select Connection in Catalog Browser under the Data tab, right−click and on the pop−up menu click newConnection to bring out the Get JDBC Connection Information dialog.

2.

Starting a Catalog

18

Page 31: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Uncheck the checkbox Use ODBC Data Source and enter jdbc:Oracle:thin:@p02_wuhb:1521:orcl in the URLfield.

3.

Enter the User ID scott and password tiger.4. Check the JDBC Driver check box. Enter the JDBC driver class name oracle.jdbc.driver.OracleDriver in theJDBC Driver text box.

5.

Click OK.6.

Example 2: Sybase

The following example illustrates how to create a connection which connects a database with the Sybase JDBC driver.

Assuming that you have installed Sybase JDBC driver, appended the archive file of the driver to the classpath in the fileJReport\bin\JReport.bat, the Sybase database server with the name SybSever, port No. 5000, database pubs2, user IDsa, and password 123456.

Start up JReport. Click the Cancel button in the Open Report Dialog. 1. Click New Catalog on the File menu. Provide the name and path for the new Catalog. Then, Catalog Browserwill pop up.

2.

Select Connection in the Catalog Browser under the Data tab, right click to pop up the Get JDBC ConnectionInformation dialog box.

3.

Uncheck the checkbox Use ODBC Data Source and enter jdbc:sybase:Tds:SybServer:5000/pubs2 in theURL field.

4.

Enter the User ID sa and password 123456. 5. Check the JDBC Driver check box. Enter the JDBC driver class name com.sybase.jdbc.SybDriver in the JDBCDriver text box.

6.

Click OK.7.

Example 3: WebLogic Connection Pool

The following example illustrates how to create a connection that connects a database with WebLogic 6.1 connectionpool.

Set up WebLogic connection pool.

Start the WebLogic server, and connect the console through a web browser: http://host:7001/console. Then go tothe left panel, and expand the JDBC node.

Click the Connection Pools node. All the defined connection pools will display in the right panel.

Click the Configure a New JDBC Connection Pool text link.

Under the Configuration tab, define the connection pool as below, then click the Create button.

Name: jinfonetURL: jdbc:odbc:jinfonetDriver Classname: sun.jdbc.odbc.JdbcOdbcDriver

1.

Starting a Catalog

19

Page 32: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Check the connection pool.

Under the Monitoring tab, click the link Monitor all Active Pools to check if the pool is active. You will then seethe connection pool you have just created appear under the Monitoring tab.

2.

Click the Targets tab. Add examplesServer to the Chosen column to assign the connection pool to the server.Click Apply to save your changes.

3.

Set up the data source.

Click the Data Sources node under the JDBC node.In the right panel, click the Configure a New JDBC Data Source text link.

Under the Configuration tab, enter values in the Name, JNDI Name, and Pool Name fields as below:Name: jinfonetDSJNDI Name: jinfonetDSPool Name: jinfonet

4.

Starting a Catalog

20

Page 33: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click Create, the new data source will be added under the Data Sources node in the left panel.Click the Targets tab and add examplesServer from the Available column to the Chosen column. Click Apply tosave the changes.

5.

Add weblogic.jar to JReport.bat

To connect WebLogic connection pool in JReport Designer, add weblogic.jar under%Weblogic_Install_Root%\wlserver6.1\lib to the classpath in the batch file used to start up JReport Designer. Inthis example, suppose you installed JReport Designer to c:\JReport, WebLogic to c:\bea, modify JReport.batunder c:\JReport\bin by adding C:\bea\wlserver6.1\lib\weblogic.jar to the classpath:

... −classpath "C:\JReport\lib\report.zip;C:\JReport\lib\resource.zip;C:\bea\wlserver6.1\lib\weblogic.jar...;C:\TEMP";"C:\JReport" −Dreporthome="C:\JReport" jet.report.ide.JReport ...

6.

Create a new connection.

Start up JReport Designer using the modified batch file JReport.bat, click the Cancel button in the ChooseReport Dialog.

Go to the File menu and select New Catalog, then input the name and path for the new Catalog. In the poppedCatalog Browser dialog, right click on the Connection node, and select New Connection.

In the Get JDBC Connection Information dialog, uncheck Use ODBC Data Source, and check Use WeblogicPool Connection, the string "weblogic.jinfonet.pool.Driver" will display in JDBC Driver text box automatically.

Fill in JDBC URL as jdbc:weblogic:jinfonet:@192.168.126.101:7001:jinfonetDS, where @192.168.126.101 is

7.

Starting a Catalog

21

Page 34: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

host of weblogic server, 7001 is port where the weblogic server listens, and jinfonetDS is JNDI Name of datasource.

Click OK.

Notes:

1). Data types longbarbinary and bigDecma are not supported when using WebLogic Pool Connection.2). You should use jdk1.3.1 or above when using WebLogic Pool Connection.

Adding Tables/Views to Connection

Tables and Views

A table/view contains fields mapped to the database fields of a table in a real database. Queries are built on table/view,and a report is developed from only one query or one of the functions similar to a query.

Adding Tables/Views

Adding tables and views allows you to add the tables and views in the data source to the catalog in JReport. To addtables,

Select the Tables node on the Data tab of the Catalog Browser, right−click and click Add Table on the pop−upmenu. You can also select a table under the Tables node, right−click and select New Table on the pop−upmenu.

1.

The Add Table dialog will then appear, as shown below:2.

Select a schema in the Schemas panel, and then click the Load Tables button. The tables contained in theselected schema will then be displayed in the Tables panel.

Note: For the SQL Server database, you can specify the database catalog first from the Database Catalog

3.

Starting a Catalog

22

Page 35: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

drop−down list. Choose the tables you want in the Tables panel and then click Add.

To choose consecutive tables, click the first table, press and hold down SHIFT, and then click the last table.To choose tables that are not consecutive, press and hold down CTRL, and then click each table.

4.

Repeat step 3 and 4 to add tables from other schemas.5. To add certain tables by name or patterns in their name, select the Table Name Pattern check box. The wildcard% displayed in the text box.

For example, if you want to add tables beginning with AL, you can type AL% (case sensitive) in the text box, andthen click the Load Tables button. All the tables beginning with AL in the selected schema are displayed in theTables panel. Choose the tables you want and click Add to add them to the catalog.

6.

After adding the required tables, click Done to close the dialog.7.

To add Views, right click on Views under Connection node, right−click and select Add View on the pop−up menu. TheAdd View dialog is similar to the Add Table dialog.

Removing a Table/View

To remove a Table/view,

Select the table/view to be removed under Tables/Views node in Catalog Browser,1. Press Delete on your keyboard, or right−click it and on the pop−up menu click Delete.2.

Note: Reports built on deleted tables will not work.

Renaming a Table/View

To rename a Table/view,

Right click on the Table/View to be renamed under Tables/Views node in Catalog Browser.1. On the pop−up menu, click Rename.2.

Note: When you want to rename a table, you need to use Catalog Doctor to re−map all the objects such as queries orformulas that were using it, so that your report will work properly.

Properties of a Table/View

To view properties of a Table/View,

Select a table/view.1. Right click and on the pop−up menu click Properties. You can also click the Expand button on the toolbar ofCatalog Browser to view the properties by expanding the Properties sheet.

2.

Modifying an Existing Connection

Using Catalog Browser to Modify Some of the PropertiesBy default, the properties in Catalog Browser are not allowed to be modified. However, under certaincircumstances, such as database with special requirements, you are allowed to modify some options.

To modify, you should first click Options on the File menu to bring out the Report Option dialog, and then onthe Advanced tab, uncheck Forbid editing data object properties. Click Apply and Ok.

Then, to modify an existing Connection, select the existing Connection in Catalog Browser, right click to displaythe option menu, select Modify.

Starting a Catalog

23

Page 36: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Get JDBC Connection Information dialog will then appear. Click the Option button on the dialog. You areallowed to edit properties such as Qualified, Date format, Quote Qualifier, Encoding Format and Transaction. Using Catalog Doctor to Change ConnectionTo modify the connection completely, such as switching to a different database, you need to use Catalog Doctor.This tool helps you make your reports function properly by re−mapping the query and table fields. For moreinformation, please refer to the Catalog Doctor chapter.

Removing an Existing Connection

To remove an existing Connection, first select it, and then press Delete on your keyboard. You can also right click on theconnection, and select Delete menu item.

Renaming an existing Connection

To rename an Existing Connection, select the existing Connection, right click to get the popup menu, then selectRename. Type the name in the name box, press Enter. The name for the connection is just a mark, the actualinformation such as jdbc:odbc:Jinfonet is recorded in the URL.

Viewing properties of a Connection

To view properties of a connection, select the connection you want to view, right click to get option menu, then clickProperties. Also, an easier way to view properties is by clicking on the Expand button in the Catalog Browser toolbar.

Index

Pre−join

Pre−join Overview

In your daily work, you may be often be dealing with a set of tables in your queries. You have to define relationships andcreate joins among different tables every time you create a new report. JReport Designer provides you with a pre−joinfeature, which is a convenient tool for you to pre−define the relationships among tables all at once.

Using the pre−join feature, you can:

Starting a Catalog

24

Page 37: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create or delete joins among tables with mouse drag−and−drop.• Modify the existing joins.• Define paths.• Edit, delete and rename paths.• Save the relationships together with catalog for future use.•

Pre−join Definition

Pre−join information is one kind of resource information stored in the catalog. It is saved in a stand−alone file, which hasthe same prefix as the catalog file with the extension .pre. It is not used at report runtime.

In JReport Designer, when a user opens a catalog the pre−join file is opened at the same time. When a user saves thecatalog the pre−join file is also saved.

Pre−join Editor

On the Catalog Browser toolbar, click the Pre−join button, select a data source and click OK to bring out the Pre−joinEditor dialog.

Now you can make joins among tables. Click the Arrange button to organize these tables.

Create and delete joins

You can create pre−join condition with mouse drag and drop. Point to one column in the source table, press and hold themouse button, then move pointer to the column in the target table, and release the mouse button. A green line with thedefault operator will then be shown, linking the two columns, representing that a join has been created.

To delete a join, double−click the equal sign in the center of the green line. On the Join Options dialog, click theDelete button.

Modify the existing joins

Double−click the equal sign in the center of the green line. The Join Options dialog will then appear.

Starting a Catalog

25

Page 38: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now, you can make modifications to the join.

Reference Note: User's Guide | Creating a Report with Report Wizard | Joins Tab

When you press left mouse button on the operator button and drag mouse cursor the button will move. The operatorbutton is then placed in a new position and the join line is redrawn when the mouse button is released.

Define paths

After you have made joins among the tables in the Pre−join Editor dialog, you can use them to define paths, which canbe used for creating or editing queries. Please note that if you want to use the pre−joins, you must first enable thePre−join feature. See Enable the pre−join feature for more information.

To define a path,

Click the Paths button on the toolbar of the Pre−join Editor dialog, the Save Pre−join Path dialog will appear.1.

Starting a Catalog

26

Page 39: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the New button, type a name for the new path in the Input Path Name dialog (by default the name will bePath1, Path2, etc), and then click OK. The Select prejoin dialog will then appear.

2.

You will see that all the joins you have made are displayed in the All Joins list. Choose the joins you want, andclick the arrow to add them to the left list.

3.

Click OK to close the dialog.4.

Notes:

The feature of multiple joins (more than one join existing between two tables) is supported.• In JReport Designer, the joins in one path should never form a loop (any table in this path will have direct orindirect joins with all the other tables). If you have specified a path that forms a loop, JReport Designer willprompt you to re−select the joins.

You cannot define a path to completely have all the same joins as with existing paths. If you have specified apath that is the same as an existing path, JReport Designer will prompt you to re−select the joins.

Edit, delete and rename paths

After you have specified the paths, you can edit, delete and rename them on the Save Pre−join Path dialog.

To edit or delete paths,

Highlight the path you want to edit or delete.1. Click the Edit or Delete button.2.

To rename paths,

Highlight the path you want to rename1. In the Rename box, type the new name, and then press ENTER to confirm.2.

Starting a Catalog

27

Page 40: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Save the relationships together with catalog for future use

You can save the relationships by clicking OK on the Pre−join Editor toolbar. Please note, the pre−join information won'treally be saved to disk until you save the catalog.

After you saved the catalog, you can use the just created pre−join to develop reports.

Note:

If you have made joins and defined at least one path, click OK to close the Pre−join Editor dialog. If joins have beenmade but no path defined,

There are no join loops among the joins: after you have clicked OK, a default path named Path1 that includes allthe joins you have made is defined by JReport Designer, and a message box will pop up to ask whether youwant to accept the default path (click Yes) or modify the default path (click No).

There are join loops among the joins: after you have clicked OK, the Save Pre−join Path dialog will appear foryou to define at least one path.

Use Pre−joins In Your Query

Enable the pre−join feature

JReport Designer provides you with the option of choosing whether or not the Pre−join feature will be used. If you want touse Pre−joins in your query, you must have this option enabled.

To turn on the pre−join feature, right−click the current connection node in Catalog Browser, select Modify to open theGet JDBC Connect Information dialog, switch to the Pre−join tab, check the Pre−join option, and then click OK. Thiswill change the value of the Pre−join property in the Properties sheet.

Notes:

If you cannot see the Properties sheet in Catalog Browser, click the Expand button to expand it.• You can also change properties in the Property sheet, as long as you have Forbid Editing Data ObjectProperties option located on the Advanced tab of Report Option dialog is unchecked.

Create queries using the pre−join feature

When you create a query using the pre−join feature, the following cases may appear:

If JReport Designer needs other tables to bridge the tables you have added, you will be prompted to decidewhether to add another table to the query, for example,

Starting a Catalog

28

Page 41: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Suppose you've added table A and C to your query, a message box will appear asking you whether to add tableD in order to create links between table A and C.If there is more than one path available in the pre−join, as with this case,

You've added table A and C to the query, and there are two paths available − ABC and ADC. JReport Designerwill then ask you to decide which path to choose, ABC or ADC.

Note:

JReport Designer provides two methods for you to see the path information of a query.

In Catalog Browser, expand the Properties sheet, select the query that uses the pre−join path. You will thensee that there is a property called pathName which shows the name of the path used.

On the Query Editor window, click the Show Path button.•

Edit queries using the pre−join feature

One query is bound with at most one path. Once a path has been specified for a query, when you modify therelationships among tables, you make changes to the specific query base on that path, but the path itself will not bechanged. When you edit the query, the following cases may appear:

Adding tables to a query that has been specified a path. If more than one path is proper after the tables havebeen added, the specified path will still be used, that is, you cannot choose another path to replace the originalone.

If the path specified for the query is deleted on the Save Pre−join Path dialog, the Show Path button will thenbe disabled on the Query Editor window.

Index

Merging Catalogs

Two catalogs can be merged in JReport Designer. When you save a report to another directory in which a catalog of thesame name already exists, the two catalogs should be merged. Friendly interfaces have been provided by JReportDesigner to help you merge the catalogs and deal with conflicting resources btween the catalogs.

Specifying the Checking Level

When merging catalogs, JReport Designer will first check the differences between the two catalogs. You can specify thechecking level to suit your requirements. To do this, go to the File menu, click Options to bring out the ReportOption dialog. On the Catalog tab, select the level you want in the Merge Catalog Option part. Below are thedescriptions of the options.

Starting a Catalog

29

Page 42: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Source catalog − The catalog of the report to be saved. Target catalog − The catalog under the directory at where the report will be saved.

When you merge the two catalogs, the resources that have the same mapping names in the two catalogs may conflictwith each other (have different property values). JReport Designer will check the differences for you according to thelevel specified here:

Identify All DifferencesJReport Designer will check for all differences between the two catalogs. All the resources of the report will be displayedin the Merge dialog with all the conflicting resources marked.Identify Critical DifferencesJReport Designer will check for differences that can cause the engine fail to run the report. All the resources of the reportwill be displayed in the Merge dialog with any critical conflicting resources marked. As a result, when this option isselected, some different values may be returned when you run the saved report later.Ignore DifferencesDo not show differences between the two catalogs. If there are conflicts between them, remain the resources in thetarget catalog. As a result, when this option is selected, the saved report might not run later.

Merging Catalogs

Open a report, on the File menu, click Save To, choose a directory where a catalog of the same name exists, and thensave the report. If Identify All Differences or Identify Critical Differences has been selected, the Merge dialog will bedisplayed for you to deal with conflicting resources.

Starting a Catalog

30

Page 43: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

As shown above, all the resources of the report are displayed with any conflicting resources are marked out. You canhighlight one conflicting resource in the Resources to be merged panel, and then select the operations Rename,Replace or Skip.

Rename − Renames the selected conflicting resource by copying it to the target catalog with a new name.Replace − Replaces the target catalog with the selected conflicting resource in the source catalog. In this case, thereports that use this object in the target catalog will be impacted. Skip − Keeps the value in the target catalog for the selected conflicting resource. In this case, the report that use thisobject in the source catalog will be impacted.

Click the Differences button, the Properties Differences dialog will then appear. The property values of the conflictingresource from the two catalogs will then be displayed in the dialog with the differences highlighted. Click theNext/Previous button on the dialog, and it will go to the next/previous conflicting resource.

Click the Target Relation button in the Merge dialog, the name of the resource and its parent node in the target catalogwill then be displayed in the Target Relation dialog. For example, sometimes a resource is marked in the Merge dialog,but in the Properties Differences dialog, no difference is shown between the two resources. In this case you can usethis button to check whether the parent nodes of the two resources are different.

Notes:

Sometimes, although some objects are marked in the Merge dialog, in the Properties Differences dialog, youwill not find difference. The reason for this is that some child objects of the two objects are different.

JReport Designer checks parameters based on the whole catalog. For example, assuming that there is aparameter named Param1 under connection1 of the source catalog, and there is also a parameter namedParam1 under the connection2 in the target catalog. These two parameters under different connections will bechecked to be a conflicting resource. You must rename the parameter in order to get a correct result.

Click the Merge button when you finish. JReport Designer will save the report according to the changes you have made.

Index

Using and Managing Cached Query Results

Introduction

Normally when you run a report JReport Engine will fetch data from the database. For reports that are built on queries,JReport Designer enables you to create cached query result files for the queries and save them somewhere in yourmachine. When you are ready to view these reports, you can choose to get data from the cached query result files ratherthan from the database. This is very useful for sending data and reports to Jinfonet Support for assistance and forworking on the design of a report while you are off−line and do not have a DBMS connection.

Creating a Cached Query Result for a Query

To create a cached query result file for a query:

On the Data tab of the Catalog Browser, select the query for which you intend to create the cached query resultfile from the Queries node.

1.

Right−click the query and click Create Cached Query Result on the context menu. The Save Cached QueryResult dialog appears.

2.

On the Save Cached Query Result dialog, specify the file name with or without extension (.txt) and the folderwhere you want to save the result file.

3.

Click OK. The file and an additional .desc file will be saved in the specified folder.4.

Starting a Catalog

31

Page 44: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using Cached Query Results to Run Reports

To run a report on a cached query result:

Open a report and create the cached query result for its query as introduced above.1. In the Report Inspector, select the root node of the report and specify its DataDriver property in the Propertiespanel as follows:

jrquery:/jet.universe.resultfile.UResultFileResultSet;Full path of the cachedquery result

For example, if the cached query result has been saved under C:\JReport\Designer\Cached with the filename test, the property value should be

jrquery:/jet.universe.resultfile.UResultFileResultSet;C:\JReport\Designer\Cached\test

2.

View the report and the report will get data from the cached query result file. 3.

Managing the Cached Query Results with the Data Source Driver Manager

You may find that it is inconvenient to input a property value that tends to be complicated and long; therefore, JReportDesigner includes another tool for you to manage your cached query results, that is the Data Source Driver Manager.Please take the following steps to use this manager:

On the Data tab of the Catalog Browser, right−click on a query and select Create Cached Query Result fromthe context menu.

In this example we will create a cached query result addressbook_cached for the query AddressBook1 andsave it under C:\JReport\Designer\Cached.

1.

On the Catalog Browser toolbar, click the Data Source Manager button. The Data Source Drive Manager dialogappears.

2.

On the Data Source Drive Manager dialog, click the Add button to add a data driver. The Data SourceEditor dialog appears.

3.

Input a name for the driver in the Driver Name box. In this example we name it AddressBook. Check theURL radio button and input the URL as follows:

jrquery:/jet.universe.resultfile.UResultFileResultSet;Full path of the cachedquery result

In our example, the URL is

jrquery:/jet.universe.resultfile.UResultFileResultSet;C:\JReport\Cached\addressbook_cached

If you check the Driver radio button to specify the driver, you need to input the class name and parameter of thedriver like below:

Class Name: jet.universe.resultfile.UResultFileResultSetParameter: Full path of the cached query result (C:\JReport\Designer\Cached\addressbook_cached inthis example)

A URL will be generated accordingly based on your input information.

4.

Click OK to add the driver to the Data Source Driver Manager. 5. Repeat the above steps to add more drivers to the manager. 6.

The added drivers will be listed in the DataDriver property dropdown list for you to choose.

Starting a Catalog

32

Page 45: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing Reports with Report WizardOnce all of the data source preparation have been completed, the actual report design work begins. JReport Designerprovides various wizards, which can help you build reports with simple drag−and−drop and point−and−click mouseoperations.

Selecting a Report Template

Report Wizard allows you to quickly create the basic design of a report. JReport Designer prompts you to define thetables, fields, summaries, and other options are used in the rough report design. In this way it saves you time in the basicorganization and layout of data from the database.

To start the Report Wizard you must first select a catalog and specify the report template type. The Open Report dialogwill show you a selection of different report templates. Each template is represented by an icon.

The Open Report dialog is the first dialog displayed when you start JReport Designer. You can also see this dialog byclicking New on the File menu or clicking the New button on the Standard toolbar when creating a new report.

There are three tabs: New, Existing and Recent, which either lead you to the Report Wizard or take you directly to theMain Window of a previously created report.

New TabThe New tab allows you to select a report type from the different templates provided, then launch Report Wizard tocreate a new report.

Reference: Go to the Report Template chapter for defining templates of your own.

Below is a brief description of each report type.

33

Page 46: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Blank ReportThis is the simplest report format. The report will not initially display any fields. Each field can be selected to bedisplayed or hidden. Organization criteria such as Display, Group, Sort and Summary can be added to enhancethe report.

Block ReportThis type places your data in a column like format. No title and fields are placed in the Group Header section, thesummary fields are placed in Group Footer and the background of that section is gray.

Cross−TabA report that summarizes data and presents summaries in a compact row and column format.

Drop TableYour data is laid out in a table and summaries are given in a separate drop table.

Executive BreakSimilar to Block format, only with borders and shadows.

IndentSimilar to Executive Break, except that the objects in the page are indented.

InvoiceThis format allows you to create a report in the format of an invoice. With this invoice format, JReport Designercan automatically add Bill to, Ship to, Invoice Number, Date... for you. However, make sure to select two groupsfirst.

Left AlignmentThe layout of this format is a combination of borders, shadows and lines with fields all left justified.

Standard ReportThis format allows a very quick organization of data. Your report will automatically display lists and groupings ofdata. The Standard Report is highly recommended, since it includes six items: Indent (default), Alignment Left,Table, Drop Table, Executive Break and Block. You can use the Style tab in Report Wizard for flexibility whendefining specific items.

SubReportThis format allows you to merge two reports into one.

TableThis places all your data into a complete table.

HblankIn addition to the normal vertical page break (that is the details go to vertically), this template is for horizontal flowof the detail records.

Existing TabThe Existing tab allows you to access a catalog and reports previously created with it. JReport Designer allows you tomodify these existing reports and run them to view the results.

In order to open a report, you must first open its corresponding catalog file (*.cat). Use the Browse button to search forthis file.

Once you have selected a Catalog, a list of reports will appear in the bottom menu. Select the report you want, clickOpen.

If you do not see your report in the directory where you saved it, make sure the correct catalog file is open.

Recent TabThis tab allows you to view and select the most recently accessed reports.

It shows you:

The Name of the Report File• The Path of the Report File• The Name of the Catalog File•

Developing Reports with Report Wizard

34

Page 47: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating a Report with Report Wizard

After selecting a report template of your choosing, press Create in the Open Report dialog. Now you can go throughReport Wizard to create a report step by step.

Note: The Report Wizard is only designed to be used for report creation, not for modification. It will re−format your reportif you open it for the second time after you have built it, and any editing information will be lost. For details on how tomodify a report, please refer to chapters: Refining the Report Layout and Editing a Report.

There are many tabs in the wizard. By default, not all the tabs are displayed, it is determined by the template selected.For example, when you choose to create a cross−tab report, you will find that the Summary tab will not appear in ReportWizard, by clicking the All Tabs button at any time, all the tabs will be displayed in the wizard.

Usually you do not need to go over all the tabs, and you are free to skip tabs according to your report designrequirements. At any time you can click Finish to generate the draft design and further refine it later in the design mode.

Working Set

Before creating a report with Report Wizard, you should know about Working Set.

The Working Set menu is a list of all the tables and fields you selected from the Catalog data source menu. The workingset can be named in the Report data source list menu. The fields and tables selected here can be accessed later inyour report through:

Catalog Browser | Query• Insert | DBField menu• the DBField button on the Edit toolbar•

To edit the Working Set for a report, click the Open Data Set button on the Standard toolbar.

Data Tab

Place your tables or fields into the Working Set so that you can access them in your report.

Developing Reports with Report Wizard

35

Page 48: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Since it is possible that there is more than one data source in the catalog, please choose the data source you want fromthe drop−down list first. The Connection of the specified data source will then be listed in the Catalog DataSource column. Double click the database file or click the plus icon to reveal the Tables and Views for each database.Double click the Table or click the plus icon to reveal the table fields. You may individually select or place all the fieldsinto the Working Set menu by highlighting a specific section and clicking on the arrow button. You can also drag thefields from the data sources tree to the Working Set.

Then go to Joins and Conditions tab to further define the new query.

Sharing a Query

In addition to creating a query with the Data, Joins and Conditions tabs, you can also use a predefined query by selectinga query from the drop−down list in the Report data source menu, or selecting one from the Catalog data source menu.Only one query can be added to the Working Set for the current report.

The query used in one report can be shared or not with other reports. In Catalog Browser, expand the query property,with the Share property, you can specify whether to share the query.

This property is password protected. If you want to share a query, you should first create a user for the query. Whensetting the value, select a query, right−click it and on the pop−up menu, click Create User, and the Create Query'sUsername and Password dialog will appear to prompt you to enter the user name and password. When you change theShare property value, the user name and password should be given in order to protect this value from being changed.

Developing Reports with Report Wizard

36

Page 49: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If you set the value of the Share property to be false, the query will not be shared. When you create a new report, andselect a query which is not shared, JReport Designer will automatically create a copy of the query instead of using thesame query, which avoids having to share queries among reports. When the query used in one report is modified, it willnot affect the other reports.

When the value of the Share property is true, you can use an existing query to build a report. The query will be sharedamong other reports also using it. For example, you have two reports: ReportA and ReportB which have been built basedon the same query: QueryA. If QueryA is changed, both ReportA and ReportB will run using the changed query, that is,the changing of a query will influence any reports using it.

Joins Tab

Click the Joins tab, and the following dialog will appear:

Linking Multiple Tables

The Joins tab shows you how multiple tables selected in the Data tab are linked. If you selected multiple tables in theData tab, JReport will automatically link them together based on JReport Designer's default settings. To remove the joinbetween them, double click the line, and click the delete option to delete their relationship.

Pre−join

JReport Designer allows you to create pre−join paths in Catalog Browser. If there are any pre−defined joins, ReportWizard will use the, otherwise it will use the auto join feature.

Developing Reports with Report Wizard

37

Page 50: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Reference Note:User's Guide | Starting A Catalog | Pre−join

Auto Join

This is a feature of JReport that will join tables together based upon certain selected criteria. The following are the defaultcriteria for Auto Join.

Primary Keys with Like NamesA primary key is a field or a combination of fields that uniquely and specifically identifies a record. Your creditcard number is an example of a primary key because it specifically links to your birthday, credit history, address,etc. In this case primary keys with identical names from different tables are joined.

Foreign KeysThis is a reference from Table A to a primary key in Table B. For example, an order form in Table A showsinformation about purchases that are made by a customer. It can also show this customer's ID #. That customerID # refers to a record in Table B which lists a specific address, phone number, name, etc for that customer. Thecustomer ID # in Table A is a foreign key because it links the customer's ordering information in Table A to thecustomer's information in Table B.

Like Column NamesThis is a link between two columns with the same name found in two different tables.

Link Tables Manually

If you wish to manually link tables together, first select a field from one table. Next, drag the highlighted field to anothertable and onto the field that it should link to. This should create a link that is shown by a green line from one field toanother. You may also want to click on the Arrange button to have JReport arrange the tables into an organized mannerwhere the crossing of green link lines is minimized.

Join Options

Once your links have been established, you may double click on the join icon on the green linking lines to modify thelinks. The following window will appear.

Outer JoinCheck this box to indicate that you want an "outer join" performed. There are two kinds of join formats: SQL92 andUse"(+)". With conventional joins, records that do not satisfy the join condition are eliminated from the result. Outer joinpreserves these records in the result and replaces the missing value with nulls. We call the join "left (right) outer join" ifthe records in the left (right) side table are preserved. For example, consider the following two tables:

Table 1

Order O# C#

Developing Reports with Report Wizard

38

Page 51: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

101 001

102 002

103 004

Table 2

Customer C# Name

001 GE

002 IBM

003 DELL

The conventional join of Customer.C# = Order.C# will produce the following result:

JoinResult O# C# Name

101 001 GE

102 002 IBM

The left outer join of Customer.C# = Order.C# will produce the following result:

JoinResult O# C# Name

101 001 GE

102 002 IBM

103 004 <null>

The right outer join of Customer.C# = Order.C# will produce the following result:

JoinResult O# C# Name

101 001 GE

102 002 IBM

<null> 003 DELL

Drop−down Menu

= Display values that are equal to each other.> Display values that are greater on the left side.< Display values that are greater on the right side.>= Display values that are greater than or equal to the left side.<= Display values that are greater than or equal to the right side.<> Display values that are not equal to each other.

Arranging Tables

As explained above, click the Arrange button to arrange the tables into an organized manner to avoid crossing of greenlink lines to some extent.

Showing Tables

In order to have a clear view of the linking layout of the tables, you can click the Advanced button to maximize the panel.At the same time, in the expanded panel, you can specify the query conditions in the QBE format.

Developing Reports with Report Wizard

39

Page 52: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Viewing SQL

An SQL statement/string is an expression that defines a Structured Query Language (SQL) command, such as SELECT,UPDATE, or DELETE, and may include clauses such as WHERE and ORDER BY. SQL strings and statements whichare typically used in queries, Recordset objects, and aggregate functions, can also be used to create or modify adatabase structure. Therefore, by clicking the View SQL button on this tab and the Conditions tab, you can view the SQLstatement used to execute the Query. It can also give you a clear idea about your selections for the query so far.

Index

Conditions Tab

The Conditions Tab allows you to specify certain criteria for the fields to be retrieved from the database. You can typeyour search criteria both in the format of Filter and QBE. As you may know, in addition to building a query here, we havethe visual query designer to build or modify a query.

Search Conditions (Filter)

By default, you will enter your conditions in Filter to further add more criteria to limit the amount of data in your report, inwhich case, a search condition expression will appear on the screen. Compared with QBE, Filter provides you with moreflexibility to enter your conditions. The Expression includes not only the DBField selected, but also formulas andparameters. You can also manually type the strings supported by the database. The following is what you will see.

Developing Reports with Report Wizard

40

Page 53: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ExpressionThis is the main section of the Filter window. You will place your criteria in this area. To place criteria, click thebutton beside the first Expression text box, then the following dialog will pop up:

All the fields in the working set, including DBField, formulas and parameters are listed under the Real Name tab.Select a field and add it to Expressions by double clicking it.

The symbols at the bottom of the dialog allow you to modify the expression. Below are the decriptions of theirfunctions:

+ icon: Add numbers or fields together in the Expression menu.

− icon: Subtract numbers or fields together in the Expression menu.

* icon: Multiply numbers or fields together in the Expression menu.

/ icon: Divide numbers or fields together in the Expression menu.

= icon: Equate fields together.

" icon: Place quotations on long character strings or name that have blanks in them (example: place quotes onvalues like 'New York' or 'Washington DC'). If the string contains single quotation mark, use two single quotationsinstead, for example, 'Bob''s Coffee'.

|| icon: Place fields together in the same Expression menu (example: 'New York' || 'Washington DC').

() icon: Place your fields in parentheses.

Click the button beside the second Expression text box, you will get all the column names of the related tableunder Field Value.

Check one of column names, then click OK, the selected field value will display.

Choose a value from the list and click Set, then the selected field value will be set in the Expression.

In addition to setting the condition value by selecting from Field Value, you can also type the value in theExpression box. If the value is a string type value, it should be like 'aaa' with quote mark. The quote mark can betyped by yourself or be added by JReport Designer automatically. To have the quote mark be added by JReport

Developing Reports with Report Wizard

41

Page 54: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Designer, go to click Options on the File menu to bring out the Report Option dialog, under the PSQL tab,check Add Quote Mark Automatically.

Notes:

1). When you type the string to set the condition value, quote mark should not be " ' " at the first or the lastcharacter. For example, 'sss, or sss'. 2). JReport adds the quote mark when an action is taken, for example, when you click a button in the Conditiondialog.

You can also create a sub−query with the second tab "Subquery" in the Expression dialog. For details, pleaserefer to User's Guide | Editing a Report | Query Editor.

OperatorThis menu lists all the operators in your selection conditions:

= equal to<> not equal to> greater than>= greater than or equal to< less than<= less than or equal toin (and not in): causes an enumerated list of values appearing in the WHERE clause predicate to be evaluatedfor a true condition.

Tip: People often choose to use a parameter within the operator. The parameter should be quoted with a bracketplus a colon as shown on the right below:

[not] between: allows the system to evaluate whether or not data values are located between a range of valuesindicated in the predicate.

is [not] null: is used in WHERE clause predicates to match null values occurring in a specified data column.[not] like: like string pattern matching operator is used to compare the first expression string value to the patternstring (the second expression).sound like: sound like operator uses a soundex algorithm to pattern match strings that sound alike.

[not] exist: is used to test if a subselect retrieves any records.

MoreClick the drop−down list arrow below the label More:, you will find the following items:

END: To finish entering the condition. AND: Logic operator AND which is applied to this line and the next line. OR: Logic operator OR which is applied to this line and the next line.

Developing Reports with Report Wizard

42

Page 55: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Insert Row: To insert a single Expression row. Delete Row: To delete the corresponding single Expression row. New Group: The Expression row from next line will be a new group.

Search Conditions (QBE)

When selecting the QBE (Query By Example) radio button, you are prompted to type the search criteria into a templateresembling the data record. The advantage of query−by−example retrieval is that you don't need to learn a querylanguage to frame a query. All the data fields are shown to you, just enter information that restricts the search to thespecified criteria. The fields left blank, however, will match anything.

The columns and menus allow you to specifically define criteria for the fields in JReport Designer. For example, let's sayone of our fields is labeled Region. This field is a list of all 50 states in the United States. Your report only wants to seeinformation from New York (NY) and California (CA). In the criteria menu, you pick NY and CA out by placing their namesin the column as seen below.

Just type in NY and CA. JReport Designer automatically places the ='xx' (equal sign and quotes) in the column for you.Below is a list of the syntax available:

Comparison predicates ( =, >, <, >=, <=, <> )• BETWEEN predicate (example: BETWEEN 1 AND 100)• IN predicate (example: NOT IN (1, 3, 5))• LIKE predicate (example: LIKE '%apple%')• NULL predicate (example: IS NOT NULL)•

Note: You can type your search criteria both in the format of Filter and QBE, the overall conditions will include them both.Always come to SQL to view your conditions.

Display Tab

Click on the tab Display, the following dialog will appear.

Developing Reports with Report Wizard

43

Page 56: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Display tab allows you to specifically define which fields you want to see in your report.

Note: This is different from selecting fields in the Data tab. In the Data tab, you select fields for the query, which allowsyou to access to them later in the report.

To select which fields to be shown in your report, first expand the directory structure by double clicking on the table nameor clicking on the plus icon in the Data Source. Second, highlight either the table name or the field name which you wantto place in the Report fields menu. Lastly, press the right−headed arrow button to place field or table you just selectedinto the Report Fields menu.

If you want to change the order of the fields in the Report fields menu, simply highlight the field and click the up or downarrow button on the top of the Report Fields menu to move it up or down.

If you do not want the fields you placed in the Report fields menu to be seen in your report, select the unwanted field andpress the opposite arrow button.

To get rid of all the fields, press the third button in the middle of the dialog.

The adding, removing, and ordering operations above can also be completed by dragging and dropping.

In the Report Fields menu, you can change which section the selected field will be placed in using the Section columnand change the property in the Style column. If you want to edit the label displayed for the fields, click the AutoLabelcolumn for the field, enter your new label string.

Developing Reports with Report Wizard

44

Page 57: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Default Section field is to specify the section in which you want to place the fields. Please note, you should firstselect from this list, then highlight the fields and click the arrow button to add them to the Report fields menu. In otherwords, if you first add the fields for display, and then select from the Default Section field, it will not take effect.

Index

Index

Topics covered in this section

Group Tab How to Use Group Ordering Your Data SpecialFunctionSort Tab How to Use Sort Ordering Your Data Sorting Groups TopN Group Filter

Group Tab

Records in a report are usually organized into groups based on certain criteria. With the Group tab, enter the criteria todefine multi−level groups. You can also specify the order of groups and order of records.

How to Use Group

To select criteria for the grouping, expand the table directory in the Report fields menu by double clicking the table iconor clicking the plus icon. Next, highlight the field you want as a criterion for the grouping. Lastly, click on the arrow buttonto place your criterion in the Group by menu. When a row in the group list is selected, you can remove it, change its orderand group option. The same procedure applies for the Sort tab.

Note: If the type of the field that is selected to group the report is date or time, it can be added to the Group By panelmore than once and you can set the special function for the field.

Ordering Your Data

Ascend and DescendYou will notice an up arrow besides each field selected to be grouped in the Direction column. This means that the fieldswill be grouped and sorted in an ascending order (A, B, C). Click on the up arrow icon and change it to a down arrow.This means that the fields will be grouped and sorted in a descending order (C, B, A).

Not SortIf you select the NO Sort icon, your data will not be sorted, and JReport Designer will generate a group break accordingto the original order.

Special GroupThe Special Group icon that is seen in the Direction column is a special way to define how to group your information.

Developing Reports with Report Wizard

45

Page 58: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For example, you placed a field named "Region" in the Group tab. This field contains all 50 states in the United States.We want to see the data between Maryland (MD) and New York (NY). In the Special Criteria section we can define thiscriterion by selecting "between" in the Operator drop−down menu and placing MD in the op1 menu and NY in theop2 menu.

User Defined Grouping CriteriaTo add a new grouping feature, click on the Add button. This will bring you to the Group Name. Create a newname for your grouping criteria. Next, select an Operator function to group your data.

The following operators can be used to define how to group your data.

between not between > (greater than) < (less than) = (equal to) <= (less than or equal to) >= (greater than or equal to) != (not equal to)

Either op1 or both op1 and op2 will be seen in the Operand menu. Place your criteria here. JReport Designerwill automatically place quotation marks on your criteria. Click Add to add more groupings. Click Remove todelete the current grouping, and OK to finish.

Keep values outside of the range in a special groupIf checked, JReport Designer will keep those values that are not included in your specified criteria and placethem in a special group.

Name for the special groupGive the special group a name here.

SpecialFunction

The SpecialFunction column next to the Direction column is available only when the field to be sorted is of date or timetype. Click the drop−down arrow, a list will be displayed. You can select one to specify to group the records by each day,each week, each half month, and so on.

Developing Reports with Report Wizard

46

Page 59: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

NoneRecords will be grouped by the selected data/time field. All the records that have the same date/time value willbe displayed together as a group.

for each dayRecords will be grouped by days. The records, of which the field values are in the same day, will be groupedtogether.

for each weekRecords will be grouped by weeks. The records, of which the field values are in the same week, will be groupedtogether.

for each bi−week Records will be grouped by double weeks. The records, of which the field values are in the same bi−week, will begrouped together.

for each half monthRecords will be grouped by half months. The records, of which the field values are in the same half month, will begrouped together.

for each monthRecords will be grouped by months. The records, of which the field values are in the same month, will begrouped together. .

for each quarterRecords will be grouped by quarters. The records, of which the field values are in the same quarter, will begrouped together.

for each half yearRecords will be grouped by half years. The records, of which the field values are in the same half year, will begrouped together.

for each yearRecords will be grouped by years. The records, of which the field values are in the same year, will be groupedtogether. .

Sort Tab

The Sort tab is very similar to the Group tab in appearance. It allows you to organize the information within the group bysorting records. You can select an item to indicate the group for which sort option will be applied.

How to Use Sort

To select a criterion for the Sort tab, expand the table directory in the Fields menu by double clicking the table icon orclicking the plus icon. Then highlight the field you want as a filter for the sorting and click on the arrow button to placeyour criterion in the Sort by menu.

Ordering Your Data

You will notice an up arrow beside each field selected to be sorted. This means that the fields will be sorted in anascending order (A, B, C). Clicking on the up arrow icon, you can change it to a down arrow to sort data in a descendingorder (C, B, A) or you can customize to sort on runtime.

When you want to sort data dynamically by using a parameter, you can also customize the ordering way when runningthe report. For example, you selected the parameter "PSortby" to sort data, then click the up arrow beside "PSortby",choose and click the icon, you will get to the following dialog:

Developing Reports with Report Wizard

47

Page 60: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

It allows you to define a parameter to specify ordering your data when viewing the report. Here we define a parameternamed RSortby, click OK.

View the report, the parameter dialog pops up.

Click on PSortby to specify the field to sort your data, and click on RSortby to decide in which order to sort: Ascendingor Descending.

Sorting Groups

By default, your selected field(s) will be sorted within the whole report. However, you can also select to further sort thegroups by DBFields, summaries or formulas (record level).

Developing Reports with Report Wizard

48

Page 61: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To sort groups, please do as the steps below:

On the Sort tab of the Group Wizard, select one of the break−by field of the report from the Sort in drop−downlist.

1.

Select the DBField, summary or formula you want from the Field panel, and add it to the Sort By panel byclicking the arrow button.

2.

In the Sort By panel, select the arrow to specify how to sort the groups, ascendingly or descendingly. 3. Click OK on the Group Wizard.4.

View the report, you will see the groups are sorted according to the value of the DBField, summary or formula you havespecified.

Notes:

Multiple sorting fields and multiple sorting types are not supported, say, if you have sort the groups of a report bya DBField, you can not further sort it by another DBField, summary or formula.

When you sort the groups by a DBField, the order of the groups depends on the value of the first record in eachgroup.

TopN

By checking the TopN box and place a number, you can specify that how many records or groups will be displayed inyour report. You can also use a parameter whose type is Integer to control the value of TopN.

To display the top N records inside a group:• Launch the Group Wizard. On the Sort tab, select The whole report from the Sort in drop−down list.1. Select the sort by criteria you want from the Fields pane, add it to the Sort by pane, and then change the arrowif necessary.

2.

Check the TopN box, and then type the number you want.3. To display the top N groups:The steps for display the top N groups are very similar. The only difference is that, you should select thecorresponding group−by criteria from the Sort in drop−down list, instead of The whole report.

Example: To display the top three groups.

In this example, we will design a report to display the best three sales according to their sales amount.

Create a new report named salesreport.cls. Here we use the demo Catalog: Tutorial.cat.1. On the Date tab, add Orders and Orders_Detail tables to the data resource.On the Join tab, select the Orders_Oder ID field from Orders table, drag the highlighted field to Orders_Detailtable and onto the Orders Detail_Order ID field.On the Display tab, add Orders_Order ID, Orders Detail_Product ID, Unit Price and Quantity to the report fields.On the Group tab, add Orders_Employee ID to the group by criteria.Click Finish.

2.

Create a Formula "Total Price" to calculate the total price for each Detail Order. Click Insert, and then place thisformula in the detail panel.

3.

Developing Reports with Report Wizard

49

Page 62: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create a summary based on formula "Total Price". Right click the formula, and then click Summary Function.The Insert Summary dialog will pop up. Check the Create a new summary radio box. Select Sum in the firstdrop−down list and Order_Employee ID in the second, click Insert, and then place the summary inGroupFooterPanel.

4.

View the report, you will find that all of the Employees in the Orders table are displayed.5.

Developing Reports with Report Wizard

50

Page 63: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If you would like to display the top three employees with the highest sales summary, then you should launch theGroup Wizard. On the Sort tab, select Order_Employee ID in the Sort in drop−down list. Add Sum_Total Priceto the Sort by field, and then click the up arrow icon and change it to a down arrow. Check TopN box, and thentype 3. View the report again, you will find that only the top three employees are displayed.

6.

Developing Reports with Report Wizard

51

Page 64: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Group Filter

JReport Designer can filter records by where condition or local where, and it can filter groups or records by TOP Nsettings. JReport Designer allows users to suppress sections or make them invisible, fields and objects conditionally.However, for some special cases, you will have to define more formulae to control properties to reach your goals. Inorder to simplify your work, JReport Designer are provided with some special group filter functions.

Group filter operation is based on groups. If the group satisfies the condition, then all the records in this group will beshown. If the group doesn't satisfy the condition, then the whole group will not be shown in report result.

Let's use some examples to illustrate the functionalities of the Group Filter dialog.

First follow the steps below to create a new report.

Launch JReport Designer, select catalog Tutorial.cat, select a template and then click Create. 1. On the Data tab, add tables Customers and Orders. 2. On the Joins tab, join the two tables as Customers_Customer ID = Orders_Customer ID. 3.

Developing Reports with Report Wizard

52

Page 65: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the Conditions tab, modify the condition expression to display USA customers only (Customers.Country ='USA').

4.

On the Display tab, select Customers_Customer ID, Customer Name and Orders_Order ID. 5. On the Group tab, add Customers_Region to the Group by list. 6. On the Sort tab, add Orders_Order ID to the Sort by list.7. Click Finish to close the Report Wizard, adjust your report to get a better view.8.

Now a basic report has been created, let's see some cases that you may probably face.

Case 1

Query: Show the regions where the smallest order ID is less than 3007.

Resolution:

Bring out the Group Wizard (Insert | Group/Sort), switch to the Sort tab.1. Select Customers_Region from the Sort in drop−down list.2. The Group Filter button becomes available, click it. 3. The Group Filter dialog appears. Fill in the fields like below:

Logic: Unchecked Function: MinField Name (before Occurs With): Orders_Order IDField Name (after Occurs With): Orders_Order IDOperator: <Value: 3007More: END

4.

Click OK to close this dialog, and then click OK again to get back to the report design. 5. Click View to view the result.

The regions whose smallest order ID is less than 3007 are shown, while other groups not fitting this condition areignored.

6.

Developing Reports with Report Wizard

53

Page 66: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 2:

Query: Show regions where at least one order ID is larger than 3035.

Resolution:

On the Group Filter dialog, fill in the fields like below:

Logic: Unchecked Function: ExistField Name (before Occurs With): Disabled in this case Field Name (after Occurs With): Orders_Order IDOperator: >Value: 3035More: END

Refer to the resolution of case 1 if you don't know how to access the Group Filter dialog.

1.

View the report.

The regions, which have one or more than one order ID larger than 3035, are shown, while other groups notfitting this condition are ignored.

2.

Developing Reports with Report Wizard

54

Page 67: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 3:

Query: Show regions where at least one "not smallest" order ID is less than 3020.

Resolution:

On the Group Filter dialog, fill in the fields like below:

Logic: Checked Function: MinField Name (before Occurs With): Orders_Order IDField Name (after Occurs With): Orders_Order IDOperator: <Value: 3020More: END

Refer to the resolution of case 1 if you don't know how to access the Group Filter dialog.

1.

View the report.

The regions, which has one or more than one "not smallest" order ID less than 3020, are shown, while othergroups not fitting this condition are ignored.

2.

Developing Reports with Report Wizard

55

Page 68: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Notes:

In the Value field, you can input constants and parameters.

For string type constants, you can just type the string without quotation marks. For Date/Time type constants, you haveto follow the Date/Time format specified on the Date Format tab of the Get JDBC Connection Information dialog.

Reference Notes : Reference | Dialog | Group Filter

Limitations:

You must ensure that the report result you get must have at least one record. Otherwise, JReport Designer will throw outan error message.

Summary Tab

The Summary tab allows you to generate count, average, sum, standard deviation and other aggregate functions for yourdata. The Summary functions are based upon how you grouped your data from the Group tab.

Developing Reports with Report Wizard

56

Page 69: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Generating a Summary

The Data Source menu contains the fields you selected in the Data tab. Select a field you want to the summary to bebased on. Next, select a function in the Function drop−down list to generate a value for your data.

Below are the functions to create a summary for a selected field:

CountGive a total count of all the values in a field.

SumSum up all the numerical values in a field.

MinimumFind the smallest numerical value in a field.

MaximumFind the largest numerical value in a field.

AverageTake the average of all the numerical values in a field.

Distinct CountTake a total count of all the distinct fields in a report.

Population Standard DeviationUse the following equation to compute its value.

Developing Reports with Report Wizard

57

Page 70: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Standard DeviationUse the following equation to compute its value.

Population VarianceUse the following equation.

Variance:Use the following equation.

Break Field

A Break Field is a defined field in which JReport Designer calculates values according to your requests.

For example, assume that you have set two groups based on Region and City. Now you would like to generate a sum ofa field, called annual sales. If you choose region in Break Field, JReport Designer will generate a total sum of the salesin the region. If we choose city in Break Field, we will get the total sum of the sales in the city.

Subtotal and Grand Total

If you leave the Break Fields empty, you can see Grandtotal in the Style column, JReport will calculate the overall valuefor a specific field and function in a report. It will be shown at the end of Report Footer. If you choose the field forgrouping in the Break Field drop down list, you can see SubTotal in the Style column. It means JReport will calculate thetotal value within a group.

Graph Tab

For information about Chart/Graph, please refer to User Guide | Chart.

Index

Cross−Tab Tab

The cross−tab summarizes data and presents the summaries in a compact row and column format.

Here is an example of a typical crosstab report.

Developing Reports with Report Wizard

58

Page 71: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

After completing all the necessary information on the Data, Joins, Conditions and other tabs, CrossTab specifications canbe filled in:

In the Field box, highlight a specific field from the query you created on the Data tab. Click the corresponding arrows inthe middle of the dialog to add to Columns, Rows and Aggregations respectively. If you select Aggregations, do notforget to select a function from the Aggregation drop−down list on the left. In the label column, you can type in somestring to indicate the meaning of the function.

You may remove unwanted fields by highlighting them and clicking on .

Highlight a field in the Rows or Columns boxes, click the Color column and select a color from the drop−down list forthe background.

Developing Reports with Report Wizard

59

Page 72: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If there are more than one field in the Rows, Columns, or Aggregations boxes, click and to alter the sequence.

The adding, removing, and ordering operations above can also be completed by dragging and dropping.

If you want to add additional calculations to the cross−tab, click on the top of the Aggregaitons panel and finish the

pop−up dialog Special Aggregaiton . For detailed information, please see: User'guide | Editing a Report | Cross−Tab.

To make crosstab more flexible, JReport adds following design options:

Orientation• Row Total on Top• Column Total on Left• Report Row Header• Avoid Orphan Header•

Using the Orientation option, you can choose horizontal or vertical layout in the summary area. The Row Total onTop and Column Total on Left options allow you to specify where to display Totals, you can place row totals on the topor column totals to the left. And you can specify to repeat the column heading on subsequent pages of a multi−pagereport by checking Repeat Row Header, specify to keep the column heading together with data by checking AvoidOrphan Header.

Reference Note: User Reference | Reporting Features | Cross−Tab

Subreport Tab

JReport allows a report (referred to as the subreport) to be inserted into another report (referred to as the primary report).There is no difference between the primary report and the subreport. A subreport can be standalone, i.e. it can be runseparately like a normal report.

Note: Instead of using the subreport template, you can first have reports developed and go to the Insert |Subreport menu item to add another report to the main report.

Choosing a Report

Click the Browse Button to select an existing report as the subreport.

Note: The report chosen as a subreport must be within the same catalog as the primary report.

Sub Links

Link is the way of creating connections between the primary report and the subreport. Sub Links are the relationshipbetween the two reports to be merged. You can build up one or more links between a primary report and a subreport.When you build a link, JReport will match up the records with equal relationships within the subreport and the primaryreport. For example, you have a primary report that is focused for customers and the subreport for orders. When we buildthe link between them, JReport will build a subreport for each customer. The subreport will only include those orderrecords for that customer.

Parameter in subreport

You need also to enter the parameter value for the subreport (if it has parameters) at run time. You can map a similartype of formula or a parameter in the catalog. Usually you do not need to use this tab, but you will find it useful if youhope to give a value for the parameter in the subreport, so that you do not need to enter the parameter value for thesubreport at each run time. Let us see an example.

Report A is the main report. Report B is the subreport with a parameter PToday (date type). When you view the mainreport with subreport, you are prompted to enter value for PToday. But you do not want to enter the value each time you

Developing Reports with Report Wizard

60

Page 73: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

run it and want to give it a fixed value. Now on the Parameters in subreport tab, you will see all the parameters andformulas of date type.

We select mytoday which is a formula and returns a value ToDate(1996,04,20). Click OK to apply the changes. Nowview the report, and no parameter dialog pops up for you to enter the value since the formula value is passed to PToday.

Return Value

When you want your subreports to return certain values to the main report, you can use the feature Return Value ofsubreport to accomplish it.

For example, you want to create a main report focused on the "Company Information", and you also want to know theinformation about the grandtotal of employee salaries of the company, you can do the following:

Create a report named CompanyInformation.cls and a new parameter, for example we name it test and the valuetype is Integer. Insert the parameter into the Report Footer section of the report.

Create a report named employeesalary.cls.

1.

Select the Menu item Insert | Subreport.2. In the pop−up Insert SubReport dialog, choose the subreport employeesalary.cls. Press on the ReturnValue tab. In the panel Fields in main report, select the parameter you created and add it into the right PanelLinks by clicking the arrow button. It will show like this:

3.

Developing Reports with Report Wizard

61

Page 74: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You can select "Sum_Salary1" as the parameter value and press OK. Then the parameter will be returned to themain report. Insert the subreport into the main report, then you will get the intended information.4.

Notes:

When you insert the subreport, you should insert it into the section above the parameter, or the parameter valuewill be returned as Null.

1.

To use the return value parameter in a formula, you need to add pagenumber in the first line in the formula.

For example, all the formula which referenced the return value parameter should like:

pagenumber;... ... ...... ... ...

The reason that you need to do so is because that the subreport will return value to the parameter at page breaktime. Therefore, formulas which referenced the return value parameter should also be calculated at page breaktime, otherwise, it will not get the parameter value. Adding "pagenumber" in a formula will enforce a formula to becalculated at page break time.

2.

Other Tab

The Other tab is used to preview your selection so far in Report Wizard. You can now make some adjustments, insertnecessary images, labels and fields or delete unwanted objects.

This tab functions somewhat like Catalog Browser and Report Inspector. Of course, when you edit in the Design modewith the help of Catalog Browser and Report Inspector, it is convenient for you to frequently check your changes in theView mode.

Developing Reports with Report Wizard

62

Page 75: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Object

This field can change the current object to a system defined special field. For example, you can change GroupName toFetchDate. When displayed, the group name in the group section becomes the date when the data is fetched.

Section

You can select from the Section column to place the user inserted object into the desired section. However, you can notchange this feature for the template style object.

Style

Highlight an object, then double click in the Style field. In the pop−up dialog, change the property for the selected objectas you do with Report Inspector. Properties of template styles are not editable. Some properties of user inserted objectswith blank styles are editable.

Inserting Label/Insert Image/Insert Field

As the name suggested, these three labels are used to insert a label, image and field respectively. You can then switchto the Object, Section and Style columns to make further changes.

Developing Reports with Report Wizard

63

Page 76: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Deleting

If you want to delete an object in the main panel, just highlight the object and then click the Delete button.

Style Tab

You can define the layout and style of your report with this tab.

The following is a definition and explanation of the options you have in the Style tab.

PaperIn the Paper section, you can select a type of paper from within the Type drop list. Or, set the paper Type toCustom size and enter the Width and Height for the paper you want.

MarginSet exact page margins for the left, right, top or bottom.

OrientationIn the Orientation section, the radio buttons offer the choice of Portrait or Landscape. Portrait mode is a verticalprint orientation in which a document is printed across the narrower dimension of a rectangular sheet of paper.Landscape mode is a horizontal print orientation in which text or images are printed "sideways"−−that is, thewidth of the image on the page is greater than the height.

Save As DefaultAll the changes you made in the above three sections (Paper, Margin and Orientation) can be saved as defaultby clicking the Save As Default button. The next time you come to the Style tab, the saved settings will bedisplayed.

Developing Reports with Report Wizard

64

Page 77: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

TypesIn this section, notice that some templates contain more than one type of the template item. By default, JReportwill build your report with the format of the first template displayed in this section. This is defined inc:JReport\template\template.properties (assuming JReport is installed under c:\JReport). For example, theStandard template includes six items, the default is Indent. You can select another item to layout your report. Ifyou want to create a custom template, simply edit the template.properties file in a text editor like notepad.

Note: In the Design mode, you can also change the paper type, margin measurement and orientation by clicking PageSetup on the File menu. This way, you can frequently switch to the View mode to check your changes.

Once you have finished designing a report with the tabs necessary in Report Wizard, click Finish, and a draft report isbuilt in design mode. Usually you do not need to go over all the tabs, and you are free to skip tabs according to yourreport design requirements. At any time you can click Finish to get the draft design and further refine it in the designmode.

Index

Multiple Data Sources

Introduction

Since JReport Designer version 6, more than one connection can be added to a catalog. With the Multiple Data Sources(MDS) feature, you can create reports using different data sources within a single catalog, which can greatly simplify yourtasks of the report management. The Multiple Data Sources feature also allows you to easily create nested reports (mainreports and sub−reports) that are using different data sources.

In Catalog Browser, which contains and manages the resources, each data source is a root node. When you createreports, JReport Designer fetches data from the data source through the connetion. The first data source is namedDefault, which can not be deleted or renamed. The Catalog Browser with the Multiple Data Sources (MDS) feature mightbe like this:

Developing Reports with Report Wizard

65

Page 78: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the above screen shot, you can see that there are two data sources in the catalog Tutorial, Default and Oracle.

However, no matter how many data sources the catalog may contain, the resources under each data source areindependent from each other. So one report can only get data from one data source.

Creating Reports with Multiple Data Sources

The MDS feature enables you to get data from different data sources for the main reports and their sub−reports. Creatingreports with multiple data sources is the same as creating reports with a single data source. You only need to specify adata source before you create the report, otherwise the Default data source will be used.

To create the main report and its sub−report with multiple data source,

Create new connections in your catalog. For the detailed information, please see JReport Designer helpUserguide | Starting a Catalog.

1.

Create the report which will be used as the sub−report following the Report Wizard.

Please note that you must specify a data source from the Catalog data source drop−down list on the Data taband then create the report step by step according to your own requirements.

2.

Developing Reports with Report Wizard

66

Page 79: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Save the report you have just created. For example, you save the reprot using the name Report1.cls.3. Create the main report.

On the Choose Report dialog, choose the sub−report template. Please remember to specify a different datasource for the main report. On the Subreport tab of the Report Wizard, specify Report1.cls as the sub−report.Do the other settings on this tab.

Of course, you can also finish the main report first and insert the sub−report by clicking Subreport on theInsert menu or clicking the Insert subreport button on the toolbar.

4.

Click Finish to generate the report.5.

For example, if you want to create a report to print all employees whose salaries are lower than the group average salaryin groups, please follow the steps below (the main report will get data from the Default data source and the sub−reportwill get data from the Oracle data source):

Create the report which will be used as the sub−report using the Oracle data source.

Click New on the File menu , specify the Standard template on the Choose Report dialog.

On the Data tab of the Report Wizard, choose the Oracle data source from the Catalog datasource drop−down list. Add the Employee table to the Report data source list.

On the Display tab, add EMPLOYEE_EMPLOYEE ID, HIRE_DATE, EMPLOYEE_POSITION, and SALARY tothe Report Fields list.

1.

Developing Reports with Report Wizard

67

Page 80: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click Finish to generate the report.

Edit the report. Make the Report Header Panel invisible.

Save the report using the name Salary.cls.Create the main report.

Choose the Subreport template on the Choose Report dialog.

Choose the Default data source on the Data tab to create the report. Add the Employee table into the Reportdata source list.

On the Group tab, add the Reports To field to the Group by list.

On the Summary tab, calculate the average of the Salary field and break it by the Reports To field.

On the Subreport tab, in the Choose a report box, browse to Salary.cls, and click Open. Create two links:Reports to = REPORTS TO, Average_Salary2 >= SALARY.

Click Finish to generate the report.

2.

Edit the report.

Select the Detail section, go to Report Inspector, and then set property Invisible to be true.

Place the sub−report to the GroupHeader section.

Delete the column name Salary in PageHeader.

Select sub−report Salary.cls, and set the background to light purple in Report Inspector.

Do some adjustments to make the report tidy. The finished report might be like this:

3.

Developing Reports with Report Wizard

68

Page 81: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Index

Developing Reports with Report Wizard

69

Page 82: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Previewing a Report

Work Area

Having completed the tabs necessary for your report in Report Wizard, you get a draft design as below:

In the report Design window that appears, you can see the work area is partitioned into different sections, consisting oftwo tabs: Design and View. The Design tab indicates the design mode while the View tab causes JREngine to run thereport and presents the result on the screen.

Design Mode

Section

Basically, there are seven sections in a report. They are Report Header, Page Header, Group Header, Detail, GroupFooter, Page Footer and Report Footer.

Definition of Sections

Report HeaderPlacing fields or objects here will allow them to only be seen on the very first page of the final report.

Page HeaderObjects and fields in this section will be seen once per page in the upper half of each page of the report.

Group HeaderPlacing fields and objects in this area will allow them to be seen once per group in the report.

70

Page 83: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

DetailDepending on how much data there is per group, fields and objects here may be seen multiple times.

Group FooterPlacing fields and objects in this area will allow them to be seen once per group in the report.

Page FooterObjects and fields in this section will be seen once per page in the lower half of each page of the report.

Report FooterPlacing fields or objects here will allow them to only be seen on the very last page of the final report.

Adding and Deleting Sections

To add or delete a section, first move the mouse cursor to the section you want to add or delete. Next, right click toreveal a menu that lists the following commands:

Title of the section• Hide• Insert Section After• Delete• Report Inspector• Save Style•

Select Delete, the section which the mouse cursor points to will be deleted.

Select Insert Section After, a copy of the section below the original you selected will be added afterwards.

Other ways of inserting sections:

Click on the Insert Section button on the Edit toolbar. • Go to the Insert menu, click Section.•

For all the above methods, a box will appear if you move your mouse cursor in the design window. Place the box in aprevious section of the report. This will insert a copy of that previous section right below it.

Resizing Sections

Every section is resizable. To resize a section, position the cursor over its split bar. After the cursor becomes adouble−headed arrow, press the left button, drag and drop the split bar to its desired position.

You can also resize more accurately with Report Inspector. Simply highlight the section and go to Report Inspector. FindHeight and Width under Geometry. You may change the area of the section by changing the value in Height and Width.

Ruler, Grid and Guideline

Ruler

In the design mode, you can display horizontal and vertical rulers for better positioning of the objects. Selecting ShowRulers from the View menu to show the rulers.

Grid

In the View menu, on the View menu, you can see Grid Size, Show Grids and Snap to Grids.

Grid SizeAdjust the size of the grids in the design area.

Show GridsReveal or hide the grids.

Previewing a Report

71

Page 84: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Snap to GridsEither objects will snap and lock with the grids, or you can freely move and place objects around.

Guidelines

Guidelines are provided for easy and accurate alignment of objects in the Design tab. To display your guidelines, you cango to the View menu and select Show Guidelines.

Adding GuidelinesTo add a vertical guideline, go to the horizontal ruler and click on it. A Guideline Handle icon should appear withthe guideline. Repeat the steps to add more guidelines.

To add a horizontal guideline, go to the vertical ruler and click on it. A Guideline Handle icon should appear withthe guideline. Repeat the above steps to add more guidelines.

Moving a GuidelineDrag the Guideline Handle icon to move the guideline along the design area. Release the icon to set theguideline in place.

Removing a GuidelineDrag the Guideline Handle away from the ruler and the guideline will disappear.

View Mode

Click the View tab and JREngine will begin running the report. The result will be shown in the viewer. To optimize theperformance, notice that JReport Designer displays report pages before they are completely generated.

Previewing a Report

72

Page 85: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Toolbar of View Tab

In the View mode, you can see a toolbar used to go backwards or forwards in viewing your report, and also to refresh thedata or stop generating the report, etc.

Below are the function expainations of the buttons on the toolbar listed one by one in sequence.

First PageDisplays the first page of the report.

Previous PageDisplays the previous page of the report.

3 of 7Indicates which page out of the total pages you are viewing.

Next PageDisplays the next page of the report.

Last PageDisplays the last page of the report.

TocShows the table of contents.

Drag Tool (Ctrl + T)Drags the page up and down.

Click this button, place your mouse cursor on any blank area of the report, when the mouse cursor becomes asmall hand. you can drag the page.

Zoom In Tool (Z)Enlarges the page.

Zoom Out Tool (Shift + Z)Reduces the page.

Refresh DataUpdates any changes you created in your data.

Note: After some modifications in the design mode, you will find the view mode does not make the changes andthe report is shown very quickly. This means you need to use this button to re−run your report.

Refetch DataRe−fetches data to re−run the report.

StopPress the it if you want JReport to stop the report generation.

Dynamic Sort

You can sort the records in the report dynamically in the report view mode. To do this, move the mouse cursor to the fieldyou want to sort, right click and select the option you want on the pop−up menu.

Select Sort Ascending, the records displayed will be sorted in an ascending order (A, B, C). Selecting SortDescending, the records will be sorted in a descending order (C, B, A).

Drill−down

You can drill down on Aggregate level fields in your report. Drilldown is made possible where there is a summary for agroup. For example, we create a report grouped by Customer Region, and create a group summary on the Annual Sales.When you view the report, point your mouse at the total annual sales for a region, and click it. The drill−down report isdisplayed.

Previewing a Report

73

Page 86: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Usually in this case we will hide the detail section and only show it in the drill−down report. To do so, select the detailsection, and go to Report Inspector. Set its Invisible property to true. Then view the report again, and it will show withoutthe details.

Place the mouse on the Annual Sales summary. When the small hand appears, click it, and the drill−down report will bedisplayed.

Previewing a Report

74

Page 87: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Designer WindowThis section will focus on the main functions of the windows, dialogs and toolbars JReport provides to you. For simpleoperations, we will give a brief how−to introduction. Other complex commands associated with this topic will be coveredin the specific sections for a feature.

JReport Designer Window

The JReport Designer window provides an intuitive and friendly design environment. As shown in the window, it containsMain Menu, Toolbar Resource Viewer and Work Area.

Main Menu

The following functions are available in the Main Menu. Frequently used menu choices are also available on toolbars(Standard toolbar and Edit toolbar).

File

NewCreate a new report using Report Wizard.

OpenOpen an existing report. To open an existing report,

On the Open Report dialog, select the Existing tab.1. Select a report type from the Report Type drop−down list. All the report of the selected type in thecatalog will be displayed in the panel above.

2.

Highlight the report you want to open, and click the Open button, or double click to open it.3.

75

Page 88: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: If you are opening a self−contained report (.clx, a report that contains not only report's layout but also thecatalog with its own resources), the Open As dialog will pop up for you to specify the catalog under which theself−contained report will work.

After opening a self−contained report, you can edit it freely as the .cls reports in JReport Designer.

CloseClose the active (currently opened) report.

SaveSave the active report.

Save AsSave the active report with a different name under the current directory. You can select four types of report:Report Binary File (*.cls), Report Source File (*.rpt), Self Contained Bin File (*.clx) or XML Format Report(*.cls.xml). A *.cls file is only a report file, including all visual objects in the layout but not the result. Thedifference between a *.cls file and a *.clx file is that the *.clx file contains not only report's layout but also thecatalog with its own resources. A *.rpt file can be edited as a text file. You can open and edit the .cls.xml formatreport by JReport Designer directly as the .cls format report.

Notes:When you save a report to the XML Format Report (*.cls.xml), a special key is needed. If you want,please contact Jinfonet support ([email protected]).

Report that contains customized UDOs cannot be saved to XML format. If you want to do so, pleasecontact Jinfonet support ([email protected]).

Save toSave the active report with a different name in another directory. This command will also merge the report'sresources to another directory by either creating a new .cat file (if there is no .cat under that directory) or mergingto the existing .cat file (if a .cat already exists under that directory).

New CatalogCreate a new catalog file.

Open CatalogOpen a catalog file (*.cat).

Save CatalogSave the catalog file.

Save Catalog AsSave the catalog file with a different name in another directory.

OptionsConfigure JReport to your preferences and needs.

Editor TabChange the View, Grid, and Field options.

Format TabChange the format of fields as the default object property values displayed in Report Inspector.

The changes configured on this tab will apply to your later inserted fields. For example, first, you changethe background of the Integer type data to 0x0000ff, and then you add a Integer type column to a table,now look at the properties of the column, the value of the background is 0x0000ff.

Internet TabConfigure for exporting to email and html output and configure your modem used when exporting to fax..

The Export To Html section is for File | Export | To HTML to view your report in browsers. Export toe−Mail section is for File | Export | To Mail to send your report result with various formats to others.Export To Fax is for File | Export | To Fax to fax your report result to other people.

Catalog TabThe Catalog tab allows you to change options on showing warning messages, and the options on sortingitems.

Show Warning Message

JReport Designer Window

76

Page 89: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Decide whether and when to show warning messages.

Sort itemsSpecify whether and how to sort items in Catalog Browser and Report Wizard. This will be the default,and you are free to change it when you use Report Wizard.

Use cached query resultThis option is most often used when troubleshooting users' problems. In order to resolve the technicalissues that you have reported, we need to access your report data so that we can re−create and analyzethe problem. Regardless of your database size, we only require access to the data returned by the queryor stored procedure of that particular report.

To extract the report data, in Catalog Browser, right click on the query or the stored procedure that yourreport is using, select the menu item 'Create Cached Query Result'. Input the data file name and click the'Save' button. The query result will be saved in the file.

When you view/run the report, a dialog box will pop up that lets you choose to use the data file to viewthe report instead of connecting with your data source.

Schema File Location This option is only for the users who use the special key, which enables the users to save the internal fileto readable format. It specifies the location of the Report.xsd, Catalog.xsd and JetUPrejoins.xsd files. Bydefault, after you save the report to .cls.xml format or catalog to .cat.xml format, you can find the threefiles under %JRepportInstallRoot%\template. To change their location, you have to copy the three files tothe location you want first and then specify the location here.PSQL TabChanges how Auto Join and Others options work on the Joins tab, specifies whether to show themessage box for the pre−join feature and specifies the default values for the preview feature..

Language TabChange the values of converting encoding for the Chinese data.

Advanced TabYou can make further changes to the default settings for Report Inspector and Catalog Browser.

Report Inspector By default, you are not allowed to change these property values because doing so may create problemswhen working on your report. For example, if you changed the query name in Report Inspector, somefields used in the report may not be available in the new query.

However, if you are very familiar with JReport product, you can make necessary changes to these valuesto satisfy your special needs. For example, you have two similar reports with the same template. Theyuse different queries, but share the same tables. In this case, you can simplify your work by uncheckingthese options to build another report with the same template, group, summary...

Security Manager If you check Start Security, you will be prompted to input User ID and password when you launchJReport Designer. If you input invalid user name and password three times, the login will fail and theprocess will stop automatically.

Please note that the user name is case sensitive and cannot be less than 4 characters, and the length ofthe password must be more than 6 digits.

To build a user after you haved launched the Security Manager, click the Manage button to bring outthe User Manage dialog, and then click Add to build a user.

To delete the existing accounts, on the User Manage dialog, highlight the account you want to delete,and then click the Remove button to delete the account.

JReport Designer Window

77

Page 90: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: The last login account cannot be deleted.

Group/Sort By default, any field you added to the catalog in JReport can be used to group and sort. However, youcan specify in this section to ask JReport to qualify whether a field can be used to group or sort. Note,the information of the qualification will be stored in the database connection.

Catalog Browser By default, you are not allowed to change the above property value of Catalog Browser. However, theremay be a need to change it, for example, sometimes the JDBC driver cannot return a proper Precisionand Scale value for a column. In this case, uncheck this option. Then, activate Catalog Browser, highlightthe column name that you have problems with, click on the expand button to show the properties list.Now you can change the property values, such as SQL type, precision, scale to what they should be.

Print JReport allows you to specify the printing methods accordingly. JDK 1.1 printing method is quick inspeed but the printing quality can not be guaranteed. However, JDK 1.2 can return you with satisfactoryresult, even for a gif file, but it is slow in speed.

The checkbox "Separate a large page " is to indicate whether to separate a large page during printing. Ifthe report page size is larger than the print paper size, and you want to separate the large report pageduring printing, you should set this property to true. If the print page size which you choose is less thanthe report page size, then the report will be printed as multiple pages serially, this means JReport willseparate the large page of the report automatically. After you set it to true, for JDK1.2 or higher, the pageformat dialog will be popped up. In this dialog, you can choose the page format which you want to printwith, JReport will use this page size for printing.

For JDK1.1.x, however, you must change the page format which you want to print with in the print dialog(click the property button, then choose the page format).

Note: This printing method is not recommended, it may cause some unexpected errors, for example, youmay get an extra blank page.

Open TemplateOpen template files(*.tpl)

Save TemplateSave currently opened template.

Manage TemplateFor details, refer to the User Defined Template section.

Page SetupSet up page parameters.

PrintPrint the current report result

Export toExport the current report result to JReport Result, Text,HTML, PDF, Mail or Applet format.

ImportImport and convert Crystal reports to JReport reports using the tool named Crystal Converter.

Reference : JReport Designer User Guide | Converting Crystal Reports to JReport reports

Deploy to Deploy resources from their original place to another, which can be the local machine or JReport EnterpriseServer.

Edit

Undo/Redo•

JReport Designer Window

78

Page 91: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Either reverse a previous action or repeat the previous action. CutErase an object and place it in the clipboard for later access.

CopyCopy an object and place it in the clipboard for later access.

PasteTake an object from the clipboard and place it in the report

DeleteErase objects from the report.

Find DBFieldFind specific DBField in the report.

Select a field from the drop−down menu. Click on the Find Next button. The field will be indicated by the greenhighlight border around it.

If you placed multiple identical fields in the same report, click the Find Next button repeatedly to search for all ofthem. The direction Up searches for these identical fields from bottom to top and the direction Down searchesfor these fields top to bottom.

Edit Style GroupSometimes, you may need your reports to all have the same font face, font size and alignment. Moreover, youwant the labels in your reports to be all the same font, centered, 9 points, bold and underlined. In this case, youcan save a finished report as a template. But the problem is you have finished most of your reports and you donot want to re−create them. In this case, you'd better use the function Edit Style Group of JReport Designer. Itallows you to edit the property of multiple types of objects at the same time.

Click Edit Style Group on the Edit menu, the Edit Style Group dialog appears.

You may notice that in the left All Style List, styles are organized according to different object types. Whenexpanding the tree by clicking on the plus icon, all the styles you have ever saved will be shown. However, foreach object type, you are only allowed to select one style to add to the right style list.

Click the New Group button and provide an ID for the new style group, and then select the styles you need fromthe left list.

After you select one style for one type of object, the type will be folded so that you cannot select it again.

Open a report, and select all the objects you want to edit, then select the style group you have defined from thestyle list on the Standard toolbar. The style you have defined will be applied to the selected objects.

Sort ParameterIf there are several parameters in your report, the parameter sequence in the pop up parameter dialog box israndom. For example, if you use the following parameters into your report, PToday, enddate, startdate, Editor,PCoutry, Cus_Region, P, P1, when you run the report, the parameters will be displayed randomly as shownbelow:

JReport Designer Window

79

Page 92: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

But sometimes you would like to have the parameters displayed in a certain order. Therefore, JReport provides asorting parameter function to edit the parameter sequence. To use this feature:

1. Start JReport Designer and open the report with parameters.

2. Click Edit | Sort Parameter to open the Sort Parameter dialog box, in which all the parameters you used inthe current query are displayed.

3. Click a parameter to highlight it, and then click MoveUp and MoveDown button to adjust the sequence. Forexample, we make the parameter display with ascending alphabetical.

4. Click the OK button to close the Sort Parameter dialog box

5. Run the report again, you will find that the parameters have been displayed with the sequence you specified:

Edit Display NameSpecifies the field display name for the Sort and Filter panel of DHTML. To make the field name displayed on theSort and Filter panel more friendly and easier to be identified, you can edit the display name for the fields inJReport Designer.

Edit Sort and FilterAllow you to pre−define sort and filter conditions for DHTML so that the report will show directly the data youdesired when the DHTML pages are loaded.

View

Turn on or turn off some tools or functions which include:

Toolbars, status line, grids, rulers, and guidelines•

JReport Designer Window

80

Page 93: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Catalog Browser• Report Inspector• Resource Viewer• Always on top: Allow you to keep Catalog Browser and Report Inspector on top of the Design window •

Insert

LabelInsert and create labels.

UDOInsert user defined objects.

SummaryInsert a summary field.

DBFieldInsert DBFields, formulas, and parameters.

Control ObjectInsert control object (Text Field, Password, Checkbox, Radio Button, Hidden Field, Button, Dropdown list, orList).

Data ObjectInsert data objects (Section, Table, Chart or Cross Tab).

Special FieldsInsert special fields not from your database.

TextPlace and create text in the report.

ChartCreate and place charts and graphs in the report.

BarcodeInsert barcode into the report.

MapInsert a map into the report.

CrosstabPlace a crosstab object in the report.

SectionAdd or delete sections in the report.

Group/SortCreate and edit the criteria by which your fields are grouped and sorted.

Sub ReportCreate and place a subreport in the main report.

DrawDraw arches, ovals, boxes, round boxes and lines in the report.

ImagePlace JPEG and GIF images into the report.

Format

Move To BackThis option places an item that overlaps one or more objects behind all the overlapping objects.

Move BackwardThis option places an item that overlaps one or more objects behind the current overlapping object.

Move To FrontThis option brings an item that overlaps one or more objects to the front of all the overlapping objects.

Move ForwardThis option brings an item that overlaps one or more objects to the front of the current overlapping object.

Align LeftShift all the objects you select to the left.

JReport Designer Window

81

Page 94: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Align RightShift all the objects you select to the right.

Align TopShift all the objects you select to the top.

Align BottomShift all the objects you select to the bottom.

Align Vertical CenterAlign the objects you select in the center vertically

Align Horizontal CenterAlign the objects you select in the center horizontally

Window

Switch among the open reports.

Resource Viewer

Introduction

Since JReport Designer version 700, a new tool named Resource Viewer which can be used to manage your data isprovided for you to edit your report more easily.

It lays on the right side of the word area. If it is invisible on the window, go to the View menu, and click ResourceViewer to bring it out. Click the cross on the up right corner to close it.

On the bottom of the Resource Viewer, there are two tabs − Resource and Inspector. When Report Inspector is notavailable, click the Inspector tab, it will be displayed here.

Objects in Resource Viewer

Four type of objects are listed in Resource Viewer:

query which is used by the currently opened report,• formulas that used and can be used in the currently opened report,• summaries that used and can be used in he currently opened report, • parameters that used and can be used in the currently opened report.•

A red arrow is marked on the icon of each used object.

Working with Resource Viewer

With the help of Resource Viewer, you can do the following jobs:

Inserting DBField

Expand the query, select the DBField you want to insert, and drag it to the position you want.

Creating formula, summary and parameter

Selecting the Formulas, Summaries or Parameters node, right click and then on the pop−up menu click AddFormula, Summary or Parameter.

Editing and renaming formula, summary and parameter

Select the formula, summary or parameter you want to edit, right click and on the pop−up menu click EditFormula, Summary or Parameter.

For rename them, just on the pop−up menu, click Rename, and then type a new name in the text field.

JReport Designer Window

82

Page 95: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Inserting formula, summary and parameter

Select the object you want to insert, and then drag it to the position in the report.

Toolbars

Standard Toolbar

Standard Toolbar contains the basic features of JReport such as New, Save, Open and Format etc. Each icon isdescribed below.

NewThe Open Report dialog is brought up, and then you can create a new report with Report Wizard.

OpenList all existing reports under the current catalog. Browse to select a catalog and open a report.

SaveSave your report under its previous name and catalog.

PrintPrint the current report with the default printer settings.

Page SetupSet the page properties for printing.

CutErase an object and place it in the clipboard.

CopyCopy an object and place it in the clipboard.

PastePaste into your report whatever object was placed in the clipboard.

DeleteDelete the selected object.

Undo and RedoThe Undo operation (left) will reverse the previous action. The Redo operation (right) will repeat the previousaction.

Open Data Set This icon takes you to the Working Set menu which contains Data, Joins and Conditions tabs. It is often used tomodify your filters after the rough design with Report Wizard.

InspectorBring out or hide Report Inspector.

Catalog BrowserBring out or hide Catalog Browser.

Show Invisible ObjectsDisplay our hide all the invisible objects.

Style drop down listShow style group name for you to select.

Font FaceSelect a font face for the selected object.

Font SizeSpecify the font size for the selected object.

Bold Italic and UnderlineMake the selected object bold, italic or underlined.

Left, Center, Right, and Justify•

JReport Designer Window

83

Page 96: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The alignment type. Choose one according to your own requirement.HighlightChoose the background color for the selected object.

Font ColorChoose the foreground color for the selected object.

HelpBring up the help menu.

Edit Toolbar

Edit Toolbar allows you to insert and create objects that you can use to enhance your report.

Insert DBField Clicking on this icon takes you to the DBFields dialog, where you can create, modify and insert a DBField.

Insert FormulaClicking on this icon takes you to the Formulas dialog, where you can build, modify and insert a formula.

Insert SummaryClicking on this icon takes you to the Summary dialog. Note: you must select a field first to enable the icon.

Insert ParameterClicking on this icon takes you to the Parameters dialog, where you can create, modify and insert a parameter.

Insert Special FieldsThe drop−down arrow will display all the available special fields.

Insert TextInsert a text box.

Insert ChartInitiate the Chart dialog to create a chart in a report.

Insert BarcodeInitiate the Barcode dialog to create barcode in a report.

Insert MapInitiate the Map dialog to create a map in a report.

Insert CrosstabInitiate the CrossTab dialog to create a Cross Tab in a report.

Insert SectionInsert a section.

Insert GroupInitiate the Group/Sort dialog for adding or modifying Groups/Sorts.

Insert Subreport Initiate the Subreport dialog to insert a subreport.

Insert Line, Insert Box, Insert Arc, Insert Oval, and Insert RoundboxInsert various common shapes with the quick launch buttons.

Insert LabelPlace a label into your report.

Insert ImagePlace a JPEG or GIF image into your report.

Hot keys

When designing or viewing reports, you may find some reports' contents are so great that they span a large spacevertically to be shown in several pages. It's time−consumed for you to move the cursor row by row to design or view yourreports. For this situation, we support hot keys in JReport Design mode and View mode.

PageUpYou can scroll contents page up in the current page by pressing this key on your keyboard.

JReport Designer Window

84

Page 97: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

PageDownYou can scroll contents page down in the current page by pressing this key on your keyboard.

Work Area

The work area consists two tabs: Design and View. It is partitioned into different sections: Report Header, Page Header,Group Header, Detail, Group Footer, Page Footer and Report Footer.

See also: User's Guide | Previewing a Report.

Index

JReport Designer Window

85

Page 98: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Refining the Report Layout

Introduction

Report Wizard generates a rough and basic design of a report. It is far from the professional appearance you require. Inthe report Design window/mode, you can make any adjustment to the report layout. JReport provides different ways foryou to edit and format your data into a well organized report.

Report Inspector can be used to examine and change the objects in a report. Just highlight a certain object, and in theReport Inspector, change properties such as font, size, and color.

Another simple way to edit your report is via dragging and dropping in the design window.

Selecting, Moving and Resizing Objects

Single Object

SelectingMove your mouse cursor to an object, click on it. The focus (A green border) appears, indicating that you have selectedthe object.

MovingMove your mouse cursor to the required object till it becomes a four−headed arrow. Then, click and drag the object to thedesired position and release.

ResizingMove your mouse cursor to the border of the selected object until it becomes a double−headed arrow (vertical, horizontalor diagonal). Then, click and drag the object's border to the preferred size and then release.

Multiple Objects and Fields:

SelectingMove your mouse to an object. Click and drag to create a selection box.

Continue to drag this selection box over multiple objects and release.

The grey stripes indicate selected objects, and the object with the green border is the focus object. By making anoperation on the focus object, the same operation will be applied to all the other selected objects.

MovingMove your mouse cursor to the focused object until the mouse cursor becomes a four−headed arrow. Click and drag theobject to the desired position and release. The rest of the objects and fields will follow.

86

Page 99: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ResizingMove your mouse cursor to the border of the focused object. When the mouse cursor becomes a double−headed arrow(vertical, horizontal or diagonal), click and drag the object's border to the preferred size and release. The rest of theobjects and fields will resize as well.

Overlapping

Organize the objects in your report by moving and shifting objects that overlap each other.

Single Object

Move To BackMoves an item that overlaps one or more objects to a position behind all of the items.

Move BackwardMoves an item that overlaps one object to the back.

Move To FrontMoves an item that is being overlapped by one or more objects to a position in front of all other items.

Move ForwardMoves an item that is being overlapped by one object forward.

Examples:

Here you can see three text boxes overlapping each other. Select the second box and right click to reveal the formatmenu. Go to Format | Move To Back, the second box would be moved all the way to the back as in the image below.

Select Format | Move To Front, the second box is moved all the way to the front and overlaps the third box.

Refining the Report Layout

87

Page 100: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Multiple Objects

Align LeftAligns all the selected objects to the left border of the focus object (with the green border).

Align RightAligns all the selected objects to the right border of the focus object (with the green border).

Align Top Aligns all the selected objects to the top border of the focus object (with the green border).

Align BottomAligns all the selected objects to the bottom border of the focus object (with the green border).

Align Vertical CenterAligns all the selected objects vertically by the center of the focus object (with the green border).

Align Horizontal CenterAligns all the selected objects horizontally by the center of the focus object (with the green border).

Example one: Align Left, Right, Top and Bottom

Normal

Align Left

Refining the Report Layout

88

Page 101: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Align Right

Align Top

Align Bottom

Refining the Report Layout

89

Page 102: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Example two: Align Vertical Center and Horizontal Center

Align Vertical Center

Align Horizontal Center

Before After

Font

The first thing to do for manipulating fonts is to select the objects you want to change.

All options can be found on the Standard toolbar.

Refining the Report Layout

90

Page 103: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Changing Font FaceFrom the Font Face drop−down list, select the font face you want. All those introduced with * are true type font.Please refer to User's Guide | True Type Font for more information.

Changing Font SizeFrom the Font Size drop−down list, select the size you want.

Changing Font StyleYou can change the font style to bold, italic or underline. Click the corresponding button.

Changing JustificationThe justification can be left, center, right or justified alignment. Click the corresponding button.

Changing ColorClick the Highlight button to specify a color for the background of the selected object. Click the Font Color buttonto specify a foreground color for the selected object.

Deleting, Copying, Cutting and Pasting

Objects in the report can be deleted, copied and moved. To delete an object, select it and click Delete from the Editmenu. To copy or cut an object, select it and click Copy or Cut from the Edit menu, then position the cursor to the placewhere you want the object to be copied or moved, click Paste from the Edit menu.

Index

Report Inspector

Introduction

Report Inspector is a helpful menus provided by JReport. It is a tool to view the properties of selected objects andsections. Some properties include color, width, location, and style. Report Inspector also allows you to edit and formatthose objects directly from this window for accurate and precise adjustments.

Reference Notes: Different types of objects will have properties of their own, please refer to User Reference book for thein−depth specifications for each property associated with different objects and sections.

Launching Report Inspector

To bring up Report Inspector, you can use one of the following ways:

MenuSelect Report Inspector on the View menu.

Standard ToolbarClick the Inspector button on the Standard Toolbar.

Right ClickRight click the selected objects or sections, select Properties.

Double Click Double click an object, Report Inspector will pop up.

Report Inspector

Refining the Report Layout

91

Page 104: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Structure

Data SourceShows what Working Set you are currently using in the report.

Report Header PanelShows what objects are located in the Report Header section.

Page PanelThis section has three areas:

Page Header PanelLists the objects that are located in the Page Header section.

Page Footer PanelLists the objects that are located in the Page Footer section.

Group PanelThis section has three sub−sections:

Group Header PanelShows the objects that are located in the Group Header section. Group Footer PanelLists the objects that are located in the Group Footer section. DetailsShows all the objects in the Details section.

Report Footer PanelShows what objects are located in the Report Footer section.

Properties

Here we are just giving you a brief introduction to the general properties.

TypeDisplays what type of object or section you have.

Field TypeDisplays what type of field you have.

DB Field NameShows the name of the DB Field.

QueryDisplays what query the field comes from.

TableIndicates which table the field comes from.

ColumnName of the column from which the field comes.

Data TypeTells you what format the field you selected is in.

Formula NameIf you select a formula field, this will show its name.

ExpressionIf you select a formula field, this will show the expression that makes up this function.

Formula EditorIf you select a formula field, click here to bring you to the Formula Editor.

Summary NameIf a summary field is chosen, this will display its name.

Summary FunctionIf a summary field is selected, this will show which summary function is used.

Summary On•

Refining the Report Layout

92

Page 105: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If a summary field is picked, this will show which field is summed. Break FieldIf a summary field is selected, this will show how the summary field is grouped.

Reference Notes: Not all of these properties are available all the time. It depends completely on what fields, objects, orsections you choose. Go to Reference | Reporting Features for the detailed properties of each type of object.

Editing Objects in Report Inspector

Report Inspector can be used to examine and edit objects in a report. Whenever you click on an object, its properties willbe displayed in Report Inspector.

Here are some examples for editing an object in Report Inspector.

Example 1: Changing Geometry

From Report Inspector, you can change the geometrical properties of shapes. Typically when we deal with coordinates,each section is a separate quadrant. The x coordinate goes from left (0) to right (720) and the y coordinate goes from top(0) to bottom (unlimited).

XThis property shows the horizontal coordinate for a field or object in a specific section. Modify the number, theobject will move horizontally across the section.

YThis property shows the vertical coordinate for a field or object in a specific section. If you adjust the number, theobject will move vertically across the section.

WidthAdjust the width of a field, an object or a section.

HeightAdjust the height of a field, an object or a section.

Top Attach Pos XChanging this number will drag the upper handle horizontally across the section, thus increasing or decreasingits width.

This object's value in Top Attach Pos X was 125

When we changed it to 0, the object's upper handle moved to the coordinate 0 thus expanding the object's area.

Top Attach Pos YChanging this number will drag the upper handle vertically across the section.

This object's value in Top Attach Pos Y was 50

When we changed it to 100, the object's upper handle moved to the coordinate100 thus decreasing

Refining the Report Layout

93

Page 106: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

the object's area.Bottom Attach Pos XChanging this value will drag the bottom handle horizontally across the section.

Bottom Attach Pos YChanging this value will drag the bottom handle vertically across the section.

Example 2: Changing Color

JReport has the option of changing the background and foreground color of any object.

Select one label field, go to Report Inspector and under the Color item, select Background and choose dark blue.Next, under the Color item, select Foreground and choose yellow.The result of your color selection will be shown instantly on the screen like this:

Example 3: Changing Format

JReport lets you define the result format for various field types including currency, date, percent etc.

Refining the Report Layout

94

Page 107: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In this example, we select a field of currency data type. In Report Inspector, find the property TextFormat and expand it,then click Format. In the drop−down menu, select $#,##0.00 for the display format.

Index

Refining the Report Layout

95

Page 108: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using Styles in Your Report

Introduction

JReport style is one of the most important concepts in both JReport Designer and JReport Enterprise Server. JReportstyles, organized in style groups, can hold a large amount of pre−defined object properties, which gives you morecontrols over the appearance and presentation of your report. By using JReport styles, you can create various visualpresentation sets from a single report, and change the visual presentation of your report at run−time according to yourneeds.

What is a style?

A style in JReport is a set of object attributes that you can assign to objects in your report to alter their appearance andcharacteristics. When you apply a style, you apply a whole group of property entries at once. For example, you may wantto format the headings of a report to make them stand out. Instead of formatting them step by step as 12pt, Arial, andcenter−aligned with blue background, you can simply achieve the same goal in one step by applying a pre−defined stylethat contains the style properties you desire.

Each style has a style type to indicate its application scope, e.g., a style with Label type can only be applied to labelobjects, and a style with DBField type can only be applied to a dbfield.

What is a style group?

A style group is a set of styles that you can apply to a report to quickly change its appearance and characteristics. Whenyou apply a style group, you apply a whole group of styles at once. To apply a style group to several report objects, youmust first have the report objects selected, and then apply the style group. The style of each style type will be applied tothe report object of the corresponding type.

By simply selecting a style group at run time, you change the look and feel of your report in a dramatic way. JReport stylegroups can be nested, where the parent group is used as a container of other groups.

Static Styles and Dynamic Styles

JReport style falls into two categories − static style and dynamic style.

A static style is a style that you can directly apply to the object in report, which means that you can see the style effectimmediately, just like what you get after setting the properties step by step in Report Inspector. The static styles aremainly used to simplify the repetitive formatting work during design period. The styles you apply using the Style box onthe Standard toolbar are all static styles.

Starting with version 5.2 JReport supports a new feature − dynamic style groups. Both of the static and dynamic styleswork together, and your existing reports still work as before.

A dynamic style, created and edited using Catalog Browser, is a style that takes effect at run−time; it doesn't affect thereport design layout in design mode. You can switch among the style groups according to your needs at run−time topresent your report in rather different look and feel. The styles you specify in the Style property entry in Report Inspectorwill run as dynamic styles.

Predefined Style Groups

There are some pre−defined style groups in JReport Designer, which is mainly used as a demonstration for reports thatcontain table objects and crosstabs.

In each predefined group, you can find styles named as column1 and column2. These two styles are used as an exampleto show how to alter the styles for each column of the table object. For reports that contain a table object, if you want the

96

Page 109: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

style of each table column to alter, in the Report Inspector, select the table object, specify a style group for the Patternproperty entry. When you view the report, you will find the styles column1 and column2 are repeatedly applied to eachtable column, in order. If you choose to run the report using other style group, the style of the table columns will also bechanged, so long as the style group you select contains the styles column1 and column2.

If you want to apply another different style for more table columns, create a new column type style using the namecolumn3. The styles will be applied to the columns accordingly like below:

Suppose there are three column type style in the style group, which includes column1, column2, and column3.

Column Type Style Applies to Column of the Table object

column1 => the 1st table column

column2 => the 2nd table column

column3 => the 3rd table column

column1 => the 4th table column

... ... ...

You can create as many column type styles as you wish, please remember to name the style as column1, column2,column3, and so on.

Setting up Styles in JReport Designer

You create and set up your own styles in JReport Designer, using the Styles tab on Catalog Browser. To open CatalogBrowser, on the View menu, click Catalog Browser.

To set up the dynamic style group feature for your report, take the following procedures:

Create new dynamic style groups1. Create new dynamic styles2. Specify a dynamic style group for your report3. Link the dynamic styles to report objects4.

Create a new dynamic style group

To create a new dynamic style group,

On the Styles tab of Catalog Browser, select the group node where you want to create the new group, and thenclick New Style Group on the toolbar.

1.

Specify the Group Name and Description, and then click OK.2.

Note:

The root of the style group tree can hold only style groups. The styles must reside in the style groups. Youcannot create a style directly under the style group tree root.

The default style group can neither be deleted nor nested; you cannot create style groups in the default stylegroup.

The name of each style group must be unique in the style group tree.•

Create a new dynamic style

On the Styles tab of Catalog Browser, right−click the group node where you want to create the new style, andthen click New Style.

1.

Specify the Style Name, Style Types and Description, and then click OK. 2. Add the property items you want to change for the style, and then click Save. You can also change the propertyvalues on this dialog.

3.

Using Styles in Your Report

97

Page 110: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the Catalog Browser, double−click the style you created to show the Properties sheet. 4. Edit the property entries for the style.5.

Notes: Sometimes you may not be able to edit the property entries in the Properties sheet. In such case, on the Filemenu, click Options, click the Advanced tab, and then uncheck the Forbid editing data object properties option.

You can create more than one style that use the same style type, thus you can apply different styles to the reportobjects that have the same type.

For example, suppose that you have a number of dbfields in your report, such as address fields, totals, quantityfields, and so on. Probably, you do not want all this fields look the same. You can create two or more styles,using the same style type − DBField, and then apply them separately to the fields that you want to distinguishfrom others.

You can apply a default style to all the objects that hold the same type.

In the Default style group, create a new style, make sure the style name and style type are the same, forexample, style name=Label, style type=Label, and then modify the style properties. Therefore, when a newobject of that type is inserted into the report, the default style will be applied to it automatically. Please note thatyou can see the difference only at run−time.

Apply a static style

To apply a static style, first select one or more report objects to which you want apply the style, and then select a style orstyle group in the Style box on the Standard toolbar.

To apply a style that you created in Catalog Browser as a static style,

In Report Inspector, click the report root node, scroll down the Properties sheet to find the StyleGroup propertyentry, and then select the style group that contains the style you want to apply from the StyleGroup drop−downlist.

1.

On the report design layout, do one of the following:

To apply a style to a single object, select the object, and then select the style in the Style box on theStandard toolbar.

To apply styles to more than one object, select the objects, and then select the style group in the Style box onthe Standard toolbar.

2.

Notes:

If only one object is selected, the styles of the same type will be shown in the Style box. If more than one objectis selected, the style groups for the report will be shown in the Style box.

The styles or style groups you select in the Style box always function as static styles or style groups. Always usethe Style box to apply static styles.

Please do not try to key in the style name in Style property entry of Report Inspector, because JReport willconsider the style you enter as a dynamic style.

The styles or style groups you created using Catalog Browser are marked with asterisks * in the Style box tomake them stand out from the built−in ones.

The styles or style groups with asterisks (*) in the Style box are used as static styles (style groups), just likenormal static styles (style groups) listed in the Style box, say, they will take effect immediately after selection, and

Using Styles in Your Report

98

Page 111: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

the applied styles of the selected objects cannot be changed dynamically. If more than one style entry in a style group share one style type, when you select this style group from the Stylebox, JReport will randomly apply a style with matching type to the objects you select.

For example, suppose you have two DBField type styles − stlNormalField and DbField − in the style groupDefault, as shown in the picture below, when you select *Default in the Style box, JReport will randomly select astyle to apply, either stlNormalField or DbField.

In such case, you are recommended to keep at most one style of each style type in one style group.

When you apply a style (style group) to an object (objects), the Style property entry in Report Inspector will befilled with the style name, or prefixed with an asterisk (*) if it is not a built−in one, for example, *Label. This doesnot mean that you can key in the style name in Report Inspector to make the styles take effect immediately, sayuse as static ones. Any styles you specify in Report Inspector will work as dynamic styles, which work atrun−time only.

Specify a dynamic style group for your report

By default, JReport Designer does not use any style group for the reports you developed. To switch among style group atrun time, you must specify a default style group for your report.

In the Report Inspector, select a style group for the StyleGroup property.

By setting the StyleGroup property to a style group you switch on the dynamic style group feature for this report.

Link a dynamic style

You need to link a dynamic style with the report objects before they can take effect at run−time.

Using Styles in Your Report

99

Page 112: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To link a dynamic style, first select one object, or more with the same type, to which you want to link the style, and thentype the style name in the Style property entry in Report Inspector.

Notes:

You can also select the style name from the drop−down list of the Style property. However, newly created styleswill not appear in the drop−down list of the Style property until the catalog is saved and the report is re−opened.

The style you link to the report object(s) will not affect the report layout in design mode until run−time.•

Modify a style

To modify a style, do one of the following:

On the Styles tab of Catalog Browser, right−click the style you want to modify, and then click Edit Style. Add orremove the property entries according to your needs, and then click Save. You can also change the propertyvalues on this dialog.

On the Styles tab of Catalog Browser, double−click the style you want to modify to show the properties sheet,change the property values on the properties sheet.

Note:

Sometimes you may not be able to edit the property entries in the Properties sheet. In such case, on the File menu, clickOptions, click the Advanced tab, and then uncheck the Forbid editing data object properties option.

Remove a style

On the Styles tab of Catalog Browser, right−click the style you want to remove, and then click Delete.

Using Styles in Your Report

100

Page 113: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Modifying the XML Style Files

In addition to modifying the styles (style groups) in JReport Designer, you can modify the xml format styles (style groups)outside JReport Designer.

When you save the catalog, the style information will be saved to disk at the same time, the location of the related file islike below:

File Name File Description Location

1. CatalogName_stl.xmlStyle Group Structure in theCatalog

Catalog Folder (The directory where thecatalog resides)

2. StyleGroupName_stl.xsdGroup/Style information %JReportInstallRoot%\template

The CatalogName_stl.xml file keeps the style group structure information, which might be like the following sample.

The style group structure in Catalog Browser: The corresponding information in Tutorial_stl.xml:

<?xml version="1.0" encoding="UTF−8"?><StyleGroup><StyleGroup name="Default"></StyleGroup><StyleGroup name="GroupA"></StyleGroup><StyleGroup name="GroupB"></StyleGroup></StyleGroup>

The StyleGroupName_stl.xsd file keeps the group/style information, which in the above sample might be like thefollowing:

The file content of GroupA_stl.xsd:

Using Styles in Your Report

101

Page 114: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

As you can see in the above code sample, an xml style group file contains style group information, style information, andthe style property entry information. You can edit the attributes of an element, such as name, type, default, and so on.

To add a style entry, copy and paste the style information section, and then modify the attributes.

To add a style property entry, copy and paste any element line, and then modify the attributes.

To delete a style entry or style property entry, select corresponding section, and delete it.

To add a new style group,

Copy and paste an existing xml style group file. 1. Rename it using the expected name (Format: GroupName_stl.xsd). 2. Change default attribute in the GroupName element line using the expected group name, please make sure it isthe same as the group name specified in the xml style group file name.

3.

Add a new line for this group in the CatalogName_stl.xml file. For example, if the new group name is GroupC,then insert the following line to the file:

<StyleGroup name="GroupC"></StyleGroup>

4.

Do the modification work in the xml style group file (GroupName_stl.xsd). 5. Open the catalog in JReport Designer, you can see the changes. 6.

Note:

The value you type must be consistent with other attributes in the element, and can be recognized by JReportDesigner.

For example, if you want to change the FontFace property, you must type a proper font name that JReportsupport for the default attribute, such as Arial, Times New Roman, Tahoma, and so on. You cannot type stringsthat cannot be recognized by JReport, otherwise the element will not take effect at run−time.

You must be sure that the GroupName attribute must be consistent with the xml style group file name.

Take GroupA for example, in the xml file, the GroupName attribute is <xs:attribute name="GroupName"type="xs:string" default="GroupA"></xs:attribute>, then the xml style group file name should beGroupA_stl.xsd.

Using Styles in Your Report

102

Page 115: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Deploying Reports to Enterprise Server

When you deploy your reports to Enterprise Server and you have set Style Group property, Deploy Wizard will ask you totransfer the style group files.

Add the style groups and then click OK, the files get transferred.

Viewing Reports on JReport Enterprise Server

After you set up the styles for your reports in JReport Designer, you deploy your reports to JReport Enterprise Server.When you schedule the report, please make sure you have the Enable Style Group option enabled and a style groupselected.

Using Styles in Your Report

103

Page 116: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using Styles in Your Report

JReport styles can simplify your work in a lot of aspects, now let's use a simple example to illustrate how to use JReportstyles and style groups in your report.

Start JReport Designer, open the existing report Invoice.cls in Tutorial.cat. We are going to apply styles to thisreport.

1.

Open Catalog Browser, switch to the Styles tab. Create a new style group called Red under style tree root. 2. Create a new style with the following information:3.

StyleName: Title

StyleType: Label

Description: [You may leavethis field blank.]

Add the property entries and fill their values as follow:

Bold: true

FontSize: 30

FontFace: Times New Roman

Alignment: LeftCenter

Italic: true

Background: Transparent

Foreground: 0xfc5e03

Create other new styles using the information below:

Using Styles in Your Report

104

Page 117: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

StyleName: Line

StyleType: Line

LineColor: 0xfc5e03

StyleName: lblFieldName

StyleType: Label

FontFace: Verdana

FontSize: 7

Bold: true

Background: 0xfc5e03

Foreground: 0xffffff

StyleName: Box

StyleType: Box

BorderColor: 0xfc5e03

Open Report Inspector, select Invoice report root, scroll to find StyleGroup property entry in the PropertySheet, type Red in the value field.

4.

Select the report title label Invoice on the report design canvas, and then type Title for the Style property field inReport Inspector.

5.

Select field name labels Bill to, Ship to, Cust ID, No., Order Date, Required Date, Ship Date, Ship Via, Terms,Item, Product No., Unit Price, Quantity, Amount, and Total, and then type lblFieldName for the Style propertyfield in Report Inspector. Use the CTRL key to select multiple objects. If you have difficulties in selecting theobjects, please use Report Inspector as an aid.

6.

In Report Inspector tree view, select all the line objects, and then type Line for the Style property field in theProperty Sheet of Report Inspector. To select consecutive objects in Report Inspector, select the first object,hold down the SHIFT key, and then click the last item.

7.

In Report Inspector tree view, select the box object, and then type Box for the Style property field in theProperty Sheet of Report Inspector.

8.

Now we are going to create a new style group called Green. In Catalog Browser, right−click Red style group, andthen click Copy Style Group. Rename the new group to Green, double−click group Green to show the PropertySheet, and then modify the information of each style in using the below information:

9.

Title

FontFace: Arial Black

FontSize: 25

Foreground: 0xfc5e03

Line

LineColor: 0xfc5e03

Box

BorderColor: 0xfc5e03

lblFieldName

Bold: true

Using Styles in Your Report

105

Page 118: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

FontSize: 7

FontFace: Arial

Background: 0xfc5e03

Foreground: 0x000000Save the report and catalog. 10. Start JReport Enterprise Server, and then deploy the report Invoice.cls together with the catalog Tutorial to theserver.

11.

Visit the URL http://localhost:8888 to access the AccessDemo catalog, point to the report Invoice and then pickAdvanced Run.

12.

On the View Format tab, check Enable Style Group, select Red from the drop down list to the right, and thenclick Submit. The report may somewhat look like the below picture.

13.

Run the report again, this time choose the Green group as the style group.14.

Using Styles in Your Report

106

Page 119: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Limitations

The subreport in the main report works as a report object and can be applied with a Subreport type style. That is to say,the original styles (if any) applied to an individual report works no longer after this report is inserted into another report asa subreport, instead, you can apply a Subreport type style to the inserted subreport to control its appearance andpresentation, just like what you do with a normal dbfield.

Index

Using Styles in Your Report

107

Page 120: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Editing a Report

Editing a Report by Inserting Objects

You are free to add more objects into your report even after initial design work with Report Wizard. Make use of both theEdit Toolbar and the Main Menu commands to insert various objects into your report. The objects you can insert includeDBfield, Formula, Parameter, Draw Object, Special Field, Section, Group/Sort, Summary, Sub−report, Chart, Cross−tab,Text, UDO etc.

DB Field

You have already selected tables or fields to the working set when you design a report and you can access them later.

Inserting Database (DB) Fields

To insert a DBField, click DBFieldon the Insert menu or click the Insert DBField button on the toolbar. The InsertDBField dialog appears.

There are three tabs on this dialog: DBField, Formulae and Parameters. Select the first tab DBFields. It contains thetables and fields in the working set for the report. You will notice that some of the field icons have red arrows. Thisindicates that these fields are active and being used in the report. To insert a new field, select any field and click on theInsert button, position the cursor at the desired location and click.

Also you can insert DB fields from Resource Viewer. Double click the Queries icon or click on the plus icons to expandthis section to reveal the desired field. Select the desired field, and then drag it to the proper location in the report.

Related Information: User's Guide | Starting A Catalog | Setting Default Values for Objects

Formula

A formula is a symbolic statement of the manipulations you want performed on certain data. If your report contains a@Sales field and a @Cost field, for example, you may want to create a @GrossProfit formula and designate its value as@Sales − @Cost. @GrossProfit is a simple formula that tells JReport to subtract the value of the @Cost field from thevalue of the @Sales field.

Inserting Formulas

There are two ways to insert a formula.

Editor ToolbarClick on the Insert Formula button on the Editor Toolbar. The Insert DBFields dialog will appear with theFormula tab. Select a formula and click Insert.

MenuClick DBField on the Insert menu. The Insert DBField dialog appears. Click on the Formula tab, select aformula and click Insert.

Related Information: User's Guide | Starting A Catalog | Setting Default Values for Objects

Creating a New Formula

To create a new formula,

In Resource Viewer, select the Formulas node, right click and on the pop−up menu click Add Formula.

Or in Catalog Browser, under tha Data tab, select the Formulas node, right click and on the pop−up menu, click

1.

108

Page 121: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add Formula.

Or on the Insert DBField dialog, select the Formulae tab, and then click the New button.The Input Formula Name dialog appear. Specify a name for the formula and then click OK. 2. Formula Editor appears.

Edit a formula in the Formula Text area. If there is no error found after clicking the Check button, click theOK button to finish.

3.

Reference Notes:

For detailed formula syntax, please refer to User Reference | Formula Syntax.• For formula usage examples, please refer to User's Guide | Writing and Using Formulas.•

Editing an Existing Formula

You can activate the Formula Editor through the following ways:

Editor ToolbarClick on the Insert Formula button on the Editor Toolbar. The Insert DBFields dialog will appear with theFormula tab. To bring up the Formula Editor, select a formula and click on the Modify button.

MenuClick DBField on the Insert menu. The Insert DBField dialog will appear. Click on the Formula tab. Select aformula and click on the Modify button.

In Catalog BrowserSelect an existing formula, right click and select the Edit Formula menu item.

Resource ViewerUnder the Formulas node of the Resource Viewer, the formulas that can be used in the currently opened reportare displayed. Select a formula from them, right click and on the pop−up menu, click Edit Formula.

After Formula Editor appears, you can edit the selected formula in it.

Parameters

Sometimes you want to have a dynamic value entered for your report at run time. For example, you may want to inputorder date as an input parameter when running a report so that only orders on that date will be displayed. Typically,parameters are used as part of the query condition (search criteria) so that only records satisfying that parameter will beretrieved to become part of the report.

Reference Notes: For the usage of parameters, please refer to User's Guide | JReport Parameter and its Application.

Inserting a Parameter

There are three ways to insert a parameter:

Using the Edit toolbarClick Insert Parameter on the Edit toolbar in JReport main window. This will open the Insert DBField dialogwith the Parameters tab shown. To create a new parameter, click New. To insert a parameter that alreadyexists, select that parameter, and then click Insert. Move the cursor to a suitable position where you want toplace the parameter, and then click the left button of your mouse.

Using menu commandsOn the Insert menu, click DBFields. Switch to the Parameter tab To create a new parameter, click New. Toinsert a parameter that already exists, select that parameter, and then click Insert. Move the cursor to a suitableposition where you want to place the parameter, and then click the left button of your mouse.

Using Resource ViewerIn Resource Viewer, all the parameters that can be used in the currently opened report are listed under the

Editing a Report

109

Page 122: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters node. Select a parameter and drag it to the proper position in the report.

Related Information:

User's Guide | Starting A Catalog | Setting Default Values for Objects

Creating and Editing a Parameter

Using Catalog BrowserTo create a new parameter, on the Data tab, select the Parameter node, right−click and on the pop−up menu, click AddParameter. To edit a parameter that already exists, right−click a parameter under the Parameters node, and then selectEdit Parameter.

Using Resource ViewerSelect the Parameters node, right−click and on the pop−up menu click Add Parameter.

Using the Edit toolbar and MenuGo to the Parameter tab in Insert DBField dialog. To create a new parameter, click New. To edit a parameter thatalready exists, select that parameter, and click Modify.

The Create Parameter dialog appears when you click the New button. If you click Modify, the caption of this dialog willbe Edit Parameter and the Parameter Name field will be unchangeable.

Parameter NameType a name for the parameter.

Value TypeSelect a type for the parameter value, such as: Integer, Number, String, Currency, and so on.

Prompting TextScreen text to prompt the user to provide correct information for this parameter.

Editing a Report

110

Page 123: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Prompting ValuesThis is the default value for the parameter. The default value must be of the same type as the type selected inValue Type.After you type a new value into the Prompting Values text box, click the plus button above the text box, thevalue will be added to the list.When you click the cross button above the Prompting Values text box, the value in the it will be removed fromthe list.

Minimum ValueInput the minimum value (optional).

Maximum ValueInput the maximum value (optional).Note: The prompting value you input must be between the minimum value and the maximum value, or an errormessage will appear.

User Defined FormatIf you have defined the value format, for example, MMM−dd−yy, all the values you input should be consistentwith it. Otherwise there will be an error message.

Bind with Column

JReport provides such a mechanism that link each field value of Display Column with the exact value of BindColumn. When you select the field value from Display Column, the field value of Bind Column is actually sentto the query and filter the query result.

Bind ColumnThe column name used to filter the data in the database.

• Display ColumnWhen viewing a report which contains parameters, the field value associated with the column name you selectedin the drop−down list of Display Column will display in the dialog popped up at runtime. You can select a valuefrom the list to query data with the bound field.

Editing a Report

111

Page 124: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

DistinctIf the Distinct option is checked, in the Enter Parameter Values dialog only identical values list instead ofduplicate values.

• RequiredIf checked, you must supply a value before the report can run.If not checked, you can either type a value, or leave it as it is. If you do not want to see this parameter in report,make sure the field is left blank.

For more information about parameters, refer to: User's Guide | JReport Parameter and its Application.

Draw Objects

Draw Objects allows you to draw arches, ovals, boxes, round boxes and lines in your report, or to insert labels andimages into your report.

Inserting LabelsYou can insert labels by using the Edit toolbar and Menu.

Using Edit toolbar: On the Edit toolbar, click the Insert Label button.

Using Menu: On the Insert menu, click Label.

After that, move your cursor to a suitable position in the design area where you want to place the label, and thenclick the left button of your mouse.

To edit in the label text, double−click the label and edit the text in it. When you have done, click anywhereoutside the label.

Inserting ImagesYou can choose the image to be inserted from your own machine or from the internet.

To insert an image from your own machine, Copy the image to the directory where the catalog locates.1. On the Insert menu, click Image, or on the Edit toolbar, click Insert Image. The Insert Image dialogappears.

2.

Input the image name in the Image Name/URL text box, or click the Browse button to bring out theSelect a Picture dialog to choose an image. You can preview the selected image on the right panel ofthe Select a Picture dialog.

3.

Click Open to choose the image and close the Select a Picture dialog.4. Click the Insert button. Move your cursor to a suitable position in the design area where you want toplace the image, and then click the left button of your mouse.

5.

To insert an image from the internet,

On the Insert menu, click Image, or on the Edit toolbar, click Insert Image. The Insert Image dialogappears.

1.

Input the URL of the image to the Image Name/URL text box.2. If you want to see the specified image before inserting it into the report, click the Preview button and theimage will be displayed in the Preview panel.

3.

Click the Insert button. Move your cursor to a suitable position in the design area where you want toplace the image, and then click the left button of your mouse.

4.

Note: The image types supported here are: .gif, .bmp, and .jpg.

Editing a Report

112

Page 125: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Inserting Arc, Box, Line, Oval and RoundboxTo insert a draw object, on the Insert menu, click Arc (or Box, Line, Oval, Roundbox), or click on thecorresponding button on the Edit toolbar.

Then, move your cursor to a suitable position in the design area where you want to place the shape, left−clickand drag the mouse to a proper position to form the shape, and then release the mouse button.

Special Field

Special Fields

All the special fields available in JReport are listed below.

Print DatePrints today's date (or the date designated on your computer).

Print TimePrints the current time on your computer.

Fetch DatePrints the date when the data is retrieved from the database.

Fetch TimePrints the time when the data is retrieved from the database.

Record NumberPrints the record number, usually it is placed in the Details section.

Total RecordsPrints the total number of the records that can be fetched from the database by the query.

Total Fetched RecordsPrints the total number of the records that will be displayed in the report. The result of this total number isaffected by the property MaxRecords (set maximum record number you want to display for the whole report.Default −1 is to display all the records) and the Special Field Total Records.

Please see the detailed information in the section Total Records and Total Fetched Records.

Group NamePrints the group name, usually it is placed in the Group Header/Footer section.

Group NumberPrints the group number, usually it is placed in the Group Header/Footer section.

Total Group NumberPrints the total group number, usually it is placed in the group Header/Footer section.

Page NumberPrints the page number for each page.

Total Page NumberPrints the total number of pages in the report.

SQL Statement Prints the SQL statements used to execute the query.

User NamePrints the User ID used when logging in to JReport Enterprise Server.

It will return NULL in JReport Designer when you view the report, while on JReport Enterprise Server, when yourun the report, it will return the name which you have used to log on to the server.

Modified DatePrints the last modified date for the catalog.

Modified TimePrints the last modified time for the catalog.

Task ID Prints the internal task ID, which is a unique time stamp. This special field works only in the JReport serverenvironment; it returns a NULL value when running in JReport Designer.

Page N of M•

Editing a Report

113

Page 126: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Prints the page number of the total page number.

You can specify the format of this special field. Select this special field, bring out Report Inspector, find theFormat property, and then choose one item from the drop−down list.

Besides the items listed here, you can customize the format. For example, if you want to display it as This ispage x of y pages, you can input the format string in the Format text box as This is page @PageNumber of@TotalPageNumber pages.

Inserting Special Fields

Two ways are provided for you to insert special fields:

Editor ToolbarClick the right arrow on the icon to list and select the special field to be inserted.

MenuOn the Insert menu, select Special Field, choose the special field you want to insert, and then click it.

Afterwards, click in the area you would like to place this special field. When you are done, click anywhere outside thespecial field to finish inserting.

Using Special Fields (User Name, Print Date, and Print Time) in Different Kinds of Data Sources

The special fields User Name, Print Date and Print Time can be used in different data sources. For detailed informationabout it, please see the table below:

Where Condition of Query HDS (General) HDS (XML) UDS SQL File

User Name Be supported (ReportWizard).

Be supportedin theParameterpanel on theImportHierarchicalData Sourcedialog.

Be supportedon theCondition tabof ReportWizard.

Be supportedin theParameterspanel on theAdd UserData Sourcedialog.

Be supportedin the SQLstatement.

User Nameused in aformula

Be supported (ReportWizard).

Not besupported.

Not besupported.

Not besupported.

Not besupported.

Print DateBe supported (ReportWizard).

Not besupported.

Not besupported.

Not besupported.

Be supportedin the SQLfile.

Print Dataused in aformula

Be supported (ReportWizard).

Not besupported.

Not besupported.

Not besupported.

Be supportedin the SQLfile.

Print TimeBe supported (ReportWizard).

Not besupported.

Not besupported.

Not besupported.

Be supportedin the SQLfile.

Print Timeused in aformula

Be supported (ReportWizard).

Not besupported.

Not besupported.

Not besupported.

Be supportedin the SQLfile.

Editing a Report

114

Page 127: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Total Records and Total Fetched Records

The relationship among MaxRecords, Total Records and Total Fetched Records is listed in the table below:

Value of MaxRecords Condition Result of Total Fetched Records

−1 −−−− Total Fetched Records = Total Records

A certain number Total Records <= MaxRecords Total Fetched Records = Total Records

A certain number Total Records > MaxRecords Total Fetched Records = MaxRecords

The Special Field Total Records and Total Fetched Records can be used in formulas. Please see the example below.

In the catalog browser, create a formula named RecordNum like this:

if(totalfetchedrecords==totalrecords)""+totalrecords+" records are fetched from the database, and all the"+totalfetchedrecords+" resords are displayed in the report."else""+totalrecords+" records are fetched from the database, and only"+totalfetchedrecords+" records are displayed in the report."

Insert RecordNum into the report header of a report.

1.

Set MaxRecords = −1 in the Report Inspector. Run the report, the returned value of the formula RecordNummight be like this:

55 records are fetched from the database, and all the 55 records are displayed inthe report.

2.

Set MaxRecords = 40 in the Report Inspector. Run the report, the returned value of the formula RecordNummight be like this:

55 records are fetched from the database, and only 40 records are displayed in thereport.

3.

Note: The two special fields Total Records and Total Fetched Records are calculated just after fetching data andbefore laying out the report. So they are not available to use in where condition, but available in report layout.

Section

To insert a section, first move the mouse cursor to the section you want to insert. Next, right click the section and clickInsert Section After to insert a section of the same type.

Other ways of inserting sections:

Edit ToolbarClick on the Insert Section button.

MenuOn the Insert menu, select and click Section.

After the above steps, this will insert a similar section right below your selected one.

Group/Sort

Records in a report are usually organized into groups based on certain criteria.

You can add or modify Group/Sort in the following three ways:

Editing a Report

115

Page 128: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Edit ToolbarClick the Insert Group button.

MenuOn the Insert menu, select and click Group/Sort.

Then, the Group Wizard will pop up.

On the Group Wizard dialog, there are two tabs: Group and Sort.

With the Group tab, modify the criteria to define multi−level groups. The Sort tab allows you to organize the informationwithin each group by sorting records within the section.

Reference Notes : User's Guide | Developing Reports with Report Wizard | Group & Sort Tab.

Summary

A summary generates a count, average, sum, standard deviation and other features for your data. The Summaryfunctions are based on how you grouped your data.

Inserting, Creating and Editing a Summary

You can insert, create and edit summaries with Resource Viewer, Catalog Browser, Edit Toolbar or Menu.

Resource ViewerIn Resource Viewer, expand the Summaries node, all the summaries that can be used in the currently openedreport are listed there.

To insert a summary into the report, select a report, and drag it to the proper place of the report.

To edit a summary in the Resource Viewer, select a report, right click it, and on the pop−up menu click EditSummary.

Catalog Browser

To edit a summary, on the Data tab, select a summary, right−click it, and on the pop−up menu, click EditSummary.

To create a new summary, on the Data tab, select the Summaries node, right−click it, and on the pop−up menuclick Add Summary, or select the Summaries node or any summary, on the toolbar, click the NewSummary button. Then the New Summary dialog appears.

Remember that activating the New Summary dialog from Catalog Browser is not for a specific report, and youwill see all the resources under the catalog you can use for a summary.

Editing a Report

116

Page 129: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select a field for the summary to compute from the Connection or Formulas directory. Click on the > button nextto Sum On.

The next field to be placed must be a field you selected from the Group/Sort or the Group/Sort tab. It means ifyou selected field A and B from a table, you must either put field A or B in the Break By menu. You may do it byfinding your field in the Connection or Formula directory and clicking the > button next to the Break By menu.

At last, select a function from the Function list for your field to be summed by.

Click the OK button to finish. A menu will pop up for you to name your new summary. You may also select aprevious name under the Summaries drop down menu.

Click the Apply button to apply your changes of the existing summary or add the new summary to the catalog.Click the OK button to apply your changes or add the new summary to the catalog, and at the same time, toclose the New Summary dialog. Click the Cancel button to cancel your action. Click the Help button to see thehelp document for this dialog.

Related Information: User's Guide | Starting A Catalog | Setting Default Values for ObjectsEdit Toolbar and MenuThe Insert Summary command is enabled only after you select a field to be computed. Therefore the commandhere is oriented for a specific report. That is, the dialog reveals only the resources the current report uses. Selecta field to be summarized in a report. This field must be from the Working Set. Click on the InsertSummary button on the Edit Toolbar or on the Insert menu, select and click Summary. Then the InsertSummary dialog appears.

On the Insert Summary dialog, if you want to create a new summary, press the Create a New summary radiobutton, select a function to use and the field by which the records are grouped. Click Insert to place your newsummary in the report.

Editing a Report

117

Page 130: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If you had selected a field in your report, all the existing summaries on this field in the catalog will be revealedand you can choose one instead of creating a new one.

Sub−report

In JReport, one report is based on one query or something that functions like a query (UDS, Stored Procedure, SQL file,etc.). So how does one combine several reports with different queries into one report? JReport has introduced thesub−report concept. One or more reports (referred to as the sub−reports) can be inserted into another report (referred toas the main report).

Inserting a Sub−report

You can create a sub−report in the following two ways.

Edit ToolbarClick the Insert Subreport.

MenuClick Subreport on the Insert menu.

The Insert SubReport dialog appears. This is similar to the one that appears when you use the Subreport template tobuild reports. Please refer to User's Guide | Develop Reports from Report Wizard | SubReport tab section for thedetailed instructions.

The difference here is that when you finish filling in the above fields, click OK and drag the mouse cursor to the designarea, you will see a box attached to the cursor. Position the cursor to the section you would like to place the sub−report inand click your mouse.

Embedded Sub−report

Beginning with version 4.0, JReport enables you to embed sub−reports as actual reports rather than as objects. Thusproperties used to control page breaks (e.g. CanCrossPage, FillWholePage, OnNewPage, etc.) can be applied tosub−reports. Thus an Embedded Sub−report has the following capabilities:

Page Header and Page Footer included − The embedded sub−report can function just like a main report. Youcan add database fields or formula fields into the Page sections or control the section properties with formula ordatabase fields.

Nested Embedded Subreports − An embedded sub−report can contain another embedded sub−report (asub−subreport).

Page Break Properties − The properties including FillWholePage, OnNewPage, KeepGroupTogether,CanCrossPage etc. work in Embedded Subreports.

Layout Flexibility − Other objects or another embedded sub−report can be laid out to the right or left of anembedded sub−report.

Page number, total page number etc. within the embedded sub−report.• Page level formulas.•

Using Embedded Sub−report

When you insert a sub−report object into the main report, you will find a property of the sub−report in Report Inspectorcalled Embedded. The default value is false which means the sub−report is inserted as an object, the section propertiesused to control page break in the sub−reports such as FillWholePage, OnNewPage, UnderLay, KeepGroupTogether,CanCrossPage, etc. do not work, and the properties cannot be controlled by formulae. To make the sub−report work asan independent report, set the Embedded property to true as shown below.

Editing a Report

118

Page 131: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Next, we will take three reports − ReportA, ReportB, ReportC − as examples to make you understand better.

Case 1: Using the FillWholePage property

In ReportB, set FillWholePage to be true for DetailPanel in Report Inspector. 1. Insert ReportB into the GroupFooterPanel of ReportA as a subreport, and make sure the Embedded property isfalse.

2.

3. View ReportA, you can see that the FillWholePage property in ReportB does not work.

Editing a Report

119

Page 132: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Go to Report Inspector and set the Embedded property to be true for Subreport.4. 5.

View ReportA again, the FillWholePage proterty works well.

Case 2: Using the nested Embedded subreport

1. Insert ReportC into ReportB as a subreport in the Detail Panel.

Editing a Report

120

Page 133: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

2. Set the Embedded property to be true, then view ReportB as below.

Insert ReportB into ReportA as a subreport in the GroupFooterPanel. In ReportB, set FillWholePage to be truefor Detail Panel. In ReportA, set CanCrossPage to be true for GroupFooter Panel, and Embedded to be true forSubreport.

3.

View ReportA. All the page footers and headers of the three reports are displayed, the special fields included,and the page break controlling property works also.

4.

Editing a Report

121

Page 134: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Index

Map

Map is a special visible object in JReport Designer. The map object contains a picture and some areas, which are boundwith groups in the report. It can be inserted into the report that has groups.

Inserting a Map

You can insert a map in the following two ways:

Editor ToolbarClick the Insert Map button.

MenuClick Map on the Insert menu.

Then you will get the following dialog.

Editing a Report

122

Page 135: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating a Map

JReport Designer provides two methods to create a map: getting data from database and creating manually. This iscontrolled by the From Database check box.

Method 1: The From Database check box is selected. Please choose items from the database for the options on thedialog. Please note that the database used here must support image object.

On the Map tab, type in the name of the map. It can be any name you like.1. Choose a position for the map. It can only be inserted into report footer/header or group footer/header exceptinner groups. The map will be inserted into the first visible footer/header.

2.

Select an image, which will be the background of the map, from the Image Source drop−down list. 3. Choose the available summaries from the left to the right list. The values of the summaries added here will bedisplayed in the areas of the map in the view mode.

4.

If you want JReport Designer to show the labels and summaries in the design mode, select the check box at thebottom of the dialog.

5.

Switch to the Area tab. Choose the corresponding item of each option from the drop−down list.

Note: When you choose the items, please pay attention to the following options on this dialog,Name: Please choose the Group−by field as the name. If there are more than one Group−by field in thereport, it will be determined by the map position. If you put the map in the report footer/header, pleasechoose the Group−by field of the report. If you put the map in the group footer/header, please choose theGroup−by field which has the highest nest−level of the group in which the map is put in.

Coords: There are three types of area shapes: Rectangle, Circle, and Polygon. You can choose thecoordinate values from the drop−down list. However, the value of each area is a record listed in thedatabase in its own format. For more information, please refer to Reference | JReport Windows and

6.

Editing a Report

123

Page 136: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Dialogs | Map Dialog.FillColor: Please choose the 0xffffff type to specify the color. This type is also used to set the bordercolor of the area.

Choose the alt type and the hyperlink for the map if you like. For detailed information, please see Reference |JReport Windows and Dialogs | Map Dialog.

7.

Set the properties of the area border according to your own requirements. 8. Click the Finish button to generate the map.9.

Method 2: The From Database check box is cleared.

On the Map tab, type in the name of the map. It can be any name you like.1. Choose a position for the map. It can only be inserted into report footer/header or group footer/header exceptinner groups. The map will be inserted into the first visible footer/header.

2.

Clear the From Database check box.3. Select an image which will be the background of the map from the Image Source frame.

You can select an image from your own machine or from the internet.

To select an image from your own machine, click the ... button and then select an image from the Select aPicture dialog. Please note that only the images that under the directory where the catalog locates can beselected.

To select an image from the internet, type the URL of the image into the text box.

4.

Click the Edit button behind the Name box.

Please note that, if you have not filled the Name box before, after you finish the options on the Map tab, theEdit button might be disabled. In this case, please press ENTER after you key in the name of the map to enablethe Edit button.

5.

An Edit Area will pop up after clicking the Edit button. You can edit your map according to your ownrequirements here. For the detailed information of the options on the Edit Area dialog, please see Reference |JReport Windows and Dialogs | Map Dialog − Edit Area.

This area has two modes: Edit Mode and Insert Mode, and the first button on the toolbar controls switchingbetween the two modes. When it is pressed down, Edit Area is in the insert mode, and now you can insert areasinto the map, while when the button is up, Edit Area is in the edit mode, and now you can edit the specified area.

6.

AreaType

Draw (Insert Mode) Move (Edit Mode)Change Size/Shape

(Edit Mode)

Rectangle

Hold down the left mousebutton as you move themouse pointer to theposition you want andrelease the mouse button.

Select it by clicking theborder of it. When themouse pointer becomesa four−headed arrow, youcan move the rectangleto the new position.

Move the mouse pointerover the border of therectangle, and the mousepointer will become adouble−headed arrow.Drag the border of therectangle to change itssize.

Circle

Hold down the left mousebutton as you move themouse pointer to theposition you want andrelease the mouse button.

Select it by clicking theborder of it. When themouse pointer becomesa four−headed arrow, youcan move the circle to thenew position.

Move the mouse pointerover the border of thecircle, and the mousepointer will become across. Drag the border ofthe circle to change itssize.

Polygon Choose the positionwhere you want to startto draw the polygon, and

Select it by clicking theborder of it. When themouse pointer becomes

You can not change thesize of the polygon, butyou can change its

Editing a Report

124

Page 137: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

click to get the first point.Move the mouse pointerand get every point of thepolygon by clicking theleft mouse button. Thepoints will be connectedby lines automatically.When you move themouse pointer to thepoint at which closes thepolygon, a blue squarewill appear. Click the leftmouse button now tofinish the polygon. If youwant to undo your lastline, click the right mousebutton.

a four−headed arrow, youcan move the polygon tothe new position.

shape. Move the mousepointer over the border orthe points of the polygon,and the mouse pointerwill become a cross.Choose a point on theline and drag it to createa new point. Choose apoint of the polygon anddrag it to move theposition of the point. Ifthere are three points onone line, the middle onewill be deletedautomatically.

Note: To move the area, move the mouse pointer close its border in the area, when the mouse pointer changesto a four−headed arrow, drag the area to the new position.

You can set the values of the properties Fill Color, Border Color, Border Style, and Border Width in both InsertMode (before you draw the areas) and Edit Mode (after you insert the areas).

In Edit Mode, change the name of each area to the corresponding name of the group.7. After editing the areas, click Close on the File menu. A message box will pop up to ask you whether to save thechanges to the map. Click Yes and you will return to the Map dialog. Set the Alt Type and the URL for the mapon the Area tab if you like.

8.

Click Finish to generate the map.9.

The Edit Area provides you a method to draw areas directly on the background, and of course you can also set theoptions on the Area tab to finish your map. To do like this, after you have finished the options on the Map tab, switch tothe Area tab, do the following steps,

Type a name for the area you are going to add to the map (it must be one of the group name in the report andmust have the same spelling as the group name), and then press ENTER to confirm.

1.

Specify the shape for the area. It can be Rectangle, Circle, or Polygon.2. Specify the position and size for the area.

RectangleX: The X−coordinate of the rectangle's top left point.Y: The Y−coordinate of the rectangle's top left point.Width: The width of the rectangle.Height: The height of the rectangle.

CircleX: The X−coordinate of the circle's center.Y: The Y−coordinate of the circle's center.R: The length of the radius.

PolygonX: The X−coordinate of one of the polygon's point.Y: The Y−coordinate of one of the polygon's point.

3.

Note: Every time after you type a number, please press ENTER to confirm.

Set the other options on this tab according to your own requirements, such as Alt Type, URL and options of thearea border. Please remember to press ENTER after you type in the width of the border.

4.

When you finish setting the options for the area, click the Add button to add it to the map. 5.

Editing a Report

125

Page 138: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To delete an area form the map, select the area you want to delete from the Area drop−down list, and then clickDelete.

6.

To modify an area, select the area you want to modify from the Area drop−down list, modify the options for thearea, and then click the Repair button to apply the changes to the area.

7.

Click the Finish button to generate the map. 8.

An example

Create a report like this: using the Left Alignment template, on the Data tab, choose the Customer table into theReport data source list. On the Display tab, select Customers_Customer ID, Customer Name, and AnnualSales into Report Field list. On the Group tab, group the record by Customers_Region. On the Summary tab,make a sum of Annual Sales and break the field by Customers_Region. Click the Finish button to generate thereport.

1.

Bring out the Map dialog. On the Map tab, name the map as Map. Clear the From Database check box andchoose an image from the drop−down list as the background of the map. In this example, usmap.gif is used.Select Sum_Annual Sales4 from the left to the right list. Select the Show label and summaries in the designmode check box.

Note: usmap.gif is not an image in the catalog tutorial.cat provided by JReport Designer. You can put any imageyou want to the same directory as the catalog of the report you are designing, and then you can choose it fromthe drop−down list.

2.

Click the Edit button to get the Edit Area dialog:

Now you are in Insert Mode. Choose Polygon as the shape type. Setting the following properties of the border

3.

Editing a Report

126

Page 139: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

style:

Border Color: 0x000000Border Style: SolidBorder Width: 2 (Please press ENTER after you key in the border width)

Using the way of drawing a polygon to draw the outlines of CO, WA, and MO on the map. The default names ofthem are Area1, Area2, and Area3. Switch to the Edit Mode, and change the names of each area: changeArea1 to CO, Area2 to WA, and Aera3 to MO (Please press ENTER every time after you input the name of thearea).

Please note that in the Insert Mode, the name shown in the Area Name box is always the name of the area,which you are going to insert. So if you want to specify the area name in the Insert Mode, please key in thename in the Area Name box before you draw it. Do remember to press ENTER every time after you key in thearea name.Click Close to save the changes to the map and return to the Map dialog.4. Specify the Alt Type of the map and the URL of the areas on the Area tab if you like. Click Finish to generate themap.

5.

In Report Inspector, set the Invisible property of the map label to be true. Set the following properties of thesummary:

Font Face: Times New RomanFont Size: 8Bold: trueForeground: 0x0000ff

6.

Click View, you can see the map in view mode like this: the value of the summary Sum_Annual Sales4 isdisplayed in each inserted area.

7.

Please note that you can also create the areas by filling the options on the Area tab.8.

Editing a Report

127

Page 140: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Notes

Map object contains label, summaries and area objects, and one map only contains one label.• In design mode, areas are invisible.• In design mode, no matter where you put the label and the summaries, in the view mode, they will be displayedat a fixed position.

Map feathers can only work in the HTML and DHTML format report.•

Index

Index

Barcode

Inserting a barcode

You can insert barcode object into your report to view or print them with your report.

To insert a barcode, on the Insert menu, click Barcode.

Then you will get the following dialog.

Creating/edit a Barcode

You use the Barcode Expert to create or edit a barcode.

Select a barcode data source from the Barcode Resource frame. The data source of a barcode can bedatabase data, formulas, parameters, or a string typed by a user.

1.

Editing a Report

128

Page 141: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select the barcode type from the Symbology drop down list, which can be UPC−A, UPC−E, EAN−13, EAN−8,Code39, Code128 and Codabar.

Note: If you choose Code128, you have to specify a Barcode128Type from the 128 Sets drop down list, whichcan be CODE128−A, CODE128−B, CODE128−C, and Auto.

2.

Select the barcode scale mode from the Scale Mode drop down list, which can be Mils (0.001 inch), Metric (0.01millimeter), and Points (1/72 inch). The scale mode you select is used as the unit for the values of Quiet Zone,Narrow Width, Supplement, Hight, and Ratio.

3.

Specify Quiet Zone size for the barcode. Quiet zone refers to the space around the barcode that must contain nodark marks. Most of symbology requires quiet zone preceding and following barcode.

4.

Specify the bar width in the Narrow Width box.5. Specify the supplements if necessary.

Note: CODE39, CODE128 and Codabar don't have supplements.

6.

Specify the height for the bar height in the Height box.7. Specifies the width ratio of the thick bar to the thin bar in the Ratio box. The ratio box can have only 2 effectivevalues, 2.0 and 3.0, any ratio values are not equal to 2.0 or 3.0 will be granted as 2.0.

Note: This setting only works for CODE39 and Codabar.

8.

You can specify the default value for the barcode in the Default Message box. The value you specify will beused for the barcode in design mode.

9.

Specify whether to include check digits using the Check Digits Enable option.10. Specify whether to display the barcode numbers together with the barcode using the HR Display option. Thisoption is enabled only for CODE39, CODE128, and Codabar.

11.

Cross−tab

Cross−tab is an object that summarizes data and presents the summaries in a compact row and column format.See also: User's Guide | Developing Reports with Report Wizard | CrossTab

Inserting a Cross−tab

To create a cross−tab, please follow the steps below:

Insert a cross−tab using either of the following ways: Editor ToolbarClick on the Insert Crosstab button.

MenuOn the Insert menu, click Crosstab.

1.

Then the Cross Tab dialog appears.

In the Fields panel, it lists the query used by the report and the available formulas for the cross−tab. Select fieldsfrom the Fields panel and click the buttons in the middle of the dialog to add the selected fields to the Columns,Rows and the Aggregations panel respectively. Click the button to exchange the fields in the Columns and

Rows panel.

2.

Click and on the top of each panel to change the order of the highlighted fields.

Click on the top of each panel to delete the highlighted fields.

3.

In the Columns and Rows panel, select a field, click the Direction column of the selected field, and then choosea sort type from the drop−down list for the field; click the Color column of the selected field, and then choose acolor form the drop−down list to set the background color for the selected field.

4.

In the Aggregations panel, select a field, click the Aggregation column, and then choose a function from thedrop−down list for the selected field. In the Label column, you can type in some strings to indicate the meaningof the function and you can modify the properties of the label in Report Inspector.

5.

Besides the totals of the rows and columns, you can also add new calculations to the cross−tab. Select an6.

Editing a Report

129

Page 142: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

aggregation in the Aggregations panel, click the button on the top of this panel, and the Special

Aggregation dialog appears. For detailed information about the special aggregation, please see the next part ofthis section: Adding Special Aggregation to a Cross−Tab.In the Orientation panel, you can specify the layout of the aggregation field and specify the number ofrows/columns to be displayed (the value is −1 by default which means all the rows/columns will be displayed).

7.

The Row Total on Top and Column Total on Left options allow you to specify where to display Totals. And youcan specify to repeat the column heading on every page by checking Repeat Row Header, and specify to keepthe column heading together with data by checking Avoid Orphan Header.

8.

Note: The adding, removing, and ordering operations above can also be completed by dragging and dropping.

Reference Note: User Reference | Reporting Features | Cross−Tab

Adding Special Aggregations to a Cross−Tab

Special Aggregation refers to calculations of percentage, permillage or difference between

sub−total and grand total,• sub−total of inner group and sub−total of outer group,• values of aggregation field and sub−total,• or values of aggregation field and grand total.•

To define a special aggregation, please do as below,

On the Cross Tab dialog, select an aggregation field in the Aggregations panel and then click the button on

the top of this panel. The Special Aggregation dialog appears.

1.

Specifies a position for the special aggregation. Options are as follows:

Row − The special aggregation will be placed into the row total cell of the cross−tab.Column − The special aggregation will be placed into the column total cell of the cross−tab.Aggregate − The special aggregation will be placed into the aggregation field cell of the cross−tab.

2.

Position Available Calculations

Row Row sub−total and grand totalRow sub−total of inner group and row sub−total of outer

Editing a Report

130

Page 143: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

group

ColumnColumn sub−total and grand total Column sub−total of inner group and column sub−totalof outer group

Aggregate

Value of aggregation field and column sub−totalValue of aggregation field and row sub−totalValue of aggregation field and grand totalNote: The Break By option is disabled in this case.

Items on the Break By drop−down list will be varied according to the position of the special aggregation. Itspecifies the first number (sub−total) that will be used in the calculation.

3.

Numbers that form the calculation of the special aggregation are determined by the Break By option and theRefer to option. All the available items are displayed on the Refer to drop−down list according to the item youselected in the Break By option. Select one as the other number of the calculation.

4.

From the Function drop−down list, select a type of function. Options are as follows: Percentage, Permillage, orDifference.

5.

Click Ok when you finish to define a special aggregation and you can see that a new field is added to theAggregations panel below the aggregation field you selected in step 1.

6.

View the report, you will get the values of the special aggregation.7.

Text

Like a word processor, a Text object is an object that holds text (a single character, a single word, entire sentences, or anentire letter). In addition, a Text object can hold database fields and formula fields as well.

Inserting a Text Object

Using either of the following ways to insert a Text Object in a report:

Edit ToolbarClick the Insert Text button.

MenuOn the Insert menu, click Text.

Then drag your mouse cursor to the design area and a text box will be attached to it. Move and click the text box into theposition where you want to insert the text.

Editing a Text Object

Double click on any text box. The following editing window appears:

Set the tab stop by clicking on the tab stop icon until you see the specific tab you want. Then click the ruler to set the tabstop.

Editing a Report

131

Page 144: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Use the blank area to type the text as you desire. Click the mouse cursor anywhere outside of the editing window tofinish the work.

Moving Text Object

Click on the text object to highlight it. Place your mouse cursor on the text so that a cross−icon appears. Click and dragthe text box to the position where you would like to move the text object.

Inserting DB Fields into a Text Object

Double click on the text object. After the editing window appears, click the Insert DBField button on the toolbar or on theInsert menu, click DBField. Select the field to be inserted from the Insert DBField dialog, and click Insert. Then dragyour mouse cursor to the design area with a box attached to the cursor. Move and click the box into the desired positionin the editing window to insert the DBField you just selected.

Editing Properties of a Text Object

To edit the properties of a text object, right click the text object. On the pop−up menu, select Properties. You can see thetext object you selected is highlighted in Report Inspector. Then change the properties such as geometry, color etc.

Reference Notes: User Reference | Reporting Features | Text Object

Data Objects

JReport provides four types of data objects: Section, Table, Cross−tab and Chart.

In the previous versions, JReport supports to build a multi−query report by inserting standalone reports as a sub−report. Beginning with Version 4.5, another way to implement a multi−query report is available by binding the data objects withdifferent queries. Compared with sub−reports, data objects have the following advantages:

The report performance is improved. Data Object is a kind of light weight sub−report. Not like a sub−report,when a data object is processed, JReport Engine takes it as an object instead of a standalone report. With adata object, something which must be processed for a sub−report will not be executed.

Data objects can be converted to query bound objects, which easily and effectively combines multiple queriesinto one report.

You have to open the sub−report when you want to modify it. However, you can modify the objects contained inthe data object directly.

Inserting Data Objects

To insert a data object, go to Insert menu, and select one of objects in the menu item: Section, Table, Chart orCross−tab.

The data object can be inserted into any area of the report while designing. Having selected one of data objects, theReport Wizard dialog will be launched. With the wizard, you can build the query bound to the selected data object. Complete the necessary specifying following the wizard and click the Finish button. Then drag your mouse cursor tothe design area, move and click the attached text box into the desired position to insert the data object into thereport.

Below are examples of different types of data objects:

Section•

Editing a Report

132

Page 145: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Table

Not like the Section data object, position of objects contained in Table is not floating but fixed in the table.

Note: When you use the date/time type field to group the data of the table data object, Special Function cannotwork.

Chart•

Cross−tab•

Editing a Report

133

Page 146: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Modifying Data Objects

You can modify properties of objects contained in Data Object with the same way as other common objects in reports.

Example 1: Suppressing columns in the Table data object

Suppose the Table has four columns and the third column will be suppressed.1. We will use formula to control the Suppress property. Please note that Data Object only supports constantformulas to control properties. Constant formulas do not change with records, which have a constant value forthe entire report. In this example, we build formula "suppresscol" as following:

if (@customerID > 10) thenreturn trueelsereturn false

Where customerID is a parameter of the integer type, which allow you to input a number at runtime.

2.

Select the third column. In Report Inspector, set the value of Suppress to be formula suppresscol. 3. View the report. Input the parameter value. When the value is larger than 10, the third column with ContactFirst Name will be suppressed.

4.

Example 2: Repeating the table header in every page.

Select Header Panel of the Table data object in Report Inspector.1. Go to the Repeat property, set the value to be true.2. When you view the report, the table header will display in each page.3.

Example 3: Hiding horizontal lines in the Table data object

Select Detail Panel of the Table data object in Report Inspector.1. Go to the ShowBottomLine property, set the value to be false. 2. View the report, you will see that the horizontal line has been hidden.3.

You can also hide horizontal lines in Header/Footer of a Table data object with the same way as in example 3.

Example 4: Adding/removing objects to/from columns of a table data object.

When you place an object inside a table data object, this object is now independent and doesn't belong to any column. If you want to manipulate the object together with one column as a whole , you can follow the procedure below (here weinsert a label):

Insert a label. On the Insert menu, click Label, and then place the label inside the first column of the table. 1. Add this label to column. Right−click the label, and then select Add To Column on the pop−up menu. Thelabel has been added to the column now. If you right−click the label again, you will find Add To Column in greyand Remove From Column enabled. You can use Remove From Column to remove it from the column.

2.

Manipulate the object together with one column as a whole. If you want to delete the whole column, in ReportInspector, scroll to find and select the proper column name, and then delete this column. You will find the whole

3.

Editing a Report

134

Page 147: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

column is deleted, including the label you've just added.

Note: The objects that can be added to a column or removed from a column include Summaries, Labels, Parameters,and Special Fields.

Example 5: Controlling the property of background with a constant formula.

Create the following formula and named it as color:

if ( @anumber >5)return "0xc0c0c0"elsereturn "0xff0000"

Where anumber is a parameter of the Integer type.

1.

Select a DBField of the Cross−tab data object.2. In Report Inspector, set the Background property of the selected DBField with formula "color".3. Go back to select the cross−tab data object and right click on it. Select Refresh to refresh the cross−tab.

Note: It is a limitation to refresh the cross−tab when you use a formula to control a property of data object.

4.

Run the report. Input "5" as the parameter value, the can see the background color of the selected DBField hasbeen changed.

5.

Notes and Limitations:

Only PSQL query and File query are supported, others like UDS, EJB, XML are not supported. Sub−links in filequery are not supported.

Data Object has no pages, say that the result is not separated into pages. It contains only groups and details. Page level formula is not supported. For example, the statement "pagenumber" can not be included in aformula.

Data object can not be inserted in a sub−report.• UDO (User Defined Object) can't be inserted in a data object.• DHTML output is not supported. • Embedded data objects are not supported. That is to say you can not insert a data object to another dataobject.

Drill−down feature is not supported in a data object.• When exporting to Postscript, some lines in the Table data object will be missing.• Dynamic group/sort is not supported, group/sort on a formula field is not supported. •

Converting Sub−reports into Data Objects

Sub−reports can be converted into data objects. The converted sub−reports will be proceeded with better performanceas data objects. In addition, the objects in the sub−report can be modified directly in the report instead of opening thesub−report.

Take the following steps to convert sub−reports into data objects:

Open the report which contains sub−reports.1. Right click on the sub−report. Select Convert to Data Object in the popped command menu. Then theobjects in the sub−report display.

2.

Notes and Limitation:

The sub−report can't include UDO, Chart, Cross−tab and embedded sub−report.• If the sub−report includes data on the page footer, the data will be missing. If a geometry object is attached tothe page footer, it will also be missing.

Editing a Report

135

Page 148: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The data source of the sub−report can only be PSQL. Other types of data source, such as File SQL, StoreProcedure, UDS etc. are not supported.

Sub−reports can only be converted into the Section data objects.• If you set property "Embedded" of a sub−report to be true or ShowSubHeaderFooter of a main report to be true,page headers of the sub−report will be converted to data object headers. Otherwise, these headers will bemissing as well as their children.

Query Editor

Query

JReport Designer helps you build various professional reports based on queries (or those similar to queries). One reportis built on only one query. Therefore, you must first make a query: select tables, place criteria or restrictions on the datato extract the data you want from a database. For example, instead of viewing all the customers that your company uses,you can view just customers from USA. To do this, you may specify the condition that limits the results to records whoseCountry field is "USA".

Recall that when you walk through with Report Wizard, the first three tabs are: Data, Joins and Conditions. They areactually building a query first for you. Below is to build a query with our Query Editor.

Creating a New Query

To create a new query,

Right click the item Query in Catalog Browser, and then click Add Query on the pop−up menu, or select theitem Query then click the New Query button on the toolbar. Then a dialog box appears prompting you to give thename for the query to be created.

1.

After defining the Query name, the Query Editor window pops up.2. On the Query menu, click Add Table, or on click the Add Table button on the toolbar. The Add Table dialogappears.

3.

Select a schema in the Schemas panel. Click the Load Tables button and the tables in the selected schema aredisplayed in the Tables panel. Choose the tables you want, and then click Add to add them to the query. ClickDone to dismiss the Add Table dialog.

For the SQL Server database, you can choose the database catalog first from the DatabaseCatalogs drop−down list before you select a schema.

4.

Check the columns to be selected as working set in the query. Click * to select all.5. In the below QBE columns to specify conditions.

On the Query menu, click Filter to further narrow down your criteria with your conditions in Filter.

6.

Reference Notes: Please go to User's Guide | Developing Reports with Report Wizard | Conditions and Display Tab formore information about QBE and Filter.

Editing a Query

Query Menu

To access the query menu, in Catalog Browser, right click on a query under the Data tab, and select Edit Query. In theQuery Editor window, click on the Query menu. Below are the descriptions of the menu items.

Add TableTo add a table,

Select Add Table to bring out the Add Table dialog.1. Select a schema from the Schemas panel and then click the Load Tables button. All the talbes in the2.

Editing a Report

136

Page 149: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

selected schema are displayed in the Tables panel.

For the SQL Server database, you can choose the database catalog from the Database Catalogsdrop−down list before you select a schema.Select one or more tables and click the Add button.3. Click the Done button to dismiss the Add Table dialog.

Based on the PSQL options that are selected, JReport Designer will automatically join the new tabletogether with the previous tables.

4.

Click the Arrange button or click Arrange Tables on the Query menu to organize these tables.5.

Note: If you add a table with the same name as the existing one in the catalog, the Input Table Name dialog willpop up for you to define a new name for the table.

If you've pre−defined joins saved in the catalog, then the pre−joins will automatically be applied to the tablesyou've added according to the pre−join settings.

For more information about Pre−join feature, please refer toUser's Guide | Starting A Catalog | Pre−join

UnionThe Union option enables to combine specified records from more than one query into one result set.

Creating a union query

To create a union query, Right click on a selected query ( here we call it primary query), select Edit Query.1. On the Query Editor, select Union from the Query menu, and then click create.2.

When creating a union query, please note that the selecting order should refer to the order in the primary query.The SQL type and number of the selected columns should match those in primary query.

For example, in primary query you selected two columns, the first one is of Integer type, the second one is ofString type. Then in the union query, you should also first select a Integer column, then select a String typecolumn. See the primary query "union1" and the union query "union11" shown as below:

Editing a Report

137

Page 150: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Modifying the existing union information

To modify the existing union,

Right click on a primary query, select Edit Query.1. On the Query Editor, select Union on the Query menu, and click select.2. In the Union list, select the Attribute column to specify the type of union.

: UNION. No duplicate records are returned.

3.

Editing a Report

138

Page 151: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

: UNION ALL. All records will be returned.To remove a union from the query, select a union in the Union list, and then click the left−headed arrow.To add a unoin to the query, select a union in the Queries list, and then click the right−headed arrow.

4.

Note: A union query can't support formulas and parameters.

Show Table NamesThis gives you the option whether or not to show the table in the Criteria menu.

With Table Names Without Table Names

Show Mapping NamesThis option allows to show the full name of the field (with table name).

Without Mapping Names With Mapping Names

Auto JoinAuto Join will join tables together based upon the default criteria in Auto Join. The default criteria are PrimaryKeys with LikeNames, Foreign Keys and Like Column Names.

FilterAdd criteria in the Filter structure.

To place criteria, click the button beside the Expression text box. Select the field in the pop−up dialog and set theoperator.

For details, refer to the chapter Developing Reports with Report Wizard | Condition & Display Tab.

Select DistinctWhen enabled, SQL SELECT statements are treated as SELECT DISTINCT statements. The query will searchfor identical records and ensures to return them only once instead of returning duplicate records from thedatabase.

Ignore Predicate If Parameter Value Is NullIf enabled, condition items (cells in QBE or lines in Filter editor) that have null value parameters will be ignoredwhen creating SQL statements at runtime. That is to say, those predicates will not appear in the SQL statement.

Join ColumnsJoin the highlighted columns in tables together .

Current Query OptionsChange Auto Join and showing options.

Column Menu

In the Query Editor window, click the Column menu, three items appear: Create Computed Column, Add Formula Fieldsand Delete Column.

Editing a Report

139

Page 152: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create Computed ColumnSelect Create Computed Column, you will see the following dialog.

The functions here are not of JReport system. They are from the connected database you use.

Note: if you change your data source, some of these functions may no longer exist. For each database, thedifferent supported functions list will be returned. The functions listed can help you in writing an expression.

icon: Add the numbers or fields together in the Expression menu.

icon: Subtract numbers or fields together in the Expression menu.

icon: Multiply numbers or fields together in the Expression menu.

icon: Divide numbers or fields together in the Expression menu.

icon: Equate fields together.

icon: Place quotations on long character strings or name that have blanks in them (example: place

quotes on values like "New York" or "Washington DC"). icon: Place fields together in the same Expression menu. (Example: "New York" || "Washington DC").

icon: Place your fields in parentheses.

Add Formula FieldsClick here and there is a menu which lists all the formulas.

Editing a Report

140

Page 153: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select a formula and Click Add. The formula will be placed into the Criteria menu. It means that you canreference a formula in the query.

Delete ColumnSelect a column in the Criteria menu and click it to delete. To undelete, find the field in the table and place acheck mark beside it.

Editing the SQL Statements

Click the SQL button, a window will show the SQL statements used to execute the Query.

Editing a Report

141

Page 154: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You can edit the query statements in the text area.

To check whether it can be parsed back to the structured psql query correctly, click Parse. No matter whether the querystatement is valid or not, a message box will pop up to show you the result.

To see whether it can be successfully processed, click Execute.

To accept the changes you have made, click OK. JReport Designer will parse and execute the query statements anddispose the Query Text Editor window.

If there are some parameters in this query, the default values of them will be used to construct statement.

Note: If JReport Designer fails in parsing or restoring the query statements, a message box will pop up to ask youwhether to apply the changes anyway. If you choose yes, a statement string will be recorded in this psql query. But afterthat, the structured statement may be not tally with the statement string.

Previewing a Query

You can preview the query you have created. To do this,

On the Query Editor window, click the Preview button, and then the Preview Option dialog appears,1.

Editing a Report

142

Page 155: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Max Records − Specifies the maximum number of records for you to preview. Records PerPage − Specifies the number of records that can be displayed on one page when you preview thequery.

When the Max Records radio button is checked, both the Max Records option and the RecordsPerPage option will take effect, and when the All radio button is checked, all the records will be displayed whenyou preview the query, and the Max Records option will be disabled.

Set the options on this dialog as you like.

Note: The values shown in the text boxes as soon as the Preview Option dialog pops up are the default values,which can be specified on the PSQL tab of the Report Option dialog (to display the Report Option dialog, clickthe Options item on the File menu). Click OK and then the Preview dialog appears. Please note that if the query has parameters, when you click theOK button, the Enter Parameter Values dialog will be displayed first. Enter the parameter value and then thePreview dialog will pop up to show the corresponding records.

Click the buttons First Page, Previous Page, Next Page and Last Page to browse the records. If the type of theresult set is TYPE_FORWARD_ONLY, the last page button will be disabled until you have browsed the last page.

You can print the result set by clicking the Print button on the toolbar. And before printing, click the PrintPerview button to preview the result set. Go to the File menu, click Page Setup to set up the page parameters.

2.

Click Close on the File menu to dismiss the Preview dialog.3.

Note: On the Preview dialog, the JTable is used to display the result set. When you open the dialog, the result set iscached, and when you close the dialog, the result set is released.

Editing a Report

143

Page 156: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating Subquery in Query Editor

In the earlier version of JReport products, if you wanted to use subselect statement in an SQL statement, e.g. SELECT *FROM TBLA WHERE COLA = ANY(SELECT COLB FROM TBLB), you have to type in the whole subselect statement inthe Condition dialog. Beginning with Version 4.0, JReport allows you to create the subquery via Query Editor.

Supported Subquery Syntax

1. Quantified Predicate

A quantified predicate compares a value with a set of values.

Syntax:expression−−−−+− = −−+− SOME −−+−− ( subselect ) +− <> −+ ANY −−−+ +− ! = −−+ ALL −−−−+ +− < −−+ +− > −−+ +− <= −−+ +− ! > −−+ +− >= −−+ +− ! < −−+

The subselect must specify a single result column and can return any number of values, whether null or not null.

When ALL is specified, the result of the predicate is:

True if the result of the subselect is empty, or if the specified relationship is true for every value returned by thesubselect.

False if the specified relationship is false for at least one value returned by the subselect.• Unknown if the specified relationship is not false for any values returned by the subselect and at least onecomparison is unknown because of a null value.

When SOME or ANY is specified, the result of the predicate is:

True if the specified relationship is true for at least one value returned by the subselect.• False if the result of the subselect is empty, or if the specified relationship is false for every value returned by thesubselect.

Unknown if the specified relationship is not true for any of the values returned by the subselect and at least onecomparison is unknown because of a null value

Examples:

SELECT qty FROM sales WHERE qty>= ALL (SELECT qty FROM sales)

SELECT BUYERID, ITEM FROM ANTIQUES WHERE PRICE != ANY (SELECT PRICE FROM ANTIQUES);

2. EXISTS Predicate

The EXISTS predicate tests for the existence of certain rows.

Syntax:

− [ NOT ] EXISTS−−(subselect)

The subselect may specify any number of columns, and

Editing a Report

144

Page 157: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The result is true only if the number of rows specified by the subselect is not zero.• The result is false only if the number of rows specified by the subselect is zero• The result cannot be unknown•

Example:

SELECT DISTINCT pub_name FROM publishers WHERE EXISTS (SELECT * FROM titles WHERE pub_id= publishers.pub_id AND type = 'business')

3. IN Predicate

The IN predicate compares a value with a set of values.

Syntax:

expression−−−−+−− [NOT] IN −−+−− ( subselect )

In the subselect form, the subselect must identify a single result column and may return any number of values, whethernull or not null.

Example:

SELECT distinct pub_name FROM publishers WHERE pub_id IN (SELECT pub_idFROM titles WHERE type = 'business')

Using Subquery in Query Editor

To use subquery in Query Editor, please follow the steps below:

Create a query named mainin in the catalog, add the table Customers and select the following columns:Customers_Customer ID, Customer Name, Customers_City, Customers_Region.

1.

Click Filter on the Query menu to open the Search Condition dialog. In the first Expressions text box, click the button to select the column Customers_Customer ID, and select in asthe operator. Go to the second Expression dialog, click the button and on the pop−up Expressions dialog, click theSubquery tab.

2.

Select an existing query in the catalog to be the subquery. To edit the selected query, click the Edit Subquery button.To create a new subquery, click the New Subquery button.

For the example, click on New Subquery button to create a new query named subin, add the table Orders,select the column Orders_Customer ID , and add a condition 'Ship Via' = 'Express Delivery' in the SearchCondition dialog.

3.

Click OK, the subquery subin will be added into the second Expression text box of the main query mainin.4. Click OK to close the Search Condition dialog, and click the OK button in the Query Editor to accept thechanges.

5.

Changing the Query Name in Report Inspector

Sometimes after you design a report, you may want to use another query to run the report. Instead of building anotherreport from scratch, JReport Designer allows you to change the query name directly in Report Inspector. In this case, youshould make sure that the new query uses the same tables as the original one. In addition, we do not recommendapplying this method before you are familiar with JReport Designer.

By default, the query name is not editable.1.

Editing a Report

145

Page 158: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To make the properties editable in Report Inspector, open the File menu and select the Options item. 2. Click the Advanced tab on the Advanced tab on the Report Option dialog, and uncheck Forbid changingquery.

3.

Back to the Report Inspector, you will find that the query name is editable.4.

You can select another query in the drop−down menu, make sure that the fields in the report match each other,otherwise there will be some errors.

5.

Showing SQL Statement of a Query

To show SQL statement of a query, expand the Query item under Data Tab in Catalog Browser, right click a query and

Editing a Report

146

Page 159: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

on the pop−up menu, click Show SQL.

Showing Properties of a Query

To show properties of a query, expand the Query item under Data tab in Catalog Browser, right click a query and selectProperties on the pop−up menu or click the Expand icon on the Catalog Browser toolbar.

Removing a Query

To remove a query, select the query to be removed under the Data tab in Catalog Browser, then press Delete on yourkeyboard, or right click a query, on the pop−up menu, click Delete. You are prompted that modifying the query will impactthe reports using it, accept this to confirm the removal.

Index

Dynamic Query

Instruction

You can build queries using JReport Query Editor or imported external SQL file. But in either way, the queries should bepre−defined. Yet sometimes you want to specify the query at runtime. For example, in catalog, you may build a query"select customers_id from customers", however, at runtime, You may want to fetch data from another table customers1,the query should be replaced according to the table index, like "select customers_id from customers1". Starting fromversion 5, JReport increases a new feature called Dynamic Query. With it, the queries could be dynamically generatedand you could fetch data from different tables at runtime.

Dynamic Query Interface

The dynamic query interface SQLStmtCreator is stored in the archive files − JREngine.zip under%JReportDesignerInstallRoot%\lib. It is contained in the package toolkit.db.api, and can be applied to any existing queryin the catalog.

How the Dynamic Query Interface Works

The following flowchart illustrates how the interface works when creating a dynamic query. The QueryInfo object will bepassed from JReport Engine to the interface as an input, and the completed SQL statement should be returned from theinterface. Then this completed SQL statement will be sent to the database eventually to get result set for the report.

Editing a Report

147

Page 160: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Methods of Dynamic Query Interface − SQLStmtCreator

This interface is very simple with only one method:

getSQLStmt(QueryInfo queryInfo);•

It receives information of a query and returns a SQL string. QueryInfo is a container that contains all information to builda SQL string. Users can call getXXX() methods to get all information step by step.

The structure of QueryInfo is described as follows:

ConnectionInfoDriver, URL, User, Password, DateFormat, TimeFormat, TimestampFormat, TransactionIsolation level,ReadOnly, QualifiedNamePattern, ExtraNamePattern, EncodingPattern

Column arrayAll the selected columns. Elements in this array are ColumnInfo object. ColumnInfo contains Mapping Name,Real Name, Table Info and Expression if this is a computed column.

Tables(array)Selected tables. Elements in this array are TableInfo objects. TableInfo contains Mapping Name, Real Name,Correlation Name, Schema, Catalog.

Joins(array)Elements in this arrays are JoinInfo objects. JoinInfo contains Column from, Column to, Operator, Join type,etc.

QBEs(array)Part of the where condition. It is retrieved from the query builder. Elements in this array are QBEInfo objects. QBEInfo contains ColumnInfo with QBE condition bound to this column.

Ands(array)Part of the where condition. It is retrieved from advanced search condition in the query builder. Elements in

Editing a Report

148

Page 161: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

the array are AndInfo objects. AndInfo contains Left expression, Operator, Right expression, and Logic. SubLinks(array)If the dynamic query is for a subreport, then the SubLinks is used to the additional where clause to filter data. Itis the way for how to link this query to the main report. Elements in this array are composed of SubLinksInfoobjects. SubLinkInfo contains Column, Operator and Value.

Parameters (array)Parameters used to create query, and users need to encode parameters that database can recognize. Theelements in this array are ParameterInfo objects. ParameterInfo contains Name, Type and Value.

OrderBys(array)Elements in the array are OrderByInfo objects. OrderByInfo contains Column and sorting direction.

Other InformationQuery name, IsDistinct, WherePortionString etc. The value of WherePortionString is set viaJRengine.setWherePortionString().

Reference Notes : JReport Javadoc toolkit.db.api.SQLStmtCreator interface. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to browse the file online.

Using Dynamic Query Interface

1. Compile the java file that you write and append the path.

You should add the compiled java file with the valid path to the classpath of JReport.bat.

2. Set value of the connection property SQLStmtCreator.

The dynamic query interface is set as a property in the Connection object in the catalog.

In JReport Designer, launch Catalog Browser, expand the Connection node, select the connection, click on theExpand button to display the property of the connection. You will find the SQLStmtCreator property, which is used toset the real class name of this dynamic query object.

Editing a Report

149

Page 162: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For example, you implemented the interface by the class UserSQLStmtCreatorImpl, then input the property value as"UserSQLStmtCreatorImpl;@para1;@para2". Para1 and Para2 are parameters used to specify criteria while creatingthe query.

For example, school year which will change at runtime, it needs to be inserted to the report template so that the inputvalue for these parameters at run−time could be passed into the dynamic query interface via QueryInfo object. And thusa corresponding SQL statement could be returned by this interface.

Please note that binding parameters are not supported by this feature.

Note: By default, you are not allowed to change the property values in Catalog Browser. To make the property valueseditable, go to the File menu and select Options..., uncheck forbid editing data object properties under theAdvanced tab in the Report Option dialog. Then, go back to Catalog Browser, highlight the column name that you wantto edit to change or set the property values.

3. Set value of the query property EnableSQLStmtCreator

In Catalog Browser, in the Properties list of a highlighted query, there is a property named EnableSQLStmtCreator, whichindicates whether this query uses the dynamic query interface to get result set or not. When it is set as true, the querycould be re−generate at runtime using the dynamic query interface.

Editing a Report

150

Page 163: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Example: Using a dynamic query

We here provide a demo code implementing the dynamic query inerface − SQLStmtCreatorImpl.java under%JReportDesignerInstallRoot%\help\pro−meterial. This file is also available on our web site athttp://www.jinfonet.com/kbase/kbase.htm (manual related materials).

This demo is to change the table name for the query sent to the Database. Specifically, when you run the report,for the tableIndex parameter, you enter 1, the query will be dynamically changed to Customer1. If you do notenter anything, you will get the result set from the Customer table.

Open this demo source code, you will see some sample methods that you can change to dynamically control thequery's clauses like

Select FromWhereOrder by...

1.

To compile SQLStmtCreatorImpl.java you need another fileMappingNameFinder.java (%JReportDesignerInstallRoot%\help\pro−meterial). You can find this file alike on ourwebsite.

Compile MappingNameFinder.java:

javac MappingNameFinder.java

2.

Compile SQLStmtCreatorImpl.java, (suppose JReport Designer is installed under C:\JReport and the class filesof the MappingNameFinder.java are under c:\jreport\help\pro−material):

3.

javac −classpath C:\jreport\lib\JREngine.zip; c:\jreport\help\pro−material; SQLStmtCreatorImpl.java

Modify %JReportDesignerInstallRoot%\bin\JReport.bat to add the path of SQLStmtCreatorImpl into the classpathin JReport.bat. For example, SQLStmtCreatorImpl is under %JReportDesignerInstallRoot%\help\pro−meterial,

4.

Editing a Report

151

Page 164: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

then add the class as below:

"c:\jdk1.3.1\jre\bin\java.exe" "−Dinstall.root=C:\JReport" −classpath"c:\jreport\help\pro−material;C:\JReport\lib\report.zip;C:\JReport\lib\resource.zip;C:\JReport\lib\JREngine.zip;... Start up JReport Designer with the modified JReport.bat. 5. Open report DynamicQuery.cls, and launch Catalog Browser. Select the connection, unfold its property list byclicking the Expand button, set the value of the SQLStmtCreator prorperty asSQLStmtCreatorImpl;@tableIndex. Parameter "tableIndex" is used to specify which table will be selected atruntime.

6.

Select query "DynamicQuery" in Catalog Browser, and set the value of its property EnableSQLStmtCreator astrue.

7.

Save the report and view it. 8. The following dialog pops up.

When you input "1" as the value of tableIndex, the report will run on table "Customers1", and when you inputnothing as the value of tableIndex, the report will run on table "Cutomers".

9.

Index

Index

Editing a Report

152

Page 165: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Editing a Report For DHTML UseReports developed by JReport Designer can be deployed to a stand−alone JReport Enterprise Server or webapplications integrated with JReport Enterprise Server, and then be viewed and analyzed in DHTML format. SomeDHTML features require a report to be pre−configured in JReport Designer before being deployed to JReport EnterpriseServer.

This chapter covers these special cases in JReport Designer:

Switching on/off the drilling feature of the summaries for DHTML• Showing detailed information for comprehensive data using master/detail reports• Setting display names for DHTML sort/filter/drill functions• Pre−defining DHTML sort & filter conditions• Using DHTML control objects in your reports•

This chapter assumes that you already have some knowledge of JReport's DHTML features. Please refer to the relatedtopics of JReport Enterprise Server: JREntServer Manual User's Guide − Viewing Reports in Dynamic HTML.

Switching on/off the drilling feature of the summaries for DHTML

As we know, when you view reports in DHTML, you can drill to see the detail records of a summary by clicking on thesummary.

You can simply disable the drilling feature for the summaries, in JReport Designer, select the summary that you want todisable its drilling feature, in Report Inspector, set the DrillToDetail property to false. By default, the drilling feature isenabled.

Notes:

The feature of switching on/off the drilling of the summaries only applies to DHTML, and it will take effect inJReport Designer view mode and other view formats.

The Drill−to feature is not available in subreport, as a result, in subreport, this feature is not available either.•

Showing detailed information for comprehensive data using master/detailreports

In most cases, your reports are affiliated with one another. Every report may emphasize one or more aspects. Somerelationships may be set up so that the user can browse from one report to another through the relationship "channels" that you create.

Such inter−report relationship network can be achieved by setting up "Join" and "WherePortion" conditions between tworeports. You can use one report to hold comprehensive report data, and the other to show detailed information on aspecific topic, where the "Join" or "WherePortion" conditions are created.

Reports can be joined together to constitute a master−detail report group. Normally, a master report should hold morecomprehensive data, while the detail reports hold some related detail information. A detail report can be a master reportof another report. In this way, by setting up more and more pairs of master−detail reports, many reports can be joinedtogether, and, a report chain is formed.

Setting up a pair of master−detail reports

To set up a master−detail relationship between two reports,

In JReport Designer, open the report that you want to use as the master report. 1.

153

Page 166: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select an object as a trigger to load the detail report. A trigger is an object defined in the master report to triggerthe detail report when running the master report in DHTML, which includes DBField, label, image, and so on. Todetermine which object can be used as a trigger in the master report, please refer to the section below.

2.

Set the properties for the trigger object to create joins between the detail report and the master report, and filterthe detail report by setting up the where portion conditions.

Open Report Inspector, scroll the Properties sheet to find the property DetailReport, click the button in the rearof the property entry.

On the Select Detail Report dialog, you are going to set three major properties for the trigger object: the detailreport name, join condition, and the where portion conditions.

3.

Editing a Report For DHTML Use

154

Page 167: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Firstly, specify the detail report name from the Report drop down list. A detail report can be any report in thesame catalog as the master report.

Secondly, specify the join condition between these two reports. The join between the master report and detailreport can have only one condition. For example, the join can be like, (Detail report) Product ID = (Master report)Product ID, therefore, the join condition should be:

(Detail RPT) expression1 operator (Master RPT) expresion2

To make the join more meaningful, expression1 should be a column or record level formula in the GROUPsection of detail report; and expression2 should be a column or record level formula in master report DETAILsection, this is because the master report is normally used to present comprehensive data, and use the detailreport to present more detailed information.

The operator can be one of ?? ?lt;? ?gt;? ?lt;=? ?gt;=? ?lt;>? The two expressions should have the same datatype, say, if data type of the expression for detail report is date type, a date type expression for master reportshould be selected. The expression of master report and the expression of detail report can belong to differenttables.

Thirdly, if you want to further filter the detail report data, specify the where portion conditions in the Conditionspanel.

The where portion condition should be:

(Detail RPT) expression1 operator (Master RPT) expresion2

The expression1 is a column or record level formula of detail report and the expression2 is a column orrecord level formula of master report.

Editing a Report For DHTML Use

155

Page 168: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Column Description

Column In DetailSelect a given field from the drop down list, all fields in detail report willbe available.

Op Select an operator, which can be =, <>, >, >=, <, and <=.

Column InMaster

Select a given field from the drop down list, all fields in master reportwill be available.

More

More operations are in the drop down list of the More field. To appenda new condition, select AND or OR from the drop down list of the lastcondition line. The AND and OR are logical relationships between twoadjacent conditions. To insert a new condition after the currentcondition, click Insert Row. To delete the current condition, click DeleteRow.

Both join and where portion work together as conditions. If you want to set a single condition, you can use join; if youwant to set a group of conditions, you can use where portion together with join condition. The relationship between joincondition and where portion condition is AND, which would be Join condition AND (where portion conditions).

If the two report are using the same encoding and DB settings, please check the option Detail report uses the sameencoding and DB settings as that of the master report. If you don't check this option, when the detail report istriggered at run−time, you will be prompted to specify the encoding and DB settings for the detail report.

After a set of Master/Detail reports are defined in JReport Designer and deployed to JReport Enterprise Server, they canbe viewed in DHTML. The detail report supports all the DHTML operations, such as sort, filter, drill, search, and so on.

Objects that can be used as a trigger

The objects that can be used as triggers in the master report include images, labels, fields, and UDOs.

Setting display names for DHTML sort/filter/drill functions

Why display names?

In JReport DHTML, you can drill report data, find specific text, sort the report data on certain DBFields, or filter the reportdata using filter conditions. As shown in the snapshot below, when you are doing sort or filter operations, you will have towork with DBField mapping names.

Editing a Report For DHTML Use

156

Page 169: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

This sometimes may be inconvenient, especially when the DBField mapping name is obscure, or when the number ofDBFields in the report is large.

JReport Designer provides you with Display Name Customization function, with which you can easily define the columnnames as you desire, and, limit the number of DBFields that will appear on the Select Field drop down list.

As shown in the following illustration,

The DBField mapping names have been changed to a more readable form, and the number of the available candidateshas been reduced to four.

Customize display names

Customizing display names is done in JReport Designer. To do this,

Open your report in JReport Designer. 1. On the Edit menu, click Edit Display Name.2. On the Edit Display Name dialog, set your display names for your DHTML sort, filter, drill, and search functions.The mapping list controls the field display names, and the number of the mapping rows determines the number

3.

Editing a Report For DHTML Use

157

Page 170: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

of mapping names to be displayed on the Sort/Filter panel in DHTML. The order of the mapping list determinesthe field list order of the Select Field drop−down list on the Sort/Filter panel in DHTML.

Select a DBField from the Resource Name column, in the Display Name column, you can specify a name orchoose a formula for the selected DBField. If you want this display name to apply to DHTML Sort panel, Filterpanel, Drill panel, or Search panel, mark the check box under each column respectively.

To add a new mapping row, click the Add button (the button with a plus sign).

To remove a row, click the Remove button (the button with a cross sign).

To adjust the order of the mapping rows, if Auto Sort is checked, the mapping rows will be sorted in alphabeticorder (case sensitive, e.g., Abc, adc, Bcd, abc is sorted as Abc, abc, adc, Bcd), and if Auto Sort is unchecked,use the Move Down and Move Up buttons to move a selected mapping row manually. When you finished editing, click OK to accept the changes.4.

Notes:

If you don't define any display names for any columns, say, leave the mapping list intact (empty), all resourcenames will be listed where display names are needed. This is to support reports created by previous version ofdesigner.

If any display names are defined but not applied to Sort or Filter panel, they will not be listed on the Sort or Filterpanel. That is to say, the Sort and Filter panel lists only the columns whose display names have been definedand applied.

NLS on Display Names

If your report are developed with national language support and you want to display local language for the display namesin your report, you can save the report with NLS.

To save NLS, on the File menu, click Save NLS.

After the report is saved and deployed to JReport Enterprise Server, view the report in DHTML, the display names are inlocal language.

Editing a Report For DHTML Use

158

Page 171: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Pre−defining DHTML sort & filter conditions

JReport DHTML allows you to re−sort data, or, filter certain records at run−time. Additionally, you can define sort and/orfilter conditions so that the report will directly show the data you desire when the DHTML pages are loaded. Theseoperations are done in JReport Designer.

Note: The defined sort and filter conditions will not affect the preview result in JReport Designer.

Define sort conditions

To define DHTML sort conditions,

1. On the Edit menu, click Edit Sort and Filter.

2. On the Edit Sort and Filter dialog, switch to the Sort dialog.

Editing a Report For DHTML Use

159

Page 172: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

3. In the Fields list, select the field that you want to sort on, click on the button with a right arrow to add this field tothe Sort By list. If you want to sort more than one field, do one of the following:

♦ Repeat this step accordingly.

♦ Or, select the fields that you want to sort in order, and then click the Add button.

Please note that the order in which the fields are listed in the Fields list is the order that they appear inthe Sort By list.

♦ Or, drag the fields one by one from the Fields list to the Sort By list.

4. To change the order of the fields in the Sort By list, do one of the following:

♦ Select the row that you want to change, and then click the Up button to move up one row, or click theDown button to move down one row.

♦ Or, select the row that you want to change and drag it over the row to a new sort order.

5.

Editing a Report For DHTML Use

160

Page 173: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To remove a row from the Sort By list, click the button with a left arrow.

6. Click OK.

Note:

To select multiple, sequential fields, click on the first field and hold down Shift while clicking on the last sequentialfield. To select non−sequential fields, hold CTRL while clicking on desired fields.

After the report with the pre−defined sort conditions are saved and deployed to JReport Enterprise Server, the conditionswill take effect immediately when the report is loaded in DHTML window.

Note: The defined sort conditions will not affect the preview result in designer, nor the result produced from being run informats other than DHTML.

Define filter conditions

To define filter conditions,

1. On the Edit menu, click Edit Sort and Filter.

2. On the Edit Sort and Filter dialog, switch to the Filter dialog.

3.

Editing a Report For DHTML Use

161

Page 174: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Enter the search conditions that will be used to generate the report by filling the condition fields.

Column: Select a given field from the drop down list.Operator: Select an operator, which can be =, !=, >, >=, <, and <=.Value: Select a value from the drop down list, or type it directly in the Value field.More: More operations are in the drop down list of the More field. To append a new condition, select AND or ORfrom the drop down list of the last condition line. The AND and OR are logical relationships between two adjacentconditions. To insert a new condition after the current condition, click Insert Row. To delete the currentcondition, click Delete Row.

4. Click OK.

After the report with the pre−defined filter conditions are saved and deployed to JReport Enterprise Server, the conditionswill take effect immediately when the report is loaded in DHTML window.

Using DHTML control objects in your reports

You can insert control objects into your report in JReport Designer, and, in JReport DHTML, use it to accomplish certaintasks. For instance, you can insert a button in JReport Designer, associate an operation with the button's onclick event,and when you view this report in DHTML and click this button, the operation that you defined will take place.

To insert a control object,

On the Insert menu, point to Control Object, and then select the object.1. Place the object on the report design canvas.2. Double click the object to show Report Inspector, and then modify the object properties.3. Save the report, and then deploy it to JReport Enterprise Server.4.

Let's see an example, open a report with multiple pages, take the steps above to insert a control object into the reportheader section, modify its properties as the following:

FontFace: VerdanaValue: NextOnclick: nextPage()

Save and deploy this report to JReport Enterprise Server, and then view it in DHTML format.

Click this button to see the result, your result may be more or less like the following screen shot.

Editing a Report For DHTML Use

162

Page 175: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The control objects available in JReport Designer are: Text field, Password, Checkbox, Radio Button, Hidden Field,Button, Dropdown List, and List.

The Event that the object supports are: OnFocus, OnBlur, OnClick, OnDblClick, OnMouseDown, OnMouseOver,OnMouseMove, OnMouseOut, OnKeyPress, OnKeyDown, and OnKeyUp.

Notes: The inserted control object is invisible in the view mode in JReport Designer.

Index

Editing a Report For DHTML Use

163

Page 176: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Charts

About Chart

Charts organize and visualize data and make it easy for users to see comparisons, trends, and patterns in data. A chartin JReport is based on the data retrieved from database and represented by a report. It represents the report data in avisually straightforward form.

Reference Title Location

A Detailed Reference of JReport Charts Reference | Reporting Features | Chart

Chart Platform Reference | Reporting Features | Chart

Chart Coordinate Paper Reference | Reporting Features | Chart

Chart Legend Reference | Reporting Features | Chart

Chart Label Reference | Reporting Features | Chart

Creating a Chart

How is data represented in a chart

A report helps you to represent the data in the database, while a chart helps you to represent the data retrieved by areport in an other visual appealing form.

To create a report, you must first develop a report to retrieve the expected data from database, and then you can createa chart base on DBFields, groups, summaries, and formulae in a report.

You can create a chart from a report that contains only simple DBFields.

You can also create a complicated chart from a report that contains DBFields, groups, summaries, and even formulae.

164

Page 177: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Normally, DBFields, summaries, and formulae in a report are represented in a chart using chart data markers, andgroups are usually used to produce category names and data series names. DBFields also can be used as categorynames.

As you know the groups in a report are nested, and JReport can only create chart base on at most two groups. If youhave more than two groups in your report, which two groups that the chart will use depends on the chart position. If youplace the chart in the report header section (or report footer section), then the first two groups with highest nest−level willbe used. If you place the chart in the group section (header or footer), then only the first two groups whose nesting−levelsare lower than and adjacent to the group where the chart resides are available for constructing the chart.

For example, suppose that you have four groups in your report: date1, Last Name, Customer_Customer ID, andOrders_Order ID, where the groups are nested, such as group date1 contains group Last Name and group Last Namecontains group Customer_Customer ID, and so on. If you place the chart in the Report section, then the summaries andformulae in the groups other than the highest and second highest level groups, date1 and Last Name in this case, will notbe able to be used in the chart. If you place the chart in the group section of group Last Name, only summaries andformulae in the group Customer_Customer ID, and Orders_Order ID will be used.

Charts

165

Page 178: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create a chart

On the Insert menu, click Chart. 1. Click the Chart Type tab on Chart Wizard dialog, select the type you want to use. 2. Click the Report Data tab, select the place where you want to put your chart. You can choose to put the chart inthe header or footer section of report, or that of the selected group panel.

3.

You can create the chart base on groups and summaries or on plain DBFields. Do one of the following:

If you want to create a chart base on group and summaries, click the Group sub−tab, select and add thesummary, the group−by DBField will automatically be added to Category Names, and the Series Names, if any.

If you want to create a chart base on DBFields, click the Field sub−tab, select and add the fields to CategoryNames and Show Data separately.

4.

Click OK when you finish.5.

For information about Chart Wizard , please refer to Reference | JReport Windows and Dialogs | Chart Wizard.

Create a combination chart

A combination chart uses two or more chart types to emphasize that the chart contains different kinds of information.

The method of creating a combination chart is more or less the same as the way to create a normal chart.

On the Insert menu, click Chart. 1. Click the Chart Type tab on Chart Wizard dialog, select the chart type Combo. Specify Type1 and Type2 fromthe drop−down menu in the Sub−type panel.

In this example, we choose Bar as Type1 and Line as Type2.

2.

Click the Report Data tab, select the place where you want to put your chart. You can choose to put the chart inthe header or footer section of report, or that of the selected group panel.

3.

Click the Field sub−tab, select and add the fields to Category Names and Show Data separately.

As the chart shows in the picture above, we add DBField Quarter to Category Names and DBFields Price,Quantity, and Sales to Show Data.

As you can see, DBFields Price and Quantity are shown as bars, and Sales is displayed in a line.

You can also add formulae to the Group Names field or the Show Data field.

4.

Click OK to insert the chart.5.

Changing the Type of a Chart

Charts

166

Page 179: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Change the chart type at design time

Do one of the following to change the chart type:

Select the chart and right−click it.1. Click Chart Wizard on the pop−up menu.2. Select the chart type you want for your chart on the Chart Type tab and then click OK. 3.

For detailed information about chart types, please refer to Reference | Chart | A Detailed Reference of JReport Charts

Change the chart type at run−time

You can also change the chart time at run time. Just view the report, right−click the chart area, and then choose a charttype from the pop−up menu.

Notes:

Changing the chart type in view mode will also affect the Design mode, say, when you get back to design mode,you will find the chart type has also been changed.

Since the chart data source is not changeable at run−time, combination chart can only be changed tocombination chart, and non−combination chart can only be changed to non−combination chart. The pop−upmenu will list the changeable chart types according to this rule.

While changing a type of 2−D chart to another type of 2−D chart, or a type of 3−D chart to another type of 3−Dchart, all the previous properties will be kept.

Nevertheless, when changing a type of 2−D chart to another type of 3−D chart, the properties of the Z axis, theY−Z wall, and Floor of the 3−D chart will be set to default values (since a 2−D chart does not have the Z axis, theY−Z wall, or Floor), and all other properties will be taken from the 2−D chart. When changing a type of 3−D chartto another type of 2−D chart, the properties of the Y2 axis of the 2−D chart will be set to default values (since a3−D chart does not have the Y2 axis).

Changing the Display, View, or Placement of a Chart

Change the display of walls, gridlines, axes, or legends

You can choose to display or hide walls, gridlines, axes, or legends in your chart. Some of these items are available onlyin certain types of charts.

To display or hide walls or gridlines in a chart,

1. Double−click to select the coordinate paper in which you want to display or hide walls or gridlines.

2. Right−click the coordinate paper and click Format Walls on the shortcut menu.

3. Select the Show Walls check box if you want to display walls. Clear the check box if you want to hide walls.

Select the check boxes for the gridlines you want to display. Clear the check boxes for the gridlines you want tohide.

Note: Pie charts do not have walls or gridlines.

To display or hide axes in a chart,

1.

Charts

167

Page 180: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Double−click to select the coordinate paper in which you want to display or hide axes.

2. Right−click the coordinate paper and click Format Axes on the shortcut menu.

3. Select the check boxes for the axes you want to display. Clear the check boxes for the axes you want to hide.

Note: Hiding an axis hides the labels and tick marks along the axis. Pie charts do not have axes.

You can display or hide a chart category legend or chart series legend, or both. However, you cannot delete a legend inJReport Designer.

To display or hide legend in a chart,

1. Double−click to select the legend you want to display or hide.

2. Right−click the legend and click Format Legend on the shortcut menu.

3. Select the check boxes for the legends you want to display. Clear the check boxes for the legends you want tohide.

Reference Note:

Reference | Chart | Chart Coordinate Paper − ShowWalls, ShowXGrid, ShowYGrid, ShowZGrid, ShowAxisX,ShowAxisY, and ShowAxisZ Reference | Chart | Chart Legend − ShowLegend

Add labels to a chart as chart title, value axis title, or category axis title

A chart label can be used as chart title, part of a chart legend entry, value axis title, category axis title, or more; you caninsert a label anywhere inside a chart. You can use a label as a chart title, value axis title, or category axis title; just placethe label to the expected position.

To add a label to a chart,

Select the chart platform inside which you want to add a label. If you have difficulties in selecting the chartplatform, please refer to section Selecting a Chart and its Elements for more information.

1.

Right−click the chart platform and click Add Label. 2. Enter text for the label in the Text property entry in Report Inspector, and then press ENTER. 3. Double−click to select the label, and then move the label to the position you want.4.

Zoom or size the chart display

You can change the size of a chart display,

Select the chart coordinate paper object. 1. Right−click it and pick Format Coordinate Paper on the shortcut menu. 2. On the Coordinate Paper tab, drag the slide bars to scale up or down the display size of the chart along the X orY axis.

3.

Reference Note : Reference | Chart | Chart Coordinate Paper − ScaleX, ScaleY, and ScaleZ

Charts

168

Page 181: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Rotate a chart

You can change the rotation for a 3−D chart.

Select the chart coordinate paper object. 1. Right−click it and pick Format Coordinate Paper on the shortcut menu. 2. On the Coordinate Paper tab, drag the slide bars to adjust the rotation angle of the chart around the X and Yaxis.

3.

Note: You can also rotate a 3−D chart using mouse; just click and drag the chart plot area inside the coordinate paperwhen it's under selection. If the chart starts to move instead of rotating, right−click the chart coordinate paper and clickRotation Mode.

Reference Note : Reference | Chart | Chart Coordinate Paper − AngleX and AngleY

Formatting Axes, Legends, and Other Chart Elements

Select a chart and its elements

Selecting a proper chart elements in JReport Designer is a rather important skill, which can help you access variouschart formatting tools effectively.

To select a chart, just press and hold the left button in the empty area, move your mouse pointer to draw a rectangleacross the chart object, and then release the mouse button. You can see the green box around the object with 8 handles,which means the object is now selected.

To select a chart element, such as chart coordinate paper, chart legend, and so on, double−click the element.

Notes:

Please take note that, in JReport Designer, directly clicking the chart object may not effectively select the chart. • If you have already selected a chart element, just single−click the chart element you want to select.•

Move or resize chart elements by using the mouse

You can move or resize most of the chart elements (such as chart, coordinate paper, and legend) by using the mouse.You can move and resize the legend with mouse but you can neither move nor resize the legend entries reside in thelegend area individually.

Click the chart element you want to move or resize. 1. To move an element, point to it, when the pointer changes to a four−headed arrow, drag it to another location.

To resize an element, point to a sizing handle, when the pointer changes to a double−headed arrow, drag thesizing handle until the element is the size you want.

2.

Change the size, color, and appearance for the chart elements

You can change the size, color, and appearance for most of the chart elements.

For the borders, you can change the border styles, border colors, pen styles, pen colors, pen thickness, pentransparency, end caps, and line joints for a border. You can also specify whether the border is outlined, or whether the

Charts

169

Page 182: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

border dashes are automatically sized, if the border is drawn with dashes.

For the backgrounds, you can change the background coverage sizes, fill patterns, colors, gradients, textures, and evenimages.

To format a chart element,

Double−click to select the chart element you want to format. 1. Right−click the chart element, click the formatting command on the shortcut menu. Fox example, if it is acoordinate paper, then you can select Format Coordinate Paper command from the shortcut menu.

2.

On the Background tab, select the options you want. If necessary, you can use the Pen Style tab on the ChartPen & Fill Effect dialog, which can be accessed using the Advanced button.

To specify the border style or border color, use the corresponding drop down lists.

To specify the border pen properties, such as pen style, pen thickness (border thickness), pen color (bordercolor), end caps, and so on, click Advanced, and then select the options on the Pen Style tab.

To specify the background size of coverage, using the insets slide bars.

To specify the background fill patterns, such as colors, gradients, textures, and images, click Advanced, andthen select the options on the Fill Pattern tab.

3.

Format axes

To format an axis,

Double−click to select the chart coordinate paper. 1. Right−click the chart coordinate paper, click the Format Axes on the shortcut menu. 2. Use the Axis Dialog to format the specified axis, which can be accessed using the Format Axis button on theChart Axes dialog.

To change the properties for axis labels and tick marks, use the Axis tab, where you can specify whether toshow tick mark labels, the number of labels, the frequency that the axis should be labeled (length of label step),the maximum and minimum values, the distance between axis and labels, the position and length of tick marks,and so on.

To change pen style properties for axis, tick marks, and labels, use the Axis Pen tab, the Tick Mark Pen tab,and the Label Pen tab, where you can pen styles, pen colors, pen thickness, pen transparency, end caps, andso on.

To change label font and color, use the Label Font tab and the Label Font Color tab.

3.

Format gridlines and wall backgrounds

To format gridlines and wall backgrounds,

Double−click to select the chart coordinate paper. 1. Right−click the chart coordinate paper, click the Format Walls on the shortcut menu. 2. Use the Pen Style dialog to format the gridlines that are perpendicular to the specified axis, which can beaccessed using the Pen Style button on the Chart Walls dialog.

To specify the background fill pattern for specified walls, click the corresponding button, and then select theoptions you want.

3.

Charts

170

Page 183: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Format legend

To format a chart legend,

Double−click to select the legend. 1. Right−click the legend paper, click the Format Legend on the shortcut menu. 2. Use the Legend tab to change the properties such as whether to show category names or series names, thelegend entry alignments, the legend entry margins, the gap between two legend entries, and the distancebetween the category names and series names.

3.

Filtering Chart Data Source

What is a chart data source filter

Same as a report, which is separated from the data source, the chart you develop will retrieve data from databaseautomatically at run−time; you do not need to bother with data at design time.

However, sometimes you may need to control the data stream to achieve your needs. See the following chart,

The value of the value axis and category names are retrieved from database, which can be reformatted to get a betterview, as the chart below,

Charts

171

Page 184: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Here, the raw data from database is represented nicely, using the chart data source filter: every data label along thevalue axis are grouped by commas, and the workweeks are indicated clearly using a prefix string "WW" and workweeknumbers, instead of the first day of every week, which are originally in date/time format.

In cases like the preceding one, filtering the chart data source could be of great help in making your chart look tidy andexquisite.

Filter chart data source

To filter chart data source, you need use the Chart Data Source Dialog. Select the chart platform object, right−click it,and click Chart Data Source on the shortcut menu.

On the Chart Filter tab, you can reverse rows or columns. You can also specify a hyperlink for the chart.

On the Filter tab, click a sub−tab at the bottom for which you are going to filter the chart data source, and then specifiesthe data filter for the data labels along that axis.

Reference Notes:

For a detailed reference about each data filter and how to filter chart data source, please refer to:

Reference | Reporting Features | Chart | A Detailed Reference of JReport Charts | DataFilter Property.

For more information about a chart hyperlink, please refer to:

Reference | Reporting Features | Chart | A Detailed Reference of JReport Charts | Hyperlink Property.

Reference Links

For detailed information about JReport charts and the property descriptions of the chart elements, please refer to:

Reference Title Location

A Detailed Reference of JReport Charts Reference | Reporting Features | Chart

Chart Platform Reference | Reporting Features | Chart

Chart Coordinate Paper Reference | Reporting Features | Chart

Chart Legend Reference | Reporting Features | Chart

Chart Label Reference | Reporting Features | Chart

Index

Index

Charts

172

Page 185: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Printing a Report

Introduction

When you finish your design work of a report, you can print it out for your convenience.

JReport provides you with different methods to print the report, such as JDK1.1 printing methods, JDK1.2 printingmethods, and JDK1.4 printing methods. The printing methods are downward compatible, say, if JDK 1.3.x is used, boththe JDK1.1 printing methods and JDK1.2 printing methods can be used, but the JDK1.4 printing methods cannot be used.

You must have a printer installed on your computer before printing reports.

Specifying Printing Methods

To specify printing method, please follow the steps below:

On the File menu, click Options. The Report Options dialog appears.1. Switch to the Advanced tab, select the method you want on the Print panel. By default, the Use JDK1.2printing method is selected.

2.

If you want to separate a large page during printing, please select the check box Separate a large page. In thiscase, when you print a report, if the report page size is larger than the print paper size, the report will be printedas multiple pages serially, say, JReport will separate the large page of the report automatically.

3.

Click the Apply button to save the changes, and then click the OK button to close the Report Options dialog.4.

Printing a Report with JDK1.1 Printing Method

The JDK1.1 printing method is quick in speed but the printing quality cannot be guaranteed. To print a report with thismethod,

Choose the option Use JDK1.1 printing method on the Advanced tab of the Report Options dialog.1. Open the report you want to print.2. On the File menu, click Print. The following dialog appears.3.

173

Page 186: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In order to overcome the limitation of JDK1.1.x, JReport needs to be calibrated on the very first print, so that linesand text can be printed correctly. You only need to calibrate once for each printer that uses JReport.

Click the Test button, and then follow the screen instructions.Click OK to print the report.4.

Printing a Report with JDK1.2 Printing Method

The JDK1.2 printing method can provide you with a satisfactory result, even for the .gif files, but it is slow in speed. Toprint reports with this method,

Choose the option Use JDK1.2 printing method on the Advanced tab of the Report Options dialog.1. Open the report you want to print.2. On the File menu, click Print. The following dialog appears.3.

Printing a Report

174

Page 187: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Follow the screen instructions.

You can click the Properties button to change the printer properties.Click OK to print the report.4.

Printing a Report with JDK1.4 Printing Method

The JDK1.4 printing method provides you with more print options to print report, such as paper tray, and colorappearance. To print reports with this method,

Choose the option Use JDK1.4 printing method on the Advanced tab of the Report Options dialog.1. Open the report you want to print.2. Go to the File menu, and click Print. The following dialog appears.3.

Printing a Report

175

Page 188: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Follow the screen instructions.Click Print to print the report.4.

Index

Printing a Report

176

Page 189: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Report Manager and Data Manager

About the Report Manager

All the report files created (.cls) are physically placed under the same directory where the catalog file resides. This way,we cannot get detailed information about the report until it is opened in JReport Designer. For example, if you want tofind a report with a special condition, you may have to load each report. For only a few reports, this is not a problem, butthe case may be different with many.

The feature for administrating reports is the manager in Catalog Browser. You can build folder items in Catalog Browser,helping you divide the reports into different types at your disposal. Then reports can be added into the folder. After this,work on them just like processing files in the file system−−add, delete, move, rename and search the items. Themanager looks like this:

Note: The root folder is named "Reports", and you can not delete or rename this item.

Working with the Report Manager

Some concepts used in the manager:

Folder Item: A container in which you can operate report items or sub folder items.Report Item: It represents a report. You can edit Name, Keywords and Description properties of this item.

Adding Folder

To add a folder,

On the Reports tab of Catalog Browser, select a folder and right−click it.1. Select Add Folder on the pop−up menu.2.

A new folder appears as a sub node, the default name of folder is Folder0, Folder1....

177

Page 190: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Adding Reports

To add reports to a folder,

On the Reports tab of the Catalog Browser, select a folder and right−click it.1. On the pop−up menu, click Add Report, and the Choose Report dialog appears.

The default reports prompted to you will be those of the current catalog. You can browse to another directory forother reports. But please note, if you use reports from another catalog, the reports cannot be loaded here.

2.

Select one report and click Open, then the report is added. The default name of the report item is the file nameof the report.

3.

Renaming Item

To rename an item,

On the Reports tab of Catalog Browser, select one item you want to rename.1. On the pop−up menu, click Rename. 2. Type a new name, and click outside the window or just press Enter.3.

Notes:

The name box cannot be empty.• Under one level/node, the names can not be duplicated.•

Moving Item

To move an item,

On the Reports tab of the Catalog Browser, select an item and right−click it.The Move Reports dialog appears.1. Select Move to on the pop−up menu and the Move Reports dialog appears. All the available folders are listed inthe dialog.

2.

Select the folder you want the file moved to, click OK , then the item is moved to that folder.3.

Deleting Item

To delet an item, on the Reports tab of Catalog Browser, select an item, right−click it, and then click Delete on thepop−up menu.

Note: When you select a report item, you will be prompted whether or not to delete the report file from the file system. Ifyou select Yes, the file will be deleted permanently.

Searching Item

For now, wildcard search for Name and Keywords of the report name in Manager is supported. To search an item,

On the Reports tab of Catalog Browser, select an item and right−click it.1. Click Search on the pop−up menu and the Search Reports dialog appears.

Below are the descriptions of the options on the Search Reports dialog. Find whatThe content you want to search is inputted here, the wildcard characters * and ? are supported.

ByOne of the search conditions. The Name is name of item displayed in the tree.

Folder and Report checkboxes♦

2.

Report Manager and Data Manager

178

Page 191: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Choose what kind of item is to be searched. For example, if Report checkbox is selected, the manageronly processes report items in the tree. Match CaseSpecify whether the searched words should match case.

Include SubfoldersSpecify whether to search subfolders.

Look inSpecify in which folder you would like to search.

Search result panelA list showing the location of all matching items. When you click on one item in the list, the report itemwill be highlighted in Catalog Browser.

Exporting to a Table

You can export the report information in the manager to a table in some DBMS. The default name of the table isReportsInfo. You can change the name as you like. Each row of the table is a report description. To export,

On the Reports tab of Catalog Browser, select the root folder and right−click it.1. On the pop−up menu, click Export and the Get JDBC Connection Information dialog appears.

Reference Note: For more information about the dialog, see also User's Guide | Installing and LaunchingJReport.

2.

Fill in required fields, click the OK button.3. Give a name for the table and then click OK on the Input dialog.

Note: If the table already exists, it will be replaced. So you must be sure that there is no duplicate name existingin the DBMS.

4.

Data Manager

Introduction

The Data Manager controls the data retrieval, including number of rows to be displayed and the duration required forretrieval. The Data Manager can also keep the access information in previous runs of the query (including Imported SQL,Stored Procedure and UDS which functions as a query).

Showing Temporary Data

Begin with version 5, a new option is provided for Data Manager. Then users can flexibly decide if keeping the temporarydata or not. By default, the temporary data will not be shown in Data Manager for better performance. If you want to showthem, please follow the steps below:

Open the file report.ini under %JReport Designer_installroot%\bin, add the command line"alwaysShowDMRecord=true" as below:

#paths#Thu Mar 06 15:47:07 GMT+08:00 2003dmPath=C\:\\JReport\\dmhelpPath=C\:\\JReport\\helptemplatePath=C\:\\JReport\\templatetempPath=C\:\\JReport\\tempalwaysShowDMRecord=true

1.

Adjust the proper "maxRows" and "maxDuration" properties.2. View a report, and then open Data Manager. You can find that the temporary data appears. 3.

Report Manager and Data Manager

179

Page 192: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Max Rows and Max Duration

Imagine that there are a huge number of records in a table on which you will build a report. After you generate the queryand design a rough report, you may want to only preview several lines of records for a test. In this case, take advantageof the two properties for a query − maxRows and maxDuration to limit the run time and record number, saving time andresources. Let us take Invoice.cls for instance:

Launch JReport Designer. 1. Open our demo report Invoice.cls. 2. On the View menu, click Catalog Browser. Catalog Browser will automatically expand the query Invoice, whichthe currently opened report uses. Select the query, and click the Expand button on the Toolbar (in CatalogBrowser) to show its properties.

3.

You will see the maxRows and maxDuration properties. However, they are in gray − cannot be edited. To editthem, on the Report Option dialog (on the File menu, click Options or click the Options button on the toolbar ofCatalog Browser), select the Advanced tab, uncheck Forbid editing data object properties, and then clickthe Apply and OK button. Go back to Catalog Browser, the properties are now editable.

4.

Modify the value of maxRows to 10, then press Enter on your keyboard to apply your change. Change the valueof maxDuration to 1 second, and press Enter to apply your change. These two steps specify that the maximumruntime is one second, and that within that time no more than ten records should be fetched.

5.

View the report. There are only ten rows fetched out within one second.6.

Notes:

If the value for maxRows/maxDuration property is zero or a negative number, it means no limit formaxRows/maxDuration.

If the number you specify for maxRows/maxDuration is equal to or more than that required for running all therecords in your report, it means no limit for maxRows/maxDuration.

After modifying the value for each property, please press the Enter key on your keyboard to apply your changes. • We recommend that you do not specify both of the two properties at one time. Sometimes the time informationfor large−data reports may not be very accurate, for example you specify 5 seconds, but you find it uses 7seconds which also includes the time for writing the history information to the file.

Report Manager and Data Manager

180

Page 193: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Always click the Refetch data button to run the report again if you find that the specified properties have nottaken effect.

The two properties are applied for the specific query, not the report. For a report with a subreport, specifying theproperties for the query used by the main report does not affect those of the subreport query, and vice versa. Forexample, Report A.cls uses query Q1, and Report B.cls uses query Q2. B.cls is inserted to A.cls as a subreport.MaxRows for Q1 is modified to 3, the main report will only fetch three records out, but this does not restrict theQ2 for subreport B.cls. To limit the subreport records, you should further restrict Q2.

Viewing the Query History Information

Another important function of Data Manager is to keep track of the run information of the query. The history informationwill be recorded in a file under %InstallRoot%\dm. Under this folder, JReport generates a subfolder for each catalog. Forexample, if we run a JReport Designer demo report, you will then find %InstallRoot%\dm\Tutorial folder. In addition, a filewith (.dmt) corresponding to the query saves its run history information.

To change the data manager information output location (the default is %InstallRoot%\dm), edit report.ini under%InstallRoot%\bin. Change the argument: dmPath=C\:\\JReport\\dm to wherever you would like the information to go, forinstance dmPath=C\:\\temp\\dm. In this case, please make sure the folder C:\temp\dm exists.

Let us learn to use data manager with our demo report Invoice.cls.

Launch JReport Designer. 1. Open our demo report OrderList.cls and do not view it.2. On the View menu, click Catalog Browser. Catalog Browser will automatically expand the query Invoice, whichthe currently opened report uses. Right−click the query, and select Data Manager. Data Manager is shownwithout any history information − we have not run it.

3.

Close Data Manager. Specify MaxRows as 5, MaxDuration 3 in Catalog Browser. Click the View tab to run thereport. After the report result is shown, go to Data Manager, you will see the first run history of the query.

The information will include when the report is run − data and time, the running duration, the number of rowsdisplayed, and the report that uses the query.

Note: When the value of Max Duration and Max #Rows are 0, the history record will not be generated.

4.

Close the report Invoice.cls. We use the query Invoice to create another report report1.cls. Then run report1.cls,the run information will be appended to the end, but the report field it shows is report1.

5.

You can also sort the items by Date, Time, #Rows, Duration, Report, simply click the column title.6.

Through Data Manager, you can find the details of current and previous runs of the query.

Server−Side Run History

To show the server−side run history information of the query,

Open the report.ini file under %JREntServer_installroot%\bin, and add the command linealwaysShowDMRecord=true as below (suppose that JREntServer has been installed under C\:JREntServer):

#paths#Tue Mar 30 16:41:36 GMT+08:00 2004dmPath=C\:\\JREntServer\\dmhelpPath=C\:\\JREntServer\\helptemplatePath=C\:\\JREntServer\\templatetempPath=C\:\\JREntServer\\tempalwaysShowDMRecord=true

After you specify alwaysShowDMRecord=true, the engine in JReport Enterprise Server also saves the runinformation for queries. Like JReport Designer, the history information will be recorded in a file under

1.

Report Manager and Data Manager

181

Page 194: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

%JREntServerInstallRoot%\dm. Under this folder, JReport server generates a subfolder for each catalog. Forexample, if we run a demo report with the server, you will then find %JREntServerInstallRoot%\dm\Tutorialfolder. In addition, a file with (.dmt) corresponding to each query saves its run history information.

To change the data information output location (the default is %JREntServerInstallRoot%\dm), change theargument dmPath=C\:\\JREntServer\\dm to others you would like, for instance dmPath=C\:\\temp\\dm. In thiscase, please make sure the folder c:\temp\dm exists.Deploy the report that has been modified the properties maxRows and/or maxDuration (in JReport Designer).2. Run the report on JReport Enterprise Server. The server engine can save the query run information, but it doesnot have the GUI to display it. You need to use the Data Manager in JReport Designer.

Open the reports on the server with JReport Designer. Make sure you have pointed the dmPath argument in%Designer_InstallRoot%\bin\report.ini to the output location (containing the dm folder) for the server. Then openthe corresponding query in Catalog Browser to show its server−side run history information.

3.

Index

Report Manager and Data Manager

182

Page 195: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Tuning Runtime PerformanceThe following ways are provided for you to make JReport Designer efficient, reliable, and fast.

Suppress all useless sections, such as group header and footer which are not adding values to the report.

To do this, select the section, go to Report Inspector, and then change the property Suppressed to True.

This is more efficient than hiding the section.

Set the precision (length) of DBFields or record level formulas to the size of the maximum value you need todisplay in the report. Make them larger than necessary wastes resources.

To do this, go to Catalog Browser, expand the Properties sheet, select the DBField or record level formula, andthen change the Precision property to an appropriate value.

Note: If you cannot change the properties on the Properties sheet, select the Report Option dialog (click theOption button on the Catalog Browser toolbar, or click Options on the File menu of JReport Designer), on theAdvanced tab, uncheck the option Forbid editing data object properties.

You can improve the report performance by setting the data buffer size to a larger value.

By default, the size of data buffer is 2MB. When data exceeds the default size, date will be written to disk, whichwill slow down the report processing. JReport Designer enables you to set data buffer size by specifying twoproperties of Report Panel in Report Inspector: RecordsPerPage and MaxPageNumber.

For detailed information, refer to JReport Designer User Reference | Reporting Features | Report Panel | DataBuffer.

Adjust Result Buffer.

The result buffer is used to store the report result in pages. Its default size is 4 which indicates 4 pages of thereport result are allocated to the result buffer, other pages will be stored on disk. If you have enough memory, toget better performance, you can increase the result buffer size to store more pages of report result.

To adjust the result buffer size, in the Report Inspector, highlight the Report panel, and then change the value ofResultBufferSize to the number of pages you want to hold in memory.

Adjust Excel Buffer for exporting to Excel.

The Excel buffer is used to store the report result in excel buffer sheets when exporting to Excel format. Itsdefault size is 1, which indicates 1 sheet of the report result are allocated to the result buffer; other sheets will bestored on disk. If you have enough memory, you can increase the Excel buffer size to store more sheets of excelformat report result in memory.

References: JReport Designer User Reference | Reporting Features | Report Panel,♦ JReport Designer User Guide | Exporting Report Result to Multiple File Formats | Exporting to Excel File.♦

When running a report to the Text (Standard Data Format) format on JReport Enterprise Server, the propertyFastPass can help you speed up the generation process. Setting FastPass to true will enable you to specify theposition of the object you want to display in the result file, thus JReport will not calculate the position for everyobject during the generation process.

To use this method,

In JReport Designer, set the properties FastPass and Columned in Report Inspector of Report Panel totrue.

1.

For each DBField or label, set the exact coordinate using the properties ColumnIndex and RowIndex.

For example, set the properties ColumnIndex=0 and RowIndex=2 for a DBField, JReport Designer willput this DBField into the first column and the third row in the generated Text file.

2.

183

Page 196: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Set the property engine.single_thread = false in the file server.propertise under%JREntServer_InstallRoot%\bin. This enables the property FastPass to take effect when runningthe report to the Standard Data Format.

3.

Reference : JReport Designer User Guide | Exporting Report Result to Multiple File Formats | Exporting to Text.

CacheSection (Detail Section).

The CacheSection property is used to cache the objects in Detail Section instead of creating them repeatedly.You can set CacheSection in Report Inspector to true to improve the performance.

Note: CacheSection doesn't work if there is CrossTab, Text object, Chart, etc. in Detail Section, because theseobjects contain Child−DBField.

CacheValue (only for DBField)

The CacheValue property is used to cache the layout attributes (font size, font face, width and so on) ofDBFields when exporting the report to any format.

To get better performance, set it to true in Report Inspector.

Index

Tuning Runtime Performance

184

Page 197: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Problem Diagnosis Tool − Catalog Doctor

What are in a Catalog

Even if you are already very familiar with the Catalog, we recommend that you still read this page. It is important to knowthe basics about how Catalog Doctor works.

There are two kinds of objects defined in a catalog. They are:

Data Objects − including connections, tables/views, queries, etc. • Class − including text−fields, cross−tabs, etc. •

Data objects are those diagnosed by Catalog Doctor.

Connection

A connection defines the raw database information from which a catalog gets the raw data. For example, it specifies thedriver such as JDBC−ODBC Bridge, the Data Source name (for JDBC−ODBC bridge), the user ID, and the password forconnecting to the raw data. As the figure above illustrates, a connection is the gate to the raw database.

Table/View

Tables/views in JReport catalog are mapped objects of those in the raw database that a connection refers to.

Mapped objects have mapped names that are probably different from their names in the raw database. A catalog storesthe information about the real tables/views mapped, such as the table name, qualifier, and owner, etc.

Since tables/views are only mapped objects, they could be mapped and remapped. That is, the information of the realtables/views stored in a catalog is changeable. This is useful when you change the connection, say from an Access

185

Page 198: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

database to an Interbase (usually under the condition that the two databases share similar table structure). You onlyneed to re−map all the tables/views in the catalog rather than creating a new catalog and all the reports over again.

Field in a Table/View

Fields/columns in JReport Catalog are mapped objects of columns in the raw database. We will refer to the fields of atable/view in a catalog as DB−Fields.

You can specify a new name for the fields (mapped field names) which is different from the name of the real columns inthe raw database. But this means that you need to remap all the objects in the catalog which use this column.

Parameter

A Parameter is a variable whose value is an input value at the run time. Please refer to User's Guide | JReport Parameterand its Applications for its usage.

Formula and Summary

Formula and summary are objects to be computed at run time. They only depend on the information from DB−Fields andparameters in the catalog, rather than the real columns that DB−Fields refer to. Therefore, formulas and summaries areindependent from the raw database. This means when a connection is changed (say, from Access database to Interbase), you don’t need to re−create the formulas and summaries. However, if you re−map a DB−Field, formulas andsummaries using that field will generate errors.

Mapping Field

DB−Fields, formulas, summaries as well as parameters are all called mapping fields. They share the same namingdomain.

Query

Query is a higher−level object in a catalog. Its concept is similar to that in the database. The columns a query can selectinclude DB−Field, formula, and computed column. The tables/views it selects from are mapped tables/views defined inthe catalog. So a query is also independent from the raw database.

Relationship among Data Objects

As illustrated by the figure above, data objects in a catalog are constructed one after another: In a query, the connectionis the basic object, tables/views come next, then the DB−Fields together with parameters, and last come formulastogether with summaries. In other words, changes in a formula will not change the validity of any DB−Field, but maychange the validity of a query.

What errors can Catalog Doctor Detect

With Catalog Doctor you can diagnose and validate data objects in a catalog.

Errors are Diagnosed Independently

Since data objects in a catalog are constructed one after another, Catalog Doctor diagnoses each type of data objectindependently. For example, when it checks formulas, it only looks into the definition of parameters and DB−Fields in thecurrent catalog. The system does not check if the DB−Fields exist in the connected database. When the system checksthe queries, it will only look for the mapping fields currently in the catalog and does not confirm whether the formulas arevalid.

Problem Diagnosis Tool − Catalog Doctor

186

Page 199: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For your convenience, in the following statements database refers to the raw database connected to via JDBC or ODBC,mapped table/view refers to the table/view in the catalog, raw table/view refers to the table/view in the raw database,and raw column refers to the columns in the raw database.

Mapped Table/View and DB−Field

Check to see if the raw table/view of the mapped table/view exists in the database.

Check to see if the raw column of the DB−Field exists in the database. If it exists, then check to see if the storedinformation such as SQL date type matches the raw column in the database.

Formulas and Summaries

Check to see if formulas and summaries have correct syntax. That is to check whether it needs to re−map parametersand DB−Fields which have been remapped.

Queries

Check to see if the mapped tables/views referenced by the query exist in the catalog.

Check to see if the mapping fields are valid:

The DB−fields of the table/view match that saved in the query; • The formulas and parameters can be found in the catalog. •

Other errors are caused by the two above.

Using Catalog Doctor

Starting Catalog Doctor

When you install JReport Designer, JReport Catalog Doctor is also installed. Under %installroot%\bin, there is a batchfile named catdr.bat. Catalog Doctor can be started by running the batch file CatDr.bat.

From the desktop, double click My Computer, then go to %installroot%\bin\catdr.bat, run cardr.bat

Or, from an MS−DOS command prompt, issue the following commands:

c:\> cd\jreport\binc:\jreport\bin\>catdr

Loading a Catalog

To load a catalog into Catalog Doctor for diagnosing,

Go to the File menu, and click Open to bring out the Open Catalog File menu.1. Select a catalog file and click Open.2.

Saving a Catalog

To save the loaded catalog to its file, go to the File menu, and then click Save.

To save the loaded catalog to another file, go to the File menu, and then click Save As.

Problem Diagnosis Tool − Catalog Doctor

187

Page 200: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Merging Catalogs

You can merge the resources in two catalogs into one in Catalog Doctor. To do so,

Go to the File menu, open the target catalog, and then select Import. Select the catalog to be imported, theImport From Catalog dialog appears. Select the resources from the catalog, and click OK.

1.

The selected resources may conflict with those in the target catalog, they are marked with red question marks.

Click the Rename button to rename them, or the Replace button to replace, or click the Skip button to ignore.

2.

Problem Diagnosis Tool − Catalog Doctor

188

Page 201: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Differences button to see the property values of the objects in the target catalog and the sourcescatalogs. The different property values are highlighted.

Click the Target Relation button to see the relationship between the object and its parental node.

Manage the conflicting resources one by one and then click the Merge button to merge the two catalogs. If thetwo connections in the two catalogs connect to different data sources, you will be asked to modify the existingdata source in the target catalog or create a new data source in the target catalog. For the safety reason, you arerecommended to create a new data source.

Note: Catalog Doctor have set different levels for checking the differences between the two catalogs. Go to theFile menu, click the Options menu item, and the Option dialog appears. In the Merge Catalog Options panel,you can specify the checking level.

Identify all differencesCatalog Doctor will check all the differences between the two catalogs. All the resources of the report will bedisplayed on the Merge dialog with all the conflicting resources marked.

Identify critical differencesCatalog Doctor will check the differences that can cause the engine fail to run the report. All the resources of thereport will be displayed on the Merge dialog with the critical conflicting resources marked.

Ignore differencesDo not show the differences between the two catalogs. If there are conflicts between them, remain the resourcesin the target catalog.

Problem Diagnosis Tool − Catalog Doctor

189

Page 202: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Save the changes and exit Catalog Doctor. Launch JReport Designer, open the merged catalog, you will find theresources you just imported (a new data source has been created).

3.

Diagnosing and Fixing

Having finished loading a catalog, you will get the Catalog Doctor dialog shown as below. All the resources in the openedcatalog are listed in the left panel of the window.

Problem Diagnosis Tool − Catalog Doctor

190

Page 203: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select a resource in the resource tree, and in the right panel, you can see the informations of the selected resoruces.

Please diagnose the resources in the following order: Connection, Tables and Fields, Formulas and Summaries,Queries.

Connection

Finding Information of the Current ConnectionSelect a connection in the resoruce tree, and the connection information will be displayed in the left panel.

Modifying the Current ConnectionRight click the connection on the resource tree, and then click Modify on the pop up menu. The Get JDBCConnection Information dialog appears for you to modifiy the connction.

For JDBC−ODBC bridge, you should give the ODBC data source name, as well as user ID and password ifnecessary.

For JDBC driver, uncheck Use ODBC Data Source, and check JDBC Driver. Fill in the class name of the driver,the URL, as well as user ID and password if necessary.

You can also change the properties values in the Properties panel directly. Select a property value, and thenchoose or type in the value you want.

Reference Note: For details about the JDBC URL format, please refer to User's Guide | Starting a Catalog |Connection

Problem Diagnosis Tool − Catalog Doctor

191

Page 204: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Tables and Fields

Finding all the Mapping Tables, Views and DB−Fields in the CatalogIn the resource tree, go to the Tables and Fields node, reveal it, and all the mapping tables, views andDB−Fields in the catalog are listed. The icon in front of each object has a specific meaning, indicating whetherthe object is valid and why.

The icon in front of each object has its specific meaning.

: Table

: Table which does not exist in the database

: Table which has invalid fields

: View

: View which does not exist in the database

: View which has invalid fields

: Field

: Field which does not exist

: Field whose name can be found in the database, but type mismatch

Problem Diagnosis Tool − Catalog Doctor

192

Page 205: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Finding the Stored Information of a Mapping Table/View or a DB−Field

Select the resource for which you would like to find the stored properties on the resource tree, and theinformation will be listed in the Properties panel.

Finding all the Raw Tables/Views

Select a table/view under the Tables and Fields node, and all the raw tables/views will be shown in the Choosefrom following to Re−Map panel. Each item there shows the name of the table/view.

Getting the Raw Columns in a Raw Table/View

First select a mapping table/view, then choose the raw table/view from the Choose from following toRe−Map panel, the raw columns will be shown in the bottom right panel.

Note: If you select a mapping table/view whose raw table/view exists, then the raw table/view will beautomatically selected.

Deleting a Set of Mapping Tables, Views or DB−Fields

To delete one mapping object, please use one of the following ways: Select the an object on the resources tree, right click and on the pop−up menu click Delete;♦ or click the Delete button on the toolbar;♦ or press the Delete key.♦

To delete a set of mapping tables, views or DBFields, select the objects you want to delete, click the Deletebutton on the toolbar, or press the Delete key.

Re−mapping(Updating) a Mapping Table/View

First select the mapping table/view to be updated on the resource tree, select the raw table/view which themapping table/view refers to from the Choose from following to Re−Map panel, and then click the Updatebutton on the toolbar.

Note: The tree is sorted by the validation status of each object (The invalid objects are listed ahead). So afteryou update a mapping table/view, the order of the objects will be probably changed. If the table was invalid andbecomes valid after updating, it will be listed after invalid objects.

Re−mapping(Updating) a DB−Field•

Problem Diagnosis Tool − Catalog Doctor

193

Page 206: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Before updating a DB−Field, you must make sure that the mapping table/view of this DB−Field is val id, that is tosay the raw table/view of that the mapping table/view refers to exists in this database.

Select the DB−Field you want to update on the resource tree, choose the raw column you want the DB−Fieldrefers to in the right bottom panel, and then click the Update button on the toolbar.Adding Tables/Views

Click Add Tables/Add Views button on the toolbar, or on the resource tree select the the following dialog willpop up.

Select the tables/views you would like to add, click Add. To finish adding, click Done.

Adding a DB−fieldSelect a table or a column on the resource tree, right click and on the pop−up menu click Insert Column to bringout the Add Column dialog. Select the column you want and click Add. When you finish adding columns, clickDone to close the dialog.

Formulas and Summaries

Finding all the Formulas and Summaries in the CatalogExpand the Formulas and Summaries node on the resources tree, the formulas and summaries in the catalogare listed on the tree and they are sorted by their validity and names. If the icon of a formula/summary is markedby a cross, it means it is an invalid one − it fails on compiling.

Problem Diagnosis Tool − Catalog Doctor

194

Page 207: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Finding the Compile Error Message of a Formula/SummarySelect the formula/summary to be checked and the compile error messages are displayed in the Error panel.

Replacing a Mapping Field with Another in Formulas and SummariesThe common error is caused because some mapping fields cannot be found in the catalog. In this case, you mayneed to replace this mapped field in formulas/summaries with another one.

To do this, please follow the steps below: Select the formula/summary which contains unknown fields on the resource tree. 1. Click the Replace All button under the Error panel. The Replace dialog appears.2.

Input the field name to be replaced in the Mapping Name text box.

Click the Browse button, the Mapping Fields Browse dialog pops up.

3.

Problem Diagnosis Tool − Catalog Doctor

195

Page 208: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the Tree View tab, you can select an existing field to replace the unknown field.

On the List View tab, you can get the following information. This view organizes mapping fields byname. You can get the type for each mapping field. If the mapping field is a DB−Field, you can see thetables/views it belongs to. Select the field you wish to use as a replacement and click OK.

Problem Diagnosis Tool − Catalog Doctor

196

Page 209: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click Replace button on the Replace dialog. 4. Editing a Formula/SummarySelect the formula/summary to be edited, click the Edit button under the Error panel.

Removing Formulas/SummariesSelect the formulas/summaries to be removed, right click and on the pop−up menu, click Delete, or click theDelete button on the toolbar.

Query

Finding all the Queries in the CatalogExpand the Queries node, all the queries are listed on the resources tree.

Problem Diagnosis Tool − Catalog Doctor

197

Page 210: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Finding the Tables/Views Selected in a QuerySelect a query and expand it, all the tables/views will be listed.

Finding the DB−Fields Selected from a Table/View in a QuerySelect a query and expand it, then click on a table/view and expand it, all the DB−Fields in the table or view willbe listed.

Finding the Formulas or Computed Columns Selected in a QueryFormulas and computed columns are listed before mapping tables/views.

Editing a QuerySelect the query to be edited, click the Edit button under the Error panel, or right click and on the pop−up menuclick Edit Query.

Deleting Queries, DB−Fields, Formulas and Computed Columns Selected in a Query and a Table/ViewSelected in a QuerySelect the objects to be deleted, click Delete.

Saving a Query as a Cached Query ResultSelect the query to be saved as a cached query result, click Run, or right click a query, and on the pop−upmenu, click Create Cached Query Result. Usually, this is for our internal use and you may not be interested.

Problem Diagnosis Tool − Catalog Doctor

198

Page 211: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing a Report from a Query File

SQL in Connection

Users can build most queries using the interactive query designer. For those who wish to write their own SQLstatements, they can put the SQL statements in a file and load these SQL statements from the file. SQL is one of theobjects in a catalog. It can work like a query. But there are two basic differences in using the two. The first difference forQuery and File Query is that a query is based on tables/views added from the raw database. In other words, if you onlyset up the connection, but have not added tables or views into the catalog, you are not allowed to build a query. But afteryou set up the connection, even if you have not added the tables or views, you can import your file query into the catalog,and make reports on it. The second difference is that queries built using the interactive query designer can work withother tables/views when you create or modify a working set. That is, if you design a report using interactively createdqueries, you can add additional objects from tables/views into the working set afterwards. But when you design a reportusing a query that is loaded from a query file, you can only use the contents already included in the SQL file. Therefore,please make sure that you have included all required fields in the query file.

Creating a Report from a Query File

Editing a File Containing an SQL Statement

To create a report from a query file, you need to create a file that contains SQL statement. Please note that at presenteach SQL file can contain only one SQL statement. Here is an example for a query file named sqlfile.txt. You can copythe example below and paste it into a file sqlfile.txt, then save this file in any directory.

SELECT Catalog."Product Type Name", Catalog."Product Type ID", Catalog.Description,Products.Category, Products."Product ID", Products.Price, Products."Product Name",Customers.Region, Customers."Contact Position", Customers.Country, Customers."CustomerID", Customers.Address2, Customers.Address1, Customers."Contact Title", Customers.Phone,Customers."Contact Last Name", Customers.City, Customers.Fax, Customers."Contact FirstName", Customers."Annual Sales", Customers."Customer Name", Customers."Postal Code",Orders."Order ID", Orders."Required Date", Orders."Customer ID", Orders."Shipping Cost",Orders."Ship Date", Orders."Order Date", Orders."Employee ID", Orders.Shipped,Orders."Payment Received", Orders."Ship Via" FROM Catalog, Products, Customers, "Orders Detail", Orders WHERE (Products."Product Type ID"=Catalog."Product Type ID") AND ("OrdersDetail"."Product ID"=Products."Product ID") AND (Orders."CustomerID"=Customers."Customer ID") AND (Orders."Order ID"="Orders Detail"."Order ID") AND ( (Customers.Country='USA' ))

Note: Since JReport Designer version 7.0, the format of the SQL file, such as comments, can be remained when it isimported into JReport Designer.

Supporting Paramters in SQL File

You can use parameters in the where clause to filter the data set. For example, you want to use a parameter to return aresult set in which the customer ID is greater than the parameter. Then the where clause would be like this:

WHERE (Products."Product Type ID"=Catalog."Product Type ID") AND ("OrdersDetail"."Product ID"=Products."Product ID") AND (Orders."CustomerID"=Customers."Customer ID") AND (Orders."Order ID"="Orders Detail"."Order ID") AND ( (Customers.Country='USA' )) AND (Customers."Customer ID" > @id)

Where, id is a parameter created in the catalog.

199

Page 212: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Reference Note: For more details on how to use parameters, please refer to User's Guide | JReport Parameter and itsApplications.

Supporting Formulas in SQL File

You can use constant level formulas in the SQL file to calculate your data. The constant level formulas are formulas thatwill never refer any DBField, page level special fields (the value of the special field will be ready at the time when thereport result is generated), or other constant level formulas. The allowed constant can be referred to the formulas are:

Parameters• Special Fields: limited to PrintDate, and PrintTime• Constant Values, such as "aaa"• Combination of the above three •

Here is an example about getting those orders of previous 20 days from today:

SELECT ORDERS.ORDER_DATE,ORDERS.CUSTOMER_ID,ORDERS.ORDER_ID FROM ORDERS WHERE @FPrev<ORDERS.ORDER_DATE and ORDERS.ORDER_DATE <@FCurrent

Where, @FPrev is defined like below in JReport Catalogprintdate−20

and @FCurrent is defined like:printdate

In the above two formulas, printdate is a constant level special field, which will get the current system date.

Supporting Special Fields in SQL file

The special fields Print Date, Print Time and User Name can be used in the SQL file.

For more information about the three special fields, please see JReport Designer manual User's Guide | Editing a Report| Editing a Report by Inserting/Editing Objects | Special Fields.

Linking the SQL File with the Catalog Browser

Start JReport Designer, open Catalog Browser. Make sure that the catalog has set up the connection with yourdatabase. In our case, we still use our demo catalog. Expand Connection until you see the SQLs node, click toselect it. Now on the toolbar of Catalog Browser, you will find the New SQL button.

1.

Right−click the SQLs node and click Add SQL on the pop−up menu or click the New SQL button on the toolbar,the Select SQL File dialog will pop up. Browse to the SQL file you want and click Open.

2.

Now the Input SQL Name dialog appears. Enter any name you want in the SQL Name text box to create a queryin Catalog Browser. For example, we will call it SQL1.

3.

Developing a Report from a Query File

200

Page 213: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

A new SQL is then added into the catalog.

Note: If you are currently connecting to a SQL Server data source, the database catalog of SQL Server will be listed inthe from DB Catalog drop−down menu, from which you can select a catalog for the newly created SQL file. Please lookat the screenshot below:

Creating a Report Using the Query File

There is no difference between building a report with a query file and with a table/view. Here is the example for creating areport from the query file.

On the File menu, click New or click the New button on the toolbar.1. When the Open Report dialog appears, click the Left Alignment template. Click the Create button to launch theReport Wizard.

2.

Select a data source from the Catalog Data Source drop−down list. Add SQL1 that you have just created to theworking set. The Joins tab and Conditions tab are disabled, because you are using a query file to create thereport.

3.

Developing a Report from a Query File

201

Page 214: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the Display tab, add Product ID, SQL1_Product Name, SQL1_Price.On the Group tab, group the records by Customer ID and Order ID.On the Summary tab, add aggregate fields, define the count function on SQL1_Price, break by Customer ID.

4.

Click Finish to exit the Report Wizard and generate the report.5. Edit the report according to your own requirements. 6.

Index

Developing a Report from a Query File

202

Page 215: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing Reports from Stored Procedures

Stored Procedure

Introduction

A stored procedure is a compiled program, consisting of one or more statements, that is saved into a database. Thestatement in a stored procedure can be an SQL statement or a control flow statement (like If−else statement, Loopstatement). The stored procedure is stored in a DBMS, so it can be called locally or remotely.

As a program, a stored procedure can take parameters. There are three types of parameters: IN, OUT and INOUT. TheIN parameter lets you pass values to the procedure. The OUT parameter will return values to the caller. The INOUTparameter enables to pass initial values to the procedure and return the updated values to the caller.

A stored procedure can use the following means to return data.

Return a result set• Return a value• Return values via OUT parameters•

How does a Stored Procedure Work with JReport

Apart from tables and views in a database, JReport also supports stored procedures. You can design and run a report onthe result set returned by a stored procedure.

In JReport system, a report is based on a data set, JReport generates a report on the data in the data set while the reportis being run. When a report uses a query, the data set is the result of the query. In the same sense, when a report uses astored procedure, the data set is the result set returned by the stored procedure.

The stored procedure can return a value, single result set or multiple result sets. Currently JReport supports storedprocedures that return a single result set. If a stored procedure returns more than one result set, the first result set will beused in JReport.

Developing Reports from Stored Procedures

Adding a Procedure to the Catalog

Before you use stored procedures in JReport Designer, you should add the stored procedure to a catalog. But make surethat you have already set up the connection with your database. When a stored procedure is added into a catalog,JReport will retrieve the stored procedure's information from DBMS via JDBC, prompt you to input the values of IN andINOUT parameters if the stored procedure has them, execute the stored procedure once to try to get the result set, andthen the field objects of the procedure object will be created according to the result set returned. You will then use thefield objects to design your reports.

To add a procedure to the catalog,

Launch JReport Designer. Open Catalog Browser.1. Expand the Connection node, and select the Procedures node.2. Right−click the Procedures node and click Add Procedure on the pop−up menu, or click the NewProcedure button on the toolbar, and the Add Procedures dialog appears. As long as you set up theconnection, you do not necessarily need to import the tables to use Stored Procedures.

3.

203

Page 216: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

This dialog displays all the stored procedures in the database, allowing you to select the stored procedures andadd them to a catalog. In the end, click the Done button to finish adding stored procedures and close the AddProcedures dialog.

When add Stored Procedures, please note that If you are using SQL Server database, on the Add Procedures dialog, the database catalog of the SQLServer is displayed in the Database Catalog drop−down list. Select different database to get differentstored procedures.

The dialog lists all the stored procedures in a three−level tree. The top level is SQL−catalog, the secondis SQL−schema and the last level is Stored Procedures. Select one or more stored procedures and addthem to the catalog.

Notes:

Not all DBMSs support database stored procedures, so you may see nothing in the panel in such a case.• When adding a stored procedure, you may get the following error:

This is because test;1 is quoted when JReport Designer finds the semicolon in it.

To remove the quotation marks, you should modify your connection information. Right click your connection andselect Modify to bring out the Get JDBC Connection Information dialog. On the Quote Qualifier tab, checkthe User Defined radio button, and remove all the characters in the Extra Characters text box and the QuoteCharacter text box.

Editing Parameter Values

When you add a stored procedure, you will be asked to input values for its parameters. Those values will be saved insidethe stored procedure object in the catalog and will be used as the default value when executing this procedure. You can

Developing Reports from Stored Procedures

204

Page 217: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

edit the stored procedure parameters at any time .

In JReport Designer Version2.0 or above, you can use the IN type parameter of the stored procedure in a report.

In Catalog Browser, select a stored procedure, and right−click it.1. On the shortcut menu, click Parameters, and the Procedure Parameters dialog appears.

This dialog displays all parameters, and provides ways to edit the value of parameters. Parameters listLists the IN and INOUT parameters in the stored procedures. Names, values, types andbindParameterName are displayed. Click on the Value cell, and the editor will appear, in which you canedit the value of each parameter.

bindParameterNameAllows you to bind the IN and INOUT parameters in the stored procedure to an existing catalogparameter with the same type. Click on the bindParameterName cell, the editor will appear, in which youcan input the parameter name as @parametername. By default, the bound parameter will be the onewith the same name of the IN and INOUT parameter which is automatically created when adding thestored procedure.

FormatDisplays the value format of the current parameter.

2.

Creating a Report Using a Stored Procedure

To create a report on the result set returned by a stored procedure, you should select the stored procedure object youwant on the Data tab in Report Wizard.

When you finish all work necessary under other tabs, click on the Finish button. A report which uses a stored procedureis created.

Running a Report Which Uses a Stored Procedure

When a report built on a stored procedure runs, you need to specify the values for the IN and INOUT typed parametersdefined in the stored procedure. The values stored inside the stored procedure object in the catalog will be the defaultvalues.

The parameter dialog will be displayed when a report is going to run, and you can input the values of the storedprocedure parameters on this dialog.

Developing Reports from Stored Procedures

205

Page 218: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click OK to view the result.

Stored Procedure for Oracle Database

Because of the unique nature of Oracle Stored Procedures, you can not add procedures of Oracle into the Catalog ofJReport Designer directly. Therefore the usage of JReport Designer is limited when you use an Oracle database. As asubstitute, we have developed User Data Source API that can use a Stored Procedure in Oracle.

Reference Notes: For more details about User Data Source API, please refer to User Reference | UDS API.

Adding UDS class

To use stored procedures in Oracle with JReport Designer, we developed a User Data Source class. The class is named"OracleProcedureUDS", in the package jet.datasource.oracle.

In the Add User Data Source dialog, the format of PARAMETER stringis:DRIVER=drivername&URL=url&USER=user&PSWD=password&OWNER=owner&PROCNAME=procname&SQL=sql&REFCURSORINDEX=index&PARAMVALUE=value1,value2,value3

Replace the words in lower case as you like.

Where:

drivername − The name of JDBC driver, for instance: oracle.jdbc.driver.OracleDriver • url − A database url of the form jdbc:subprotocol:subname, for instance: jdbc:oracle:thin:@dbserver:1521:orcl • user − The database user on whose behalf the Connection is being made, for instance: scott • password − The user's password, for instance: tiger • owner − The owner of the procedure, may be empty, for instance: scott. • procname − The name of the Stored Procedure, for instance: getAuthor. • sql − The sql statement which is used to call the procedure or function, for instance of procedure: {callgetAuthor(?, ?)}; for instance of function: {? = getAuthor(?, ?)}

index − The index of the output parameter whose data type is Ref Cursor, the start index is 1. • valueX − The value of parameter separated by ',' , and their data types must correspond to the ones defined inthe DBMS. If the valueX should contain a set of values, for example, 10, 20, and 30 together serve as valueX,you need to use '\\' to escape the comma. For example, if the PARAMVALUE part of the PARAMETER string islike the following:

...&PARAMVALUE=10\\,20\\,30,30\\,10\\,23,,a,

Then the parameter values will be parsed as follows,

ParaValue1 =10,20,30

Developing Reports from Stored Procedures

206

Page 219: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ParaValue2 =30,10,23ParaValue3 =nullParaValue4 =aParaValue5 =null

Or, instead of typing the parameter values one by one in the above PARAMETER string, you can also use theparameters in the catalog to substitute the parameter values, for example,

...&PARAMVALUE=@PARAM1,30\\,10\\,23,,a,

In this case, on the Create/Edit Parameter dialog, the prompting value of parameter PARAM1 must be typed likethis:

10\\,20\\,30

An example of parameter string:

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@dbserver:1521:orcl"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=getAuthor&SQL={call getAuthor(?, ?,?}&REFCURSORINDEX=2&PARAMVALUE=0.5,1999−7−10

If you want to change the connection dynamically, you can define the parameters like this:

oracle.jdbc.driver.OracleDriver=@driver, jdbc:oracle:thin:@dbserver:1521:orcl=@url, scott=@user,

then the PARAMETER string will be like:

DRIVER=@driver&URL=@url&USER=@user&PSWD=tiger&OWNER=SCOTT&PROCNAME=getAuthor&SQL={call getAuthor(?, ?,?}&REFCURSORINDEX=2&PARAMVALUE=0.5,1999−7−10

You can change the parameter dynamically to fit your needs.

Note: When your PARAMETER string contains characters like: At sign('@'), ':', double quotation mark('"'), or other stringwhich does not need to be parsed by JReport, use a pair of double quotation marks to quote them. For example, yourparameter string may be:

jdbc:oracle:thin:@204.177.148.30:1521:orcl

Here, '@' is a character used by the URL. If you add this PARAMETER into Catalog, JReport thinks '204' is name of aparameter in Catalog, so the correct form is:

"jdbc:oracle:thin:@204.177.148.30:1521:orcl"

Example: Adding an Oracle Stored Procedure into Catalog

Suppose that the Oracle stored procedure is defined as below:

Package SHDEMO as type curtype is ref cursor;end SHDemo;Procedure empquery (param1 in varchar2, cur OUT SHdemo.curtype)aslcur shdemo.curtype;beginopen lcur for select * from EMP WHERE JOB = param1;cur:=lcur;

1.

Developing Reports from Stored Procedures

207

Page 220: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

end empquery; Add the stored procedure into JReport Catalog

Go to View | Catalog Browser to launch Catalog Browser, right click on UserDataSource, and select NewUserDataSource | General. Then the Add User Data Source dialog will appear.

We input the following in the Add User Data Source dialog:

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@222.222.222.45:1521:orcl815"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=empquery&SQL={callempquery(?,?)}&REFCURSORINDEX=2&PARAMVALUE=@job1

2.

Click on the OK button, the UDS class will be added into the Catalog of JReport. Then you can build the reportusing UDS named "pdemo" in Catalog.

Reference Note: Please refer to User's Guide | Developing Reports from User Data Source.

3.

Notes:

The UDS class is in a package named "jet.datasource.oracle", and the UDS class needs classes in package"oracle.jdbc.driver" when being added into Catalog Browser, so before adding it, make sure the classpathcontains package oracle.jdbc.driver.

The procedure can only contain one OUT type parameter, and the data type of the parameter must be "REFCURSOR". If the procedure doesn't have such a parameter, it can not be added into Catalog of JReport becauseJReport can not create a report without a ResultSet.

The default format of Date or Time data type is:Date: yyyy−MM−ddTime: hh:MM:ssTimestamp: yyyy−MM−dd hh:MM:ss.SSS

You can modify the format in the Connection Dialog.

Reference Notes: User's Guide | Starting from Catalog | Connection for detailed information.

Examples

Example 1: Stored Procedure defined outside a package

Suppose that the Oracle stored procedure is defined as:

CREATE OR REPLACE PACKAGE SHDEMO as type curtype is ref cursor;END SHDEMO;CREATE OR REPLACE PROCEDURE empquery (p_job in varchar2, cur OUT SHDEMO.curtype) as lcur SHDEMO.curtype; begin open lcur for select * from EMP WHERE JOB = p_job; cur:=lcur;END empquery;

1.

Add the stored procedure into JReport Catalog

Go to View | Catalog Browser to launch Catalog Browser, right click on UserDataSource, and select NewUserDataSource | General.... Then the Add User Data Source dialog will appear.

We input the following in the Add User Data Source dialog:

UDS class: jet.datasource.oracle.OracleProcedureUDS

2.

Developing Reports from Stored Procedures

208

Page 221: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@192.168.126.38:1521:oracle8"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=empquery&SQL={callempquery(?,?)}&REFCURSORINDEX=2&PARAMVALUE="SALESMAN"

Click on the OK button, the UDS class will be added into the Catalog of JReport. Then you can build the reportusing UDS named "pdemo" in Catalog. Reference Note: Please refer to User's Guide | Developing Reports fromUser Data Source.

3.

Example 2: Stored Procedure declared&defined in a package&package body

Suppose that the Oracle stored procedure is defined as:

CREATE OR REPLACE PACKAGE DEMO_PKG AS type curtype is ref cursor; PROCEDURE empquery_proc(p_job in varchar2, cur OUT DEMO_PKG.curtype);end DEMO_PKG ;

CREATE OR REPLACE PACKAGE BODY DEMO_PKG AS PROCEDURE empquery_proc(p_job in varchar2, cur OUT DEMO_PKG.curtype) AS lcur DEMO_PKG.curtype; begin open lcur for select * from EMP WHERE JOB = p_job; cur:=lcur; end empquery_proc;end DEMO_PKG;

1.

Add the stored procedure into JReport Catalog.

Go to View | Catalog Browser to launch Catalog Browser, right click on UserDataSource, and select NewUserDataSource | General.... Then the Add User Data Source dialog will appear.

We input the following in the Add User Data Source dialog:

UDS class: jet.datasource.oracle.OracleProcedureUDS

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@192.168.126.38:1521:oracle8"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=empquery_proc&SQL={calldemo_pkg.empquery_proc(?,?)}&REFCURSORINDEX=2&PARAMVALUE="SALESMAN"

2.

Click on the OK button, the UDS class will be added into the Catalog of JReport.3.

Example 3: Functions defined outside a package

Suppose that the Oracle stored procedure is defined as:

CREATE OR REPLACE PACKAGE SHDEMO AS type curtype is ref cursor;end SHDEMO;

CREATE OR REPLACE FUNCTION "SCOTT"."DEPTQUERY"(p_dname in varchar2) return SHDEMO.curtypeis lcur SHDEMO.curtype; begin open lcur for select * from dept where dname = p_dname; return lcur;

1.

Developing Reports from Stored Procedures

209

Page 222: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

end DEPTQUERY; Add the stored procedure into JReport Catalog.

Go to View | Catalog Browser to launch Catalog Browser, right click on UserDataSource, and select NewUserDataSource | General.... Then the Add User Data Source dialog will appear.

We input the following in the Add User Data Source dialog:

UDS class: jet.datasource.oracle.OracleProcedureUDS

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@192.168.126.38:1521:oracle8"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=deptquery&SQL={? = calldeptquery(?)}&REFCURSORINDEX=1&PARAMVALUE=@p_dname

p_dname is the parameter defined in JReport Catalog, you should give some default values.

2.

Click on the OK button, the UDS class will be added into the Catalog of JReport.3.

Example 4: Functions declared&defined in a package&package body

Suppose that the Oracle stored procedure is defined as:

CREATE OR REPLACE PACKAGE "SCOTT"."SHDEMO_PKG" AS type curtype is ref cursor; Procedure empquery_proc (p_job in varchar2, cur OUT SHDEMO_PKG.curtype); Function deptquery_func (p_dname in varchar2) return SHDEMO_PKG.curtype;end SHDEMO_PKG;

CREATE OR REPLACE PACKAGE BODY "SCOTT"."SHDEMO_PKG" AS Procedure empquery_proc (p_job in varchar2, cur OUT SHDEMO_PKG.curtype)as lcur SHDEMO_PKG.curtype; begin open lcur for select * from EMP WHERE JOB = p_job; cur:=lcur; end empquery_proc;

Function deptquery_func (p_dname in varchar2) return SHDEMO_PKG.curtypeas lcur SHDEMO_PKG.curtype; begin open lcur for select * from dept where dname = p_dname; return lcur; end deptquery_func;

end SHDEMO_PKG;

1.

Add the stored procedure into JReport Catalog.

Go to View | Catalog Browser to launch Catalog Browser, right click on UserDataSource, and select NewUserDataSource | General.... Then the Add User Data Source dialog will appear.

We input the following in the Add User Data Source dialog:

UDS class: jet.datasource.oracle.OracleProcedureUDS

2.

Developing Reports from Stored Procedures

210

Page 223: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

DRIVER=oracle.jdbc.driver.OracleDriver&URL="jdbc:oracle:thin:@192.168.126.38:1521:oracle8"&USER=scott&PSWD=tiger&OWNER=SCOTT&PROCNAME=deptquery_func&SQL={? = callshdemo_pkg.deptquery_func(?)}&REFCURSORINDEX=1&PARAMVALUE="SALES" Click on the OK button, the UDS class will be added into the Catalog of JReport.3.

Trouble Shooting Guides for Importing Oracle Stored Procedure

1. If you get "ArrayOutOfBound" error or "Not all variables are bound" error while importing a stored procedure, check thebelow things:

Make sure the OWNER is correct • If your stored procedure is defined in Package/Package Body, the PROCNAME argument does not containpackage name, but the call argument does.

Your REFCURSORINDEX is set the correct. For example if you define the Out cursor is the third arguments inyour Stored Procedure, then this number is 3.

2. When you get NegativeArraySizeException error while running a report designed with a stored procedure. Go to checkwhether some UDS columns returns negative scale (right click the UDS column, select Properties. Then check Scale). Ifso, that means your original table column called by the stored procedure is likely to be a Float data type. This will get thewrong Scale for a UDS column. Please follow the steps below to modify the UDS column's scale.

Go to the File | Options menuitem. Under the Advanced tab, find the Catalog Browser section and uncheckForbid editing data object properties. Click the Apply and OK buttons.

Go to Catalog Browser, highlight the UDS column name that you have problem with it, click the expand buttonto show the properties list. Now you can change the property values, such as SQL type, precision, scale to bethat it should be. For instance, you can change the negative scale for the problematic column to be the rightvalue.

Index

Index

Developing Reports from Stored Procedures

211

Page 224: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing Reports from User Data Source

Introduction

Before starting this section, we assume that you have already read the User Reference | UDS API chapter to get familiarwith the UDS API concepts.

As a database application, JReport Designer can access data stored in a database through the JDBC connection. Now,through User Data Source API, JReport Designer can also access data from an external data source, such as a text file,Lotus Notes etc., which is not stored in a database, or when no JDBC driver is available.

The UDS API is a part of JReport Data Access Model as shown in this diagram:

The User Data Source API

is a Java interface that provides a data set to JReport. • has a PARAMETER string, which can be changed when the UDS object is added into JReport Designer. Theresult set may be different according to the PARAMETER string. It is very flexible and convenient for you.Note: The PARAMETER here is the parameter string given to UDS interface. That is, UDS API provides amethod getResultSet(String strParam), and PARAMETER is String strParam in the above method. After readingthe subsequent information on UDS API, it will become clearer to you. We just remind you that PARAMETERhere is different from that in JReport Catalog. To distinguish them, we used upper−case PARAMETER to refer tothe parameter string in UDS and lowercase parameter for a parameter object in a catalog.

Reference Notes: Refer to User Reference | UDS API.

Case 1: Address Data Source

Introduction

This example is a plain text file AddressesList.txt which contains the data information like a dummy table:

Laurena Croft 34826 Atwood St. New York City NY 10004 USA...Jonathan Hopkins 5062 Brandon Green Ave. Minneapolis MN 55402 USA...

212

Page 225: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Jeremy Miner 9283 Cherry Leaf Lane Palo Alto CA 94303 USA.......

You can see each line sequentially records the name, address, state, region, zip code, country, email address and otherinformation. We will show you how to build a report using the data stored in a formatted text file. You can modify thisexample to satisfy your requirements.

Compiling and Running Address UDS

The data file is AddressesList.txt. There are three classes used in this example and their source codes are:AddressListUDS.java, AddressListResultSet.java and AddressListResultSetMetaData.java. These files are available onour web site at http://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials).

If you use your own UDS classes, you must be sure that the class files can be found while running. Therefore, thedirectory should be classpath/package name. For this demo UDS classes, the classes belong to a package named"help", you may copy the above necessary files under %JReportPro_Installroot%\help, and add the additional entry intothe classpath statement of the batch file starting JReport.

For example, on Windows, if you install JReport into the default directory c:\JReport and all the UDS classes are locatedunder c:\jreport\help, you need the following entry in the batch file c:\JReport\bin\JReport.bat:...java −classpathc:\jreport;c:\jreport\lib\report.zip;c:\jreport\lib\JREngine.zip...

On Unix, if you install JReport into the /usr/jreport:classpath = %classpath%:/usr/jreport:

Compile the example: go to the directory %installroot%\help and enter:javac −classpath ".;%Installroot%\lib\JREngine.zip;" Address*.java

Adding Address UDS into JReport Catalog

After compilation, start JReport with the batch file you just modified. You are prompted with the our demo catalogand reports. Click Cancel.

1.

Since UDS API will be connected with a user data source and is independent of the JDBC connection, you cancreate another catalog instead of building reports in the demo catalog Tutorial.cat. Go to File | New Catalog.We created a catalog uds.cat.

2.

In Catalog Browser, right click UserDataSource, on the context menu, click Add UserDataSource.3.

Developing Reports from User Data Source

213

Page 226: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Add User Data Source dialog, enter the following information, and then click OK4.

Developing Reports from User Data Source

214

Page 227: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now expand the added Address UDS, and you will see the table−like tree structure.5.

Developing Reports from User Data Source

215

Page 228: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Making a Report with Address UDS

Now go to File | New... menu item or click the New Report button on the Standard Toolbar to launch Report Wizard −Astep by step report designer assistant to build your report. Now let us view the result of our demo lesson7b.cls.

Developing Reports from User Data Source

216

Page 229: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Edit your report afterwards to give it a professional appearance.

Case 2: SQL Data Source

Introduction

This example is little bit complicated. It is to execute an SQL statement and return a ResultSet through JDBC API.

This is the Java code of class definition:

public class SQLDataSource implements JRUserDataSource{// Define data.public ResultSet getResultSet(String param) throws JRUserDataSourceException{// Method body.}

/*** Free the resources such as : Connection, Statement, ResultSet.*/public void releaseResultSet() throws JRUserDataSourceException{// Method body.

Developing Reports from User Data Source

217

Page 230: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

}}

The following explains the code:

The format of String variable parameter is "DRIVER=driver&URL=url&USER=user&PSWD=password&SQL=sql" .For example, we use HSQL DB as Data Source , and "C:\JReport\Demo\db\demo" is the hsql db path; "sa" is the user'sname; the password is "" and the SQL string is "select * from authors", the parameter string may be similar to:

DRIVER="org.hsqldb.jdbcDriver"&URL="jdbc:hsqldb:C:\\JReport\\Demo\\db\\demo"&USER=sa&PSWD=&SQL=select *from employeeIf you want to use pre−defined parameters in the catalog of JReport, you can input the parameter string like:

DRIVER="org.hsqldb.jdbcDriver"&URL="jdbc:hsqldb:C:\\JReport\\Demo\\db\\demo"&USER=@un&PSWD=&SQL=@sql

where, @sql is a parameter pre−defined in the catalog, and its default value is "select * from employee". The defaultvalue of @un is "sa".

The getResultSet() method will parse the parameter string, build a connection to the URL, and execute the SQLstatement.

The releaseResultSet() method will release the resource such as: Connection, Statement, ResultSet etc.

Compiling and Running SQL Data Source

In this example, the SQLDataSource will return the result set from our demo hsql db. Therefore, you should set up hsqldb path in the URL string pointing to our demo database at %installroot%\Demo\db\demo.

There is one class used in this example and its source code is: SQLDataSource.java. The file is available on our web siteat http://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials).

Store SQLDataSource.java is under %installroot%\help\. Compile the SQLDataSource.java (located under%installroot%\help\) and generate SQLDataSource.class. Append the path %installroot% to the classpath startingJReport Designer, so that at run time SQLDataSource can be found.

Adding SQLDataSource UDS into JReport Catalog

After compilation, start JReport with the batch file you just modified. You are prompted with our demo catalogand reports. Click Cancel.

1.

Since UDS API is to connect with user data source, you can therefore create another catalog instead of buildingreports in the demo catalog Tutorial.cat. Go to File | New Catalog... We created a catalog uds.cat.

2.

In Catalog Browser, right click UserDataSource | General...3.

Developing Reports from User Data Source

218

Page 231: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Add User Data Source dialog, enter the following information. Recall that if you check the Specify columnsoption, the column definitions list will be enabled and you can add column definitions. If you don't specify thecolumn definitions, the program will get them from the result set automatically. You can further specify thecolumn definitions especially for the precision, length, SQLType as in the dialog below.

4.

Developing Reports from User Data Source

219

Page 232: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Here, we will not specify column definitions. We will use the default ones from the ResultSet andResultSetMetaData. Fill in employees in the Name field and help.SQLDataSource in the Class Name field.Then in the Parameter panel enter:DRIVER="org.hsqldb.jdbcDriver"&URL="jdbc:hsqldb:C:\\JReport\\demo\\db\\demo"&USER=sa&PSWD=&SQL=select* from employeeThen, click OK.

Developing Reports from User Data Source

220

Page 233: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now expand the added employees UDS, and you will see the table−like tree structure.5.

Developing Reports from User Data Source

221

Page 234: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Making a Report with SQLDataSource UDS

Now go to File | New... menu item or click the New Report button on the standard Toolbar to launch Report Wizard−−Astep by step report designer assistant to build your report. Now let us view the result:

Developing Reports from User Data Source

222

Page 235: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Edit your report afterwards to give it a professional appearance.

Add Dynamic SQLDataSource UDS into JReport Catalog

JReport Designer supports Dynamic UDS feature. This feature can improve the performance significantly by retrievingonly the selected fields. At runtime, an option is provided for users to pick up those columns they want to see in areport, and JReport Designer will generate dynamic report according to user's selection.

Let's take the SQLDataSource as an example to illustrate the usage and effect of Dynamic UDS feature.

Assume that you have generated SQLDataSource.class, start JReport with the batch file you just modified. 1. Create a parameter, enter the information as below.

Parameter Name: sqlValue Type: StringPrompting Values:select * from employeeselect salary from employeeselect employeeid,employeeposition,hiredate,notes,salary,photo from employee

2.

Developing Reports from User Data Source

223

Page 236: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In Catalog Browser, right click UserDataSource | Add UserDataSource.3. In the Add User Data Source dialog, enter the following information.Name: employeesClass Name: help.SQLDataSourceParameters:DRIVER="org.hsqldb.jdbcDriver"&URL="jdbc:hsqldb:C:\\JReport\\demo\\db\\demo"&USER=sa&PSWD=&SQL=@sql

4.

Developing Reports from User Data Source

224

Page 237: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Use this data source you just added to create a new report, include all the fields.5. Click View, select select * from employee as the parameter.6.

You can see that data for all the fields is retrieved.7.

Developing Reports from User Data Source

225

Page 238: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Go back and run this report again, choosing select salary from employee this time.8. You can see that only the data for the Employees_Salary is fetched out.9.

Note: You may notice that there are no groups divided and the group name changes to NULL, this is because onlyEmployess_Salary field is selected this time. JReport Designer will not bother the employee position column, on whichthe group is based.

Case 3: Applying UDS for Stored Procedure in Oracle

Because of the unique nature of Oracle Stored Procedure, you are not able to add procedures of Oracle into a Catalog ofJReport directly. Therefore the usage of JReport is limited when you use an Oracle database. We have developed aUser Data Source class that can use Stored Procedures in Oracle. The class is named "OracleProcedureUDS", in the

Developing Reports from User Data Source

226

Page 239: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

package jet.datasource.oracle.

Reference Note: For how to use stored procedures in Oracle, please refer to User's Guide | Developing Reports fromStored Procedures.

Index

Index

Case 4: Creating Reports from Java Object Data Sources

Introduction

The JReport Designer UDS can use any Java object as a data source for you to create reports. To implement thisfunction, JReport Designer provides a class UDSForJavaBean, in which the getResultSet() method createsinstances for the interface JavaBeanDataProvider, and then uses the method init() to initialize the data of thecreated instances.

Below is the java code of the class definition:

public class UDSForJavaBean implements JRUserDataSource { // Define data. public ResultSet getResultSet(String param) throwsJRUserDataSourceException { // Method body. }

/*** Free the resources such as : Connection, Statement, ResultSet.*/ public void releaseResultSet() throws JRUserDataSourceException { // Method body. } }

The interface JavaBeanDataProvider is defined as follows:

public interface JavaBeanDataProvider { public void init(String dataID, Properties initprops) throws JavaBeanDataProviderException; public Class getMetadataJavaBean() throws ClassNotFoundException; public Object next() throws JavaBeanDataProviderException; public boolean requireDetails(String collectionPropName); public int getMaxShareTimes(String collectionPropName); public int getTimeoutForSubCollection(String collectionPropName); public void exit()throws JavaBeanDataProviderException; }

All the classes and interfaces of the example are compressed in UDSForJavaBean.zip under<install_root>\help\pro−material.

Developing Reports from User Data Source

227

Page 240: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For examples of how to create reports using the Java object data interface, JReport Designer provides two demos whichare also in UDSForJavaBean.zip under <install_root>\help\pro−material. Below are the detailed steps of thedemos.

Before running the demos, you need to do the following:

Extract UDSForJavaBean.zip to <install_root>\help\UDSForJavaBean.

Note: You need to create the UDSForJavaBean directory.

1.

Compile all the java files,

javac −classpath<install_root>\help\UDSForJavaBean;<install_root>\lib\JREngine.zip;<install_root>\lib\log4j−1.2.8.jar; *.java

2.

Add the path <install_root>\help\UDSForJavaBean in setenv.bat in the<install_root>\bin directory.

3.

Demo 1: Creating Reports from Simple Java Object Data Sources

In this example, a Java object named Person will be used as the data source, you can find the person.java fileunder<install_root>\help\UDSForJavaBean\jreport\uds\javabean\beans. It is defined as follows:

public class Person implements Serializable {

private String gender; private String ssn; private String emailAddress; private Date birthDate; private Long newbornWeight; private YesNo isDataVerified; private Name name; private Address currentMailingAddress; private Phone currentWorkPhone;

/*** @return the birthDate.*/ public Date getBirthDate() { return birthDate; } }

Similar to the code above, other attributes of the Person object are defined by other Java objects, such ascurrentMailingAddress which is defined by the Address class.

Create a report from the Person Java object

Please follow the following steps:

After adding <install_root>\help\UDSForJavaBean to the classpath, start JReport Designer.1. This demo uses generated data, in order to get the real collection of the data objects, please create twoparameters before you import the Person Java object.

2.

Developing Reports from User Data Source

228

Page 241: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Open the Catalog Browser, create two parameters as shown below:

Parameter Name: pUseFakeData (Specify whether to use generated data when running the report.)Value Type: BooleanPrompting Value: True

Parameter Name: pNumOfFakeData (Specify the number of data records to generate that will be shown whenrunning the report.)Value Type: IntegerPrompting Value: Any integer numberOpen the Catalog Browser, right click the UserDataSource node, then click Add UserDataSource on thecontext menu. The Add User Data Source dialog appears.

3.

On the Add User Data Source dialog, type Person in the Name text box.4. For the Class Name text box, click the Browse button, go to<install_root>\help\UDSForJavaBean\jreport\uds\javabean, and then choose theUDSForJavaBean.class. The UDS class UDSForJavaBean.class will import the classjreprot.uds.javabean.beans.Person with full class name.

5.

In the Parameters text box, please type in the following string:

JavaBeanDS_DataProvider=jreport.uds.javabean.GenericBeanDataProvider&JavaBeanDS_RuntimeDataID=&GBeanProvider_BeanClsName=jreport.uds.javabean.beans.Person&GBeanProvider_UseFakeData=true&GBeanProvider_NumOfFakeData=@pNumOfFakeData&GBeanProvider_RptDataInitializer=

All the highlighted names in the parameter string above are the key words for the information required by thisUDS and related Java class. See the detailed explanation below:

JavaBeanDS_DataProvider is used to specify the Java class which implementsjreport.uds.javabean.JavaBeanDataProvider interface, and will return the list of required dataobjects at runtime – in this demo, it is a list of Person objects.

JavaBeanDS_RuntimeDataID is a reserved value used as a key to get data objects from theDataCenter.

GBeanProvider_* are required values for the special data provider −jreport.uds.javabean.GenericBeanDataProvider − which is specified byJavaBeanDS_DataProvider.

You can use this provider (jreport.uds.javabean.GenericBeanDataProvider) or create yourown provider by implementing the interface jreport.uds.javabean.JavaBeanDataProvider.

6.

Click OK on the Add User Data Source dialog. The UDS named Persons is generated.7. Create a report with this UDS by using the Report Wizard.8. Click View to run the report. Type 3 as the value of the parameter pNumOfFakeData, and click OK. Threerecords will be returned. However, the data you get now is the generated data, because in the Parameter stringof the UDS, you have specified the value of the key word GBeanProvider_UseFakeData to true.

9.

In order to get the real collection of data objects, the parameter pUseFakeData will be used to control the valueof the key GBeanProvider_UseFakeData value dynamically as follows.

In the Catalog Browser, right click Persons under the UserDataSource node, and click EditUserDataSource on the context menu. The Edit User Data Source dialog appears.

On the Edit User Data Source dialog, in the Parameters text box, modify the value ofGBeanProvider_UseFakeData to @pUseFakeData.

10.

Open that report and run it again and specify the value of pUseFakeData as false to get the real collection ofdata at runtime.

Please note that the key word GBeanProvider_RptDataInitializer in the data providerjreport.uds.javabean.GenericBeanDataProvider is used to specify the Java class name whichimplements jreport.uds.javabean.RptDataInitializer interface. So if you are using the data providerjreport.uds.javabean.GenericBeanDataProvider, you just need to provide a class which implements

11.

Developing Reports from User Data Source

229

Page 242: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

jreport.uds.javabean.RptDataInitializer to return a collection, list, or array of the data objectsaccording to different reports and parameters.

Also, jreport.uds.javabean.GenericBeanDataProvider can recognize vector, collection and array of objects andretrieve the objects inside of the collection one by one.

Methods in the demo

Using jreport.uds.javabean.GenericBeanDataProvider

jreport.uds.javabean.GenericBeanDataProvider implements the interface ofjreport.uds.javabean. JavaBeanDataProvider by using the following methods:

public void init(String dataID, Properties initprops) throwsJavaBeanDataProviderException;public Class getMetadataJavaBean() throws ClassNotFoundException;public Object next() throws JavaBeanDataProviderException;public boolean requireDetails(String collectionPropName);public int getMaxShareTimes(String collectionPropName);public void exit()throws JavaBeanDataProviderException;

init()This method is called by UDSForJavaBean to ask the data provider to prepare the data collection/list by thegiven initProperties. Basically, the initProperties are the name and value pairs parsed from the UDS parameterstring.

For example, the GenericBeanDataProvider will get the list of properties with the following keys:

JavaBeanDS_DataProviderJavaBeanDS_RuntimeDataIDGBeanProvider_BeanClsNameGBeanProvider_UseFakeDataGBeanProvider_NumOfFakeDataGBeanProvider_RptDataInitializer

The values for those keys will be used by GenericBeanDataProvider to prepare the data collection. Forexample, if the value of GBeanProvider_UseFakeData is true, the GeneridBeanDataProvider will use the fakedata, otherwise it will create an instance by the class name provided by GBeanProvider_RptDataInitializer andask the data initializer object to return the collection of data objects.

getMetadataJavaBean()This method is called back from the UDS to get the bean class in order to construct the meta data for UDS. ForGenericBeanDataProvider, the Java bean class in the collection is passed in by the keyGBeanProvider_BeanClsName when you define this data source by UDS.

next()This method is called back from the UDS to fetch the next data object as a record for the report at runtime. ForGenericBeanDataProvider, the init() method constructs the data object collection, and the next() method isgoing to check if the collection is a Vector, Collection, or array of objects to determine automatically how to getthe next object from the constructed collection.

exit()This method is called back from theUDS when the JReport engine closes the result set returned by UDS. ForGenericBeanDataProvider, it will call the data initializer to close if the data is constructed by data initializer.

requireDetails()This method is called back by the UDS to check if a certain collection attribute from Java bean needs to bedisplayed in the metadata.

getMaxShareTimes()The sub−collection attribute from the Java data object could be shared among sub−reports. This is the call−backmethod from the UDS to determine the maximum number of times that a certain sub−collection object is going to

Developing Reports from User Data Source

230

Page 243: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

be shared by the current report. If your report is trying to share the same sub−collection of a Java data objectmore than this specified value, you will get an error at runtime. However, if your report actually needs to beshared less than the number specified, the data will stay in the buffer without being cleaned.

Using jreport.uds.javabean.RptDataInitializer

The implementation of this interface will be used by GenericBeanDataProvider to provide the collection of Java objectsfor different reports and parameters.

The following methods need to be implemented for this interface:

public Object getDataCollection(Properties props)throws RptDataInitializerException;public void close();

getDataCollection()This method is called by GenericBeanDataProvider to return the data collection object. The input props arepassed down from GenericBeanDataProvider and includes all the values passed down into the init() method ofthe GenericBeanDataProvider.

close()This method is called back by GenericBeanDataProvider when exit() function is called there.

Demo 2: Creating Reports from Java Objects with Multi−levels of Collections

Sometimes, the attributes of a Java object are defined by other lists/collections, such as the Java objectSimpleBeanTest under <install_root>\help\UDSForJavaBean\jreport\uds\javabean\beans. It is definedas follows:

public class SimpleBeanTest implements Serializable { private String test; private long l; private int i; private int[] intarray; private Person[] persons; private Collection addresses; private Date dMyDate;

From the code above, you can see that the Java class SimpleTestBean contains an array of Persons, a collection ofaddresses and an array of int values.

For this kind of Java object, JReport Designer can create a report that gets records from the SimpleTestBean, but it cannot show the list of persons information in the same report. If you want to create such a report − each record comes fromthe SimpleBeanTest object, and for each record, display the list of persons information − you have to use the mainreport and sub−report to implement this function. For how to do it, please see the demo below.

Create the main report using SimpleTestBean

Open the Catalog Browser, right click the UserDataSource node, and then click Add UserDataSource on thepop−up menu. The Add User Data Source dialog appears.

1.

On the Add User Data Source dialog, type SimpleTestBean in the Name text box.2. For the Class Name text box, click the Browse button, go to<install_root>\help\UDSForJavaBean\jreport\uds\javabean, and then chooseUDSForJavaBean.class. The UDS class UDSForJavaBean.class will import the classjreport.uds.javabean.beans.SimpleTestBean with full class name.

3.

In the Parameters text box, please type in the following string:

JavaBeanDS_DataProvider=jreport.uds.javabean.GenericBeanDataProvider&JavaBeanDS_RuntimeDataID=&GBeanProvider_BeanClsName=jreport.uds.javabean.beans.SimpleBeanTest&GBeanProvider_UseFakeData=true&GBeanProvider_NumOfFakeData=@pNumOfFakeData

4.

Developing Reports from User Data Source

231

Page 244: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

&GBeanProvider_FakeDateSubCollectionInfo=persons,jreport.uds.javabean.beans.Person&GBeanProvider_RptDataInitializer=&GBeanProvider_ListOfDetailProps=persons,1,30000

All the highlighted names in the parameter string above are the key words for the information required by thisUDS and related Java class. See the detailed explanation below:

GBeanProvider_ListOfDetailProps specifies the following items:the list of property names of sub−collections that will be displayed in the meta−data,how many times that this report is going to share the sub−collection per main object,the timeout for the shared data in the DataCenter in milliseconds (the default value is 1 min).

In this demo, only the sub−collection property persons will be imported from the SimpleTestBean class,and the share time is 1. If you want to create another sub−report using addresses, you have to specifythe value for this key word as the following:

=&GBeanProvider_ListOfDetailProps=person,1,30000$addresses,1,30000

and different properties are separated by the symbol $.

GBeanProvider_FakeDateSubCollectionInfoThe value of this key word is used to construct the fake data for SimpleTestBean collections. Each Javaclass can have multiple sub−collection objects, and it is allowed to not construct the values of thesesub−collection objects if you do not want to use it. However, if you do not specify them here in thisparameter string as <property name>,<property class name>$<propertyname>,<property class name>, the fake data for those sub−collections will not be constructed, andproblems will occur when running the report on fake data.

Click OK on the Add User Data Source dialog. The UDS SimpleTestBean is generated. In the Catalog Browser,you will see that persons appears in the resource tree under the SimpleTestBean node.

5.

Create the main report based SimpleTestBean, and name the report as MainRpt.cls.6.

Create the sub−report

Before importing the data source for the sub−report, please create a parameter namedpRunTimeDataInfo, which will be used when setting up the link between the main report and the sub−report.

Parameter Name: pRunTimeDataInfoValue Type: String

1.

On the Add User Data Source dialog, type PersonsAsSubRpt in the Name text box.2. For the Class Name text box, click the Browse button, go to<install_root>\help\UDSForJavaBean\jreport\uds\javabean, and then chooseUDSForJavaBean.class.

3.

In the Parameters text box, please type in the following string:

JavaBeanDS_DataProvider=jreport.uds.javabean.GenericBeanDataProvider&JavaBeanDS_RuntimeDataID=@pRunTimeDataInfo&GBeanProvider_BeanClsName=jreport.uds.javabean.beans.Person&GBeanProvider_UseFakeData=@pUseFakeData&GBeanProvider_NumOfFakeData=@pNumOfFakeData&GBeanProvider_RptDataInitializer=jreport.uds.javabean.SubRptCollectionDataInitializer

All the highlighted names in the parameter string above are the key words for the information required by thisUDS and related Java class. See the detailed explanation below:

JavaBeanDS_RuntimeDataID is defined to use a parameter which will be the link point from thesub−report to the sub−collections in the main report

GBeanProvider_RptDataInitializer's value isjreport.uds.javabean.SubRptCollectionDataInitializer, which is our build−in dataprovider set up especially for the sub−report to return the collection of data by referencing thesub−collection in the main report. The referencing information is passed via the parameter value@pRunTimeDataInfo which will be used when we set up the link between the main report and the

4.

Developing Reports from User Data Source

232

Page 245: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

sub−report. The class name for GBeanProvider_BeanClsName is Person because the sub−report will use thePerson object.

Click OK on the Add User Data Source dialog. The UDS PersonsAsSubRpt is generated.5. Create the sub−report based PersonsAsSubRpt, and named the sub−report as SubRpt.cls.6.

Link the main report and the sub−report

In the Catalog Browser, create a formula named NotUseFakeData to return false all the time. This formula willbe passed into the sub−report as the value of the parameter pUseFakeData in the sub−report. So that when thesub−report runs with the main report, it will always use the data from the main report instead of constructing thefake data itself.

1.

Open MainRpt.cls, add a new detail section into the report and bring up the Insert SubReport dialog. 2. On the Insert SubReport dialog:

Click the Browse button, choose the SubRpt.cls as the sub−report.♦ On the Parameters in SubReport tab, specify values for the parameters as follows:♦

Parameter Value

pNumOfFakeData pNumOfFakeData

pUseFakeData NotUseFakeData (gives a false value to the parameter)

pRunTimeDataInfoSimpleTestBean_persons (specifies to use thesub−collection persons of the main report as the datasource of the sub−report at runtime)

3.

Click Ok on the Insert SubReport dialog and put the sub−report to the second detail section of the main report.4. Run the report, and you will find that the corresponding persons information are displayed in the sub−report.5. If you want to insert another sub−report which shares the same sub−collection with SubRpt.cls, you shouldmodify the value of the key word GBeanProvider_ListOfDetailProps in the main report UDS parameterstring to GBeanProvider_ListOfDetailProps=persons,2,30000.That changes the share amount of thepersons property from 1 to 2.

6.

Index

Index

Developing Reports from User Data Source

233

Page 246: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing Reports from Hierarchical Data Source

Introduction

Before starting this section, we assume that you have already read the User Reference | HDS API chapter to get familiarwith the HDS API concepts.

As a database application, JReport Designer can not only access data stored in a database through the JDBCconnection and User Data Source (UDS), but support to import data from Hierarchical Data Source (HDS).

The HDS API is a part of JReport Data Access Model as shown in this diagram:

The Hierarchical Data Source API

is a Java interface that provides a data set to JReport. • has a PARAMETER string, which can be changed when the HDS object is added into JReport Designer. Theresult set may be different according to the PARAMETER string. It is very flexible and convenient for you.

Note: The PARAMETER here is the parameter string given to HDS interface. That is, HDS API provides amethod getResultSet(String strParam), and PARAMETER is String strParam in the above method. After readingthe subsequent information on HDS API, it will become clearer to you. We just remind you that PARAMETERhere is different from that in JReport Catalog. To distinguish them, we used upper−case PARAMETER to refer tothe parameter string in HDS and lowercase parameter for a parameter object in a catalog.

Reference Notes: Refer to User Reference | HDS API.

XML Data Source

XML HDS Overview

As the XML technology has become a popular standard for data interchange on the web, JReport Designer directlysupport XML format data source by wrapping the provided hierarchical data source API.

234

Page 247: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Importing XML format HDS into JReport Catalog

Since JReport Designer has its built−in classes to implement the XML format hierarchical data source interface, you candirectly import the XML data source using Catalog Browser.

You are about to connect with external hierarchical data source, you can therefore create another cataloginstead of building reports in the demo catalog Tutorial.cat. Go to File | New Catalog... We will create a catalognamed HDS.cat.

1.

Here we use an XML file as an example, the data structure inside the XML file is like below.2.

In Catalog Browser, right−click HierDataSource, and then click Add Import XML.3. On the Import Hierarchical Data Source dialog, provide the information respectively according to your datasource information.

JReport Designer supports all kinds of URI as the XML data source. Please see the detailed information below: If you you are using an XML file as the data source, and also you want to specify a schema file for theXML data source file, you must make sure the schema file path specified in the XML data source file isconsistent with the path you specified in the XSD URI text box, and the file actually exists. Click theParse button to load the structure of the XML file, and the root of the file will be listed in the RootName text box.

4.

Developing Reports from Hierarchical Data Source

235

Page 248: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Designer supports static string inline with multiple parameters, for example:

"http://localhost:8888/jrserver%2fhsqlDemo%2fTutorial.cat/GroupingWithFormulas.cls?jrs.cmd=jrs.try_vw&jrs.result_type=7"

It is the URL used to run the demo report GroupingWithFormulas.cls to the XML format of JReportEnterprise Server. Type the URL into the XML URI text box, and click the Parse button, the structure ofthe returned XML stream will be loaded in the Structure panel.

Please note that you should check the No Security Checking option on the Advanced tab of the serverAdministration page before parsing this URL.

In addition, JReport parameters can be dynamically referenced in the URI for setting different values atruntime.

Note: The colon ':' and '@' symbols are used to identify JReport parameter names. If these symbols are used inyour XML URI and you do not want JReport to parse them as parameters, you must add quotation marks tothem. For example, when you browse to d:\test\employee.xml, −− you can quote it either as"d:\test\employee.xml" or d":"\test\employee.xml. Doing so is required for new reports created withV7.2. Reports built with previous versions can be automatically run. Once the existing reports and catalog aresaved with V7.2, JReport will automatically convert them to the new convention.

Now expand the added Report root, and you will see the tree structure of the tables and sub−tables.5.

Developing Reports from Hierarchical Data Source

236

Page 249: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Notes:

An XML data source file without any schema file is also allowed, say, you can leave empty the XSD URI entry.However, the data type VARCHAR will be used for all the columns in the data source. For more informationabout importing XML format HDS with XSD file, please refer to User Reference | The XSD File.

When import the XML file, you have to define the types of some data in the Format column. For example, if it isa Date type, shch as 1978−03−12, in the corresponding Format column, type in yyyy−MM−dd. If the data is$12,345.32, in the corresponding Format column, type in $##,###.##.

When import the XML file, by default, the value of the Scale column is 0, so for the decimal type data, you haveto specify the scale value in its corresponding Scale column: modify the value to the number of the digits to theright of the decimal point. For example, if the data is 123.23, then in the Scale column, modify the value to 2.

For the Currency, and Array columns, check them if necessary.• When specify a schema file for the XML data source file, beause the schema file is complex, there are somelimitations:

About namespace: now, only default namespace (3w) is supported by JReport Designer. You can definea prefix, such as xs, or xsd, but the value of elementFormDefault must be qualified. The value ofattributeFormDefault should be unqualified, but JReport Designer dose not allow you to add prefixesbefore the attributes of the elements.

About type: if the customized simpleType or compexType is used, please do not add the prefix to thevalue of the type, while if the built−in simpleType or compexType is used, the prefix must be added.

Developing Reports from Hierarchical Data Source

237

Page 250: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Making a Report with Hierarchical Data Source

Now you can develop your report using the hierarchical data source you have imported. Developing a report from thehierarchical data source is rather the same as that from a standard database.

Go to File | New menu item or click the New Report button on the standard Toolbar to launch Report Wizard − A step bystep report designer assistant − to build your report.

The report result of the above example will be somewhat like the following:

Please note that the report result on the screen shot is decorated with different colors to make its group structure clear.Your report does not need to be necessarily like this.

Notes:

The Joins tab will not be available for the reports created from hierarchical data source. • The report you create from hierarchical data source is automatically grouped. On the Group tab, you will not beable to add or remove group−by fields. However, you can make changes to the existing group criteria.

Developing Reports from Hierarchical Data Source

238

Page 251: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Viewing Reports with Dynamic XML URI

Since JReport Designer version 6, dynamic XML URI is supported. The XSD file defines the structure of the XML formatHDS and the XML file in fact only provides the data, so one XSD file can match more than one XML file. That enablesyou to view the report with dynamic XML URI.

To view the report with dynamic XML URI,

In Catalog Browser, create a new parameter. On the Create Parameter dialog, give a name to the parameter,choose String as the Value Type, and in the Prompting Values box, type in the URI of a XML file.

1.

Import the XML format HDS. On the Import XML Data Source dialog, in the XML URI box, type in@ParameterName, for example, if you named the parameter in the first step as XML_URI, here you should typein @XML_URI. In the XSD URI box, specify the URI of the corresponding XSD file.

2.

Specify the Root Name and click Parse. Click OK to finish importing the HDS to JReport Designer.3. Create report with the imported HDS. When you view the report, type in the URI of the XML file which matchesthe XSD file in the parameter, and then you will get the different data displayed in the report.

4.

In addition, you can also use another way to view report with dynamic XML URI.

In Catalog Browser, import XML data source with the XSD file.1. Create report with the imported HDS.2. Create a new parameter using the way mentioned above.3. In Catalog Browser, go to the root node of the imported HDS, expand the Properties panel, and then change theproperty URI to @ParameterName.

4.

Now you can view the report with dynamic XML file.

Running Reports on JReport Enterprise Server

When you want to run reports based on the XML data source on JReport Enterprise Server, the following method isrecommended:

In Catalog Browser, expand the Properties panel, browse to the imported HDS used by the report, and thenchange the URI property to a relative path, say, only remain the name of the XML file.

1.

Create a new folder. 2. Copy the report, the catalog, the XML file and the XSD file (if any) to the newly created folder.3. On JReport Enterprise Server, deploy the folder.4.

Now you can run the report on the server.

Also, you can deploy the report from JReport Designer to JReport Enterprise Server first and then run it on the server,but before deploying, you must do the followings:

In Catalog Browser, change the URI property of the XML file to a relative path.1. Copy the XML file to the same path as the catalog's. 2.

Now please deploy the report from JReport Designer to JReport Enterprise Server and then run it on the server.

General Hierarchical Data Source

General HDS Overview

JReport Designer provides you with a set of hierarchical data source application programming interfaces to allow you toimport your customized hierarchical data source from outside.

Developing Reports from Hierarchical Data Source

239

Page 252: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

This is the Java code of class definition:

public class HierarchicalDataSource implements JRHierarchicalDataSource{ //Define data. public JRHierarchicalDataset getHierarchicalDataset(String param) throwsJRUserDataSourceException { //Method body. }

public void releaseHierarchicalDataset() throws JRUserDataSourceException { //Method body. }}

The following explains the code:

The getGetHierarchicalDataset() method will get the data in JRHierarchicalDataset according to parameters.

The releaseHierarchicalDataset() method will release the data and related resources.

Compiling and Running Hierarchical Data Source

In this example, the HierarchicalDataSource.java will return the result set from our demo hsql db.

There is three classes used in this example and the source code files are: HierarchicalDataSource.java,HierarchicalDatasetMetaData.java, and HierarchicalDataset.java. These files are available on our web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials).

Store these files under %installroot%\help\. Modify the demo hsqldb path in HierarchicalDatasetMetaData.java andHierarchicalDataset.java. Compile them (located under %installroot%\help\) and generate HierarchicalDataSource.class,HierarchicalDatasetMetaData.class, and HierarchicalDataset.class. Append the path %installroot%\help to theclasspath starting JReport Designer, so that at run−time HierarchicalDataSource can be found.

Adding SQLDataSource HDS into JReport Catalog

After compilation, start JReport with the batch file you just modified. You are prompted with our demo catalogand reports. Click Cancel.

1.

You are about to connect with external hierarchical data source, you can therefore create another cataloginstead of building reports in the demo catalog Tutorial.cat. On the File menu, click New Catalog. We willcreate a catalog named HDS.cat.

2.

In Catalog Browser, right−click HierDataSource, select New HierDataSource | HDS General.3.

Developing Reports from Hierarchical Data Source

240

Page 253: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the Import Hierarchical Data Source dialog, click the Browse button to find the classHierarchicalDataSource.class. Type a number in the Parameter box, only the records whose employee ID is lessthan this number will be fetched. Click Load Tree, the data source tree will be parsed.

Click OK when you finish.

4.

Developing Reports from Hierarchical Data Source

241

Page 254: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now expand the added Report root, and you will see the tree structure of the tables and sub−tables.5.

Use this data source you just added to create a new report, the report result will be somewhat like the following:6.

Developing Reports from Hierarchical Data Source

242

Page 255: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Please note that the report result on the screen shot is decorated with different colors to make its group structureclear. Your report does not need to be necessarily like this.

Reference Note: For more information about the HDS APIs, please refer to Reference | HDS API.

Parallel Hierarchical Data Source

Parallel HDS Overview

JReport Designer supports parallel hierarchical data source. A parallel HDS is similar to the normal HDS. The differencebetween them is that the parallel HDS contains more than one parallel branches.

Before using the parallel hierarchical data source feature, it's necessary for you to have a general idea about somespecific concepts and terminologies related to the parallel HDS source in JReport Designer.

Data in Parallel HDS are organized in a tree structure, which contains branches and leaves. Among these branches,there are some parallel branch nodes that split the trunk of the data source tree into more deep and complex branches.

Developing Reports from Hierarchical Data Source

243

Page 256: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Fig 1− PHDS Structure Illustration

What's a leaf?A leaf in parallel HDS refers to a column (DBField), nodes that contains no sub−nodes.

What's a branch?A branch in parallel HDS is a special table that contains leaves or sub−branches.

Fig 2 − Branch Definition

What're parallel branches?If the contents of two branches have no parental relationships, we call these branches parallel branches.

Using Parallel HDS

The usage of the parallel HDS is the same as that of the normal HDS. Please refer to the sections above.

General HDSXML HDS

However, there are some key points that you should know:

Developing Reports from Hierarchical Data Source

244

Page 257: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parallel HDS Support LimitsSome report templates don't support parallel HDS, such as HBlank, Invoice and Table templates. Data Objectsdon't support parallel HDS.

Groups in Parallel HDSWhen you insert a group by field, its children will be inserted together. As shown in the screen shot below, whenyou add the column Country, its sub tables will be added together, including Products, Customers, and Orders.

The parallel structure in the parallel HDS is represented as groups in JReport Designer. Therefore, when youdevelop a report from a parallel HDS, your report will be automatically grouped.

Developing Reports from Hierarchical Data Source

245

Page 258: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

By default, JReport Designer will use the first found field as the group by field. Please note that you can neitheradd a new group by field nor remove the group by fields that are automatically added. However, if there are morethan one field available for grouping the sub−tables, it can be replaced by one of the other available fields. Rules for Inserting an ObjectA. Objects in different branches should be placed in the section they belong to, say, one section cannot hold theobjects that belong to different branches.

B. The children of a branch, including the columns, formulas, summaries, sub−branches, and children of thesub−branches, can be inserted into any of its parent sections. If the parent section is shared by more than onebranchs, say, the parent section works as a trunk (global section), it can be shared by the children of all thebranches it holds. However, you must note that each instance of a section, such as a report ( page/group )header ( footer ) section, and detail section, can only hold the children in the same branch. If you want to insertthe children of different branches into the shared global section, please create as many instances of this sectionas the number of branches, and then insert the children of each branches into these sections respectively.

For example, we insert a branch Orders into a report, whose tree is shown as the below picture.

Developing Reports from Hierarchical Data Source

246

Page 259: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Orders branch contains a sub−branch named OrderDetails, who holds two parallel branches namedOrder_ProductInfo and Order_DetailInfo.

On the report design canvas, you should notice that the columns belongs to these two parallel branches areinserted to two separate detail sections. You will not be able to insert these four columns into one detail section,because they belongs to different branches.

You can insert the columns to its parent sections, such as group header section, however, if you insert both theDiscount and Shipped columns into GroupHeaderPanel(CUSTOMER_ID1), when you try viewing the report, youwill get errors. To insert these two columns to that section, insert a section afterGroupHeaderPanel(CUSTOMER_ID1), and then insert these two columns to these two sections separately.

Developing Reports from Hierarchical Data Source

247

Page 260: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

C. Where a formula/summary can be inserted depends on the branch attributes of the formula/summary.Generally speaking, when a formula/summary creates relationships to a column, it will get the same branchattriblutes as that of the related column, and it can be placed in the sections where the column can be placed.

The global formula, which is not associated with any branch columns, can be placed to any position of the report.When you remove a branch using the Report Form Creation Wizard, the relevant section will also be removed.• The chart based on field can be only placed in its own sections, which including most of the global sections,except for the detail section.

The crosstab must be built upon the same branch data, and it should be placed in the location where the branchdata reside.

Where a text object can be inserted depends on the branch attriblutes of the columns (formulas/summaries) thatit contains. A text object can hold only the data of the same branch.

Developing Reports from Hierarchical Data Source

248

Page 261: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Developing Reports with OOJDBC

Introduction

OOJDBC is defined to cover an OODS(Object Oriented Data Source) with a JDBC interface. It is similar to a JDBC driverand is based on Java application, EJB(Enterprise Java Bean), LDAP(Light Weight Directory Access Protocol), SF(SanFrancisco) which can be defined as a Database. We have also developed a tool named Model Wizard so that you canrun this tool to import the data via XML datasource.

Here is the main frame for OOJDBC:

OOJDBC includes Wizard and OOJDBC Driver.

Wizard: Open/Save Model FileDefine a Java Class as a tableDefine a method as a columnHow to access the instance of the class

OOJDBC Driver: Read the table/column definitions from Model FileReturn Meta−Data to JReport Construct QUERY data Return Record to JReport

Let us follow with several examples of its applications.

249

Page 262: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 1: XML

As we know, XML(Extensible Markup Language) is a new generation of HTML. Now in JReport Designer, we cansupport XML as a datasource via OOJDBC.

This example will use employee.xml. This file is available on our web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials). You can store it to%installroot%\Demo\reports.

Importing XML Files

Run ModelWizard.bat under %Installroot_JReportPro%\bin, then the following dialog will appear:

Add Table: Add a new table.Remove Table: Remove the current existing table.Modify: Revise the current existing table.

In our example, we now fill in the Table Name as employee. The class name iscom.jinfonet.jdbc.RecordResult, and it is a class of Jinfonet. Then press the Parse button.

1.

Developing Reports with OOJDBC

250

Page 263: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Where,Column Name: Methods of the class you have defined. SQL Type: Returned type of your column name. You can also double click the field and choose the sql type youwant. Precision: Precision of the current column. You can also click on the field and change it manually. Scale: Scale of the current column. You can also click on the field and change it manually. Nullable: Current status of the column (null or not). You can also double click on the field and choose the currentstatus:Nullable, No Nulls or Nullable Unknown etc. Currency: If your db field contains $, you should check it. Add: Add new columns.Remove: Remove the current existing column.Direct Access Path: Select the path. OOJDBC driver can save and restore the table you have defined throughthis path.Modify Column: Modify parameters of the current table. Press the Remove button to get rid of the current existing columns as shown below: 2.

Developing Reports with OOJDBC

251

Page 264: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then click the Add button in the Add Table dialog and the following panel will appear. If you want to define thedata type as integer, you can add "int", press on it and in "Default Value", fill in 0. Press the Add button, then thereturn value int has already been added in.

3.

Developing Reports with OOJDBC

252

Page 265: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the above dialog, if you want to use "DynamicParameter", you can choose the option "Is Dynamic". The syntaxof the method is an array of boolean values to indicate which parameter is dynamic at run time. If the parameteris dynamic the value should be prompted and initialized before executing a SQL.

If you use dynamic parameters, that is, you choose the option "Is Dynamic", this parameter will be passed toJReport Designer. After you create a new connection, in Catalog Browser, you will find parameter under thenode "parameters". This also applies for another Return Type java.lang.String, give the default value as 1. Click the Add button.4.

Developing Reports with OOJDBC

253

Page 266: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click OK in the Access Indirect Columns to go back to the Add table dialog, Click Direct Access Path , then thefollowing dialog appears. In the Root Class Name text field, fill in com.jinfonet.jdbc.xml.XMLReader, press theParse button. Let us take an example: in default Value, for param0, fill infile:///c:/jreport/demo/reports/employee.xml, then in param1, fill in record employee column id 4 columnfirst_name 12 .

5.

Developing Reports with OOJDBC

254

Page 267: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Where,1. param0 is the valid xml file name with its path.

2. param1 is the query sentence for selecting from the xml file which columns to be used for reporting. record isthe keyword, followed with the xml file name (without the extension .xml).

Following this is another keyword column with the actual tag name from the xml file. In this case for instance,here is the part quoted from employee.xml: <employee> <id>0799</id> <first_name>Jack</first_name> <second_name>Smith</second_name> <birthday>12/28/75</birthday> <title>manager</title> <salary>$7000.00</salary> </employee>Since we want first_name and id, then you should give the actual tag name here.

The number afterwards is the sql type of the column. "4" is for Integer type, and "12" is for String type. For

Developing Reports with OOJDBC

255

Page 268: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

detailed information about java sql types, please refer to JDK package java.sql.types.java.

Note:1. In the param1, the order of the columns is depended by the default values given while adding the column. Inthis example, the first column is "int" and the default value is "0", so the param1 should be record employeecolumn id 4 column first_name 12 instead of record employee column first_name 12 column id 4.2. The sql type BINARY, VARBINARY and LONGVARBINARY are not supported. Press the Next button, then follow with the OK button in the panel above, we will see that the two columns havealready been added in.

Here, you can rename the default column name by editing the Column Name tag. We recommend for you to givethe name as the actual tag definition in the .xml file, like here first_name and id.

6.

Press the OK button, the table employee has already been added in: 7.

Developing Reports with OOJDBC

256

Page 269: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Go to File | Save menu item, and you will be prompted to save the .odf file. You should save it to %installroot ofJReport Designer%\lib or the directory where the catalog will be. Here we save it as xml.odf.

Notes:

1). The same odf file can not exist both under %installroot of JReport Designer%\lib or the directory where thecatalog locates.2). Since JReport Designer version 6, you can also save the odf (oojdbc data definition file) to XML format, that iswith the extension .odf.xml, if you have purchased the readable key. For the files that have been saved with the.xml extension before, in order to make them available after version 6, manually change the extension from .xmlto .odf.xml.

8.

Importing the XML.odf to JReport Catalog

Start JReport Designer with the modified batch file. 1. Cancel the Choose Report dialog. Go to File | New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved theodf file under C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In Get JDBC Connection Information panel, uncheck Use ODBCData Source, and check JDBC Driver. Enter com.jinfonet.jdbc.obj.ObjectDriver in the JDBC Driver field.Type jdbc:jinfonet:object:@Filename in the JDBC URL as . Please note: @File name should be the .odf nameyou have saved. So in our case, it should be jdbc:jinfonet:object:@xml

2.

Developing Reports with OOJDBC

257

Page 270: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now, the table structure will be added into the catalog, with which we can build a report. Click the New Reportbutton on the Standard Toolbar. Walk through the tabs, and finish developing the report.

3.

You will see the report in the design mode like this:4.

Developing Reports with OOJDBC

258

Page 271: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: When you deploy the catalog and its reports to JReport Enterprise Server, whatever the odf file locates in%installroot of JReport Designer%\lib or the directory where the catalog exists, the odf file will be deployed to the pathwhere the catalog is on the server side.

Case 2: Direct XML File Import

The above way of importing an XML file with Model wizard can be simplified with our built−in xml file import functionality.It is very easy−to−use. After the .odf file is saved, other steps of adding .odf to the catalog file and building a report willbe the same.

This example will use orgchart_data.xml. This file is available on our web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials). You can store it to%installroot%\Demo\reports.

Importing XML Files

Run ModelWizard.bat under %Installroot_JReportPro%\bin, then the following dialog will appear:1.

Developing Reports with OOJDBC

259

Page 272: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select the menu File | Import XML Files, we browse to the demo orgchart_data.xml, and check all for theColumn field. Please change the Format and Type of PhoneExt and Estabished as below.

Element: Methods of the class you have defined. Type: Returned type of your column name. You can also double click the field and choose the sql type as youlike. Precision: Precision of the current column. You can also click on the field and change it manually. Scale: Scale of the current column. You can also click on the field and change it manually. Nullable: Current status of the column (null or not). You can also double click on the field and choose the currentstatus:Nullable, No Nulls or Nullable Unknown etc. Currency: If your db field contains $, you should check it.

Reference note: For the details about how to set the format field, please refer to Examples of format.

2.

Press the OK button, the table employee will be added like this:3.

Developing Reports with OOJDBC

260

Page 273: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Go to the File | Save menu item, and you will be prompted to save .odf file. You should save it to %installroot ofJReport Designer%\lib or the directory where the catalog will be. Here we save it as orgchart.odf. For theinformation about saving the odf to XML format, see Case 1: XML in the section above.

Notes: The same odf file can not exist both under %installroot of JReport Designer%\lib or the directory wherethe catalog locates.

4.

Importing orgchart.odf to JReport Catalog

Start JReport Designer with the modified batch file.

Note: Beginning with Version 5, you needn't to add the three jars into the batch file starting JReport Designerwhen importing .xml or .odf files to JReport Catalog. So you can just start JReport Designer with the originalbatch file.

1.

Cancel the Choose Report dialog. Go to File | New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved theodf file under C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In the Get JDBC Connection Information dialog, uncheck UseODBC Data Source, and check JDBC Driver. Enter com.jinfonet.jdbc.obj.ObjectDriver in the JDBC Driverfield. Type jdbc:jinfonet:object:@Filename in the JDBC URL field. Please note: @File name should be the .odfname you have saved. So in our case, it should be jdbc:jinfonet:object:@orgchart.

2.

Developing Reports with OOJDBC

261

Page 274: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now, the table structure will be added into the catalog, with which we can build a report. Click the New Reportbutton on the standard Toolbar. Walk through the tabs, and finish developing the report.

3.

Note: When you deploy the catalog and its reports to JReport Enterprise Server, whatever the odf file locates in%installroot of JReport Designer%\lib or the directory where the catalog exists, the odf file will be deployed to the pathwhere the catalog is on the server side.

Developing Reports with OOJDBC

262

Page 275: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 3: Importing XML with Dynamic Parameters

When you design a report from the tables imported through OOJDBC, and the tables have the same input parameters,you surely won't want to input the same parameters again and again. JReport provides a way to allow you bind likeparameters in the catalog, so they can share the same parameter value. The following example demonstrates how toimport tables with dynamic parameters from the .odf file generated by Model Wizard.

Importing XML File

Run ModelWizard.bat under %Installroot_JReportPro%\bin. 1. Add two tables as you did in Case 1. The first table named employee1 has one String type column, the secondtable named employee2 has one Int type column. They have the same input parameter for param0, the defaultvalue is h:\xml\employee.xml. Please make sure to check the option Is dynamic as shown.

Note: If you choose the option "Is Dynamic", this parameter will be passed to JReport Designer. After youcreate a new connection, you will find this parameter under the node "parameters" in Catalog Browser.

2.

Go back to the Object Source Wizard dialog and select the File | Save menu item, save it asxmlparam.odf under %installroot%\lib or the directory where the catalog will be. For the information about

3.

Developing Reports with OOJDBC

263

Page 276: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

saving the odf to XML format, see Developing Reports with OOJDBC.

Note: The same odf file can not exist both under %installroot%\lib or the directory where the catalog locates.

Importing odf File to JReport Catalog

Start JReport Designer. 1. Create a new catalog, then create a new parameter named path to be bound to the parameters in the tablesimported through OOJDBC.

2.

Developing Reports with OOJDBC

264

Page 277: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create a new connection in Catalog Browser, set the JDBC connection information as shown below.3.

Click OK. The Add Table dialog appears to prompt you to add the listed tables. Select the employee1 tableand click the add button. You will get into the following dialog. Single click in the cell under the New columnand select the path parameter from the drop down list to bind the param0 to path.

4.

Repeat the above step to add the employee2 table and bind its parameter param0 to the parameter path. Nowthe parameters in the two tables share the same parameter path.

5.

Follow the Report Wizard to build a new report with the two newly inserted tables.6.

Developing Reports with OOJDBC

265

Page 278: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

When viewing the report, the following dialog pops up to prompt you to input the parameter. You only need toinput the path of imported xml file one time since the parameter is shared with the parameters in the two tables.

7.

Modifying the Dynamic Parameters in Catalog Browser

You can modify the links between the parameters in OOJDBC and parameters in JReport Catalog. To do this,

Launch Catalog Browser in JReport Designer. 1.

Developing Reports with OOJDBC

266

Page 279: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select the table with the dynamic parameters to be modified. Right click on the specified table, then selectParameters in the popped up menu.

2.

Highlight the parameter in Catalog, then select the parameter from the drop down list to bind it to the parameterin OOJDBC.

3.

Developing Reports with OOJDBC

267

Page 280: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

How does OOJDBC Work with Java Objects?

First: You should define a class that specifies the column name and the method of getting data from this column. Forexample: the file com\jinfonet\jdbc\demo\Products.java in our demo. In this class, the method public intgetProductID() implies that the column name is ‘ProductID’ and you can get the product ID via this method.

Second: You should publish a method to access a group of products. That means OOJDBC needs a ResultSet withmultiple rows, and each rows is one of the products, so that you should define a class that can retrieve the rows. Say,com\jinfonet\jdbc\demo\SQLReader.java in the demo. In this file, there is a static* method "JCollectionexecSQL(String jdbcDriver, String url, String sql)", and this method returns a collection that containsthe rows of the products. This collection can be one of the following three classes java.util.collection for Java2,java.util.Vector for Java1.1 and com.jinfonet.jdbc.obj.JCollection for both.

Case 4: Importing the Product Table via Model Wizard

Installation

Case 3 and Case 4 will all generate the .odf file in two different ways. We will use demo.zip. This zip file contains all thenecessary class files. In addition, we also include the source code for them for your reference. It is available on our website at http://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials). Save it under %installroot%\help,and add the demo.zip to the CLASSPATH of the the batch file starting Model Wizard(%installroot%\bin\ModelWizard.bat) and JReport Designer (%installroot%\bin\JReport.bat). Add%JReport_InstallRoot%\lib\hsqldb.jar to the batch file ModelWizard.bat.

Importing Product Table

Launch Model Wizard with the modified batch file under %installroot%\bin\ModelWizard.bat.1.

Click Add Table. In the ClassName field type com.jinfonet.jdbc.demo.Products. Input demo in the TableName field. Then, click the Parse button.

2.

Developing Reports with OOJDBC

268

Page 281: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click Direct Access Path. On the Access Method dialog, input com.jinfonet.jdbc.demo.SQLReader in theRoot Class Name field. Then click the Parse button. In the Method section, select the execSQL method, and inthe Parameters section, you can fill in the default values like: Param0 (the driver of the database): org.hsqldb.jdbcDriverParam1 (the connection URL of the database): jdbc:hsqldb:e:\JReport\Demo\db\demoParam2 (the user name): saParam3 (the password): (no value)Param4 (the SQL statement):select * from products

3.

Developing Reports with OOJDBC

269

Page 282: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the OK button and save demo.odf under %installroot%\lib or the directory where the catalog will be. Forthe information about saving the odf to XML format, see Developing Reports with OOJDBC.

Note: The same odf file can not exist both under %installroot%\lib or the directory where the catalog locates.

4.

Importing demo.odf to JReport Catalog

Start JReport Designer with the modified batch file. 1. Cancel the Open Report dialog. Go to File | New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved theodf file under C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In Get JDBC Connection Information panel, uncheck Use ODBCData Source, and check JDBC Driver. Enter com.jinfonet.jdbc.obj.ObjectDriver in the JDBC Driver field.Type jdbc:jinfonet:object:@Filename in the JDBC URL. Please note: @Filename should be the .odf name youhave saved. So in our case, it should be jdbc:jinfonet:object:@demo

2.

Developing Reports with OOJDBC

270

Page 283: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now, the table structure will be added into the catalog, with which we can build a report. Click the New Reportbutton on the Standard Toolbar. Walk through the tabs, and finish developing the report.

3.

Note: When you deploy the catalog and its reports to JReport Enterprise Server, whatever the odf file locates in%installroot of JReport Designer%\lib or the directory where the catalog exists, the odf file will be deployed to the pathwhere the catalog is on the server side.

Developing Reports with OOJDBC

271

Page 284: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Optimization of OOJDBC

Starting from JReport version 4.5, we have greatly improved the performance of joins among tables. In addition, weprovide an interface com.jinfonet.interfaces.query.TableFilter and a simple implementationcom.jinfonet.jdbc.obj.TableFilterImpl, through which the performance of Select clause and Where clause ina query could also be improved. You could extend TableFilterImpl to create your own Reader class. We have made ademo FilterSQLReader.java for your reference. Pay attention that if you are using FilterSQLReader.java instead ofSQLReader.java, the Root Class Name field in the Access Method dialog should inputcom.jinfonet.jdbc.demo.FilterSQLReader.

Case 5: Importing com.jinfonet.jdbc.demo.common.RecordResult via ModelWizard

Installation

Case 4 will generate the .odf file in a different way from Case 3. We will again use demo.zip. This zip file contains all thenecessary class files. In addition, we also include the source code for them for your reference. It is available on our website at http://www.jinfonet.com/webpage/kbase/kbase.htm (manual related materials). Save it under %installroot%\help,and add the demo.zip to the CLASSPATH of the the batch file starting Model Wizard(%installroot%\bin\ModerWizard.bat) and JReport Designer (%installroot%\bin\JReport.bat).

Importing com.jinfonet.jdbc.demo.common.RecordResult via Model Wizard

Launch Model Wizard with the modified batch file under %installroot%\bin\ModerWizard.bat.1.

Click Add Table. In the ClassName field type com.jinfonet.jdbc.demo.common.RecordResult. Input demo inthe Table Name field. Then, click the Parse button.

2.

Developing Reports with OOJDBC

272

Page 285: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Remove button to remove all the columns in the table. Then click the Add button to add new columnsin the table. You should use this method to add the parameter value in the column. The parameter value is thecolumn index.

3.

Developing Reports with OOJDBC

273

Page 286: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the OK button to go back to the Add Table dialog.4.

Developing Reports with OOJDBC

274

Page 287: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Direct Accessing Path button. In the Access Method dialog, inputcom.jinfonet.jdbc.demo.common.SQLReader in the Root Class Name field. Then click the Parse button. Inthe Method section, select the execSQL method then in the Parameters section, fill in the default values like: Param0: sun.jdbc.odbc.JdbcOdbcDriverParam1:jdbc:odbc:jinfonetParam2:select * from products( It uses sun’s jdbc−odbc driver to connect our demo database, ‘jdbc:odbc:jinfonet’ is our odbc datasource name.)

5.

Developing Reports with OOJDBC

275

Page 288: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the OK button and save demo.odf under %installroot%\lib or the directory where the catalog will locate asin Case 3. For the information about saving the odf to XML format, see Developing Reports with OOJDBC.

6.

Go back to Case 3 for using the demo.odf to make a report. 7.

Supporting EJB via OOJDBC in JReport

Introduction

You may have learned that JReport can support any data source through UDS. But to implement it, users need to beable to code with java language, so that the usage of UDS is confined to more advanced users. To resolve theproblems, we have defined OOJDBC to cover an OODS (Object Oriented Data Source) with a JDBC interface andsupport EJB as a datasource via OOJDBC(Currently we support EJB2.x). OOJDBC is similar to jdbc driver and is basedon Java application, EJB(Enterprise Java Bean), LDAP(Light Weight Directory Access Protocol), SF(San Francisco)which can be defined as a database. We have also developed a tool named Model Wizard so that users can run thistool to import their data via EJB datasource.

Developing Reports with OOJDBC

276

Page 289: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 6: Supporting EJB Deployed in J2EE

Installation

First: Install j2ee. You can download it from http://java.sun.com/j2ee/download.html. After the installation of j2ee, youwill find j2ee.jar under %installroot of j2ee%\lib. Please add j2ee.jar into the batch files of JReport Designer andModelWizard respectively.

Second: Install Jaxp1.1. You can download it using the URL: http://java.sun.com/xml/download.html.

After the installation, you will find three jars xalan.jar, crimson.jar and jaxp.jar under the installroot of Jaxp1.1.

Install JReport Designer, then you will find the batch file ModelWizard.bat under %installroot of JReport Pro%\bin, whichis for starting Model Wizard. Add the three jars into the classpath in the batch files ModelWizard.bat and JReport.bat. For example:...c:\jdk1.2.2\bin\java −classpath g:\java\classes;c:\jaxp1.1\xalan.jar;c:\jaxp1.1\crimson.jar;c:\jaxp1.1\jaxp.jar;com.jinfonet.jdbc.model.wizard.ModelWizard...

Note: After you deploy your ejb to j2ee server, it will return a jar in the root directory. In our case, we use Java(TM) PetStore Demo of jps1.0 in j2ee, the versions above jps1.0 are not supported. After we deploy it to j2ee server, it will returnestoreClient.jar in the root directly, then we add it in the batch file ModelWizard.bat. For example:...−classpath "c:\jps1.0\estoreClient.jar;c:\jaxp1.1\xalan.jar;c:\jaxp1.1\crimson.jar;c:\jaxp1.1\jaxp.jar;...

Importing EJB with ModelWizard

Make an EJB initializing class, and this class is coded by Jinfonet. This class is for looking up EJBHome by the JNDIname.

JNDI (The Java Naming and Directory Interface ™) is an API that provides naming and directory functionality. The JNDIprovides applications with methods for performing standard directory operations, such as associating attributes withobjects and searching for objects using their attributes. Using the JNDI, an application can store and retrieve any typeof named Java object. In particular, a J2EE application uses JNDI to find interfaces used to create enterprise beans,JTA UserTransaction objects, JDBC DataSource objects, and message connections.Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming anddirectory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. This allowsapplications to coexist with legacy applications and systems.

This example is using "Java(TM) Pet Store Demo". JNDI Name is "estore/catalog"; The class name is"com.sun.estore.catalog.model.Category". This table is defined by users. Users can get the table they requestthrough parsing the class.

Launch Model Wizard with the modified batch file under %installroot%\bin\ModerWizard.bat.1.

Developing Reports with OOJDBC

277

Page 290: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the Add Table button. As we explain above, in our example: JNDI Name is "estore/catalog" and the classname is com.sun.estore.catalog.model.Category. Define the table name as Category, then press theParse button.

2.

Click the Direct Access Path button to define the accessing path of order table. In the Access Method dialog,fill in com.jinfonet.jdbc.ejb.EJBInitializer for the Root Class Name field. Then press the Parse button. In the Parameter section, find the DefaultValue column and fill in estore/catalog by which EJB in J2ee server will

3.

Developing Reports with OOJDBC

278

Page 291: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

be accessed. Check the CastTo option, and enter com.sun.estore.catalog.ejb.CatalogHome.

Please note: After you fill in DefaultValue , you should press Enter, or an error will occur. When you set cast to,you should start J2ee server through running j2ee.bat under installroot of J2ee at the same time. And youshould also choose the button first, followed by .

In the dialog above, if you want to use a dynamic parameter, check the option IsDynamic. The syntax of themethod is: An array of boolean values to indicate which parameter is dynamic in runtime. If the parameter isdynamic the value should be prompted and initialized before the SQL is executed.

If specifying to apply dynamic parameters, that is, you choose the option Is Dynamic, this parameter will bepassed to JReport Designer. After you create a connection, in Catalog Browser, you will find the parameterunder the node "parameters". Press the Next button. In the following dialog, we chose create as Method Name. 4.

Developing Reports with OOJDBC

279

Page 292: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the Next button and the following dialog will appear. We can see the return type of the method namegetCategories defined previously.

5.

Developing Reports with OOJDBC

280

Page 293: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the OK button, the table Category has already been added.6.

Developing Reports with OOJDBC

281

Page 294: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Go to the File | Save menu item and save as ejb.odf under %installroot%\lib or the directory where the catalogwill be. For the information about saving the odf to XML format, see Developing Reports with OOJDBC.

Note: The same odf file can not exist both under %installroot%\lib or the directory where the catalog locates.

7.

Importing ejb.odf to JReport Catalog

Go back to JReport Designer, please note: before you run JReport Designer, you should also add the three jarsxalan.jar, crimson.jar and jaxp.jar into the batch file of JReport Designer, for example: ..."c:\jaxp1.1\xalan.jar;c:\jaxp1.1\crimson.jar;c:\jaxp1.1\jaxp.jar;C:\JReport\lib\report.zip;C:\JReport\lib\resource.zip;C:\JReport\lib\JREngine.zip;

Before you create reports, you should start your database first. In our case, we should first start cloudscapeunder the installroot of j2sdkee1.2.

1.

Start JReport Designer with the modified batch file. 2. Cancel the Choose Report dialog. Go to File | New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved theodf file under C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In Get JDBC Connection Information panel, uncheck Use ODBCData Source, and check JDBC Driver. Enter com.jinfonet.jdbc.obj.ObjectDriver in the JDBC Driverfield. Type jdbc:jinfonet:object:@Filename in the JDBC URL field. Please note: @File name should be the .odfname you have saved. So in our case, it should be jdbc:jinfonet:object:@ejb

3.

Developing Reports with OOJDBC

282

Page 295: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select the two tables in the Tables panel, and click Add button on the right.

Now, the table structure has been added into the catalog, with which we can build report. Click the New Reportbutton on the Standard Toolbar. Walk through the tabs, and finish developing the report.

4.

Developing Reports with OOJDBC

283

Page 296: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Case 7: Supporting EJB Deployed in BEA Weblogic Server

Installation

1. Install JReport Designer. In this test case, we install JReport Designer under c:\JReport510.

2. You should have BEA Weblogic Server installed. To download BEA WebLogic server, go to the BEA WebLogic'sWeb site: http://www.weblogic.com/licbeta.html, install and configure your server properly. We install this server atD:\Weblogic510. You will find weblogicaux.jar under %installroot%\lib. Please add weblogicaux.jar into the classpath inthe batch files of JReport Designer and Model Wizard respectively.

And in this demo, we use the property value Context.INITIAL_CONTEXT_FACTORY ="weblogic.jndi.WLInitialContextFactory" to create the connection, and the class weblogic.jndi.WLInitialContextFactory islocated under D:\Weblogic510\classes. Therefore add D:\Weblogic510\classes into the classpath in the batch filestarting JReport Designer and Model Wizard.

3. Install Jaxp1.1. You can download it using the URL: http://java.sun.com/xml/download.html. After installation, therewill be three jars xalan.jar, crimson.jar and jaxp.jar under the installroot of Jaxp1.1. Please add the three jars into theclasspath of the batch files starting JReport Designer and Model Wizard respectively.

4. In addition, add some system property values into the batch files. In this test case, we set :−Djava.naming.factory.initial="weblogic.jndi.WLInitialContextFactory" −Djava.naming.provider.url="t3://localhost:7001"to connect to BEA Weblogic server.

Developing Reports with OOJDBC

284

Page 297: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

After these steps, the batch file starting Model Wizard should be like this:

"d:\jdk1.2.2\jre\bin\java.exe" "−Dinstall.root=C:\JReport510" −classpath"C:\JReport510\lib\report.zip;C:\JReport510\lib\resource.zip;C:\JReport510\lib\JREngine.zip;C:\JReport510\lib\DeployToEntS.zip;C:\JReport510\lib\mail.jar;C:\JReport510\lib\activation.jar;C:\JReport510\lib\unicode.zip;C:\TEMP";"C:\JReport510";D:\Weblogic510\lib\weblogicaux.jar;D:\Weblogic510\classes;w:\sf\lib\xalan.jar;w:\sf\lib\crimson.jar;w:\sf\lib\jaxp.jar;d:\weblogic510\myserver\ejb_basic_beanManaged.jar −Dreporthome="C:\JReport510"−Djava.naming.factory.initial= "weblogic.jndi.WLInitialContextFactory" −Djava.naming.provider.url="t3://localhost:7001"com.jinfonet.jdbc.model.wizard.ModelWizard %1 %2 %3 %4 %5 %6 %7 %8 %9

Deploying your EJB

1. Make the EJB include methods to return Collection or JCollection

After you install BEA Weblogic server, you could find several EJBs. In this test case, we used the Entity beanexamples.ejb.basic.beanManaged.AccountBean. The jndi name is beanManaged.AccountHome. The remote interfaceis examples.ejb.basic.beanManaged.Account.class. The home interface isexamples.ejb.basic.beanManaged.AccountHome.class. Before deploying it, we do need to provide a method whichreturns java.util.Collection or com.jinfonet.jdbc.obj.JCollection. JCollection is an interface coded by Jinfonet.In Model Wizard, you need to inform OOJDBC driver to call which method to fetch data. OOJDBC driver can onlyaccept the method which returns java.util.Collection or com.jinfonet.jdbc.obj.JCollection.

So in this test case, we change the AccountBean.java to add the following method:

/*** Finds all EJBeans. * @return Enumeration EJBean Primary Keys* @exception javax.ejb.EJBException* if there is a communications or systems failure*/public Collection ejbFindAllAccounts() {log("getAllAccounts ()"); HashSet col = new HashSet();Connection con = null;PreparedStatement ps = null;

try {con = getConnection();ps = con.prepareStatement("select id from ejbAccounts");ps.executeQuery();ResultSet rs = ps.getResultSet();

String pk;while (rs.next()) {pk = rs.getString(1);col.add(pk);}return (Collection)col;} catch (SQLException sqe) {log("SQLException: " + sqe);throw new EJBException (sqe);} finally {cleanup(con, ps);}}

And we have added a method in AccountHome.java:

/*** Finds all EJBeans. * Returns a Collection of found EJBean primary keys.** @return Collection of Account* @exception javax.ejb.FinderException if there is an error while accessing the persistent storage* @exception java.rmi.RemoteException if there is a communications or systems failure* @see examples.ejb.basic.beanManaged.AccountBean*/public Collection findAllAccounts()throws FinderException, RemoteException;

Developing Reports with OOJDBC

285

Page 298: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

2. Create the ejb−jar file

After calling javac.exe of jdk1.2.2 to compile ejb classes, create a standard ejb jar file, including XML deploymentdescriptors. Then use the tool Weblogic EJB Deployer to create the deployable jar file.

3. Deploy the EJB

In Step 2, we create the jar ejb_basic_beanManaged.jar. Now put the jar into the classpath of the Weblogic server, editthe weblogic.properties file to include the new EJB. After stopping and restarting the Weblogic server, you can accessthe EJB in a client.

First, create 20 accounts.

Then, add the jar ejb_basic_beanManaged.jar into the classpath both in the batch file of JReport Designer and that ofModel Wizard.

Importing EJB via OOJDBC

Make an EJB initializing class, and this class is coded by Jinfonet. This class is for looking up the EJBHome by theJNDI name.

JNDI (The Java Naming and Directory Interface ™) is an API that provides naming and directory functionality.The JNDI provides applications with methods for performing standard directory operations, such as associatingattributes with objects and searching for objects using their attributes. Using the JNDI, an application can storeand retrieve any type of named Java object. In particular, a J2EE application uses JNDI to find interfaces usedto create enterprise beans, JTA UserTransaction objects, JDBC DataSource objects, and message connections.Because JNDI is independent of any specific implementations, applications can use JNDI to access multiplenaming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, andNIS. This allowsapplications to coexist with legacy applications and systems.

1. You can run the batch file ModelWizard.bat under % installroot of JReport Pro%, then the following dialog willappear:

Add Table: Add a new table.

Developing Reports with OOJDBC

286

Page 299: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Remove Table: Remove the selected table.

Modify: Revise the selected table.

2. Define Columns

The jndi name of the entity bean examples.ejb.basic.beanManaged.AccountBean is beanManaged.AccountHome. Theremote interface is examples.ejb.basic.beanManaged.Account.class. The home interface isexamples.ejb.basic.beanManaged.AccountHome.class.

Press the Add Table button and define a table named Account, then press the Parse button, the following dialogappears:

Column Name: Methods of the class you have defined.

SQL Type: Returned type of your column name. You can also double click the field and choose the sql type as you like.

Precision: Precision of the current column. You can also click on the field and change it manually.

Scale: Scale of the current column. You can also click on the field and change it manually.

Nullable: Current status of the column (null or not). You can also double click on the field and choose the currentstatus:Nullable, No Nulls or Nullable Unknown etc.

Currency: If your db field contains $, you should check it.

Developing Reports with OOJDBC

287

Page 300: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add: Add new columns.

Remove: Remove selected columns.

Direct Access Path: Select the path, and OOJDBC driver can save and restore the table you have defined through thispath.

Modify Column: Modify parameters of the current table.

3. Select the method to return data

Click Direct Access Path to define the accessing path of the Account table, then the following dialog will appear. In theRoot Class Name text box, fill in com.jinfonet.jdbc.ejb.EJBInitializer, then press the Parse button. For DefaultValue,fill in jndi name beanManaged.AccountHome, and select CastTo asexamples.ejb.basic.beanManaged.AccountHome. Please note: After you fill in DefaultValue, you should pressEnter in your keyboard, or an error will occur. Before you set CastTo, you should start BEA Weblogic server. Choosethe ... button first, followed with the down arrow. These actions will connect to the server.

Developing Reports with OOJDBC

288

Page 301: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the panel above, if you want to use DynamicParameter, you should check the option IsDynamic. The syntax of themethod is: An array of boolean values to indicate which parameter is dynamic at run time. If the parameter is dynamic,the value should be prompted and initialized before the SQL is executed.

If you use dynamic parameters, that is, you choose the option Is Dynamic, this parameter will be passed to JReportDesigner. After you create a connection, you will find the parameter under the node Parameters in Catalog Browser.

Root Class Name: You can define the class name by yourself and our OOJDBC driver will save the table you havedefined via the class.

Return Type: This tab indicates the return type of the method you are using.

Method Name: This tab indicates the methods in the class.

Parameters: This tab indicates the parameters in your methods.

Press the Next button, then in the following dialog, select the method findAllAccounts as the Method Name.

Press the OK button, the table Account has already been added:

Developing Reports with OOJDBC

289

Page 302: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the Save button to save a odf named weblogic.odf as in Case 1. For the information about saving the odf to XMLformat, see Developing Reports with OOJDBC.

Using Imported EJB in JReport

Now we start to load Account into a catalog file, and create reports with it. Before starting JReport Designer, make surethe classpath has included relative jar files and path, and has set relative system property values. In this test case, thebatch file for starting JReport Designer is like this:

"C:\jdk1.3\jre\bin\java.exe" "−Dinstall.root=C:\JReport510" −classpath"C:\jreport510\lib;C:\JReport510\lib\report.zip;C:\JReport510\lib\resource.zip;C:\JReport510\lib\JREngine.zip;C:\JReport510\lib\DeployToEntS.zip;C:\JReport510\lib\mail.jar;C:\JReport510\lib\activation.jar;C:\JReport510\lib\unicode.zip;C:\TEMP";"C:\JReport510";D:\Weblogic510\lib\weblogicaux.jar;D:\Weblogic510\classes;w:\sf\lib\xalan.jar;w:\sf\lib\crimson.jar;w:\sf\lib\jaxp.jar;d:\weblogic510\myserver\ejb_basic_beanManaged.jar −Dreporthome="C:\JReport510"−Djava.naming.factory.initial="weblogic.jndi.WLInitialContextFactory" −Djava.naming.provider.url="t3://localhost:7001" jet.report.ide.JReport %1 %2%3 %4 %5 %6 %7 %8 %9

Start JReport Designer, open the menu File | New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved the odf fileunder C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In the Get JDBC Connection Information dialog, uncheck Use ODBCData Source, and check JDBC Driver, fill in JDBC Driver as com.jinfonet.jdbc.obj.ObjectDriver. Fill in JDBC URLas jdbc:jinfonet:object:@File name. Please note: @File name should be the .odf name you have saved. Therefore inour case, it should be jdbc:jinfonet:object:@weblogic as follows:

Developing Reports with OOJDBC

290

Page 303: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

With Report Wizard , create a report with the the table Account:

Developing Reports with OOJDBC

291

Page 304: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add the columns and other objects that you want to add and continue on to other tabs. Click on the Finish button toview your draft report.

Index

Case 8: Supporting EJB 2.0 Deployed in BEA Weblogic's Server 6.1

Installation

Install Weblogic Server 6.1. under d:\bea\wlserver6.1_beta.1. Install JReport Designer under d:\jrp520.2. Install Jaxp 1.1 under D:\jaxp1.1.3. Download EJB 2.0 classes package from http://java.sun.com/products/ejb/docs.html.The downloaded classes packaged is called ejb−2_0−pfd2−class.zip. Save it to your disk and unzip the ejb.jarfrom this package to your D:\downloads\jdk\EJB\2.0 directory.

4.

Download EJB Upgrade 2.0 from http://commerce.bea.com/downloads/weblogic_server.jsp. The package nameis ejb20.zip. Unzip ejb20.jar inside this package to d:\bea\wlserver6.1_beta\lib, and modifyd:\bea\wlserver6.1_beta\config\mydomain\startWeblogic.cmd file to include the ejb20.jar in the classpath as thefollowing:

5.

set CLASSPATH=.;D:\bea\wlserver6.1_beta\lib\ejb20.jar;....

Developing Reports with OOJDBC

292

Page 305: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Modifying and Rebuilding EJB

The demo EJB we use is located at d:\bea\wlserver6.1_beta\samples\ejb20\basic\beanManaged:Account.javaAccountBean.javaAccountHome.java

Modifying the Source Codes

1. AccountBean.java

Add the following two functions:

/*This function is used to display the primary key in your report ( a limitation to the java.lang.Object return type). */

public String getPrimaryKeyString() {// return (String) ctx.getPrimaryKey(); return accountId;}

/*** Finds all EJBeans.* @return Enumeration EJBean Primary Keys* @exception javax.ejb.EJBException* if there is a communications or systems failure*/public Collection ejbFindAllAccounts() {log("getAllAccounts ()"); HashSet col = new HashSet();Connection con = null;PreparedStatement ps = null;

try {con = getConnection();ps = con.prepareStatement("select id from ejbAccounts");ps.executeQuery();ResultSet rs = ps.getResultSet();

String pk;while (rs.next()) {pk = rs.getString(1);col.add(pk);}return (Collection)col;} catch (SQLException sqe) {log("SQLException: " + sqe);throw new EJBException (sqe);} finally {cleanup(con, ps);}}

Note: Please add the "import java.util.HashSet;" into the AccountBean.java file.

2. AccountHome.java

Developing Reports with OOJDBC

293

Page 306: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add the following function:

/*** Finds all EJBeans. * Returns an Collection of found EJBean primary keys.** @return Collection of Account* @exception javax.ejb.FinderException if there is an error while accessing thepersistent storage* @exception java.rmi.RemoteException if there is a communications or systems failure* @see examples.ejb.basic.beanManaged.AccountBean*/public Collection findAllAccounts() throws FinderException, RemoteException;

3. Account.java

Add the following function:

/*used to display the primary key in reportspublic String getPrimaryKeyString() throws RemoteException;

4.Client.java

This class is used to create EJB objects. Comments included below are the statements used to remove the EJB objects:

/* log("Removing beans...");

for (int i=0; i<numBeans; i++) {

accounts[i].remove();

}*/

Modifying Commands in build.cmd

Modify the file D:\bea\wlserver6.1_beta\samples\examples\ejb20\basic\beanManaged\build.cmd as below:

*** Begin of build.cmd ***

@REM Copyright (c) 2000−2001 BEA Systems, Inc. All Rights Reserved.@REM You must set your environment by running the setExamplesEnv shell script @REM prior to executing this script.

SETCLASSPATH=D:\jdk1.3\jre\lib\rt.jar;D:\downloads\jdk\EJB\2.0\EJB.JAR;D:\bea\wlserver6.1_beta\lib\weblogic.jarSET WL_HOME=D:\bea\wlserver6.1_betaSET APPLICATIONS=D:\bea\wlserver6.1_beta\config\mydomain\applicationsSET EX_WEBAPP_CLASSES=D:\bea\wlserver6.1_beta\config\examples\applications\examplesWebAppSET CLIENT_CLASSES=D:\bea\wlserver6.1_beta\config\examples\clientclasses

@REM Create the build directory, and copy the deployment descriptors into itmkdir build build\META−INFcopy *.xml build\META−INF

@REM Compile EJB classes into the build directory (jar preparation)d:\jdk1.3\bin\javac −classpath %CLASSPATH% −d build Account.java AccountHome.java

Developing Reports with OOJDBC

294

Page 307: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ProcessingErrorException.java AccountBean.java

@REM Make a EJB jar file, including XML deployment descriptorscd buildD:\bea\jdk130\bin\jar cv0f std_ejb20_basic_beanManaged.jar META−INF examplescd ..

@REM Run EJBC on jar filed:\jdk1.3\bin\java −classpath%WL_HOME%/lib/weblogic_sp.jar;%WL_HOME%/lib/weblogic.jar;%CLASSPATH% weblogic.ejbc−compiler d:\jdk1.3\bin\javac build\std_ejb20_basic_beanManaged.jar%APPLICATIONS%\ejb20_basic_beanManaged.jar

@REM Compile servlets and EJB interfaces into WEB−INF/classes directory of the ExamplesWeb App@REM This ensures that the EJB can be accessed by JSPs and servlets of the Examples WebAppd:\jdk1.3\bin\javac −classpath %CLASSPATH% −d %EX_WEBAPP_CLASSES% Servlet.javaAccount.java AccountHome.java ProcessingErrorException.java

@REM Compile EJB interfaces & client app into the clientclasses directoryd:\jdk1.3\bin\javac −classpath %CLASSPATH% −d %CLIENT_CLASSES% Account.javaAccountHome.java ProcessingErrorException.java Client.java

*** End of file build.cmd ***

Building EJB Object

Execute build.cmd to build up ejb20_basic_beanManaged.jar.

Setting up Demo Data Source

Set up the demo data source following the steps below:

1. Copy d:\bea\wlserver6.1_beta\samples\eval\cloudscape\lib\cloudscap.jar to d:\bea\wlserver6.1_beta\lib

2. Modify d:\bea\wlserver6.1_beta\config\mydomain\startWeblogic.cmd to include cloudscape.jar in the classpath and setthe home of cloudscape as d:\bea\wlserver6.1_beta\samples\eval\cloudscape\data where the database is located.

set CLASSPATH=.;...D:\bea\wlserver6.1_beta\lib\cloudscape.jar;

echo on"%JAVA_HOME%\bin\java" −hotspot −ms64m −mx64m −classpath %CLASSPATH%−Dweblogic.Domain=mydomain −Dweblogic.Name=myserver "−Dbea.home=d:\bea"−Dcloudscape.system.home=D:\bea\wlserver6.1_beta\samples\eval\cloudscape\data"−Djava.security.policy==d:\bea\wlserver6.1_beta/lib/weblogic.policy"−Dweblogic.management.password=%WLS_PW% −Dreporthome=d:\jns520 weblogic.Server

3.Start weblogic server from Start menu.

4. Use web browser to connect to the console http://localhost:7001/console

5. Expand Service−>JDBC and select the Connection Pool node. From the right panel, click on the link: Create a newJDBC Connection Pool...

6. Define the Connection Pool as below:

Developing Reports with OOJDBC

295

Page 308: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Name: demoPoolURL: jdbc:cloudscape:demoDriver Classname:COM.cloudscape.core.JDBCDriverProperties:autocomit=true

Click on the Create button to create this connection pool.

7. Click on Target tab, add myserver to the Chosen list. Then click on the Apply button

8. Under the Monitoring tab, click the link Monitor all Active Pools... to check if the pool is active. The following panel willappear under the Monitoring tab.

Developing Reports with OOJDBC

296

Page 309: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

9. Click on the Data Source from the left pane under JDBC node.

10.Click on Configure a new JDBC Data Source... to create a new datasource.

11.On the Configuration tab, input the following information:Name: demoPoolJNDI Name: examples−dataSource−demoPoolPool Name: demoPool

Developing Reports with OOJDBC

297

Page 310: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then click the Create button to create this data source.

12. Click on the Targets tab to add myserver to the right text field, and click on the Apply button to apply thesechanges.

Now your demo datasource for the beans is set up.

Run the class Client.class to create EJB objects.

This class has been compiled when you run build.cmd, and output to theD:\bea\wlserver6.1_beta\config\examples\clientclasses directory. The command should like this:d:\jdk1.3\bin\java −classpathD:\jdk1.3\jre\lib\rt.jar;D:\downloads\jdk\EJB\2.0\EJB.JAR;D:\bea\wlserver6.1_beta\lib\weblogic.jar;D:\bea\wlserver6.1_beta\config\examples\clientclasses examples.ejb20.basic.beanManaged.Client t3://localhost:7001

Importing EJB via Model Wizard

1. Modify d:\jrp520\bin\ModelWizard.bat as below:

"d:\jdk1.3\jre\bin\java.exe" "−Dinstall.root=D:\jrp520" −classpath"D:\jrp520\lib\report.zip;D:\jrp520\lib\resource.zip;D:\jrp520\lib\JREngine.zip;D:\jrp520\lib\DeployToEntS.zip;D:\jrp520\lib\mail.jar;D:\jrp520\lib\activation.jar;D:\jrp520\lib\unicode.zip;C:\TEMP";"D:\jrp520";D:\bea\wlserver6.1_beta\lib\weblogic.jar;D:\bea\wlserver6.1_beta\config\mydomain\applications\ejb20_basic_beanManaged.jar;D:\jaxp1.1\jaxp.jar−Dreporthome="D:\jrp520" −Djava.naming.factory.initial="weblogic.jndi.WLInitialContextFactory"

Developing Reports with OOJDBC

298

Page 311: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

−Djava.naming.provider.url="t3://localhost:7001" com.jinfonet.jdbc.model.wizard.ModelWizard %1 %2 %3 %4 %5 %6 %7%8 %9

2. Start Model Wizard using ModelWizard.bat, then the following dialog will appear:

3. Define Tables and Columns

The jndi name of the entity bean examples.ejb20.basic.beanManaged.AccountBean isejb20−beanManaged−AccountHome. The remote interface is examples.ejb20.basic.beanManaged.Account.class. Thehome interface is examples.ejb20.basic.beanManaged.AccountHome.class.

Press the Add Table button and define a table named "Account", then press the Parse button and the following panelwill appear:

Developing Reports with OOJDBC

299

Page 312: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In this method, we only store the balance value while creating EJB objects in Client.java, so you can remove deposit,withdraw, isIdentical. That is to say, only the column balance and PrimaryKeyString are left, then the following panelpops up.

Developing Reports with OOJDBC

300

Page 313: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

4. Select the method to return data.

Click Direct Access Path to define the accessing path of the Account table , then the following dialog will appear. Inthe Root Class Name field, fill in com.jinfonet.jdbc.ejb.EJBInitializer, then press the Parse button. In "DefaultValue",fill in jndi name ejb20−beanManaged−AccountHome, check CastTo and selectexamples.ejb20.basic.beanManaged.AccountHome.

Notes: After you fill in "DefaultValue", you should press Enter on your keyboard, or the error will occur. Before you set"cast to", you should start BEA Weblogic's server. And you should also choose the button first, then follow with

. These actions will connect you to the server.

Developing Reports with OOJDBC

301

Page 314: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the panel above, if you want to use "DynanmicParameter", you should check off the option "IsDynamic". The syntaxof the function is: An array of boolean values to indicate which parameter is dynamic in runtime. If the parameter isdynamic, the value should be prompted and initialized before executing SQL.

If you use dynamic parameters, that is, you choose the option "Is Dynamic", this parameter will be passed to JReportDesigner. After you create a connection, in Catalog Browser, you will find the parameter under the node "parameters".

Press the Next button, the following panel will appear, select the function "findAllAccounts" as Method Name.

Developing Reports with OOJDBC

302

Page 315: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press the OK button, the table Account has already been added:

Developing Reports with OOJDBC

303

Page 316: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Save button to save a odf named weblogic.odf under %installroot%\lib or the directory where the

catalog will be. For the information about saving the odf to XML format, see Developing Reports with OOJDBC.

Note: The same odf file can not exist both under %installroot%\lib or the directory where the catalog locates.

Using Imported EJB in JReport

Now we start to load Account into a catalog file, and create reports with it. Before starting JReport Designer, pleasemake sure the classpath includes relative jar files and path, and has set relative system property values. In this testcase, the batch file of JReport Designer is like this:

"d:\jdk1.3\jre\bin\java.exe" "−Dinstall.root=D:\jrp520" −classpath"g:\temp\jdbc\d.zip;D:\jrp520\lib\report.zip;D:\jrp520\lib\resource.zip;D:\jrp520\lib\JREngine.zip;D:\jrp520\lib\DeployToEntS.zip;D:\jrp520\lib\mail.jar;D:\jrp520\lib\activation.jar;D:\jrp520\lib\unicode.zip;C:\TEMP";"D:\jrp520";D:\bea\wlserver6.1_beta\lib\weblogic.jar;D:\bea\wlserver6.1_beta\config\mydomain\applications\ejb20_basic_beanManaged.jar;D:\jaxp1.1\jaxp.jar;D:\jaxp1.1\xalan.jar;D:\jaxp1.1\crimson.jar;D:\bea\wlserver6.1_beta\lib\ejb20.jar;D:\bea\wlserver6.1_beta\lib\wlepool.jar −Dreporthome="D:\jrp520"−Djava.naming.factory.initial="weblogic.jndi.WLInitialContextFactory" −Djava.naming.provider.url="t3://localhost:7001"jet.report.ide.JReport %1 %2 %3 %4 %5 %6 %7 %8 %9

In JReport Designer, select from the menu File|New Catalog. Specify the catalog name and path.

Please note that if you saved the odf file in the directory where the catalog will be, for example, you saved the odf fileunder C:\odf, the new catalog should be created also under C:\odf.

In Catalog Browser, create a new connection. In the Get JDBC Connection Information dialog, uncheck Use ODBCData Source, and check JDBC Driver, fill in JDBC Driver as com.jinfonet.jdbc.obj.ObjectDriver. Fill in JDBC URL asjdbc:jinfonet:object:@File name. Please note that @File name should be the .odf name you have saved. Thereforein our case, it should be "jdbc:jinfonet:object:@weblogic61" as below.

Developing Reports with OOJDBC

304

Page 317: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click OK, the Add Table dialog pops up. Select table to be added, then click Done to add it into the catalog.

Now create a report with the table Account. Select File | New to launch Report Wizard.

Developing Reports with OOJDBC

305

Page 318: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Walk through the necessary tabs in Report Wizard, then click on the Finish button to complete developing the report.

View the report, the result of report will be shown as below:

Developing Reports with OOJDBC

306

Page 319: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Index

Developing Reports with OOJDBC

307

Page 320: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Deploying Resources From JReport Designer

Introduction

JReport Designer is the report design tool. Developed reports are save as .cls files for running in distributedenvironments. You can deploy your resources about reports or catalog and so on from JReport Designer to your machineor to our JReport Enterprise Server.

Deploying Resources From JReport Designer

Deploying Resources Locally

JReport Designer supports you to deploy your resources to any directory in your machine or over your intranet, that isdeploying resources locally. A tool named Deployment Wizard is provided when you deploy resources locally. You canrun it both in JReport Designer or running it as an independent application.

Running Deployment Wizard in JReport Designer

To do so,

Launch JReport Designer, in the File menu, select Deploy to, and then click Local Directory. The DeploymentWizard pops up.

1.

On the Deployment Wizard, click the Browse button to select a catalog and all the reports of the specifiedcatalog will be displayed in the Selected Report list.

You can also type the catalog name with its full path directly into the From Catalog text box, and then pressENTER.

2.

Select reports that you want to deploy from the Select Report list and click the arrow button to add them to theright list. Or directly drag them to the right list.

Note: If no report is selected here, only the catalog will be deployed.

3.

Specify a directory for the catalog and reports to be deployed.

Click the Browse button to the right of the To Local Directory text box, and find a directory on the GetDirectory dialog.

You can also type the directory in the text box directly. You are allowed to type a directory which does not exist,and JReport Designer will created it automatically.

4.

Click Next to modify the properties of the connection.

You can select a data source from the Catalog Data Source drop−down list, and the connection properties ofthe selected data source are displayed.

If you want to change the property values, click Modify, the Get JDBC Connection Information dialog appearsfor you to modify the properties.

5.

Click the Finish button to deploy the catalog and reports.6.

Running Deployment Wizard as an Independent Application

To do so, please use the following command line:

java −Dreporthome=<home> −classpath path deployment.DeployWizard [−options]

Where <home> refers to the path where your JReport product containing the Deployment package is installed. Forexample, if your deployment package is included in your JReport Designer Edition, and you installed this edition in

308

Page 321: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

c:\JReport, then the <home> should be c:\JReport.

where −classpath path tells the Java interpreter the classpath. Usually you should append the JReport Designer libpath to the Java classpath. E.g., if the JReport Designer was installed at c:\JReport, then this parameter should looklike:

−classpathc:\jreport\lib\report.zip;c:\jreport\lib\DeployToEntS.zip;c:\jreport\lib\JREngine.zip;c:\jreport\lib\resource.zip;c:\JReport\lib\log4j−1.2.8.jar

and where [−options] includes:

−help − Print the help message about the usage of [−options].• −c<:filename> − Specify the catalog you want to deploy.• −vDebug − Enable the output of debug messages. This option is available only when your product version is adebug version.

−vError − Enable the output of error messages. This option is available only when your product version is adebug version.

Deploying Resources to JReport Enterprise Server

To deploy your resources to JReport Enterprise Server,

Launch JReport Designer, on the File menu, select Deploy to, and then click JReport Enterprise Server. TheConnect dialog appears.

1.

This dialog is used to connect to JReport Enterprise Server.

Type in the host of remote web server in the Host text box.

Type in the port of the server in the Port text box.

Type in /jrserver in the Servlet Path text box. Since JReport Enterprise Server version 6.0, the JSP isenabled by default, therefore, you should use /jrserver in the URL to access the servlet.

If the server is integrated with another web server which supports SSL, you can select the SSL (Security SocketLayer) check box to create a SSL connection.

Check Remember connection information to make JReport Designer remembers the connection information.

Provide the user name and password of the server.

Select the check box Remember connection information

2.

Click Connect, and the Deployment Settings dialog appears. 3. In the Deploy Resource To text box, specify the directory on the server for the resources that will be deployed.Use the default location (the My Reports node in the server resource tree) or click the Browse button to specify alocation in the server.

4.

From the Resource Type drop−down list, select a type for the resource that will be deployed. Options are asfollows:

5.

ReportOnly deploy a report.

CatalogOnly deploy a catalog.

FolderDeploy a folder whose name can be specified in the text box below.

Folder with ContentsDeploy a folder and all resources in the folder.

Catalogs, Reports and Folders in Folder♦

Deploying Resources From JReport Designer

309

Page 322: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Deploy resources in a folder. Catalogs and Reports in FolderDeploy catalogs and reports in a folder.

After you have selected the resource type, click the Browse button to find the directory where your resourceslocated, or type in the directory. Click the Load Tree button to load the resources under that directory in thepanel below.

6.

In the panel, select the check boxes in front of the resources that you want to deploy.7. On the Properties tab,

Specify a name which will be displayed in the server resource tree for the selected resource in the panel. Type aname in the text box or click the Browse button, the Select Resource Name dialog will pop up. All the resourcesnames with the same type as the selected resource under the Deploy Resource To path are displayed on thedialog. You can select one of them.

In the Description text box, type a brief description to describe the resource to be deployed.

If you a folder is selected, type a real path in the Real Path box. If no path is specified, default path will be used.

8.

If you are deploying a folder in the cluster environment, please make sure you check the Map SharedDisk option, the folder will be mapped instead of be copied.

Check Archive Policy to apply archive policy to the resource to be deployed.

9. On the Permissions tab, check Enable user permission to specify permissions to the selected resource.

Note: If you are deploying resources to My Reports, this tab is disabled.

10. The Connection tab is only available when a catalog is selected. You can modify the properties of theconnection and after modification, please click the Apply button to save the changes.

Click the Submit button to deploy the resources to server. If the resource that you are deploying contain reportsthat use style groups or have special fonts, a dialog named Deploy Font and Style will pop up for you to specifythem.

11.

Deploying Resources From JReport Designer

310

Page 323: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Executing Reports from JReport Beans Or APIs

Introduction

JReport is Java−centric object−oriented reporting tool written entirely in Java. We provide bean components, so that youcan easily incorporate JReport in your own applications. JReport beans can be used inside IDE tools like JBuilder, VisualCafé, Visual Age, and SilverStream. Additionally, please consult the next chapter, "Using JReport Beans in Forte™ forJava" for special instructions on using JReport beans in that IDE. Combining the power of JReport bean APIs, and thereusability of the JReport beans, you will not need to open JReport GUI each time to run, print, or diagnose the problemsof the report.

Altogether, we provide the following beans or API:

JReport Design API − Design reports programmatically (for each report design command and operation).•

311

Page 324: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Catalog API − Modify or create a catalog programmatically.• JReport Engine Bean (JREngine) − Run report result, export the result to multiple file formats (e.g. PDF, HTML,RTF) and to a printer.

JReport Result Viewer Bean (JRResultViewer) − Show the report result file, export to multiple file formats and aprinter.

JReport Design Bean (JRDesign) − Load the visual report design environment for modifying a report.• JReport Catalog Bean (JRCatalog) − Manipulate and access the catalog of JReport.•

Detailed descriptions of each will follow later in this chapter.

JReport Engine Bean

JReport Engine Bean provides a programming API to the report running and exporting process. JReport Engine is mainlyresponsible for fetching data qualified from the data source and returning the result to JReport.

Briefly, JReport Engine Bean enables the user to:

Run the result for a pre−developed report• Assign new values for the pre−defined objects in the report, and then run the result with the new values. Theseobjects include parameter, whereportion, data driver, connection and others.

Export the report result to multiple file formats (HTML, PDF, XLS, RTF, Postscript, Text, CSV, Applet, Email) or aprinter.

Installation

Installing with JReport Designer

When you install JReport Designer, JReport Engine Bean will be installed at the same time. After installation, you shouldhave the main components as below:

lib\JREngine.zip* − Archive file for JReport Engine Bean.bin\report.ini* − Configuration file.lib\log4j−1.2.8.jar* − Jar file used for JReport Engine logging system. lib\JimiProClasses.zip − Non−GUI Engine class library, please append this to the classpath besides JREngine.zip.lib\resource.zip − Resources of JReport Designer. lib\xerces.jar − Jar file used when exporting to xml.lib\JRResultViewer.zip − Archive file for JRResult Viewer Bean.lib\JRResultViewer.jar − Jar file for JRResult Viewer Bean.lib\chart.jar − Jar file used when exporting to html with images to be embedded as a chart applet in the html file.lib\udo\udo.ini − Register of user defined objects.lib\activation.jar − Jar file used when exporting to mail.lib\mail.jar − Jar file used when exporting to mail.lib\Itext.zip − Archive file used when exporting to PDF.lib\poiHSSF_151.jar − Jar file used when exporting to Excel.Readme.txt, License.txt − Information about release.help\pro−material\TestEngineBean.java, TestWherePortion.java, LocalWherePortion.java, TestSunVMMPValue.java, −simple test programs to demonstrate how to call and use JReport Engine Bean. Or you can find them on our Web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm for the manual related materials.

Note: The asterisk * for the first three means that when you call JReport Engine Bean, these three files must be used.

Preparation for calling JReport Engine Bean

Before calling JReport Engine Bean, you must make sure that:

Executing Reports from JReport Beans Or APIs

312

Page 325: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Because the only archive file for JReport Engine Bean is JREngine.zip. You need to set the CLASSPATHenvironment variable before you compile and run the program. Append the following string to the CLASSPATH:<JReport_Install_Dir>\lib\JREngine.zip;<JReport_Install_Dir>\lib\log4j−1.2.8.jar.

1.

Beginning with Build 569, before you call the methods for exporting a report to Mail, PDF, Excel or XML format,you should add the corresponding class files or jars with valid path in your classpath.a. Mail: mail.jar and activation.jarb. PDF: Itext.zipc. Excel: poiHSSF_151.jard. XML: xerces.jar

2.

When you set the report home in the bean, JReport will get information from the file report.ini under%ReportHome%\bin and check whether they are valid by setting runtime key in the bean. Open report.ini, youwill find the configuration information, including the temp path, template path and the help path. JReport EngineBean will use the temp path to export the temporary files. Therefore, make sure the temp folder specified inreport.ini exists.

3.

Deploying JReport Engine Bean Runtime Components

When you only use the JReport Runtime instead of JReport Designer, you should deploy Engine Bean Runtimecomponents which include the following files:

JREngine.zip − JReport Engine BeanJRResultViewer.zip − Result Viewer BeanJRResultViewer.jar − Result Viewer Bean in jarlog4j−1.2.8.jar − Jar file used for JReport Engine logging system chart.jar − Chart appletudo.ini − Register of user defined objectsreport.ini − Configuration fileactivation.jar − Used when export to mailmail.jar − Used when export to mail

Notes:

report.ini − In your code if you set the reportHome "c:\\jreport", we will read the file report.ini under the directoryc:\jreport\bin. You will find in this file the configuration information, including the temp path, template path andthe help path. JReport Engine Bean will use the temp path to export the temporary files. Therefore, you shouldensure there exists the temp folder specified in the file report.ini.

1.

If you only want to generate a report, you need only JReport Engine Bean, while if you want to view the reportresult file, you will use JReport Result Viewer Bean. Of course, you will need both beans if you want toaccomplish your goals of generating and viewing reports in one instance of a class.

2.

Properties

JREngine Bean has following properties. All the data types of the properties are of Java strings. These properties arelisted below:

UID − The JReport run−time user ID.• key − The JReport run−time key.• reportHome − The home path where the report.ini and other JReport system files exist.• reportName − 'The report name which the engine will run.• catName − The name of the catalog which contains all the required objects used in the report.• paramValues − The string containing the parameter values, separated by comma (',').• paramFile − The name of the parameter value file. This will be ignored if paramValues is specified.• resultFile − The name of the result file.•

The following methods are used for value assignment to the above properties:

Executing Reports from JReport Beans Or APIs

313

Page 326: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

setUID("UID")• setKey ("key")• setReportHome("HomePath")• setReportName("ReportName")• setCatName("CatalogName")• setParamValues("ValuesString")• setParamFile("ParamFileName")• setResultFile("ResultFileName")• runReport( ) or runReport(boolean genRst)•

Where,

UID − The JReport run−time User ID.• Key − The JReport run−time Key. • HomePath − The installation path for JReport Designer. Strictly speaking, if you set the HomePath as"c:\\jreport", then the first thing JREngine will do when running the report is to check jslc.dat and report.ini filesunder c:\jreport\bin to see whether they are valid.

reportName − A string which contains both report path information and the report name. • catName − A string which contains both catalog path information and the catalog name. The report path and thecatalog path may be different.

ValuesString − The string to assign new value for the parameter used in the current report. The parametershould be the one defined in the catalog.

ParamFileName − The name of the parameter value file. This will be ignored if paramValues is specified. • ResultFileName − The name of the result file. If you want to generate the report result file (with .rst extension),then set the result file name (.rst extension) with full file path. For example, setResultFile("c:\\temp\\test.rst"). TheresultFile contains both the path and the file name information. If there is no path specified, the current path willbe used. If there is no file name specified, the reportName will be used (with the .rst extension).

Notes:

Beginning with Version 4.0, when you call JReport Engine Bean in your application program, your run−time userID and run−time Key are needed.

The method runReport ( ) will have the same effect as setLoadReport ("yes"). setLoadReport ("yes/no") is themethod in the last Engine Bean version.

When JReport Engine Bean runs out the report result, it will generate the .rst file first. But you may want to runthe report result out and then export to other formats like html, pdf without gnerating any .rst file. Now, wesupport this feature. runReport( ) and runReport(true) are equivalent, and we will always generate the .rst file.But if you hope not to generate .rst file, please call runReport(false), this way we will print, output the report resultwithout getting out the .rst file and the performace will be improved also.

If more than one parameter is needed in the report, you can pass multiple parameters in the paramValues string.The ValuesString format is: paraName1=paraValues1, paraName2=paraValue2 where the paraName1 andparaName2 are the parameter names and paraValue1 and paraValue2 are the values. The comma is theseparate operator, and the equal sign is to separate the parameter name and parameter value. If the parametername or parameter value contains the separate operator −− comma or equal sign, it needs escape. We providethe the escape operator −− \\. If your put the escape operator before the separate operator, we will not treat it asthe separate operator. For example:* the parameter string is: "param1=aaa\\,aa,param2=bbbbb,param3=ccccc", this parameter string will be parsedtothe value for param1 is aaa, aathe value for param2 is bbbbcthe value for param3 is ccccc* the parameter string is: "pa\\=ram1=aaa\\,aa,param2=bbbbb,param3=ccccc", this parameter string will beparased tothe value for pa=ram1 (name) is aaa, aa (value)the value for param2 is bbbbbthe value for param3 is ccccc

Executing Reports from JReport Beans Or APIs

314

Page 327: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The format of the parameter file is: one parameter name−value pair will take one line, another parametername−value pair will start from a new line. Each line is formatted as paramname=paramvalue, and we alsoprovide the escape for equal sign same as above.

Note: you do not necessarily set all parameters value, and default value will be used for the parameter whosevalue is not set here. If you do not set a parameter value, JReport will use the default value for this parameter.If you want to know the report's parameters without running reports, call the method getReportParams(). Thismethod will return a vector and each element of this vector is jet.formula.ParamDesc. The class ParamDesc hasfive public properties:

name − Parameter name, this property is String type.type − Parameter type, this property is String type.promptText − Parameter prompt text, this property is String type.value − Parameter value, this property is String type.isColumn − Indicate whether this parameter must be a DB column name or a boolean type. If this parameter is aDB column name, this parameter's value must be an available group field. You can call methodgetAvlGroupFields(), this method will return a vector which contains all the available group fields. Please benoted, if more than one parameter is DB column name, the values of these parameters can not be the same.

Programming with JReport Engine Bean

Import the classes of JREngine Bean by adding the following import statements at the beginning of your program. Thefirst import statements bring into the bean class;import jet.bean.*;import java.awt.*;import java.awt.event.*;

Then, we will create an instance. To report with JREngine Bean, you should create an instance of JREngine Beanfirst.Note: From version 4.0, when you call JREngine Bean in your program, you should set your user id and key ofJReport Runtime.

bean = new JREngine();

//From Version 4.0bean.setUID("JReport Runtime User ID");bean.setKey("JReport Runtime Key");

After the object is created, set the report home, report file, catalog file, result file (if necessary), parameter values (ifnecessary).

bean.setReportHome("c:\\jreport");bean.setReportName("c:\\jreport\\demo\\reports\\DateParameterUsage.cls ");bean.setCatName("c:\\jreport\\demo\\reports\\Tutorial.cat");bean.setParamValues("STARTDATE=05/15/1998,ENDDATE=06/10/1998");bean.setResultFile("c:\\jreport\\temp\\phaseorder.rst");bean.runReport();

Note: You could run or export a self−contained report by calling JReport Engine Bean. Suppose you want to run aself−contained report "customerlist.clx" which was saved under c:\jreport\demo\reports, you do not need to set thecatalog name in your code, you could just set the report home, report file, show debug and error information (ifnecessary), log file (if necessary) as below:

bean.setReportHome("c:\\jreport");bean.setReportName("c:\\jreport\\demo\\reports\\customerlist.clx");bean.setShowInfoLevel( bean.vDebug | bean.vError );

Executing Reports from JReport Beans Or APIs

315

Page 328: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

bean.setLogFile("");bean.runReport();

For more information about Self−contained Report, see User's Guide | JReport Designer Window | Main Menu.

Reference Note: JReport Enterprise Server User's Guide | Clients Accessing JReport Enterprise Server | Report.

With JREngine Bean object, you can manipulate and access many reports. You never need to create a bean for eachreport. There are a lot of useful methods provided in JREngine Bean, and you can call them before/after runReport()method.

Showing Information

The two properties showInfoLevel and logFile are used for controlling debug, error and other information displayed. Thefollowing two methods are used to set values to these properties:

setShowInfoLevel (vDebug/vError/vOff)• setLogFile ("LogFileName")•

Note:

vDebug, vError and vOff are used for showing debug information, error information and turning off debug anderror information.

1.

LogFileName specifies where the debug, error and other information will go. LogFileName contains both the pathand the file name. If no path is specified, the current path is used. If no file name is specified, the file jreport.log isused.

2.

Returning Code

The method getStatus() returns a message about the status after runReport() in JReport Engine Bean is called. If it isapplied earlier, it will only return "No report load" for that the method just stores static value. The getStatus () method mayreturn one of the following messages:

"OK"• "Error: Cannot find the resource file JRsIndex.jrc!". This is caused by the incorrect setting of the report home path.• "Error: Cannot open the catalog "Catalog Name"!". The JREngine cannot open the given catalog file.• "Error: Cannot open the report "Report Name"!". The JREngine cannot open the given report file.• "Error: Cannot open the parameter file "Parameter file name"!". The JREngine cannot open the given parameterfile.

"Error: Unknown format in Parameter values!". The parameter values string has the wrong format.• Other errors. JREngine bean encountered other exceptions.•

Exporting To HTML, Mail, PDF, TEXT, XLS, PS, RTF, XML and Fax

There are also several methods with which JReport Engine will export the result file (with the .rst extension) to differentfile formats (HTML, PDF, TEXT, XLS, PS etc.). The example program TestEngineBean.java will demonstrate how touse them. One method can be implemented by using different parameters. For more information about it, please refer tothe JReport Java doc.

exportToHtml

Note: The method exportToHtml(java.lang.String htmlFileName) will take the methodexportToHtml(java.lang.String htmlFileName, boolean bChartApplet, booleanisMultiFile, boolean bUsingTable, boolean bHyperlink, boolean bPageNum, booleanbAbsolute, int iBrowser) using the default parameter values like this:exportToHtml("HtmlFileName", false, true, false, true, true, true, JREngine.IE).

Executing Reports from JReport Beans Or APIs

316

Page 329: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

exportToMail

Before the method exportToMail is called, the mail server should be configured with the following method:

configMailServer(String SMTPServerIP, String MyMailAddress, int SMTPServerPort)whereSMTPServerIP is the mail server IP addressMyMailAddress is the sender's mail addressSMTPServerPort is the mail server port

exportToMultiMail• exportToPdf• exportToText

The method exportToText(java.lang.String textFileName, boolean isNormalText)willtake the method exportToText(java.lang.String textFileName, booleanisNormalText, boolean isRepeat, char delimiter) using the default parameter values likethis: exportToText( "TextFileName", isNormalText, false, ' ').

The method exportToText(java.lang.String rstFileName, java.lang.StringtextFileName, boolean isNormalText) will take the methodexportToText(java.lang.String rstFileName, java.lang.String textFileName,boolean isNormalText, boolean isRepeat, char delimiter) using the default parametervalues like this: exportToText( "ResultFileName", "TextFileName", isNormalText,false, ' ').

exportToXls• exportToPS• exportToRtf• exportToXML• exportToFax

If you want to export the report result to fax, please download the files listed in the tables below from the web sitehttp://java.sun.com/products/javacomm/index.html, and put them in the specified locations first (on Windows):

File Name Location

comm.jar %JReportHome%\lib

javax.comm.properties %JavaHome%\jre\lib

Win32Com.dll %JavaHome%\jre\bin

Printing Reports

There are four methods provided for printing the report:

printReport ( )• printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground, booleanbUseJDK11)

printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground, booleanbUseJDK11, boolean bSeparateLargePage)

printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground,boolean bUseJDK11, boolean bSeparateLargePage, String jobName)

printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground,boolean bUseJDK11, boolean bSeparateLargePage, String jobName, String printer)

printReport(java.lang.Object job, boolean bInteractive, java.lang.Object pf, boolean bInBackground,JReportPrintListener jreportprintlistener, int useJDK, java.lang.String jobName, java.util.Vector attributeInfo,java.lang.String printer)

getPrintStatus ( )•

Parameters:

Executing Reports from JReport Beans Or APIs

317

Page 330: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

printJob −− The job of this printing.• pageFormat −− Description for the size and orientation of a page to be printed.• bInteractive −− A boolean value. If you set it to false, the print setup dialog will not show up.• bInBackground −− A boolean value. If you set it to true, the printing dialog will not show up.• bUseJDK11 −− A boolean value. If you set it to true, it will use JDK1.1.x to print the report. Otherwise if you setfalse, it will use the JDK which you are running to print the report. The JDK 1.1 printing method is quick in speedbut the printing quality is not guaranteed. The JDK 1.2 method can give you a satisfactory result, even for a giffile, but it is slow in speed.

bSeparateLargePage −− A boolean value, if the report page size is larger than the print paper size, and you wantto separate the large report page during printing, you should set this property to true. If the print page size whichyou choose is less than the report page size, then the report will be printed as multiple pages serially, this meanswe will separate the large page of the report automatically. After you set it to true, for JDK1.2 or higher, the pageformat dialog will be popped up. In this dialog, you can choose the page format which you want to print with, wewill use this page size for printing. For JDK1.1.x, however, you must change the page format which you want toprint with in the print dialog (click the property button, then choose the page format).

jobName −− A String value of the job name. When printing, the job name you defined will list in the window whichshows information, such as the status of documents and the owner of a document etc.

printer −− The name of the printer used to print the report. Please note that if you set bUseJDK11 to be false,you can't set printer but use the default printer only.

job −− The print job of this print action. It is a instance of PrintJob or PrinterJob.• bUseJDK −− An integer value. If you set it to 0, it will use JDK1.1 to print the report. If you set it to 1, it will usethe JDK1.2, which you are running to print the report. If you set it to 2, it will use the JDK1.4, which you arerunning to print the report. The JDK 1.1 printing method is quick in speed but the printing quality is notguaranteed. However, The JDK 1.2 method can return you with satisfactory result, even for a gif file, but it is slow in speed. JDK 1.4provides more options to do print such as specifying the paper tray.

attributeInfo −− A vector whose elements are string.Each string has defined in interface PrintConfig.Interface PrintConfig located in package jet.bean. Forexample,you can implement PrintConfig and call its fields like this:attributeInfo.add(TRAY_MANUAL);attributeInfo.add(ORIENTATION_PORTRAIT).

Note:

The first method printReport ( ) is called to start printing. It will take the third method using the default parametervalues like this:printReport(null, null, true, false, false, false)

1.

The second and third method allows you to pass the parameters −− printJob, pageFormat, bInteractive,bInbackground, bUseJDK11 and bSeparateLargePage.

2.

The third printing method (with the bSeparateLargePage parameter) is not recommended, it may cause someunexpected errors, for example, you may get an extra blank page.

3.

After printing is started, the method getPrintStatus ( ) can be used to get the print job status. Returned values ofgetPrintStatus ( ) are:"No print job""Busy""OK""No report load" Other error messages if there are errors.

4.

Example1: Under JDK1.2 or higher, if you use JDK1.2 printing method (boolean bUseJDK11), you can call theprintReport method like this:PrinterJob printJob = PrinterJob.getPrinterJob();bean.printReport(printJob, printJob.defaultPage(), false, false, false);Or, if you do not want to getPrinterJob, simply call:bean.printReport(null, null, false, false, false);

Executing Reports from JReport Beans Or APIs

318

Page 331: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Example2: Under JDK1.2 or higher, if you use JDK1.1 printing method, you are best recommended not to getPrintJob,just call:bean.printReport(null, null, false, false, true);

Example 3: Under JDK 1.2 or higher, if you use JDK1.1 printing method and select a network printer, you can call theprintReport method like this:bean.printReport(null, null, false, false, true, false, "job1", "\\\\GUOF\\HP LaserJet 6L Pro PCL5e");

Example 4: Under JDK 1.2 or higher, if you use JDK1.1 printing method and select a local printer, you can call theprintReport method like this:bean.printReport(null, null, false, false, true, false, "job1", "HP LaserJet 6L Pro PCL5e");

WHERE Portion

Also JReport Engine provides the methods to add, delete, save and get a new WHERE portion in the catalog. Pleasenote that the the join relationships of tables will remain in the new where clause. By specifying the name of the WHEREportion, you can pick it out from report catalog and bind it up with the current query:

setNamedWherePortion(queryName) − Set a named WHERE portion from the catalog to the query of the currentreport. If this WHERE portion can not be found in the catalog, return to the "false".

setWherePortion(WherePortionString) − Set the WHERE portion in the string format to the query of the currentreport.

saveWherePortion(queryName, WherePortionString) − Save the WHERE portion in string format with the specificquery name in report catalog.

deleteWherePortion(queryName) − Delete a specific WHERE portion from report catalog, update and save thecatalog after deletion.

getAvailableQueryFields() − Get the available query fields from the query for the current report. This will returnan enumeration of the names of fields, formulas and parameters and their corresponding data types which will beneeded to build up the WHERE portion and validate the condition.

getAvailbleWherePortions() − Get an enumeration of the names of all the WHERE portions saved in the reportcatalog.

SaveCatalog() − Save the current catalog. Return to " true" if successfully saved.•

Parameters:

queryName − The name of the WHERE portion in SQL query.• WherePortionString − The string of the Where Portion.•

Data Driver

The setDataDriver() method is used to specify the user data source driver. JReport can use user data source driver asthe data source of a report. By default, JReport uses JDBC connection. Only when the report works with the user datasource can users call this method.

Note: This method is mutually exclusive with the method of setResultSet(). Users can only use one of them at the sametime.

setDataDriver(String dataDriver)•

Parameter:

dataDriver − The URL specifying the User Data Source, for example"jrquery:/AddressListDataSource;c:\AddressList.txt"

Executing Reports from JReport Beans Or APIs

319

Page 332: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Cached Query Result

The setResultSet() method is used to set the cached query result to work with JReport. When this method is called,JReport will load the specified cached query result and generate reports with data from the cached query result.

Note: This method is mutually exclusive with the method of setDataDriver(). Users can only use one of them at the sametime.

setResultSet(String cachQueryResultSetFile)•

Parameter:

cachQueryResultSetFile − The full file path of Cached Query Result, for example "c:\myresult"•

National Language Support (NLS)

JReport products support the National Language feature. If you specified to apply NLS, when you design and save thereport, the language−dependent text of Label object will be extracted to a resource file(.properties). Copy the resourcefile for another language and modify the text in the file. When JReport is running, JReport Engine will retrieve thelanguage−dependent text according to the current locale, the end user will get a report result that matches his localesetting.

setLocale(Locale currentLocale)• setEncoding(String encoding)•

Notes:

At run time, you can specify the encoding and Locale for rendering the report result accordingly. But pleasemake sure that when you design the report, you have set it to support NLS and have made the property file forthe language you hope to apply.

1.

In addition, we also provide the following method that might be very useful.Vector getAvailableLocales(String clt)This method will get all of the Locales that current report supported. The parameter clt is current client's Locale. Ifclt is in current report Locales it is moved to the index at zero.

2.

Getting the Communicator of this report

getReportCommunicator()•

The Communicator here is a class defined by JReport. This method will launch to run JReport Engine Bean, but do notsave to the result file. It returns the Communicator of this report.

You are recommended to use this method in JReport Engine Bean and setCommunicator() in JReport Result ViewerBean. That is,resultViewerBean.setCommunicator( engineBean.getReportCommunicator() );

Modifying User Information

modifyUserInfo(String strUserName, String strPassword)•

Obviously, this method is to modify user's information: user ID and password.

Setting Connection Information

setConnection(String strURL, String strUID, String strPSWD, String strJdbcDriver)•

Executing Reports from JReport Beans Or APIs

320

Page 333: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

setConnection(String strURL, String strUID, String strPSWD, String strJdbcDriver, boolean fetchSupportInfo)•

Parameters:

String strURL − The URL of the database. For the format of the URL please refer to the instructions of yourJDBC driver.

String strUID − The user ID for the driver.• String strPSWD − The user's password for the driver.• String strJdbcDriver − The full qualified name of class. The class is responsible for connecting to the databaseand fetch the data. For example, com.sybase.jdbc.SybDriver or oracle.jdbc.driver.OracleDriver. If not specified,the default one will be used.

boolean fetchSupportInfo − Set true to get the user support information in DBMS. This method will only workwhen the user has set the connection object or url.

This method enables users to set the connection information before running the report. You can let the user specify theuser id and the password before running a report to ensure the security. Another application of this method is thatreaders can select a different database before running reports, so they can see different report results. Of course, usuallyin this case, the two databases have the same structure and this will ease the work of building another catalog.

For example, this method may be called like this:setConnection("jdbc:Oracle:thin:@204.177.148.30:1521:orcl","scott","tiger","oracle.jdbc.driver.OracleDriver");

Setting Result Set

setUserResultSet(java.sql.ResultSet userResultSet)•

Parameter:

userResultSet − The JDBC ResultSet object created by the user. Users should release it by themselves.•

This method is used to set the result set required to run the report.

For example, this method may be called as below:

Class.forName("oracle.jdbc.driver.OracleDriver");Connectionconnection=DriverManager.getConnection("jdbc:oracle:thin:@222.222.222.45:1521:orcl815","System","manager");Statement stmt = connection.createStatement();ResultSet rs = stmt.getResultSet();bean.setUserResultSet(rs);

Getting the Version Number of JReport Engine Bean

String getVersion()•

This method will get the version number of your Engine Bean.

Example: you can use this method like below:bean = new JREngine();System.out.println(bean.getVersion());Then the method will print out:JReport Engine Bean version : 3.1.1; Build Number : 512; Help Version : 505The Help version is the matched help version number of the current engine. The two may be different.

Executing Reports from JReport Beans Or APIs

321

Page 334: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Getting Page Orientation

getPageOrientation ()•

The method getPageOrientation is used for getting the orientation of the report page. You should call this method aftercalling runReport method. The return value is an int value, and it can be LANDSCAPE or PORTRAIT. If it is −1, it makesno sense, say you may have called it before calling runReport method, which is wrong.

Getting DBField Information

getDetailsFields()•

The method is used to get the information of all DBFields in the Detail section, including DBFields in the Detail section ofthe subreport which is inserted in the Detail section. The method returns a vector which contains name, type and SQLtype of DBFields.

Note: The method will return DBField information whatever the Detail section is invisible or suppressed.

Getting Report Information

getRptInfo()•

The method is used to get the information of reports, including record number, total page number, print time, username.

Note: Before this method is used, method runReport( ) or loadReport( ) should be called first.

Single Thread

getSingleThread()•

The above method checks whether the current engine is single−threaded. The returned value is of boolean type. If thecurrent engine is single−threaded, it will return true, otherwise false.

setSingleThread(boolean single)•

The above method can be set to to run the engine with a single thread. It is specially used in the environment like EJBwhich only allows single thread when doing any transactions.

Parameters:

single − set to true if to use single−thread, otherwise, we will use the default multi−threaded engine.•

Run−time Key

Beginning with version 4.0, when you call JReport Engine Bean in your application program, your user ID and runtimeKey are needed.

getUID( )Get and return the JReport Runtime UserID.

setUID(String uid)Set the JReport Runtime UserID to call the JREngine.

getKey()Get and return the JReport Runtime key.

setKey (String key)Set the JReport Runtime key.

Executing Reports from JReport Beans Or APIs

322

Page 335: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters:

uid − the JReport Runtime User ID.• key − the JReport Runtime key.•

The Illustrative Example

After you installed JReport Engine Bean, you will find the illustrative test programs under%installroot%\help\pro−material. Or you can go to our web site at http://www.jinfonet.com/webpage/kbase/kbase.htm forthe manual related materials.

TestEngineBean.java − a test program. Let us explain how TestEngineBean.java works, and how it uses the methodsprovided by JReport Engine Bean mentioned above. First, the example file TestEngineBean.java contains somehard−coded paths. These must be modified before they can be compiled and run. For example, assuming JReportDesigner is installed under d:\jreport, then the "Test A" section can be modified to the following:

bean.setUID("test");bean.setKey("ffffffffffffffffffffffffffffffffffffffff");bean.setReportHome("d:\\jreport");bean.setReportName("d:\\jreport\\Demo\\Reports\\GroupingWithFormulas.cls");bean.setCatName("d:\\jreport\\Demo\\Reports\\Tutorial.cat");bean.setResultFile("d:\\jreport\\temp\\ GroupingWithFormulas.rst");

The result file will be saved under the d:\jreport\temp directory and the result file name will be GroupingWithFormulas.rst.In addition, TestEngineBean.java will also show how to use JReport Engine to export result file (with the .rst extension) todifferent file formats (HTML,PDF,TEXT,etc.). Assuming the GroupingWithFormulas.rst has already been generated byJREngine, now we export it to different file formats:bean.exportToPdf("d:\\jreport\\temp\\ GroupingWithFormulas_0.pdf");bean.exportToText("d:\\jreport\\temp\\GroupingWithFormulas_0.txt", true);bean.exportToHtml("d:\\jreport\\temp\\GroupingWithFormulas_0.html");

d:\\jreport\\temp\\... is the location where users specify the new generated files. At last, TestEngineBean.java will call themethods to add, delete, save and get the WHERE portion in the report catalog:bean.saveWherePortion("condition2","@\"Customers_Customer ID\" < 20");bean.setNamedWherePortion("condition 2");bean.setWherePortion("((@\"Customers_Customer ID\" > 10) and (@\"Customers_Customer ID\" < 20))");bean.deleteWherePortion("condition2");bean.getAvailableQueryFields();bean.getAvailableWherePortions();

To run the TestEngineBean.java, use the following command to compile the test program first:javac −classpath d:\JReport\lib\jrengine.zip;d:\JReport\lib\log4j−1.2.8.jar; TestEngineBean.java

Here we assume d:\JReport is the place where JReport Engine is installed and it is the current directory when usersexecute these commands. Finally, the test program can be run with the following command:java −classpath d:\JReport\lib\jrengine.zip;d:\JReport\lib\log4j−1.2.8.jar; TestEngineBean

When the test program is complete, you will note a temporary file <reportname>.rst. In this test program, this will beeither customerlist.rst or phaseorder.rst depending on which report has been executed. These result files can be readand displayed by either JReport Viewer (the thin client viewer) or JReport Result Viewer Bean.

TestWherePortion.java − A test program purely for the method operated on WHERE Portion. You can add, save anddelete new WHERE portion just like what we do in TestEngine.java. The difference is that the user can do all thesethings in his own report home, catalog and the report file. These result files can be read and displayed by either JReportViewer (the thin client viewer) or JReport Result Viewer Bean.

Executing Reports from JReport Beans Or APIs

323

Page 336: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Result Viewer Bean

JReport Result Viewer Bean (JRResultViewer Bean) is used to view local JReport result files generated by JReportEngine. JReport Engine could be called in three different ways: by JReport Designer, by JReport Enterprise Server, orby JReport Engine Bean. That is to say, the report result file .rst could be generated by JReport Designer, JReportEnterprise Server or JReport Engine Bean.

Briefly, JRResultViewer Bean enables the user to:

Show the report result file .rst.• Export the report result to multiple file formats (HTML, PDF, XLS, RTF, Postscript, Text, CSV, Applet, Email) andprinter.

Note: JRResultViewer Bean requires JDK1.1.6 or the above version.

See also: JReport Javadoc jet.bean.JRResultViewer class. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to download the latest version of the Javadoc zip file or browse thefile online.

Installation

When you install JReport Designer, JRResultViewer Bean is installed at the same time. After the installation, you shouldhave some main components as below:

lib\JRResultViewer.zip* − Archive file for JRResult Viewer Bean.• lib\log4j−1.2.8.jar* − Jar file used for JReport Engine logging system. • lib\JRResultViewer.jar − Jar file for JRResult Viewer Bean• lib\activation.jar − Jar file for exporting to mail• lib\mail.jar − Jar file for exporting to mail• lib\resource.zip − Archive file used when exporting to xml• lib\xerces.jar − Jar file used when exporting to xml• lib\Itext.zip − Archive file used when exporting to PDF.• lib\poiHSSF_151.jar − Jar file used when exporting to Excel.• DeployToEntS.zip − If RPTExecutor UDO has been inserted in the report, to view the correct result of it, this zipfile should be added in the classpath to start JReport Result Viewer Bean.

Readme.txt, License.txt − Information about release• help\pro−material\TestResultBean.java − A simple test program to demonstrate how to display the result. Oryou can find it on our web site at http://www.jinfonet.com/webpage/kbase/kbase.htm for the manual relatedmaterials.

Note:

The asterisk * means that when you call JRResultViewer Bean, these two files must be used. 1. Other files without * should be added accordingly in your classpath calling JRResultViewer Bean under differentcircumstances. For example, when you use JRResultViewer Bean to export to a mail, you should also add mail.jar andactivation.jar with valid path in your classpath. And when you use JRResultViewer Bean to export to xml, youshould also add resource.zip with valid path in your classpath; when you use JREngine Bean to export to Excel,you should add poiHSSF_151.jar with valid path in your classpath; when you use JREngine Bean to export toPDF, you should add Itext.zip with valid path in your classpath.

2.

Properties

JRResultViewer Bean has four properties: reportName, showInfoLevel, logFile and loadReport. The following fourmethods are used to set the value of these properties:

Executing Reports from JReport Beans Or APIs

324

Page 337: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

setReportName ("ReportName")• setTempPath("theTemporaryPath");• setShowInfoLevel (vDebug/vError/vOff)• setLogFile ("LogFileName")• setLoadReport ("Yes/No")•

Parameters:

ReportName − Specifies the name of the JReport result file to be viewed. It contains both the path informationand the file name. Note here the report name is the result file name with .rst extension NOT the report file .cls.

theTemporaryPath − The temporary files path. When the bean runs, the temporary files will be written underthis path. You should set the full path of the temporary files in this method, like this:bean.setTempPath("c:\\temp");If you do not set the temporary path, the default path is the directory where you are running the Bean.

vDebug/vError/vOff are used for showing debug and error information and how to turn off them. LogFileNamespecifies where the debug, error and other information will go. LogFileName contains both the path and thefile name. If no path is specified, the current path is used. If no file is specified, the file jreport.log is used. 'Yes/No' indicates whether to start to view the result of the report (the file specified by ReportName).

Programming with JReport Result Viewer Bean

Import the classes of JRResultViewer Bean by adding the following import statements at the beginning of your program. The first import statements bring into the bean class;import jet.bean.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;

Then, we will create an instance. To run with JRResultViewer Bean, you should create an instance of JRResultViewerBean first. The constructor of JRResultViewer Bean has no parameter. After the object is created, you should set thereport name, set temp path (if not set then the current path will be the default):

bean = new JRResultViewer();bean.setShowInfoLevel(bean.vDebug | bean.vError);bean.setReportName("c:\\test\\customerlist.rst");bean.runReport("yes");

With JRResult Bean object, you can show the report result and export to other formats or printers. You never need tocreate a bean for each report. There are a lot of useful methods provided in JRResultViewer Bean.

Exporting To HTML, PDF, TEXT, XLS, PS, RTF and XML

There are also a couple of methods with which JReport Result Bean will export result file (with the .rst extension) todifferent file formats (.htm, .pdf, .txt):

exportToHtml("HTMLFileName")• exportToHtml("HTMLFileName", bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute,iBrowser)

exportToHtml("HtmlFileName", bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute,iBrowser, Drilldownfile)

exportToHtml( "rstFileName", "HtmlFileName", bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum,bAbsolute, iBrowser, bincdrilldownfile, noMargin)

exportToDhtml(rstFileName, htmlFileName, bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum,bAbsolute, iBrowser, bincdrilldownfile, noMargin)

Executing Reports from JReport Beans Or APIs

325

Page 338: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

exportToDhtml( htmlFileName )• exportToDhtml(htmlFileName, bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute,iBrowser)

exportToDhtml(htmlFileName, bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute,iBrowser, bincdrilldownfile)

exportToDhtml(htmlFileName, bChartApplet, isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute,iBrowser, bincdrilldownfile, noMargin)

exportToPdf("PdfFileName")• exportToPdf( "PdfFileName", noMargin )• exportToPdf("PdfFileName", noMargin, isSimPrintMode)• exportToPdf("PdfFileName", noMargin, isSimPrintMode, isCompressImage)• exportToPdf(rstFileName, pdfFileName, noMargin, isPrintMode, isCompressImage, isTransparent)• exportToText("TextFileName", isNormalText)• exportToText( "TextFileName", isNormalText, chWidth, chHeight)• exportToText("TextFileName", isNormalText, isRepeat, delimiter)• exportToText("TextFileName", isNormalText, isRepeat, delimiter, compress )• exportToXls("xlsFileName")• exportToPS("psFileName")• exportToPS( "psFileName", noMargin )• exportToRtf("rtfFileName")• exportToRtf( "rtfFileName", noMargin )• exportToXML(String xmlFileName, boolean isMultiFile, boolean isOnlyData)•

Parameters:

HtmlFileName −− The name of the HTML format result file with full path.• bChartApplet −− A boolean value indicates whether the chart in html file is an applet. The default value is true.• isMultiFile −− A boolean value indicates whether html is generated to a file or to multiple files. The default valueis true.

bUsingTable −− A boolean value indicates whether to use html table format when exporting html files. Thedefault value is false.

bHyperLink −− A boolean value indicates whether the hyperlink is generated. The default value is true.• bPageNum −− A boolean value indicates whether to generate page number. The default value is true.• bAbsolute −− A boolean value indicates if the font size is absolute or relative. The default value is true.• iBrowser −− A int value indicates whether the html browser is IE or NETSCAPE. 0 means IE, 1 means Netscape.The default value is 0.

Drilldownfile −− A boolean value indicates whether to generate the drilldown html files in the file list. The defaultvalue is false.

rstFileName −− The name of the result file (with the .rst extension) which need to be converted to the requiredformat.

PdfFileName −− The name of PDF format result file with full path.• isSimPrintMode − A boolean value indicates whether to use Simulated Printing Mode (true) or Standard Mode(false) (To PDF). The Standard Mode is supported since version 4.0. By checking it, the exporting speed will bemuch improved.. The default value is false.

isCompressImage − A int indicates the compression ratio of the image in the report (To PDF). The value rangesfrom 1 to 100. The default value is 20.

isTransparent − A boolean value which indicates whether keep the GIF image transparent background.• TextFileName −− The name of TEXT format result file with full path, "true/false' is to set whether this text file is anormal text format or a standard data format (standard data format text file is the text file that each row of itrepresents each record in the report. It can be used as a text datasource to exchange data with otherapplications).

isNormalText −− A boolean value indicates whether this text file is a normal text format or not. When it is set tobe false, the output format is standard data format. The default value is true.

isRepeat −− A boolean value indicates whether the same contents are repeated. The default value is false.•

Executing Reports from JReport Beans Or APIs

326

Page 339: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

delimiter −− A character which will be used in SDF (Standard Data Format) format. The delimiter will be usedonly when the "isNormalText" parameter is set to be false. The default delimiter is a blank space.

compress −− A boolean value indicates whether to remove empty lines or redundant delimiters in the exportedtext file. The default value is false.

xlsFileName −− The name of the Excel format report result file with full path.• psFileName −− The name of the Postscript format result file with full path.• rtfFileName −− The name of the Rich Text Format file with full path.• noMargin −− A boolean value indicates whether to generate the file without page margin. The default value isfalse.

chWidth −− User defined char height which is used in plain text format. It would be given up if the value is 0 orless than 0 (To TEXT) default is −1.

chHeight −− User defined char height which is used in plain text format. It would be given up if the value is 0 orless than 0 (To TEXT) default is −1.

xmlFileName − The XML file name.• isMultiFile − A boolean value indicates whether xml is generated to one file or multiple files.• isOnlyData− A boolean value indicates only database column information is exported to XML file, otherwise allthe report details, including all the properties will be exported. The default value is false.

Note:

Method exportToHtml("HtmlFileName") will take the method exportToHtml( "HtmlFileName", bChartApplet,isMultiFile, bUsingTable, bHyperlink, bPageNum, bAbsolute, iBrowser) using the default parameter values likethis: exportToHtml("HtmlFileName", false, true, false, true, true, true, JRResultViewer.IE).

1.

Method exportToText("TextFileName", isNormalText) will take the method exportToText( "TextFileName",isNormalText, isRepeat, delimiter) using the default parameter values like this: exportToText( "TextFileName",isNormalText, false, ' ').

2.

Printing Reports

There are four methods provided for printing the report:

printReport ( )• printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground, booleanbUseJDK11)

printReport (Object printJob, Object pageFormat, boolean bInteractive, boolean bInBackground, booleanbUseJDK11, boolean bSeparateLargePage)

printReport(java.lang.Object job, boolean bInteractive, java.lang.Object pf, boolean bInBackground,JReportPrintListener jreportprintlistener, int useJDK, java.lang.String jobName, java.util.Vector attributeInfo,java.lang.String printer)

getPrintStatus ( )•

Parameters:

bInteractive −− A boolean value. If you set false, the print setup dialog will not show up.• bInBackground −− A boolean value. If you set true, the printing dialog will not show up.• bUseJDK11 −− A boolean value. If you set true, it will use JDK1.1.x to print the report. Otherwise if you set false,it will use the JDK which you are running to print the report. The JDK 1.1 printing method is quick in speed butthe printing quality is guaranteed. The JDK 1.2 method can provide a satisfactory result, even for a gif file, but itis slow in speed.

bSeparateLargePage −− A boolean value, if the report page size is larger than the print paper size, and you wantto separate the large report page during printing, you should set this property to true. if the print page size whichyou choose is less than the report page size, then the report will be printed as multiple pages serially, this meanswe will separate the large page of the report automatically. After you set it to true, for JDK1.2 or higher, the pageformat dialog will be popped up. In this dialog, you can choose the page format which you want to print with, wewill use this page size for printing. For JDK1.1.x, however, you must change the page format which you want toprint with in the print dialog (click the property button, then choose the page format).

Executing Reports from JReport Beans Or APIs

327

Page 340: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

job −− The print job of this print action. It is a instance of PrintJob or PrinterJob.• bUseJDK −− An integer value. If you set it to 0, it will use JDK1.1 to print the report. If you set it to 1, it will usethe JDK1.2, which you are running to print the report. If you set it to 2, it will use the JDK1.4, which you arerunning to print the report. The JDK 1.1 printing method is quick in speed but the printing quality is notguaranteed. However, The JDK 1.2 method can return you with satisfactory result, even for a gif file, but it is slow in speed. JDK 1.4provides more options to do print such as specifying the paper tray.

attributeInfo −− A vector whose elements are string.Each string has defined in interface PrintConfig.Interface PrintConfig located in package jet.bean. Forexample,you can implement PrintConfig and call its fields like this:attributeInfo.add(TRAY_MANUAL);attributeInfo.add(ORIENTATION_PORTRAIT).

Note:

The first method printReport ( ) is called to start printing. It will take the third method using the default parametervalues like this:printReport(null, null, true, false, false, false)

1.

The second and third method allows you to pass the parameters −− printJob, pageFormat, bInteractive,bInbackground, bUseJDK11 and bSeparateLargePage.

2.

The third printing method (with the bSeparateLargePage parameter) is not recommended, it may cause someunexpected errors, for example, you may get an extra blank page.

3.

After printing is started, the method getPrintStatus ( ) can be used to get the print job status. Returned values ofgetPrintStatus ( ) are:"No print job""Busy""OK""No report load" Other error messages if there are errors.

4.

Example1: Under JDK1.2 or higher, if you use JDK1.2 printing method (boolean bUseJDK11), you can call theprintReport method like this:PrinterJob printJob = PrinterJob.getPrinterJob();bean.printReport(printJob, printJob.defaultPage(), false, false, false);Or, if you do not want to getPrinterJob, simply call:bean.printReport(null, null, false, false, false);

Example2: Under JDK1.2 or higher, if you use JDK1.1 printing method, you are best recommended not to getPrintJob,just call:bean.printReport(null, null, false, false, true);

Getting Page Orientation

getPageOrientation ( )•

The method getPageOrientation is used for getting the orientation of the report page. You should call this method aftercalling runReport method. The return value is an int value, and it can be LANDSCAPE or PORTRAIT. If it is −1, itmakes no sense, say you may have called it before calling runReport method, which is wrong.

Browsing Report Pages

The following methods are also available to JReport Result Viewer Bean.

Methods returning the current page number and the total number of pages of the current report onto the screen:

getCurrentPageNumber ( )•

Executing Reports from JReport Beans Or APIs

328

Page 341: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

getTotalPageNumber ( )•

The Method displaying the page specified by PageNumber on the screen. If PageNumber is out of the range of thecurrent report, the first page (if the pageNumber is less than 0) or the last page will be shown on screen and the returnedvalue is the current page number.

int gotoPage (int pageNumber)•

Methods showing the page specified on the screen:

firstPage ( )• prevPage ( )• nextPage ( )• lastPage ( )•

The return value of the above methods is a string. The value could be:

"OK"• "No more page"• other error messages such as "No report load".•

Zooming the Report

If you want to zoom in or out on the report, there is a method named zoom( ) that will satisfy your requirement.

zoom( ratio )•

Parameter:

ratio − Integer type, standing for a percentage value.•

Example1: If you want to enlarge the report to two times the original size, you can use a method like this:zoom(200)

Example2: If you want to reduce the report size by half, you can use a method like this:zoom(50)

To see another example, please refer to TestResultBean.java under %installroot%\help\pro−material.

ClickActionListener

When clicking a field in the viewer, you can get the entire record of the field. We have an interface in packagejet.thinviewer named ClickActionListener that can implement this function. This interface is defined like this:

interface ClickActionListener{void clickOnField(jet.connect.Record currentRecord);}

If you have a class A which wants to listen to the click event of the field, then this class can implement this interface. Next after you instantiated a bean, you add this ClickActionListener to the bean (Note: this action must be implementedbefore running the report). Finally after the report has been shown and you click on a field, we will call theClickActionListener's method clickOnField, and you will get the values of all columns in that field from the parametercurrentRecord.

To see an example, please refer to TestResultBean.java under %installroot%\help\pro−material.

Executing Reports from JReport Beans Or APIs

329

Page 342: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Setting the Communicator of this report

SetReportCommunicator(Communicator)•

Parameter

communicator − The Communicator here is a class defined by JReport. After users set the communicator, thisviewer will load the report from this communicator, not the result file.

You are recommended to use getReportCommunicator() in JReport Engine Bean and this method in JReport ResultViewer Bean. That is,resultViewerBean.setCommunicator( engineBean.getReportCommunicator() );

Set User Input Stream

To view the result file with JReport Result Viewer, you most often set the report name to a physical .rst file, or if you wantto set the stream of .rst file, you use the below method:

setInputStream(InputStream ins, boolean zip)

Parameters:

ins −− the user input stream.• zip −− Whether the result is compressed or not. To see whether the result is compressed or not, you can callthe below method:

boolean isZipStream(InputStream ins)

Parameter:

ins −− the user input stream.•

Return:

true: is compressed stream• false: is uncompressed stream.•

Exiting the Bean

exit ( )•

This method should be called when you want to quit from JReport Result Viewer Bean. It will do some clean up worksuch as deleting temporary files. It is important to free the resources of the result file open, so do not forget to follow thismethod!

Illustrative Examples

TestResultBean.java − an example program called TestResultBean.java (under%installroot%\help\pro−material) included in JReport Result Bean package.

The properties for the report are very simple, you only need to set the ReportName. Please note, here the report nameis the report result .rst file generated by JReport Engine (JReport Designer, JReport Engine Bean or JReport EnterpriseServer) not .cls file. The call of the runReport and show() methods displays the report result.

Like with JReport Engine Bean, the report result can be exported to other formats like HTML, PDF and RTF or a printer. What you need to do is use the appropriate methods with the corresponding parameters.

Executing Reports from JReport Beans Or APIs

330

Page 343: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To run the TestResultBean.java, you can use the following command to compile the test program first (We assumeJReport Designer is installed under c:\jreport):

javac −classpath c:\JReport\lib\jrresultviewer.zip;c:\JReport\lib\log4j−1.2.8.jar;TestResultBean.java

Using JReport Catalog Bean

Introduction

Report Catalog Bean provides a programming API to manipulate and access the catalog of JReport. The catalog is usedto hold all the resources that are used to build a report in JReport.

Create an empty catalog. • Add objects to a catalog. • Remove objects from a catalog. • Get object description in a catalog. •

JReport Catalog Bean requires JDK1.1.6 or higher.

Installation

When you install JReport Designer, JReport Catalog Bean will be installed at the same time. After installation, the youshould have some main components as listed below:

lib\JREngine.zip* − Class library that contains JReport Catalog Bean. • lib\log4j−1.2.8.jar* − Jar file used for JReport Engine logging system. • bin\jslc.dat* − License control file.• bin\report.ini* − Configuration file. • help\pro−material\TestCatalogBean.java − The testing tools of Catalog Bean with graphics user interface. Or youcan find it on our web site at http://www.jinfonet.com/webpage/kbase/kbase.htm for the manual related materials.

JReport Catalog Bean is combined with JReport Engine Bean and is stored in the same class library calledJREngine.zip. You need to set the CLASSPATH environment variable before you compile and run the program. Appendthe following string to the CLASSPATH:<JReport_Install_Dir>/lib/JREngine.zip;<JReport_Install_Dir>/lib/log4j−1.2.8.jar

Classes

JRCatalog Class

JReport Catalog is the principal class that manipulates and accesses the catalog. The application creates JRCataloginstance and uses JReport Catalog methods to manipulate the catalog.

JReport Catalog has two properties:

reportHome − The string that contains the installation path of JReport Catalog Bean.catName − The string that contains the full file path of catalog. The path will be used in loading or creating the catalog.

See also: JReport Javadoc jet.bean.JRCatalog class. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to download the latest version of the javadoc zip file or browse the fileonline.

Executing Reports from JReport Beans Or APIs

331

Page 344: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JRCatalogException Class

JRCatalogException is the class that describes the error information. This exception is thrown when an error occurs. Thisexception describes many kinds of errors. The error code in the exception represents the type of the exception. The errorcode and error message can be viewed through public means.

See also: JReport Javadoc jet.bean.JRCatalogException class. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to download the latest version of the javadoc zip file or browse the fileonline.

ConnectionDesc

ConnectionDesc is the class that describes the JDBC connection information. This class is used to create/modifyconnection and get connection information.

See also: JReport Javadoc jet.universe.ConnectionDesc class. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to download the latest version of the javadoc zip file or browse the fileonline.

Programming with JReport Catalog Bean

Importing

Import the classes of JReport Catalog Bean by adding the following import statements at the beginning of your program.The first two import statements bring into the bean class and exception class; the third is added to the connectiondescription class.

import jet.bean.JRCatalog;import jet.bean.JRCatalogException;import jet.universe.ConnectionDesc;

Creating an Instance

To manipulate the catalog, you should create an instance of JReport Catalog Bean first. The constructor of catalog beanhas no parameter. After the object is created, you should set the report home to the object. JRCatalog jrCatalog = new JRCatalog(); jrCatalog.setReportHome( "c:\\jreport");

With JReport Catalog Bean object, you can manipulate and access many catalogs. You never need to create a bean foreach catalog.You can load an existing catalog or create a new catalog. After the catalog is created or loaded, you can manipulate thecatalog before you close it. The closeCatalog method closes the catalog, releases resource and clears up the temporaryfile. And the program needs to utilize the closeCatalog method when the operation on the catalog is completed.

Creating a New Catalog

The newCatalog method will create an empty catalog according to the catalog name set in catName, and save thecatalog to disk.When creating a new catalog, the directory of the catalog name should exist and contain no catalog files. You shouldmake sure of this before you create a new catalog.Try{ jrCatalog.setCatName("c:\\a.cat"); newCatalog();}catch(JRCatalogException e)

Executing Reports from JReport Beans Or APIs

332

Page 345: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

{ System.out.println(e);}

Loading an Existing Catalog

The loadCatalog method will load the catalog according to the catalog name set in catName.

try{ jrCatalog.setCatName("c:\\a.cat"); loadCatalog();}catch(JRCatalogException e){ System.out.println(e);}

Manipulation

The manipulation of a catalog includes adding, deleting and editing the objects in the catalog. A catalog contains manykinds of objects. These objects include connection, table, view, file query, stored procedure, query, where portion,formula, summary and parameter. Ideally, all the objects can be manipulated by program via catalog bean, but in theinitial version, only a few objects can be manipulated via catalog bean.For example, you can modify the connection, the name, the URL, the user, the password and the driver.try{ ConnectionDesc conDesc = new ConnectionDesc(); conDesc.strName = "Demo"; conDesc.strURL = "jdbc:oracle:thin:@myhost:1521:orcl"; conDesc.strUser = "system"; conDesc.strPassword = "manager"; conDesc.strDriver = "oracle.jdbc.driver.OracleDriver"; jrCatalog.modifyConnection(conDesc);}catch(JRCatalogException e){ System.out.println(e);}

Accessing

To access is to get information about objects in a catalog.For example, you can get the connection information via the method getConnectionDesc().try{ ConnectionDesc conDesc = bean.getConnectionDesc();}catch(JRCatalogException e){ System.out.println(e);}

Saving

The changes in the catalog will be saved to a disk only when the saveCatalog method is used.

Executing Reports from JReport Beans Or APIs

333

Page 346: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For example, try{ jrCatalog.saveCatalog();}catch(JRCatalogException e){ System.out.println(e);}

Handling Exceptions

When an error occurs, the JRCatalogException will be thrown out. Your program should catch the exception and handlethe error.The exception describes the error code and detailed message as following:

Code: 0Message: "System initialize failed."Description: The system initialize failed. The JRCatalog needs to be initialized to resolve the environment. This error iscaused by reasons like wrong report home, bad installation.Detail: The reason why the initialization failed.

Code: 1Message: "The catalog name is null."Description: The catalog name is null. The catalog name should be set before the loadReport() or newReport() methodare used.Detail: None.

Code: 2 Message: "Creating the catalog failed, because the specified directory does not exist or there is an existing catalog inthat directory."Description: Cannot create a catalog in the specified directory, because the directory does not exist or there is a catalogin the directory.Detail: None

Code: 3 Message: "Cannot open the catalog file."Description: Cannot open the specified catalog file. The reason is file not found, file corrupt, format error or versionmismatch.Detail: The reason why opening catalog file failed.

Code: 4Message: "Save catalog failed."Description: Cannot save the catalog file successfully. The reason is file writing error or formula file save failed.Detail: The reason.

Code: 5Message: "No catalog loaded."Description: The loadCatalog() or newCatalog() methods should be used before other methods. And closeCatalog()should be used in the end.Detail: None

Code: 6Message: "The name of the where portion is invalid or already exists."Description: The name specified is invalid or has already been used by other where portion.Detail: None

Executing Reports from JReport Beans Or APIs

334

Page 347: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Code: 7 Message: "The specified where portion does not exist."Description: The specified where portion does not exist.Detail: None.

Code: 8Message: "A catalog can contain only one connection."Description: A catalog can contain only one connection, and this error occurs when adding the second connection.Detail: None.

Code: 9Message: "The name of the connection is invalid or already exists."Description: The name specified is invalid or has already been used.Detail: None

Code: 10Message: "Connection failure."Description: The JDBC connection failed when trying to create a connection to the database.Detail: The message of SQLException or ClassNotFoundException.

Code: 11Message: "The name of the file query (customer SQL) is invalid or already exists."Description: The name of file query is either invalid or exists.Detail: None.

Code: 12Message: "Cannot create the file query."Description: Cannot create file query object.Detail: The reason.

Code: 13.Message: "There is no connection in the catalog."Description: There is no connection in the catalog. If you are deleting or modifying the connection, the problem is there isno connection existing at all. If you are adding a file query, the problem is you can not create a file query without aconnection.Detail: None

Code: 14.Message: "The specified file query doesn't exist."Description: The specified file query does not exist.Detail: None.

Code: 15.Message: "Unknown Error."Description: The unexpected error.Detail: None

Code: 16.Message: "Invalid user ID or password"Description: The user ID or password is invalid.Detail: None

Code: 17.Message: "Only Tables or Views can be added into catalog."Description: The table type users specified are not supported.Detail: None

Executing Reports from JReport Beans Or APIs

335

Page 348: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Code: 18.Message: "Close connection failure."Description: When closing connection, an error occurred.Detail: None

Samples for JReport Catalog Bean

try{ // create catalog bean JRCatalog jrCatalog = new JRCatalog();

// set report home jrCatalog.setReportHome( "c:\\jrcbean");

// load catalog jrCatalog.setCatName("c:\\a.cat"); loadCatalog();

// modify connection ConnectionDesc conDesc = new ConnectionDesc(); conDesc.strName = "Demo"; conDesc.strURL = "jdbc:oracle:thin:@myhost:1521:orcl"; conDesc.strUser = "System"; conDesc.strPassword = "Manager"; conDesc.strDriver = "oracle.jdbc.driver.OracleDriver"; jrCatalog.modifyConnection(conDesc);

// save catalog jrCatalog.saveCatalog();

// close catalog jrCatalog.closeCatalog();}catch(JRCatalogException e){ System.out.println(e);}

Test program

help\pro−material\TestCatalogBean.java − A test tool of JReport Catalog Bean. It is primarily designed and built for youto test all the methods of JReport Catalog Bean.

The test program has a user interface; All the functions of JReport Catalog Bean can be invoked by the menu item. Youcan get the return result, or the message of exception.

To run the test program, you should first compile the source code TestCatalogBean.java and type the command:java TestCatalogBean

After activating the problem, a window will pop up. Before starting other commands, you should first set the home pathand the catalog name.1. Select the menu File|Set Home Directory to set home directory.2. Select the menu File|Set Catalog Name to set the catalog name.

Then you can create a new catalog with the specified catalog name, or load an existing catalog in the same way.

Executing Reports from JReport Beans Or APIs

336

Page 349: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The test tool also provides the source code of each method, and you can copy them from the text window and put theminto your program.

Index

JReport Designer API

About JReport Designer APIDesigner API & Server Designer APILicenseInstallationGetting StartedProgramming with Designer APIIllustrative Examples for Using Designer API

About JReport Designer API

Besides editing a report with the design panel in JReport Designer, you can edit a report with Designer API. By creating aDesigner instance in your Java program, you can modify a report with the methods provided by Designer API. Comparedwith JReport Designer Bean which will actually pop up the design GUI of JReport Designer, JReport Designer API isactually designing the report with your application.

JReport Design Bean will actually initiate the designer GUI. You will modify report layout just like you do with JReportDesigner. However, JReport Designer API fully realizes designing the report programmatically. That is, using DesignerAPI, you can edit the layout of a report all in your code: to change property values, or modify the report by insertingobjects such as DBfield, formula, text object, chart.... you can also create and design a report with Designer API.

Designer API & Server Designer API

There are two types of package for JReport Designer API − workstation version and server version. We call the JReportDesigner API package for a workstation as Designer API, and for the server as Server Designer API. The maindifferences between these two packages are:

There are some special methods that are used to edit the catalog, queries, reports, parameters and so on. Thesemethods are included in Designer API and Server Designer API. When invoking these methods in ServerDesigner API, you should provide an additional parameter: uID ( it is used to distinguish the different users, it canbe a number or a string.) But when invoking them in Designer API, you need not provide that parameter.

1.

Designer API can only edit one report at a time, while Server Designer API allows concurrent users to modifytheir reports.

Reference Note: For details about how to programming with JReport Designer API and those special methods,please refer to the section Programming with Designer API below.

2.

License

JReport Designer API and JReport Server Designer API uses independent license from JReport other products. You arerequired to contact your Jinfonet sales to get this special license key if you want to use JReport Designer API or JReportServer Designer API on the machine with JReport Designer or JReport Enterprise Server. The license will be applied inyour program instead of being applied on the installation of JReport Designer API or JReport Server Designer API.

The keys for JReport Designer API and JReport Server Designer API are different. You CANNOT use the key forJReport Designer API on JReport Server Designer API, and vice versa.

It is illegal to copy JReport Designer API or JReport Server Designer API package out from JReport Designer or JReportEnterprise Server and use it with this special license key on another machine. If you want to use JReport Designer API or

Executing Reports from JReport Beans Or APIs

337

Page 350: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Server Designer API package for each workstation without JReport Designer and Server, you need to get validlicense for each of the work station.

Installation

JReport Designer API and JReport Server Designer API packages can be easily downloaded and installed to your localmachine, and you can program with them without installing any other JReport products. However, full designer APIpackages are also included in JReport Designer and JReport Enterprise Server. JReport Designer includes the singlethreaded Designer API, while JReport Enterprise Server includes the multi−thread Designer API.

Installing Independent JReport Designer API

Download designAPISetup.exe from http://www.jinfonet.com/download2.htm. Run designAPISetup.exe and follow theprompts to install.

After you install JReport Designer API by running designAPISetup.exe, you need to take the following two steps beforeyou compile and run the program.

Set the CLASSPATH environment variable. Append the following string to your CLASSPATH starting thedesigner API:<designAPI_Install_Dir>\lib\designAPI.zip;<designAPI_Install_Dir>\lib\log4j−1.2.8.jar;<j2sdk_Install_Dir>\lib\tools.jar;

1.

Set the −Dreporthome parameter equal to the root path of the designAPI.2.

Installing Independent JReport Server Designer API

Download svrdsgAPISetup.exe from http://www.jinfonet.com/download2.htm. Run svrdsgAPISetup.exe and follow theprompts to install.

After you install JReport Server Designer API by running svrdsgAPISetup.exe, you need to take the following two stepsbefore you compile and run the program.

Set the CLASSPATH environment variable. Append the following string to your CLASSPATH starting theserverDesignAPI:<serverDesignAPI_Install_Dir>\lib\serverDesignAPI.zip; <serverDesignAPI_Install_Dir>\lib\log4j−1.2.8.jar;<j2sdk_Install_Dir>\lib\tools.jar;

1.

Set the −Dreporthome parameter equal to the root path of the serverDesignAPI.2.

Installing JReport Designer API by JReport Designer

When you install JReport Designer, Designer API will be installed at the same time. After installation, you will have thecomponents listed below:

lib\JREngine.ziplib\report.ziplib\log4j−1.2.8.jar (Jar file used for JReport Engine logging system)

Notes:

Designer API classes are stored in the archive files − report.zip and JREngine.zip.

You need to take the following two steps before you compile and run the program.

Set the CLASSPATH environment variable. Append the following string to your CLASSPATH starting thedesigner API:<JReport_Install_Dir>\lib\report.zip; <JReport_Install_Dir>\lib\JREngine.zip;

1.

Executing Reports from JReport Beans Or APIs

338

Page 351: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

<JReport_Install_Dir>\lib\log4j−1.2.8.jar;<j2sdk_Install_Dir>\lib\tools.jar Set the −Dreporthome parameter equal to the root path of the JReport Designer.2.

Getting Started

In order to help you start with using Designer API, we would like to use a simple sample to show you how to compile andrun a program using Designer API package.

In this tutorial, we are going to compile a Java class returning connection information from a catalog file. And we aregoing to use JReport Designer API package to run this sample.

Download Sample Code TellMeConnection.java

Compile Sample Code

javac −classpath <DesignerAPI_Path>\lib\designAPI.zip TellMeConnection.java

Run Sample Code

java −classpath <DesignerAPI_Path>\lib\designAPI.zip;<DesignerAPI_Path>\lib\log4j−1.2.8.jar;<j2sdk_Path>\lib\tools.jarTellMeConnection <catalog path> <catalog name>

or

java −classpath<ServerDesignerAPI_Path>\lib\serverDesignAPI.zip;<ServerDesignerAPI_Path>\lib\log4j−1.2.8.jar;<j2sdk_Path>\lib\tools.jarTellMeConnection <catalog path> <catalog name>

Example:

java −classpath c:\designAPI\lib\designAPI.zip;c:\designAPI\lib\log4j−1.2.8.jar;c:\j2sdk\lib\tools.jar TellMeConnectionc:\designAPI\Demo\Reports Tutorial.cat

And the output should be like the following:

Driver: org.hsqldb.jdbcDriverURL: jdbc:hsqldb:C:\JReport\Demo\db\demoUser: sa

Programming with Designer API

Class API is the root of class hierarchy of JReport Designer API (Designer API and Catalog API) . It is an abstract classand provides a series of editing methods for users. Designer API class has API as a super class.

Designer and MultiUserDesigner are the principal classes that manipulates a report. The application createsDesigner instance and calls Designer methods to create or modify a report. Here we list the methods provided byDesigner API, for detail about summary of FIELD, CONSTRUCTOR and METHOD, see reference JReportjavadoc jet.api package which includes all the documents generated by Javadoc. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm for the links to the JReport Designer JavaDoc. We also providesome sample files, you can get them on http://www.jinfonet.com/webpage/kbase/kbase.htm for the links to RelatedMaterials.

Setting License Key

The license information is set via a method call setUserInfo(String uid, String key). uid is the user ID, key is the licensekey. This method should be called before you call any other methods of Designer API.

Executing Reports from JReport Beans Or APIs

339

Page 352: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Getting Handles

All the objects in a report are organized and browsed from a tree structure. For each report, Report Inspector consists ofthe report objects tree at the top part of the view panel and its corresponding reporting features or properties at thebottom part. Selecting any object node on the tree also selects the same element on the report design panel. Thebelow two figures cover all the objects that can be used in a report as well as their relationship. Please note: the downarrow indicates the Father−Children inheritance for the objects.

Executing Reports from JReport Beans Or APIs

340

Page 353: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Every node and object in the report tree is identified by a HANDLE in JReport Designer API. So you need to get handleinformation first when you create or edit a report with Designer API. Super class API provides the following methods toget handles of different nodes and different types.

getHandles()Gets all the handles of a report and returns a handle array.

getHandles(String handle)Gets handles of sub node in the current node and returns a handle array. If it fails, it will return null.

getHandles(String handle, int type)Gets sub node handles of the same types for the given node and returns a handle array. If it fails, it will returnnull.

getParent(String handle, int type, int depth)Gets the parent handle of an object and returns the parent handle. If it fails, it will return null.

Executing Reports from JReport Beans Or APIs

341

Page 354: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters:handle − Parent node handle when getting sub node handles; object handle when getting parent handle.type − Class type value that is defined in the API class.depth − It is related to the current level in the report tree. When the depth is −1, all the handles of the report will be got.When the depth is 0, the handles of the current level will be got. When the depth is number n, the handles of n levels andthe current level will be got.

Creating and Deleting a Report

create(String name, String query)Create a new report with report name and return the handle of the new report. If it fails, a null value is returned.

deleteReport (java.lang.String name)Delete an existing report with report name and returns true if the report is successful removed.

Parameters:name − Report name to be created or deleted.query − Query name on which the report is created.

Notes: 1. The report should be created based on the existing catalog file, otherwise you will get an error. 2. The queryshould exist in the given catalog, otherwise you will get an error.

Opening and Closing a Report

open(String name)Opens an existing report and returns the handle of the report. Parameter:name − Name of the report to be opened.

close(String handle)Closes an opened report and saves the changes.Parameter:handle − Ancestor handle of the opened report.

quit(String handle)Closes an opened report without saving it. Parameter:handle − Ancestor handle of the opened report.

Inserting and Deleting an Object

insert(String parent, int type, String name)Inserts an object into the parent node.

insert(String parent, int type, String name, String mapping)Inserts a DBfield, parameter, formula or summary into the parent node.

insert(String parent, String name, CTRowColFieldInfo colInfo[], CTRowColFieldInfo rowInfo[],CTAggFieldInfo aggInfo[])Insert a crosstab object and its children into the parent node.

insert(String parent, CTRowColFieldInfo colInfo, CTRowColFieldInfo rowInfo, CTAggFieldInfo aggInfo)Inserts crosstab children into the crosstab.

insert(String parent, String name, String paperName, int charttype, String gName1, String gName2, Stringvalue, ChartLegendInfo chartLegendInfo, ChartLabelInfo chartLabelInfo)Inserts a chart object and its children into the parent node.

insert (String parent, int type, String name, String topSection , String bottomSection)Inserts a shape object into report and returns handle of the new shape.

insert(String parent, String name, GroupInfo groupInfo)Inserts a group/sort into the parent node.

delete(String handle)Deletes an object from its parent node.

Executing Reports from JReport Beans Or APIs

342

Page 355: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters:

parent − Parent handle node.type − Class type that you want to insertname − Instance name of new objectmapping − Mapping name of the database field, parameter, formula or summary.colInfo − Field information array of Column. rowInfo − Field information array of Row. aggInfo − Field information array of Aggregate.paperName − Instance name of ChartCoordinatepaper object.charttype − Type of Chart.group1 − Mapping name of the first group.group2 − Mapping name of the second group. It can be null.value − Mapping name of a summary.chartLegendInfo − Field information array of the chart legendchartLabelInfo − Field information array of the chart title and notes.handle − Handle of the object to be deleted.topSection − Handle of top section attached by the shape.bottomSection − Handle of bottom section attached by the shape.groupInfo − The group information.

Getting Property Information

Note: All the methods mentioned in this section are provided in the API class.

Getting Property Value

The following methods are used to get property value of different types and return the property value.

getInt(String handle, String name)getLong(String handle, String name)getFloat(String handle, String namegetDouble(String handle, String name)getString(String handle, String name)getBool(String handle, String name)getColor(String handle, String name)getControlFields(String handle, String name)

Parameters:handle − Object handle.name − Property name.

Note: The getControlFields(String handle, String name) method is used to get fields that can control property value atruntime.

Getting Property Name, Type and Checking Property Name

getPropType(String handle, String name)Gets and returns the property type defined in the Designer class.

getPropnames(String handle)Gets property names and returns name array.

containPropName(String handle, String name)Checks whether the property name exists, if it exists, then it will return true.

Executing Reports from JReport Beans Or APIs

343

Page 356: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters:handle − Selected object handle.name − Name of the property.

Changing Property Value

The following methods are used to change property values of different types, they will return true if the value ischanged.Note: These methods are provided in the API class.

set(String handle, String name, Boolean value)set(String handle, String name, int value)set(String handle, String name, long value)set(String handle, String name, float value)set(String handle, String name, double value)set(String handle, String name, String value)set(String handle, String name, Color value)setReference(String handle, String name, String refHandle)setControlFields(String handle, String prop, String field)

Parameters: handle − Target object handle.name − Property name. value − Property value. refHandle − Referenced object handle.prop − Property name.

Notes: The setControlFields(String handle, String prop, String field) method is used to set a field to control the propertyvalue at runtime. The setReference(String handle, String name, String refHandle) method is used to change thereference property value of an object.

Getting a Catalog API Instance

public CatalogAPI getCatalogAPI()Gets a Catalog API instance. It's used for Catalog API.

Getting Objects and Object Information

getDBFields(String handle) Gets DBFields that can be used in the report and returns the mapping name array.

getControlFields(String handle, String name)Gets fields that can control the property value at runtime.

getFormulae(String handle)Gets formulas that can be used in the report and returns the mapping name array.

getSummaries(String handle)Gets summaries that can be used in the report and returns the mapping name array.

getParameter()Gets parameters in the catalog and returns the mapping name array.

getQueries()Gets parameters in the catalog and returns the mapping name array.

getQueryName(String handle)Gets the query name of a report.

getProcedures()Gets procedures in the catalog and returns the mapping name array.

getSections(String handle, boolean visible)getSections(String handle)Gets handles of sections in a report.

Executing Reports from JReport Beans Or APIs

344

Page 357: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

getGroups(String handle)Gets handles of groups in a report.

public GroupInfo[] getGroupInfo(String handle)Gets the group information in a report

public ReportSortInfo getReportSortInfo(String handle)Gets sort information of a report

public SortInfo[] getSortInfo(java.lang.String handle)Gets sort information of a group.

getSQLs()Gets SQLs in the catalog.

getUDS()Gets UDSs in the catalog.

getViews()Gets VIEWs in the catalog.

getObjectInfo(String resourceName, int type)Gets name and type information of a object.

getObjectInfo(String handle)Gets the handle of a object in a report.

Parameter:handle − Report node handle.name − The property name.visible − A boolean type parameter to specify whether the section is visible.resourceName − The object name.type − A int type parameter to specify the object type.

Getting Instance Name and Class Type

getInstanceName(String handle)Gets the instance name of an object and returns null if it fails, or returns the instance name.

getClassType(String handle)Gets the class type of an object and returns one of the class type values that are defined in the Designer class. Ifan error or a warning occurs, it will return UNKNOWN.

Parameter:handle − Object handle.

Getting Information

getWarning()Gets the warning message and returns the warning message. If the operation is successfully executed, it willreturn null.

clearWarning()Clears the warning message.

getError()Gets the error message and returns the error message. If the operation is successfully executed, it will returnnull.

clearError()Clears the error message.

clearMsg()Clears all the warning and error messages.

setLog(OutputStream log, String encoding)Sets the log to get error, debug and other information.

writeLog(String msg)Writes the message to the log.

closeLog() throws IOException•

Executing Reports from JReport Beans Or APIs

345

Page 358: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Closes the log.

Exit

exit()Exits the editing status, releases all the resources and saves all the reports and catalog.

quit()Quits editing status without saving, releases all resources. It will return false if fails, otherwise true.

Concurrent Control

Most of the methods in JReport Designer API could also be used when programming with JReport Server Designer API.But there are some special methods in JReport Server Designer API. When you program with JReport Server DesignerAPI, you should use these methods by using the parameters list in MultiUserCatalogAPI.html andMultiUserDesigner.html. Those methods which named same but do not include uid in their parameters could not be used.

Notes:

The number of concurrent reports and users is depend on your license. 1. A user does not means a people, it means a section. Concurrent users means concurrent sections. 2. When using JReport Server Designer API, you must make sure that each user could only open one report andeach report could only be opened by one user at the same time.

3.

Reference Note: For details about these special methods, please go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm for the links to the JReport Designer JavaDoc.

Illustrative Examples for Using Designer API

You are provided some test programs which demonstrate how to use Designer API to create or edit reports. They are

TestDesignInvoice.javaTestMutiUserDesign.javaTestDesignEditInvoice.javaTestDesignGraph.javaTestDesignCrosstab.javaTestDesignSubreport.java

you can get them on http://www.jinfonet.com/webpage/kbase/kbase.htm for the links to JReport Designer RelatedMaterials.

Example 1: TestDesignInvoice.java

The TestDesignInvoice.java test program is primarily designed to create a report with the methods provided by DesignerAPI.

Using this test program, an invoice report is designed, we can view it with JReport Designer:

Executing Reports from JReport Beans Or APIs

346

Page 359: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Let us explain how TestDesignInvoice.java works, and how it uses the methods provided by Designer API mentionedabove.

Creating an Instance of DesignerThe constructor of Designer has two parameters: path and name. They are respectively path and name of thecatalog with which the report will be created.

desg = new Designer(path, cat);

Setting log if Necessary

desg.setLog(new FileOutputStream(log), "8859_1");

The output stream log points the path and file where to write log message. Parameter "8859_1" is the encodingof message.

Getting Handles

handles = desg.getHandles(report, Designer.PAGE);

This method gets all handles of PAGE type and returns a handle array. Parameter report is the parent handle;Designer.PAGE is class type value which is defined in the Designer class.

Creating a Report

report = desg.create(name, "invoice");

This method creates a new report and returns its handle. Parameter name is the name of the report to becreated, "invoice" is the name of query with which the report is created.

Inserting a Group Panel

group = desg.insert(handles[0], Designer.GROUP, "GroupPanel1", "Customers_Customer ID");

This method inserts a new group panel and returns its handle. Parameter handle[0] is the parent node handle,the newly inserted object will be under this node; Designer.GROUP is the class type you want to insert,"GroupPanel1" is the name of group panel to be inserted; "Customers_Customer ID" is the mapping name to

Executing Reports from JReport Beans Or APIs

347

Page 360: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

group by. Inserting a Label

handle = desg.insert(header, Designer.LABEL, "Label1");

This method inserts a label named "label1" in the group header. Parameter header is the parent handle, thenewly inserted object will be under this node. "desg.LABEL" is the class type that you want to insert. "Label1" isthe object name to be inserted.

Inserting DBField

handle = desg.insert(header, Designer.DBFIELD, "DBField1", "Orders_Order ID");

This method inserts DBField named "DBField1" into the group header. Parameter header is handle of the parentnode; Designer.DBFIELD" is class type to be inserted; "Orders_Orders ID" is the mapping name of the databasefield.

Inserting a Formula, Parameter and SummaryTo insert a formula, parameter or summary, use the same method as inserting DBField. The formula, parameteror summary to be inserted should exist in the catalog. For example, in our test program, parameter PToday,formula customeraddress12 , summary Sum_total9 are already there in the catalog.

handle = desg.insert(header, Designer.PARAMETER, "Parameter1", "PToday");handle = desg.insert(header, Designer.FORMULA, "formula1", "customeraddress12");handle = desg.insert(footer, Designer.SUMMARY, "summary1", "Sum_total9");

Inserting an Image, Box and LineTo insert an image, box or line, use the same method as inserting a label. For example, in our test program,insert the image, box and line as follows:

handle = desg.insert(header, Designer.IMAGE, "Image1");handle = desg.insert(report, Designer.BOX, "Box1");handle = desg.insert(report, Designer.LINE, "Line1");

Setting the Property ValueTo set the property value, you should provide three parameters: object handle, property name and propertyvalue. In our test program, set the following property value:

desg.set(handle, "Width", 1.74f);desg.set(handle, "Height", 0.35f);desg.set(handle, "Text", "Invoice");desg.set(handle, "Alignment", desg.LEFTCENTER);desg.set(handle, "Foreground", new Color(0x900000));desg.set(handle, "Bold", true);desg.set(handle, "FontSize", 0.31f);

Exiting and Closing all Reports.

desg.exit();

This method ends the editing status, releases all resources and saves all of the reports and catalog.

Compiling and RunningTo compile and run the demo program, you should add the report.zip and JREngine.zip with their path into theclasspath. For example, use the following command to compile the test program:

D:\JReport\help>javac −classpath d:\JReport\lib\report.zip;d:\JReport\lib\JREngine.zip; TestDesignInvoice.java

When you run the test programs, you should provide two or three parameters. If you use two parameters, theyshould be catalog path and catalog name, the command line should be like this:

D:\JReport\help>java −classpath

Executing Reports from JReport Beans Or APIs

348

Page 361: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

"d:\jreport\lib\jrengine.zip;d:\jreport\lib\report.zip;d:\JReport\lib\log4j−1.2.8.jar;d:\JReport\lib\hsqldb.jar;d:\j2sdk\lib\tools.jar"TestDesignInvoice d:\jreport\demo\reports tutorial.cat

If you use three parameters, they should be catalog path catalog name and log file with full path name, thecommand line should be like this:

D:\JReport\help>java −classpath"d:\jreport\lib\jrengine.zip;d:\jreport\lib\report.zip;d:\JReport\lib\log4j−1.2.8.jar;d:\JReport\lib\hsqldb.jar;d:\j2sdk\lib\tools.jar"TestDesignInvoice d:\jreport\demo\reports tutorial.cat d:\test\log.txt

Here we assume JReport is installed under d:\JReport and the current directory when you execute thesecommands is under the d:\JReport\help where the test programs are located.

Running the program, you can find the newly created file "invoice1.cls" under d:\JReport\demo\reports.

Example 2: TestMutiUserDesign.java

The TestMutiUserDesign.java test program is primarily designed to create four reports at the same time with the methodsprovided by Designer API.

Using this test program, three reports are created:

Creating the first Instance of MultiUserDesignerThe constructor of MultiUserDesigner has two parameters: path and name. They are respectively path and nameof the catalog with which the reports will be created.

desg = new MultiUserDesigner(path, cat);

Creating the first ReportThis method creates a new report and returns its handle. Parameter name is the name of the report to becreated, "invoice" is the name of query with which the report is created, User is the uid of the user.

report = desg.create(name, "invoice", User)

Getting HandlesThis method gets all handles of PAGE type and returns a handle array. Parameter report is the parent handle;Designer.PAGE is class type value which is defined in the Designer class.

handles = desg.getHandles(report, Designer.PAGE);

Inserting a Parameter, Dbfield, FormulaTo insert a parameter, Dbfield or Formula. The following methods are examples of the special methods that wementioned before. User is the name of each concurrent user.

handle = desg.insert(User, header, Designer.PARAMETER, "Parameter1", "PToday")handle = desg.insert(User,header, Designer.DBFIELD, "DBField1", "Orders_Order ID")handle = desg.insert(User, header, Designer.FORMULA, "formula1", "customeraddress12")

Creating the other Reports. User is the name of each concurrent user. There are four users in this demo.

report = desg.create(name,"westregionsales",User)report = desg.create(name,"Myregionsalesgraph",User)report = desg.create(name,"Mysalesbyregion",User)

Example 3: TestDesignEditInvoice.java

The TestDesignEditInvoice.java test program is designed to apply the methods of Designer API to modify a report. Itdemonstrates how to change the image in the report "invoice1".

Let us explain how TestDesignEditInvoice.java works with the methods provided by Designer API.

Executing Reports from JReport Beans Or APIs

349

Page 362: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating an Instance Create the instance with the same method as used in the TestDesignInvoice.java.

desg = new Designer(path, cat);

Setting LogSet log with the same method as used in the program TestDesignInvoice.java

desg.setLog(new FileOutputStream(log), "8859_1");

Opening an Existing Report

report = desg.open(name);

This method opens an existing report with its name and returns the handle of the report.

Getting Handles

handle = desg.getHandles(report, Designer.IMAGE)[0];

This allows the handle of the object to be modified.

Changing the Property Value

// change the image "coffee.gif" to "sky.gif" desg.set(handle, "PictureName", "sky.gif");

// change the image position desg.set(handle, "X", 2.24f);

// change the image width desg.set(handle, "Width", 4.76f);

Exiting and Closing all Reports.

desg.exit();

Compiling and RunningCompile and run the test program TestDesignEditInvoice.java as you do in test program TestDesignInvoice.java.

After running TestDesignEditInvoice, you will get the modified report shown as below.

Executing Reports from JReport Beans Or APIs

350

Page 363: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Following is some demo code:

TestCatalogBean.java a test program for test Catalog Bean on your computer. • TestDesignCrosstab.java an example of designing a report with a crosstab. • TestDesignGraph.java an example of designing a report with a chart. • TestDesignSubreport.java an example of designing a report with a subreport • TestDesignInvoice.java an example of designing a report with an invoice.• TestDisplayName.java an example of editing display names for DTHML.•

Catalog API

Introduction

JReport Catalog API is intended for those who want to work with a catalog programmatically. You can create a catalogand manage objects in the catalog with the methods provided by Catalog API instead of using the GUI design mode inJReport Designer. Compared with Catalog Bean, Catalog API offers much more comprehensive functionality. As with acatalog in JReport Designer, Catalog API provides methods which enable you to:

Create a connection• Add and delete objects such as tables, queries, formulae, parameters, where portion etc.• Modify a query• Get object information•

The combination of Catalog API and Designer API provides you with a Java development environment that enables youto create any report to meet your needs.

Installation

When you install JReport Designer, Catalog API will be installed at the same time. After installation, you should have thecomponents listed below:

%InstallRoot%\lib\report.zip%InstallRoot%\lib\JREngine.zip%InstallRoot%\lib\log4j−1.2.8.jar (Jar file used for JReport Engine logging system)...

Catalog API class is stored in the archive file report.zip. You need set the CLASSPATH environment variable beforeyou compile and run the program. Append the following string to your CLASSPATH to start the Catalog API:

%InstallRoot%\lib\report.zip;%InstallRoot%\lib\JREngine.zip;%InstallRoot%\lib\log4j−1.2.8.jar

Programming with Catalog API

JReport CatalogAPI is the principal class that manipulates and accesses the catalog. The application creates CatalogAPIinstance and uses CatalogAPI methods to operate the catalog. We will list the methods in Catalog API later in thischapter, for more details about summaries of FIELD and METHOD, please see our reference JReport javadoc jet.apipackage which includes all the documents generated by Javadoc. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm for the links to the javadoc. We also provide sample files under%InstallRoot%\help\pro−material.

With the methods in Catalog API, you can do the following:

Executing Reports from JReport Beans Or APIs

351

Page 364: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating a Designer Object

First of all, use the following constructor in Designer API to create a designer object. The constructor has twoparameters: the catalog path and catalog name. The catalog name can be the name of an existing catalog when youwant to open a catalog, or the name of a new catalog when you want to create a catalog.

Designer(String path, String name)

Getting a Catalog API Instance

To do this, use the following method in Designer API to get the Catalog API instance.

getCatalogAPI()

Creating a Connection

insert(boolean UseJDBCODBCBridge, String name, String desc, String url, String driver)• insert(boolean UseJDBCODBCBridge, String strName, String strDesc, String URL, String DRV,ConnectionInfo info)

These methods insert a database connection and return the handle of the newly inserted connection. If it fails, a nullvalue will be returned.

Parameters:UseJDBCODBCBridge − indicates to connect to the database by a JDBC−ODBC Bridge.name − the connection namedesc − the description for the connectionurl − the URL used to connect to the databasedriver − the database driverstrName − the name of the connectionstrDesc − the description for the connectionURL − The URL used to connect to a database

Executing Reports from JReport Beans Or APIs

352

Page 365: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

DRV − the database driverinfo − the connection information

Note : Class ConnectionInfo is used to create the connection information. For details, refer to User Reference | JReportjavadoc jet.api package which includes all the documents generated by Javadoc.

Inserting an Object

insert(String name, int type)Inserts an object into the catalog and returns the handle of the newly inserted object.

Parameters:name − the object nametype − the object type

Inserting a Table/View

insert(String catalogName, String schemaPattern, String tableName, int type)Inserts a table or view into the catalog and returns the handle of the newly inserted object.

Parameters:catalogName − the catalog nameschemaPattern − the schema patterntablePattern − the table nametype − the table type

Note: For more details about the object handle, refer to the chapter: Executing the reports from beans and APIs |Designer API

Inserting a Stored Procedure

insert(String procName,String catalog,String schema,String name,String remarks,int iType)Inserts a stored procedure into the connection and returns the handle of the newly inserted procedure.

Parameters:procName − the procedure mapping namecatalog − the catalog name of the procedureschema − the schema name of the procedurename − the procedure nameremarks − the remark on the procedureiType − the result type of the procedure

Importing an SQL File

insert(String SQLName, String filename)Imports an sql file and returns the handle of the newly inserted file sql.

Parameters:SQLName − the SQL namefilename − the imported filename

Inserting a UDS

insert(String strDSName, String strClassName, String strParameter, UDSColumnInfo udsColInfo)Inserts a user defined data source and returns the handle of the newly inserted UDS.

Executing Reports from JReport Beans Or APIs

353

Page 366: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Parameters:strDSName − the UDS namestrClassName − the name of the UDS classstrParameter − the parameter valueudsColInfo − the specified column information

Inserting a Query

insert(StringqryName, QueryFieldInfoqueryFieldInfo,QueryJoinInfoqueryJoinInfo,QueryQBEInfoqueryQBEInfo, QueryAndInfoqueryAndInfo)Inserts a query into the catalog and returns the handle of the newly inserted query.

Parameters: qryName − the query name queryFieldInfo − the table and fields information queryJoinInfo − the join information queryQBEInfo − the QBE information queryAndInfo − the where condition information

Note: For the details about the classes QueryFieldInfo, QueryJoinInfo, QueryQBEInfo and QueryAndInfo, please refer toUser Reference | JReport javadoc jet.api package which includes all the documents generated by Javadoc.

Inserting a Formula, Summary, Parameter or a WherePortion

Set(String handle, SummaryInfo info)• Set(String handle, FormulaInfo info)• Set(String handle, ParameterInfo info)

Inserts a summary, formula or parameter into the catalog and returns true if the specified object is insertedsuccessfully, otherwise false if failed.

Parameters:handle − the handle of the specified object, which is got by the method of inserting an object.info − the object info. For a summary, it includes the summary name, description, function type, the field name calculatedon and the field name grouped by. For a formula, it includes the formula name, description and expression. For aparameter, it includes the parameter name, description, prompt information, the parameter data type and the defaultvalue.

The following methods also can be used to insert a formula, a summary or a parameter, but they are deprecated.

insert(String formulaName, String desc, String expression)Inserts a new formula into the catalog and returns the handle of the newly inserted formula.

insert(String summaryName, String desc, int functionType, String fieldName, String groupByFld)Inserts a new summary into the catalog and returns the handle of the newly inserted summary.

insert(String parameterName, String desc, String prompt, String type, String default Value)Inserts a new parameter into the catalog and returns the handle of the newly inserted parameter.

insert(String wherePortionName, String desc, WherePortionInfo whereportionInfo)Inserts a where portion into the catalog and returns the handle of the newly inserted where portion.

Parameters:formulaName − the name of the formuladesc − the description of the objectexpression − the expressionsummaryName − the name of the summaryfunctionType − the type of the functionfieldName − the field name calculated on

Executing Reports from JReport Beans Or APIs

354

Page 367: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

groupByFld − the field name grouped byparameterName − the parameter Nameprompt − the input text prompttype − the parameter data typedefaultValue − the defaultValue of the parameterwherePortionName − the where portion namewhereportionInfo − the whereportion information

Deleting an Object

delete(Stringhandle)Deletes an object from its parent node and returns true if the specified object is removed.

Parameters: handle − the handle of the object to be deleted

Modifying a Query

Add or Delete a Table

set(StringqryName, Stringtablename, booleanselectAllFields)Adds a new table to the query and returns a boolean value: true if successful, else false.

delete(String qryName, String tablename)Deletes the selected table in the query and returns a Boolean value: true if successful, else false.

Parameters: qryName − the query nametablename − the name of table to be inserted or deleted selectAllFields − indicates whether to insert the table with all its fields or not

Note: The tables to be added should exist in the specified catalog.

Add or Delete a Field

set(StringqryName, Stringtablename, Stringcolumnname, booleanisFormula)Adds a new field to the query and returns a Boolean value: true if successful, else false.

delete(String qryName, String tablename, String columnname)Deletes the selected fields in the query and returns a Boolean value: true if successful, else false.

Parameters: qryName − the query name.tablename − the table name of the inserted or deleted fieldisFormula − indicates whether the inserted field is a formulacolumnname − the column name of the deleted field

Add or Delete a Join

set(String qryName, String tableFrom, String columnFrom, String operator, String tableTo, StringcolumnTo)Adds a new join to the query and returns a Boolean value: true if successful, else false.

delete(String qryName, String tableFrom, String columnFrom, String operator, String tableTo, StringcolumnTo)Deletes joins in the query and returns a Boolean value: true if successful, else false.

Parameters:qryName− the query name

Executing Reports from JReport Beans Or APIs

355

Page 368: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

tableFrom − the name of the table from which the join linkscolumFrom − the name of the column from which the join linkstableTo − the name of the table to which the join linkscolumnTo − the name of the column to which the join linksoperator − operator of the join to be inserted or deleted

Add or Delete a QBE Condition

set(String qryName, String tablename, String columnname, String expression)Adds a new QBE condition to the query and returns a Boolean value: true if successful, else false.

delete(String qryName, String tablename, String columnname, String expression)Deletes the QBE condition in the query and returns a Boolean value: true if successful, else false.

Parameters:qryName− the query nametablename − the name of the table where the QBE condition will be added or deletedcolumnname − the name of the column where the QBE condition will be added or deletedexpression − the expression of the QBE condition

Add or Delete a Where Condition

set(String qryName, String sLogic, String sExpression1, String sOperator, String sExpression2)Adds a new where condition to the query and returns a Boolean value: true if successful, else false.

delete(String qryName, String sLogic, String sExpression1, String sOperator, String sExpression2)Deletes where conditions in the query and returns a Boolean value: true if successful, else false.

Parameters:qryName− the query handlesLogic − the logic string of the where condition to be inserted or deleted.sExpression1 − the first expression of the where condition to be inserted or deleted.sOperator − the operator of the where condition to be inserted or deleted.sExpression2 − the second expression of the where condition to be inserted or deleted.

Getting objects in Catalog

Get Tables

getTables()Gets tables and views in the connection and returns the mapping name array.

getTables(boolean bIncludeSystemTable)Gets tables and views in the data source and returns the name array.

Get Stored Procedures

getProcedureNames()Gets all stored procedures in the catalog and returns the mapping name array.

Get SQLs

getSQLs()Gets all SQL files in the catalog and returns the mapping name array.

Get UDSs

getUDSs()Gets all UDSs in the catalog and returns the mapping name array.

Executing Reports from JReport Beans Or APIs

356

Page 369: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Get Queries

getQueries()Gets queries in the catalog and returns the mapping name array.

getNewQueryName()Gets a default name for the new query, which must be unique. The name for the first query in the catalog will bequery1, the following will be query2, query3...

Get Columns

getColumns(String queryName, boolean allColumns)Gets columns in the query and returns the table name and column real names.

getColumnMappingnames(String queryName)Gets column mapping names in the query and returns the table name and column mapping names.

getColumnsCanBeGroupedBy(java.lang.String queryName)Gets columns which can be grouped by in the query.

Parameters:queryName − the query nameallColumns − select all columns in the specified tables

Get Fields

getDBFields(String qryName)Gets DBFields that can be used in the query and returns the mapping name array.

getMappingnames(String DSName)Gets the field mapping names in the data source and returns the table name and column mapping names.

Parameters:qryName − the query nameDSName − the data source object name, such as Query, SQL, UDS, Procedure

Get Formulas, Summaries or Parameters

getFormulae()Gets formulae that can be used in the catalog and returns the mapping name array.

getFormulaeCanBeGroupedBy(String queryName)Gets formulae which are valid to the query and returns the formula names.

getFormulaeCanBeGroupedBy(String queryName, String groupBy)Gets formulae which are valid to the query and returns the formula names.

getSummaries()Gets summaries that can be used in the catalog and returns the mapping name array.

getSummaryCanBeSortedBy(String queryName, String groupBy)Gets summaries which can be sorted by.

getParameter()Gets parameters in the catalog and returns the mapping name array.

getParameterCanBeGroupedBy()Gets parameters which can be grouped by.

Parameters:queryName − the query namegroupBy − the groupBy field

Get Joins

getJoins(String queryName)•

Executing Reports from JReport Beans Or APIs

357

Page 370: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Gets joins in the query and returns the join info array. Note: String[i][0] = Table "From" Name, String[i][1] =Column "From" Name, String[i][2] = Table "To" Name, String[i][3] = Column "To" Name

Parameters:queryName − the query name

Get AND or QBE condition

getAndConditions(String queryName)Gets AND conditions in the query and returns condition info array. Note: String[i][0] = "Logic", String[i][1] ="Expression1" String[i][2] = "Operator", String[i][3] = "Expression2"

getQBEInfo(String queryName)Gets QBE condition in the query and returns QBE info array. Note: String[i][0] = column Name, String[i][j](j>=1) =condition expression of this column.

Parameters:queryName − the query name

Get Report Names

getNewReportName()Gets a default name for the new report, which must be unique. The name for the first report in the catalog will bereport1, the following will be report2, report3....

Saving

save()Saves an opened catalog and returns a boolean value: false if fails, else true.

saveAs(String path, String name)Saves an opened catalog as new catalog file. You can save the catalog to a binary catalog, or an XML formatcatalog. Use extention ".cat" for the name parameter to save the catalog as a binary catalog. Use extention".cat.xml" for the name parameter to save the catalog as an XML format catalog.

An Illustrative Example

You are provided with a demo program which demonstrate how to use Catalog API to create or modify a catalog.

TestCatalogAPI.java

located at %InstallRoot%\help\pro−material.

Below we take TestCatalogapi.java as the example to explain how methods work in Catalog API.

Create Designer object. Designer dr=new Designer(".\\","demo.cat");

If the catalog named demo.cat exists, it will be opened. Or it will be created.

Get a CatalogAPI instanceCatalogAPI cat=dr.getCatalogAPI();

Create a connectionConnectionHandles = cat.insert(true,"jinfonet","Accessdbase","jinfonet",null);

Insert objects into the catalog

For example, insert a table named Customer:tablehandles = cat.insert(null,null,"Customer",cat.TABLE);

Executing Reports from JReport Beans Or APIs

358

Page 371: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Insert a formula named "total":String formulahandles=cat.insert("total",cat.FORMULA);FormulaInfo formulainfo=new FormulaInfo("total","total formula","@\"Unit Price\" *@Quantity − @Discount");cat.set(formulahandles,formulainfo);

Import a SQL filecat.insert("SQL1","D:\\task\\sqlfile.txt");

Save cat.save();

Compile and runTo compile and run the demo program, you should add necessary classes into the classpath. For example, usethe following command to compile and run the demo program:

D:\JReport\help\material>javac −classpathd:\JReport\lib\report.zip;d:\JReport\lib\JREngine.zip;d:\JReport\lib\log4j−1.2.8.jar;d:\test\classesTestCatalogapi.java

D:\JReport\help>java −classpath"d:\jreport\lib\jrengine.zip;d:\jreport\lib\report.zip;d:\JReport\lib\log4j−1.2.8.jar;d:\JReport\help;d:\test\classes"TestCatalogapi

Here we assume that all the classes used in the demo are included under d:\test\classes, such as the classes tocreate a UDS, etc.

After running the program, the new catalog file demo.cat is created.

Index

Executing Reports from JReport Beans Or APIs

359

Page 372: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using JReport Beans in Java IDEJReport is written entirely in Java to take full advantage of the Java architecture. JReport Engine and Viewer Beans canbe easily integrated into your applications, giving them the ability to view or print reports. JReport IDEs includeSilverStream, Forte for Java, JBuilder, Visual Age, Visual Cafe.

Using JReport Beans in Forte for Java

Here we will learn how to use JReport Beans in Forte for Java step by step. We have packed three special jars for Forte− Designer, Engine and Result Viewer. At this time, reports must be modified within the JReport Design window,however, we are currently working on Designer API, which in the future will enable Forte for Java developers to modifyreport design in the code.

Installing JReport Software

Before using JReport Beans in Forte for Java, you should first :

Install JReport DesignerDownload the JReport install program jrpsetup.exe from the Jinfonet web site: http://www.jinfonet.com. Thenrun jrpsetup.exe and follow the prompts to install. We assume JReport is installed under D:\JReport.

Then reason you need to install JReport Designer first is to find the license and other information files. Specifically, when you set the report home in the bean to that of JReport Designer (here is D:\JReport), thenJReport will try to find jslc.dat and report.ini files under %ReportHome%\bin and check whether they are valid. Open report.ini, you will find the configuration information, including the temp path, template path and the helppath. JReport Designer Bean uses the template file under the template path, JReport Engine Bean uses thetemp path to export the temporary files. Therefore, make sure the template and temp folders specified inreport.ini exist.

1.

Set up the ODBC Data SourcePlease note that Forte for Java does not appear to have a feature that enables one to connect to the user's owndatabase, so here we use JReport demo database as the example. Assuming that JReport is installed inD:\JReport, you can find the demo database in D:\JReport\Demo\db.

You need to create a data source before you can view the sample reports in D:\JReport\demo\reports. To dothis you should have Microsoft Access ODBC Driver (or an equivalent driver) installed and create a data sourcepointing to the demo database.

For more details, please go to http://www.jinfonet.com/webpage/kbase/kbase.htm. Lesson one in Tutorialshows you how to install JReport Designer and how to set up the ODBC Data Source step−by−step.

2.

Download the Three Jars packed for FortePlease go to our download centre at http://www.jinfonet.com/webpage/support/download.htm to downloadJReport Designer, JReport Engine and JReport Result Viewer beans for Forte. We save them in the localdirectory D:\jrbean\lib.

3.

Reference Note: Please go to JReport Designer Manual | User's Guide | Executing Reports from JReport Beansor APIs chapter for the methods description and JavaDoc for each bean.

4.

Adding JReport Beans into Component Palette of Forte for Java

You should add JReport Beans into the Component Palette before using them in Forte for Java. To do this, please followthe following steps.

Assume that JReport Beans are located in the directory D:\jrbean\lib.

Start Forte For Java. 1.

360

Page 373: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Choose Tools | Install New JavaBean from the main menu.2.

The Install JavaBean dialog appears as below. In the dialog box, select the path and JAR file of the JReportBeans component and click OK.

3.

Now you get the Select JavaBean dialog. A list will appear with available JavaBeans. Select the ones youwant and click OK. For example, select JRDesign.

4.

Using JReport Beans in Java IDE

361

Page 374: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Palette Category dialog box that appears next, choose where in the Component Palette (under which tab)you would like to place the bean(s) and click OK. Here we select Beans.

5.

Now JRDesign has been added into the Component Palette. You can see the new bean appears under the tabyou indicate. Position the cursor over the bean to see the name of each installed JReport Bean.

6.

Repeat the same procedure to add JREngine and JRResultViewer Beans.7.

Using JReport Beans in Java IDE

362

Page 375: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using JReport Beans in Forte for Java

Creating a new project

When you work in the IDE, you always work in a project, whether it is the default project or one that you have created.

Choose New Project from the Project menu. When prompted, type a name for your new project and click OK. 1. You will be prompted with the choice to either use the file system or systems currently mounted in Filesystems orto remove them and mount a new one. Here we click New.

2.

You will be prompted with whether or not to save the current project. If you click Yes, any changes you havemade to your current project will be saved before it is closed and the new project is opened.

3.

The file chooser will then appear prompting you to pick a directory to mount under the Filesystems tab.4.

Creating New Classes

In Forte for Java, you create new classes with templates. The template serves as a skeleton for the class and includesbasic source code for that class. If you prefer to write all of the code yourself, you can choose the Empty template.

Choose New From Template... from the File menu.In the New From Template wizard that appears, expand the appropriate template category node, for example,AWT Forms, and then select one of the templates. Here we choose Frame.

1.

Using JReport Beans in Java IDE

363

Page 376: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press Next to move to the Target Location page of the wizard. In the Name field, type the name you want togive the object. Here we type JReportDesigner. Do not type the extension for the file type, it will be addedautomatically. Then choose a package for the template. You can do this either by typing a package name in thePackage field or by selecting one of the packages shown in the tree. Press Finish to exit the wizard.

2.

Completed the aforementioned steps will create the object, you can see the object JReportDesigner in the Explorerwindow.

Using JReport Beans in Java IDE

364

Page 377: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: The first time you create an object from template, you will be prompted whether or not you want to add the file tothe current project. If you select Yes, the new file will be visible under both the Filesystems and Project tabs of theExplorer and will be among the classes affected if you compile by project.

Editing Your Source Code

Double−click the object in the Explorer to open the Editor (or select the node of the object and press ENTER). You willsee an Editor with a basic frame skeleton as we selected a Frame template.

As an example, we will demonstrate how to edit JReportDesigner.java. Users of PDF format manual can find it athttp://www.jinfonet.com/webpage/kbase/kbase.htm, then go to the link for the manual related material.

1. Adding Components

First we will add a menu to our Frame. Flip to the AWT tab of the Component Palette, and select MenuBar. Clickanywhere on the Form Editor surface to add the menu bar. In the component listing in the Component Inspector, youwill see a menu bar. If you expand its node, you will see a menu listed. Initially the menu is blank.

Note: All changes made in the Form Editor window are reflected in the source code in the Editor window.

Then add items to this menu. Right−click on the menu in the Component Inspector and choose New | MenuItem.

Next add the second and third menu item in the same way.

Using JReport Beans in Java IDE

365

Page 378: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

With the object (for example, menu3[menu]) selected in the Component Inspector, scroll through the list of its propertiesto the label property; set this to "JReport". Press ENTER to set the new value.

Set the label properties of the menu item in the same way you set menu object. In this demo, we set the label value forthe three items as "Designer" and "View" and "Exit" respectively.

Next we will add JReport Beans to the frame. Select the bean you need from the Beans tab of the Component Paletteand place it on the panel of the Form Editor surface.

2. Adding the Code

Adding handling code to the menu itemsFor the Designer menu item, simply double−click the item in the component list in the Component Inspector.You will see the Editor jump towards the new handler generated.

Then add your handling code into here.

For this demo, we add the following code for Designer menu item:

private void menuItem2ActionPerformed (java.awt.event.ActionEvent evt) {

if ( jRDesign1 != null && jRDesign1.isVisible() ){ //jRDesign1.getActivated().toFront();}else{

jRDesign1 = new JRDesign(); jRDesign1.setShowInfoLevel( jRDesign1.vError | jRDesign1.vDebug );

Using JReport Beans in Java IDE

366

Page 379: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

jRDesign1.setReportHome("d:\\jreport");

jRDesign1.setCatName("d:\\jreport\\Demo\\Reports\\tutorial.cat");

jRDesign1.setReportName("");

jRDesign1.runReport();

String sStatus = jRDesign1.getStatus(); //Get the current JReport Design Bean state to the string sStatus

System.out.println("**** status:" + sStatus); }

}

Add your handling code for the View menu item in the same way. For this demo, we add the following code:

private void menuItem3ActionPerformed (java.awt.event.ActionEvent evt) {

FileDialog fd = new FileDialog(this, "Open Report");

fd.setDirectory("d:\\jreport\\Demo\\Reports\\");fd. setFile("*.cls");fd.setVisible(true);

String path, filename;

path = fd.getDirectory();filename = fd.getFile();

if ( path != null && filename != null ){

jREngine1.setUID("test");

jREngine1.setKey("ffffffffffffffffffffffffffffffffffffffff");

jREngine1.setShowInfoLevel( jREngine1.vError | jREngine1.vDebug );

jREngine1.setReportHome("d:\\jreport");

jREngine1.setCatName("d:\\jreport\\Demo\\Reports\\tutorial.cat");

jREngine1.setReportName(path + filename);

jREngine1.runReport();

String sStatus = jREngine1.getStatus(); //Get the current JReport Design Bean state to the string sStatus

System.out.println("**** status:" + sStatus);

if (jRResultViewer1 != null){ jRResultViewer1.exit(); remove(jRResultViewer1);}

jRResultViewer1.addClickActionListener(this);add("Center", jRResultViewer1);

jRResultViewer1.setCommunicator(jREngine1.getCommunicator());jRResultViewer1.setLoadReport("yes");jRResultViewer1.show();

System.out.println("**** status:" + jRResultViewer1.getStatus());}

Add your handling code for the Exit menu item as shown below:

private void menuItem3ActionPerformed (java.awt.event.ActionEvent evt) {System.exit (0);

}

Adding some importsFor this demo, add the following imports:

import java.awt.*;import java.awt.event.*;

Using JReport Beans in Java IDE

367

Page 380: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

import jet.bean.*;import jet.thinviewer.*;

import jet.connect.*;

Notes:

The JReportDesigner is designed as a demo program to use JReport DesignerBean, EngineBean and JReportResultViewerBean.

For the demo program, we assume that JReport Designer is installed in D:\JReport.• JReport Designer Bean (JRDesign) is used to create or modify a report, JReport Engine bean (JREngine) isused to generate the JReport result. JReport Result Viewer bean (JRResultViewer) is used to view the reportresult generated by the JReport Engine.

• For more details on how to use JReport beans, please refer to related files in %install_root%\help or goto http://www.jinfonet.com/webpage/kbase/kbase.htm.

Compiling the Object

Select the JReportDesigner object in the Editor window, choose Build |Compile from the main menu or press F9.

Running your Java application

Select the JReportDesigner object in the Editor window, choose Build | Execute from the Main Window or use thekeyboard shortcut CTRL+F9.

After you have finished running JReportDesigner, you will get the following window.

Select JReport | Designer, JReport will be started. Then you can create a new report or open and modify an existingreport.

Using JReport Beans in Java IDE

368

Page 381: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: For how to create a new report, modify or open an existing report, please refer to the appropriate chapter in theUser's Guide.

Select JReport | View, and you are prompted to select the report. In our example, we select the report namedInvoice.cls, then clicked Open. The report result will be generated, and you can view the report result as shown below.

Integrating JReport Beans with JBuilder 5

Integrating JReport Design Bean

JReport Design Bean (JRDesign) is intended for those who want to utilize JReport Designer within their java application.The way of editing and refining a report is the same as in JReport Designer Window. Designer API is also provided whichenables developers to modify report design in the code.

Installing JReport Design Bean

To install JReport Design Bean,

Download DesignSetup.exe from the Jinfonet web site:http://www.jinfonet.com/download/DesignerBean/DesignSetup.exe

1.

Run DesignSetup.exe and follow the prompts to install.2.

After installation, you should have some main components as below:

lib\JRDesign.zip − The JReport Designer class library. •

Using JReport Beans in Java IDE

369

Page 382: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

bin\jslc.dat − License control file. • bin\report.ini − Configuration file. • lib\JREngine.zip − The class library for JReport Engine Bean and JReport Result Viewer Bean, which can beused together with this design bean to run and view the report designed.

help\pro−material\TestDesignBean.java − A simple test program demonstrating how to use Designer Bean,which is located under %installroot%\help\pro−material. Or you can find it on our Web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm with the manual related materials.

Reference Note: Please go to JReport Designer Manual | User's Guide | Executing Reports from JReport Beans or APIschapter for the description of the methods and JavaDocs for each bean.

Using JReport Design Bean in JBuilder 5

Please take the following steps to integrate JReport Design Bean. Here we assume that JReport Design Bean is installedin H:\jrdbean, and JBuilder 5 in H:\jbuilder5.

Start up JBuilder 5.1. Create a new project by selecting New Project in the File menu. The Project Wizard pops up. Set a projectname, e.g. JRDBean, then set the Root Path where your project will be kept. The default Root Path will normallybe something like C:/WINNT/Profiles/may/jbproject, but you can change it to another directory, e.g.%installroot_JBuilder5%\samples.

2.

Click on the Next button, then you will need to modify the settings for your new JBuilder project. In the Requiredlibraries panel, click the Add button to open the Select One or More Libraries dialog

3.

Using JReport Beans in Java IDE

370

Page 383: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click on the User Home folder, then click on the New button, and the New Library Wizard will open.4.

First, specify a library name, e.g. JRDBean. In the Library paths panel, click on the Add button to open theSelect One or More Directories dialog. In this dialog, select the two archive files JRDesign.zip and JREngine.zipwhich are located at %installroot_JRDesignBean%\lib, then click the OK button to go back to the New Library

5.

Using JReport Beans in Java IDE

371

Page 384: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Wizard. Next, click the Ok button to return to the Select One or More Libraries dialog.

Now the new library has been created under User Home folder. Select this newly created library and click OK toreturn to the Project Wizard. In the Project Wizard, click the Next button, and the Wizard will ask you to enter adetailed description of the project. You can click on the Finish button to ignore this step.

6.

Having created the project, you can run our sample program. Click File | Open File, and select the fileTestDesignBean.java which is located at %installroot_JRDesignBean%\help\pro−material.

7.

Make sure that you have set the correct report home and catalog name in the code. Then click Project | Make"TestDesignBean.java " to compile TestDesignBean.java. During this procedure, you may receive a warningasking you to check the source path. You can just ignore this warning if there are no other compiling errors.

8.

Click Run | Run Project to run this sample, a Runtime Properties dialog will pop up to let you configure the mainclass. In the example, TestDesignBean.java, the main class is itself TestDesignBean. You can select the classby clicking on the browser button ... to open Select Main Class for Project dialog. If you cannot find the class inSelect Main Class for Project dialog, you can directly input TestDesignBean in the Class name field box andclick OK to go back to the Runtime Properties dialog.

9.

Using JReport Beans in Java IDE

372

Page 385: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

After specifying the main class, you can also specify VM or Application parameters. Finally, click OK to run thesample.

10.

When a frame pops up, click on Test | Test Design, and JReport Designer Bean will start the JReport Designerinterface to let you design a report.

11.

Integrating JReport Run−time

JReport Run−time provides JReport Engine Bean and Result Viewer Bean. Engine Bean mainly responsible for fetchingdata qualified from the data source and returning the result to JReport, JReport Result Viewer Bean (JRResultViewerBean) is used to view local JReport result files generated by JReport Engine. In addition, JReport Run−time alsoprovides methods to export the report result to multiple file formats (HTML, XML, PDF, XLS, RTF, Postscript, Text, CSV,Applet, Email) or a printer.

Installing JReport Engine Bean and Result Viewer Bean

When you install JReport Designer, JRResultViewer Bean is installed at the same time. After the installation, you shouldhave some main components as below:

bin\jslc.dat* − License control file.bin\report.ini* − Configuration file.

lib\JREngine.zip* − Archive file for JReport Engine Bean. lib\JRResultViewer.zip* − Archive file for JRResult Viewer Bean.lib\JRResultViewer.jar − Jar file for JRResult Viewer Beanlib\JimiProClasses.zip − Non−GUI Engine class library, please append this to the classpath besides JREngine.ziplib\resource.zip − Archive file used when exporting to xml.lib\chart.jar − Jar file used when exporting to html with images to be embedded as a chart applet in the html file.lib\udo\udo.ini − Register of user defined objects.lib\activation.jar − Jar file used when exporting to mail.

Using JReport Beans in Java IDE

373

Page 386: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

lib\mail.jar − Jar file used when exporting to mail. help\pro−material\TestEngineBean.java, TestWherePortion.java, LocalWherePortion.java,TestSunVMMPValue.java, TestResultBean.java − simple test programs to demonstrate how to call and useJReport Engine Bean and Result Viewer Bean. Or you can find them on our Web site athttp://www.jinfonet.com/webpage/kbase/kbase.htm for the manual related materials

Note:

The archive file for JReport Engine Bean is JREngine.zip, and for Result Viewer Bean is JRResultViewer.zip.1. The asterisk * means that when you call JReport Run−time, these files must be used.2. Other files without * should be added accordingly in your classpath calling JReport Run−time under differentcircumstances. For example, when you use JRResultViewer Bean to export to a mail, you should also addmail.jar and activation.jar with valid path in your classpath. And when you use JRResultViewer Bean to export toxml, you should also add resource.zip with valid path in your classpath.

3.

Using JReport Run−time in JBuilder 5

The steps to use JReport Run−time JBuilder 5 is the same as we did with JReport Designer Bean. But please note thatyou should select JREngine.zip and JRResultViewer.zip located in the %InstallRoot%\lib when you create the new libraryin the step 5.

Index

Integrating JReport Beans with IBM VisualAge 3.0

Installing JReport Beans

JReport beans mainly include JReport Engine Bean, JReport Result Viewer Bean and JReport Design Bean.

JReport Engine Bean is responsible for fetching data qualified from the data source and returning the result to JReport,JReport Result Viewer Bean is used to view local JReport result files generated by JReport Engine. Both Engine Beanand Result Viewer Bean provide methods to export the report result to multiple file formats (HTML, XML, PDF, XLS, RTF,Postscript, Text, CSV, Applet, Email) or a printer. And JReport Design Bean is intended for those who want to utilizeJReport Designer within their java application. The way of editing and refining a report with Design Bean is the same asin JReport Designer Window.

Installing JReport Design Bean

To install JReport Design Bean,

Download DesignSetup.exe from the Jinfonet web site:http://www.jinfonet.com/download/DesignerBean/DesignSetup.exe

Run DesignSetup.exe and follow the prompts to install.•

After installation, you should have some main components as below:

lib\JRDesign.zip − The JReport Designer bean class library. • bin\jslc.dat − License control file. • bin\report.ini − Configuration file. • lib\JREngine.zip − The class library for JReport Engine Bean and JReport Result Viewer Bean, which can beused together with this design bean to run and view the report designed.

Installing JReport Engine Bean and Result Viewer Bean

When you install JReport Designer, JReport Engine Bean and JReport Result Viewer Bean are installed at the sametime. After the installation, you should have some main components as below:

Using JReport Beans in Java IDE

374

Page 387: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

bin\jslc.dat* − License control file.bin\report.ini* − Configuration file.

lib\JREngine.zip* − Archive file for JReport Engine Bean. lib\JRResultViewer.zip* − Archive file for JRResult Viewer Bean.lib\JRResultViewer.jar − Jar file for JRResult Viewer Bean

Reference Note: Please go to JReport Designer Manual | User's Guide | Executing Reports from JReport Beans or APIschapter for more details.

Integrating JReport Beans with IBM VisaulAge 3.0

Here we take JReport Engine Bean and Result Viewer Bean as the example to illustrate how to integrate JReport beans.Assume that JReport Designer is installed in h:\jreport, and IBM VisualAge is in H:\visualage.

Start up VisualAge and go to Workbench.1. Create a new project by right clicking on the Project tab, and select Add | Project.... In the popped up dialog,type a project name, e.g. JRBean, then click Finish.

2.

Highlight and right click on the JRBean project, select Import... to add JReport Engine Bean (JREngine.zip).First select Jar files as the import source, then input the file name to be imported with its path, and specify thetype of files you want to import.

3.

Using JReport Beans in Java IDE

375

Page 388: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Repeat the step 3 to import Result Viewer Bean(JRResultViewer.zip) and swingall.jar.Note: If you use JDK 1.1 instead of JDK 1.2 and above, swingall.jar is needed to import. You can download thejar file from http://java.sun.com.

4.

Right click on the JRBean project and select add | class..., enter the new class name "EngResultBean", thenspecify Superclass, click next to go to the next step.

5.

Using JReport Beans in Java IDE

376

Page 389: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add import statements by clicking Add Package, and click the Add button to select interfaces to beimplemented, finally click the Finish button.

6.

Using JReport Beans in Java IDE

377

Page 390: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click on the EngResultBean class and edit your java code in the Source section. Please refer to our demoTestResultBean.java under %JReport_InstallRoot%\help\pro−material.

7.

Select the save item from the edit menu to save the EngResultBean class. 8. Go to the Selected menu and select Run | Run main... to run report. 9.

Index

Deploying JReport Engine Bean as EJB to WebLogic 8.1 on Windows/Linux

Introduction

The demo is to show how the JReport Engine Bean is deployed as EJB to WebLogic Server 8.1 on Linux and Windows.The below steps are based on Linux. For the steps on Windows, they are similar to Linux, you just need to change thepath information.

In this demo, an EJB client application is created to call EJB module deployed in WebLogic Server 8.1. In the EJBmodule, the session bean calls JReport Engine Bean to run and export a report to the PDF format. The below image

Using JReport Beans in Java IDE

378

Page 391: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

illustrates the working structure of this demo.

JReport Engine Bean is the module running report templates against a data source and exporting report results to thespecified format such as HTML, PDF, RTF and so on.

Reference Note: Please refer to JReport Designer User's Guide | Executing Reports from JReport Beans or APIs |JReport Engine Bean to see more methods about exporting report result to other formats.

Below are the steps of this demo.

Installation

Install WebLogic Server 8.1 to /home/bea/weblogic81.1. Download J2EE SDK from http://java.sun.com.2. Install JReport Designer to /home/jreport. You will get JREngine and related libraries under/home/jreport/lib.

JREngine.jar − Please rename JREngine.zip to JRengine.jar. It is required for this demo. log4j−1.2.8.jar − Required for this demo. It is called by JREngine to generate log information at runtime.hsqldb.jar − Necessary for this demo. This demo runs a report against HSQL database, and hsqldb.jar is thehsqldb driver.Itext.zip − Necessary for this demo. It is used to export to PDF.

Add the above four files to the classpath in startWeblogic.sh.

This demo will export the report result to the PDF format, and if you want to export the report result to otherformats, please add the corresponding class files or jars. The class files or jars are:

Mail: mail.jar and activation.jarExcel: poiHSSF_151.jarXML: xerces.jar

Note: The JREngine under JReport Designer is of single thread, that is, you can only have it run one report at atime. To build your production EJB calling JReport Engine for concurrent multiple reports, please contact JinfonetSupport for the JReport Server Engine product.

3.

Wrapping JReport Engine Bean into Session Bean

When deploying JReport Engine Bean as EJB to WebLogic 8.1, JReport Engine Bean is wrapped into Session Bean. Formore information, please refer to our demo code in ejbweblogic81.zip under /home/jreport/help/pro−material.

Using JReport Beans in Java IDE

379

Page 392: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Reference: For the usage of JReport Engine Bean, see the Chapter Executing Reports from JReport Beans and APIs.

Creating and Building EJB

Compiling the source code

Create a directory /home/ejb_build, and then copy JREngineEJB.java, JREngineObj.java,JREngineHome.java and JREngineClient.java (the four .java files are our demo code in ejbweblogic81.zip) to/home/ejb_build. Compile the four java files,

javac −classpath /home/j2ee/j2ee.jar:/home/jreport/lib/JREngine.zip *.java

and then the corresponding .class files are generated, they are JREngineEJB.class, JREngineObj.class,JREngineHome.class and JREngineClient.class.

1.

Create a directory /home/ejb, and then create a sub−folder META−INF under /home/ejb. Copy the three filesJREngineEJB.class, JREngineObj.class, and JREngineHome.class to /home/ejb.

2.

Generating deployment descriptor

Create EJB deployment descriptor files, and make sure they are under /home/ejb/META−INF folder.

You have two methods to create the deployment descriptor files, copying and pasting the following contents to create thetwo files, and using the WebLogic Builder to generate them.

Method 1: Copy and paste the following contents to create the file weblogic−ejb−jar.xml and ejb−jar.xml

Contents in weblogic−ejb−jar.xml:

<!DOCTYPE weblogic−ejb−jar PUBLIC '−//BEA Systems, Inc.//DTD WebLogic 8.1.0 EJB//EN''http://www.bea.com/servers/wls810/dtd/weblogic−ejb−jar.dtd'>

<!−− Generated XML! −−>

<weblogic−ejb−jar><weblogic−enterprise−bean><ejb−name>JREngineBean</ejb−name><stateful−session−descriptor><stateful−session−cache></stateful−session−cache>

<stateful−session−clustering></stateful−session−clustering>

</stateful−session−descriptor>

<transaction−descriptor></transaction−descriptor>

<enable−call−by−reference>True</enable−call−by−reference><jndi−name>MyJREngine</jndi−name></weblogic−enterprise−bean></weblogic−ejb−jar>

Contents in ejb−jar.xml:

Using JReport Beans in Java IDE

380

Page 393: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

<!DOCTYPE ejb−jar PUBLIC '−//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN''http://java.sun.com/dtd/ejb−jar_2_0.dtd'>

<!−− Generated XML! −−>

<ejb−jar><enterprise−beans><session><ejb−name>JREngineBean</ejb−name><home>JREngineHome</home><remote>JREngineObj</remote><ejb−class>JREngineEJB</ejb−class><session−type>Stateful</session−type><transaction−type>Container</transaction−type></session></enterprise−beans>

<assembly−descriptor><container−transaction><method><ejb−name>JREngineBean</ejb−name><method−name>*</method−name></method><trans−attribute>Required</trans−attribute></container−transaction></assembly−descriptor>

</ejb−jar>

Method 2: Generate the files using the WebLogic Builder,

Start WebLogic Builder.1. Open the ejb folder, and on the General tab, fill in the options like this:

EJB name: JREngineBeanTransaction type: ContainerJNDI name: MyJREngine

On the Classes tab,

Bean: JREngineBeanHome: JREngineHomeRemote: JREngineObj

2.

Save the module. A folder META−INF that contains the files weblogic−ejb−jar.xml and ejb−jar.xml aregenerated automatically in the ejb folder.

3.

Packing the files

Pack all the files under /home/ejb, using the following command,

jar −cvf demoejb.jar *

and then a compressed file demoejb.jar is generated, including all the files under /home/ejb.

Using JReport Beans in Java IDE

381

Page 394: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Generating the container classes

To generate the container classes, please run the command below:

java −classpath/home/bea/weblogic81/server/lib/weblogic.jar:/home/jreport/lib/JREngine.zip:/home/bea/jdk142_05/lib/tools.jarweblogic.appc demoejb.jar

Deploying EJB to Weblogic

To deploy the demoejb.jar to the WebLogic Server,

Launch the WebLogic Server, and click the EJB Modules option on the left panel of the server window.1. Click Deploy a New EJB Module to deploy demoejb.jar.2.

Running Client Application

Start WebLogic Server and run JREngineClient.class to execute the session bean. To run JREngineClient.class, youcan use a script file, for example, use the following file testclient.sh:

java −classpath /home/bea/weblogic81/server/lib/weblogic.jar:. JREngineClient

If you want to execute JREngineClient.class on another machine, please copy the file weblogic.jar to your local disk,such as D:\, and then run the batch file:

java −classpath D:\weblogic.jar;.; JREngineClient

Deploying JReport Engine Bean as EJB to Weblogic 6.1

Installation

1. Install Weblogic Server 6.1 under d:\bea\wlserver6.1_beta.

2. Install JReport Designer under c:\jreport.

3. Download EJB 2.0 class package ejb−2_0−pfd2−class.zip from http://java.sun.com/products/ejb/docs.html. Save it toyour disk and unzip ejb.jar in this package to D:\downloads\jdk\EJB\2.0.

4. Download the EJB Upgrade 2.0 package ejb20.zip from http://commerce.bea.com/downloads/weblogic_server.jsp. Unzip ejb20.jar in this package to d:\bea\wlserver6.1_beta\lib, and modify startWeblogic.cmd underd:\bea\wlserver6.1_beta\config\mydomain to include the ejb20.jar in the classpath as below:

set CLASSPATH=.;.\lib\weblogic_sp.jar;.\lib\weblogic.jar;D:\bea\wlserver6.1_beta\lib\ejb20.jar;c:\jreport\lib\jrengine.zip;

Wrapping JReport Engine Bean into Session Bean

1. To deploy JReport Engine Bean as EJB into WebLogic 6.1, JReport Engine Bean is wrapped into Session Bean. Formore details, please refer to our demo code JREngineEJB.java, JREngineObj.java, JREngineHome.java andJREngineClient.java.

Reference Note: For the usage of JReport Engine Bean, see the Chapter "Excuting Reports from JReport Beans andAPIs"

2. Create a directory \jrejb\enginebean under D:\bea\wlserver6.1_beta\samples\examples\ejb20, then placeJREngineEJB.java, JREngineObj.java, JREngineHome.java and JREngineClient.java into

Using JReport Beans in Java IDE

382

Page 395: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

D:\bea\wlserver6.1_beta\samples\examples\ejb20\jrejb\enginebean

Creating and building EJB

Creating xml file

Create three xml files before creating build.cmd to describe EJB, then save the xml files toD:\bea\wlserver6.1_beta\samples\examples\ejb20\jrejb\enginebean.

1. Creating weblogic−ejb−jar.xml as below:

<?xml version="1.0"?>

<!DOCTYPE weblogic−ejb−jar PUBLIC '−//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN''http://www.bea.com/servers/wls600/dtd/weblogic−ejb−jar.dtd'>

<weblogic−ejb−jar>

<weblogic−enterprise−bean>

<ejb−name>JREngineBean</ejb−name>

<stateful−session−descriptor>

<stateful−session−cache><max−beans−in−cache>100</max−beans−in−cache></stateful−session−cache>

</stateful−session−descriptor>

<jndi−name>MyJREngine</jndi−name>

</weblogic−enterprise−bean>

</weblogic−ejb−jar>

2. Creating ejb−jar.xml as below:

<?xml version="1.0"?>

<!DOCTYPE ejb−jar PUBLIC '−//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN''http://java.sun.com/dtd/ejb−jar_2_0.dtd'>

<ejb−jar><enterprise−beans><session> <ejb−name>JREngineBean</ejb−name> <home>JREngineHome</home> <remote>JREngineObj</remote> <ejb−class>JREngineEJB</ejb−class> <session−type>Stateful</session−type> <transaction−type>Container</transaction−type> </session></enterprise−beans><assembly−descriptor><container−transaction>

Using JReport Beans in Java IDE

383

Page 396: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

<method> <ejb−name>JREngineBean</ejb−name> <method−intf>Remote</method−intf> <method−name>*</method−name> </method> <trans−attribute>Required</trans−attribute></container−transaction></assembly−descriptor></ejb−jar>

3. Creating build.xml as below:

<project name="ejb20−basic−statefulSession" default="all" basedir=".">

<!−− set global properties for this build −−><property file="../../../../examples.properties"/><property name="src" value="."/><property name="build" value="${src}/build"/><property name="dist" value="${src}/dist"/>

<target name="all" depends="clean, init, compile_ejb, jar_ejb, ejbc,compile_webapp, compile_client"/>

<target name="init"><!−− Create the time stamp −−><tstamp/><!−− Create the build directory structure used by compileand copy the deployment descriptors into it−−><mkdir dir="${build}"/><mkdir dir="${build}/META−INF"/><mkdir dir="${dist}"/><copy todir="${build}/META−INF"><fileset dir="${src}"><include name="*.xml"/></fileset></copy></target>

<!−− Compile ejb classes into the build directory (jar preparation) −−><target name="compile_ejb"><javac srcdir="${src}" destdir="${build}"includes="JREngineObj.java, JREngineHome.java, JREngineEJB.java"/></target>

<!−− Make a standard ejb jar file, including XML deployment descriptors −−><target name="jar_ejb" depends="compile_ejb"><jar jarfile="${dist}/std_ejb20_jrejb_enginebean.jar"basedir="${build}"></jar></target>

<!−− Run ejbc to create the deployable jar file −−><target name="ejbc" depends="jar_ejb"><java classname="weblogic.ejbc" fork="yes"><sysproperty key="weblogic.home" value="${WL_HOME}"/><arg line="−compiler javac ${dist}/std_ejb20_jrejb_enginebean.jar ${APPLICATIONS}/ejb20_jrejb_enginebean.jar"/>

Using JReport Beans in Java IDE

384

Page 397: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

<classpath><pathelement path="${WL_HOME}/lib/weblogic_sp.jar;${WL_HOME}/lib/weblogic.jar"/></classpath></java></target>

<!−− Compile EJB interfaces & client app into the clientclasses directory −−><target name="compile_client"><javac srcdir="${src}"destdir="${CLIENT_CLASSES}"includes="JREngineObj.java, JREngineHome.java, JREngineEJB.java, JREngineClient.java"/></target>

<target name="clean"><delete dir="${build}"/><delete dir="${dist}"/></target></project>

Creating build.cmd

Create the file build.cmd under D:\bea\wlserver6.1_beta\samples\examples\ejb20\jrejb\enginebean as below:

*** Begin of build.cmd ***

@REM Copyright (c) 2000 BEA Systems, Inc. All Rights Reserved.@REM You must set your environment by running the setExamplesEnv shell script @REM prior to executing this script.

SET JAVA_HOME=d:\bea\jdk131

SET WL_HOME=D:\bea\wlserver6.1_betaSET APPLICATIONS=D:\bea\wlserver6.1_beta\config\mydomain\applicationsSET EX_WEBAPP_CLASSES=D:\bea\wlserver6.1_beta\config\examples\applications\examplesWebAppSET CLIENT_CLASSES=D:\bea\wlserver6.1_beta\config\examples\clientclassesSETCLASSPATH=%JAVA_HOME%\lib\tools.jar;%WL_HOME%\lib\weblogic_sp.jar;%WL_HOME%\lib\weblogic.jar;%CLIENT_CLASSES%;%EX_WEBAPP_CLASSES%;d:\bea;c:\jreport\lib\jrengine.zip;D:\bea\wlserver6.1_beta\lib\ejb.jar;

@REM Create the build directory, and copy the deployment descriptors into itmkdir build build\META−INFcopy *.xml build\META−INF

@REM Compile EJB classes into the build directory (jar preparation)%JAVA_HOME%\bin\javac −classpath %CLASSPATH% −d build JREngineObj.java JREngineHome.javaJREngineEJB.java

@REM Make a EJB jar file, including XML deployment descriptorscd buildD:\bea\jdk131\bin\jar cv0f std_ejb20_jrejb_enginebean.jar META−INF JREngineObj.class JREngineHome.classJREngineEJB.classcd ..

@REM Run EJBC on jar file%JAVA_HOME%\bin\java −classpath%WL_HOME%/lib/weblogic_sp.jar;%WL_HOME%/lib/weblogic.jar;%CLASSPATH% weblogic.ejbc −compiler

Using JReport Beans in Java IDE

385

Page 398: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

%JAVA_HOME%\bin\javac build\std_ejb20_jrejb_enginebean.jar %APPLICATIONS%\ejb20_jrejb_enginebean.jar

@REM Compile EJB interfaces & client app into the clientclasses directory%JAVA_HOME%\bin\javac −d %CLIENT_CLASSES% JREngineEJB.java JREngineObj.java JREngineHome.javaJREngineClient.java

*** End of file build.cmd ***

Building EJB Object

Execute build.cmd to build up the ejb20_jrejb_enginebean.jar. The ejb20_jrejb_enginebean.jar will be deployed to weblogic 6.1 shown as below:

Running JREngineClient.class

Start WebLogic server and run JREngineClient.class to execute the session bean. To run JREngineClient.class, youcould use a batch file, for example, use the following file testclient.bat:

d:\bea\jdk131\bin\java −classpathD:\bea\wlserver6.1_beta\lib\weblogic.jar;D:\bea\wlserver6.1_beta\config\mydomain\applications\ejb20_jrejb_enginebean.jar;D:\bea\wlserver6.1_beta\lib\ejb.jar;.;D:\bea\wlserver6.1_beta\config\examples\clientclasses JREngineClient

The result is displayed as below:

Using JReport Beans in Java IDE

386

Page 399: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Index

Deploying JReport Engine Bean as EJB to WebSphere 5.1 on Windows/Linux

Introduction

This demo is to show how JReport Engine Bean is deployed as EJB to WebSphere 5.1 for both windows 2000professional and Linux. The below steps are based on Windows. For the steps on Linux, they are similar to Windows,you just need to change the path information.

In this demo, an EJB client is HttpServerlet which calls EJB module deployed in the same WebSphere 5.1. In the EJBmodule, the session bean calls JReport Engine Bean to run and export a report to the HTML format. The below imageillustrates the working structure of this demo.

JReport Engine Bean is the module running report templates against a data source and exporting report results to thespecified format such as HTML, PDF, RTF and so on.

Using JReport Beans in Java IDE

387

Page 400: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Reference Note: Please refer to JReport Designer User's Guide | Executing Reports from JReport Beans or APIs |JReport Engine Bean to see more methods about exporting report result to the other formats.

Below are the steps of this demo.

Installation

Install WebSphere 5.1 to C:\websphere5.1.1. Install WebSphere Studio Application Developer 5.1 (abbreviated as WSAD) to C:\IBM. In this example, we willuse WSAD to

develop EJB session beans♦ develop EJB client servlet♦ generate deployment descriptors♦ generate the ear file for the later deployment♦

2.

Install JReport Designer to C:\jreport, you will get JREngine and related libraries under C:\jreport\lib.

JREngine.jar − Please rename JREngine.zip to JRengine.jar. It is required for this demo. log4j−1.2.8.jar − Required for this demo. It is called by JREngine to generate log information at runtime.hsqldb.jar − Necessary for this demo. This demo runs a report against HSQL database, and hsqldb.jar is thehsqldb driver.

This demo will export the report result to the HTML format, and if you want to export the report result to otherformats, please add the corresponding class files or jars. The class files or jars are:

Mail: mail.jar and activation.jarExcel: poiHSSF_151.jarXML: xerces.jarPDF: Itext.zip

Note: The JREngine under JReport Designer is of single thread, that is, you can only have it run one report at atime. To build your production EJB calling JReport Engine for concurrent multiple reports, please contact JinfonetSupport for the JReport Server Engine product.

3.

Developing EJB Session Bean and Servlet Calling EJB

In WSAD, first create a project that contains the framework of the EJB and the servlet calling the EJB. Next, go to theireditors to modify the code for EJB and Servlet calling it. Please follow the steps below:

Start WebSphere Studio 5.1. Create a new J2EE project named JReportEJBDemo.

To create the new project JReportEJBDemo, Select Project from the File menu, and the New Project dialog will appear.a. Highlight J2EE in the left panel on the New Project dialog, and then choose Enterprise ApplicationProject in the right panel. Click the Next button on this dialog, and it goes to the New EnterpriseApplication Project dialog. Click Next on this dialog directly.

b.

Type JReportEJBDemo into the Project name text box. Click Next.c. Click New Module and on the New Module Project dialog, select EJB Project and Web Project. Andthen click the Finish button.

d.

You will see JReportEJBDemoEJB and JReportEJBDemoWeb are generated. Click Finish.e. Add source files for the EAR.

Right click Utility JARs under JReportEJBDemo, click Import from the pop−up menu. TheImport dialog appears. Select File System from Select an import source panel, and then click theNext button.

Click the Browse button and select the directory C:\jreport\lib. Select the files JREngine.jar,

f.

1.

Using JReport Beans in Java IDE

388

Page 401: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

log4j−1.2.8.jar, and hsqldb.jar. For the Into folder text box, click the Browse button and selectJReportEJBDemo. Click Finish on the Import dialog.

Create an EJB session bean named JReport for JReportEJBDemoEJB.

To do this, From the J2EE Hierarchy tree, expand EJB Modules, right click Session Beans underJReportEJBDemoEJB, and on the pop−up menu, click Session Bean from the sub−menu of New.

a.

On the New Enterprise Bean dialog, click Next.b. This dialog helps you Create a 2.0 Enterprise Bean. Type JReport in the Bean name text box. Typedemo in the Default package text box. Click Next to the dialog which shows the Enterprise BeanDetails, do nothing on this dialog but click Next. Click Finish.

Now on J2EE Hierarchy tree, under the Session Beans node, three EJB classes are generated. Theyare automatically named JReportHome, JReport, and JReportBean.

Please note that JReportHome is EJB home class, JReport is EJB object class and JReportBean isEJB bean class.

c.

2.

Edit the three EJB classes.

JReportHome: Insert a method which is used to create the EJB object.

JReport: Insert methods which are defined to call JREngine.

JReportBean: Implement the methods in the JReport class (the EJB object object class).

3.

Check JNDI name.

Double click the the session bean JReport, in the right panel, find out the JNDI name, which will be used in theservlet lookup in the future.

4.

Put external classes/jars to the WSAD compiler.

Please follow the steps below: Right click JReportEJBDemoEJB, and choose Properties on the pop−up menu.a. Select Java Build Path in the left panel.b. Click the Libraries tab. Click the Add External JARs button to add JREngine.jar (go to C:\jreport\lib,rename the file JREngine.zip to JREngine.jar).

c.

On the Order and Export tab, check JREngine.jar, and move it to the top.d. Click OK.e.

5.

Add JREngine.jar, log4j−1.2.8.jar, and hsqldb.jar to the classpath which is used to run the EJB.

To do so, On the Window menu, click Other from the sub−menu of Open Perspective. a. Select Plug−in Development on the Select Perspective dialog.b. In the Package Explorer, expand JREportEJBDemoEJB, under META−INF of ejbModule, double clickMANIFEST.MF to open it.

c.

In the Dependencies panel of JAR Dependency Editor, select all the jar files in the JAR orModule column.

d.

6.

Using WSAD to build the container classes and deployment descriptors for the EJB.

To do this, right click JREportEJBDemoEJB under EJB Modules, click Deployment and RMIC Code from theGenerate sub−menu. Check JReport. Click Finish on the Generate Deployment and RMIC Code dialog andsave the resources.

7.

Export this JREportEJBDemoEJB to a jar. Right click the JREportEJBDemoEJB and select Export EJB JAR File from the Export sub−menu.a. On the Export dialog, specify a directory in the Destination text box. Use the default nameJReportEJBDemoEJB. The JReportEJBDemoEJB.jar will be generated in the specified path.

b.

8.

The EJB, that is JReportEJBDemoEJB, is ready now. Next we should finish the servlet code in the created web9.

Using JReport Beans in Java IDE

389

Page 402: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

module, that is JReportEJBDemoWeb, to call this EJB via RMI.

To generate the servlet code, Double click JReportEJBDemoWeb.a. In the Web Deployment Descriptor, click Details of Servlets and JSPs panel.b. Click New to bring out the New Servlet dialog. Type JRServer in the Class name text box. And clickFinish. The JRServer.java is generated.

c.

Add the following code into the JRServer.java.

InitialContext ic = new InitialContext();Object objRef = ic.lookup("java:comp/env/jreport");JReportHome home =(JReportHome)PortableRemoteObject.narrow(objRef,JReportHome.class);this.jreport = home.create();

Note: the above code Object objRef = ic.lookup("java:comp/env/jreport") callsAliasName – jreport. Therefore, we will create an Alias Name for the EJB in the web module.

To do so,

a). Double click JReportEJBDemoWeb, in the References panel, click Details.b). In the EJB References panel, click Add, and rename New EJB Ref to jreport.c). In the Details panel, click Browse after Link text box, select JReportEJBDemoEJB in theLocation panel on the EJB selection dialog, and click OK.d). In the WebSphere Bindings panel, check the JNDI Name, to make sure it is the same as the namementioned in step four.

d.

Double click JReportEJBDemoWeb, in the Pages panel, click Details. In the Login panel, selectBasic from the Authentication method drop−down list. Type index.jsp to the Realm name text box.

e.

Create index.jsp.

Switch to Plug−in Development Perspective, in the Package Explorer, under JReportEJBDemoWeb,right click WebContent, and select File from the New sub−menu.On the New File dialog, type index.jsp in the File name text box, and then click Finish.Write your JSP page code into the index.jsp file.

f.

Now both EJB and Servlet are ready in the same application. Next we will export an EAR which includes the EJBand web project.

To do this, In the J2EE Hierarchy tree, select JReportEJBDemo, right click it and click Export EAR File.a. On the Export dialog, specify a directory in the Destination text box, and use the default nameJReportEJBDemo. JReportEJBDemo.ear will be generated in the specified directory.

b.

10.

Deploying EAR and Starting the Servlet

To deploy EAR,

Open WebSpheres admin page.1. Select Install New Application under Applications in the left panel of the page.2. For the Preparing for the application installation section, click the Browse button of the Local path, go to thedirectory where JReportEJBDemo.ear exists, and select it.

Click Next for all the following steps until finish, and save the task.

3.

To start the Servlet,

Select Enterprise Application under Applications in the left panel of the admin page. 1.

Using JReport Beans in Java IDE

390

Page 403: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Enterprise Application panel, select JReportEJBDemo and then click the Start button. 2. Using a browser to load the JSP page. The URL may be like this: http://192.168.129.53:9080/JRServer/index.jsp. 3.

Note: When deploying JReport Engine Bean as EJB to Websphere5.1, JReport Engine Bean is wrapped into SessionBean. For more information, please refer to our demo code in ejbWebsphere51.zip under C:\jreport\help\pro−material.

Reference: For the usage of JReport Engine Bean, see the Chapter Executing Reports from JReport Beans and APIs.

Deploying JReport Engine Bean as EJB to J2EE 1.2

Preparation

Installation

Suppose that:

J2EE SDK1.2 is installed under e:\j2eesdk1.21. JReport Designer is installed under c:\jreport2. JDK1.2 is installed under c:\jdk1.23.

Setting environment variable

Set J2EE_HOME=e:\j2eesdk1.2, JAVA_HOME=c:\jdk1.2 in the batch file e:\j2eesdk1.2\bin\j2ee.bat.

Setting up properties

Put the line:<permission java.io.FilePermission "<<ALL FILES>>", "read, write";>into the file e:\j2sdkee1.2\lib\security\server.policy.

1.

Put the line: <permission java.security.AllPermission "${reporthome}${file.separator}lib${file.separator}jrengine.zip";> into the file e:\j2sdkee1.2\lib\security\server.policy

2.

In the batch file e:\j2sdkee1.2\setenv.bat, change the line<set JAVACMD=%JAVA_HOME%\bin\java −Xmx128m %EHOME% %ACTIVATION% −Djava.compiler=NONE>to<set JAVACMD=%JAVA_HOME%\bin\java −Xmx128m %EHOME% %ACTIVATION% −Djava.compiler=NONE−Dreporthome=c:\jreport>

3.

In the batch file e:\j2sdkee1.2\setenv.bat, append the classpath c:\JReport\lib\JREngine.zip after CPATH. 4.

Wrapping JReport Engine Bean

1. To deploy JReport Engine Bean as EJB intoJ2EE, JReport Engine Bean is wrapped into Session Bean. Formore details, please refer to our demo code JREngineEJB.java, JREngineObj.java, JREngineHome.java andJREngineClient.java.

Reference Note: For the usage of JReport Engine Bean, see the Chapter "Excuting Reports from JReportBeans and APIs"

Compile these java file with the following commands:

set J2EE_HOME=e:\j2eesdk1.2set CPATH=.;%J2EE_HOME%\lib\j2ee.jar;c:\JReport\lib\JREngine.zip

2.

Using JReport Beans in Java IDE

391

Page 404: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

c:\jdk1.2\bin\javac −classpath %CPATH% JREngineEJB.java JREngineHome.java JREngineObj.java.

Deploying JReport Engine Bean as EJB to J2EE 1.2

Creating the J2EE Application

You cannot deploy an enterprise bean directly into an J2EE server. Instead, you can add the bean to a J2EEapplication, which you then deploy. In this section, you will create a new J2EE application called JREngineApp andstore it in the file named JREngineApp.ear.

At the command line prompt, start the J2EE server:j2ee −verbose

1.

In another command window, run the Application Deployment Tool:deploytool

2.

Create a new J2EE application. 3.

a. In the Application Deployment Tool, select the File menu.

b. From the File menu choose New Application.

c. In the New Application dialog box, enter JREningeApp in the Application Name field.

d. Click the ... button to pop up a file chooser.

e. In the file chooser, locate the directory where you want to place the .ear file that contains the J2EEapplication. In our example, we choose e:\jrejb.

f. In the File name field, enter JREngineApp.ear.

g. Click New Application.

h. Click OK, then the following panel will appear.

Using JReport Beans in Java IDE

392

Page 405: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Packaging the Enterprise Bean

In this section you will run the New Enterprise Bean Wizard of the Application Deployment Tool to perform these tasks:

Create the bean's deployment descriptor.• Package the deployment descriptor and the bean's classes to an EJB .jar file.• Insert the EJB .jar file into the application's JREngineApp.ear file. •

To start the New Enterprise Bean Wizard, from the File menu choose New Enterprise Bean. The wizard first displaysthe Introduction dialog, click Next to go to the EJB JAR box.

Using JReport Beans in Java IDE

393

Page 406: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the combo box labeled "Enterprise Bean will go in," select JREngineApp. In the Display Name field enterJREngineJAR. Representing the EJB .jar file that contains the bean, this name will be displayed in the tree view.

Click the Add button next to the Contents text area. In the Add Contents to JAR dialog box, choose the directorycontaining the .class files. In our case, we choose the e:\jrejb.

Select JREngineObj.class, JREngineEJB.class and JREngineHome.class from the text area and click the Add button. Note: You must compile .java before you selecting classes.

Click OK, then go to Next. The General Dialog Box appears.

Using JReport Beans in Java IDE

394

Page 407: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Classname combo box, select JREngineEJB. In the Home Interface combo box, select JREngineHome. In theRemote Interface combo box, select JREngineObj. Then check the Session radio button and the Stateful radio button.

In the Display Name field, enter JREngineBean. This name will represent the enterprise bean in the tree view. ClickNext to go to the Environment Entries Dialog Box. Skip the remaining dialog boxes, click Finish.

Deploying the J2EE Application

Now that the J2EE application contains an enterprise bean, it is ready for deployment.

1. Specify the JNDI name of the enterprise bean

In the Application Deployment Tool, select JREngineApp in the tree view. Select the JNDI Names tab. In the JNDINames field, enter MyJREngine and press Return. The client will use this name to locate the home interface.

Using JReport Beans in Java IDE

395

Page 408: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

2. Deploy the J2EE application

From the Tools menu, choose Deploy Application. In the first dialog box, verify that the Target Server selection iseither "localhost" or the name of the host running the J2EE server. In our example, we select the LAB02. CheckReturn Client Jar.

Using JReport Beans in Java IDE

396

Page 409: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Press Next , then Press Back. After this, the text field will appear. Enter the full path name for the fileJREngineClient.jar. This file will reside in the e:\jrejb. The first dialog box will appear as below.

Using JReport Beans in Java IDE

397

Page 410: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click Next. In the second dialog box, verify that the JNDI name for the JREngineBean is MyJREngine. Click Next to thethird dialog box, and click Finish.

In the Deployment Progress dialog box, click OK when the deployment completes.

Using JReport Beans in Java IDE

398

Page 411: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Compiling and Running the Client

Compile JREngineClient.java using the following commands:

set J2EE_HOME=e:\j2eesdk1.2set CPATH=.;%J2EE_HOME%\lib\j2ee.jar

c:\jdk1.2\bin\javac −classpath %CPATH% JREngineClient.java

1.

Use the following command to run the client.

set J2EE_HOME=e:\j2eesdk1.2set CPATH=.;%J2EE_HOME%\lib\j2ee.jar;e:\JREJB\JREngineAppClient.jar;%JAVA2%

c:\jdk1.2\bin\java −Dorg.omg.CORBA.ORBInitialHost=localhost −classpath "%CPATH%" JREngineClient

2.

The result will display as below:3.

Index

Supporting EJB Deployed in JBoss 3.0.7

Preparation

Using JReport Beans in Java IDE

399

Page 412: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Installation

Suppose that

JavaTM

2 SDK Version 1.4.1 is installed under C:\j2sdk1.4.1_01; 1. JReport Designer is installed under C:\JReport; 2. JBoss 3.0.7 with integrated Tomcat 4.1.24 is installed under D:\jboss−3.0.7_jakarta−tomcat−4.1.24.3.

In order to simplify your work, we provide you with a zip called ant_jreport_ejb.zip. You can downloadant_jreport_ejb.zip from Jinfonet website at URL: http://www.jinfonet.com/manualpro/pro−material/ant_jreport_ejb.zip.Extract it to D:\jboss−3.0.7_jakarta−tomcat−4.1.24 directory.

ant_jreport_ejb.zip

This zip file contains a build utility Ant and JReport EJB Demo Source Code.

Ant is a third party tool, which compiles the Java source code, builds the EJB JAR, and deploys the JAR simplyby copying it to JBoss's deploy folder.

A file called build.xml is also included in the zip file, which is needed by the Ant utility to figure out what tocompile and how to build your JARs. It gives the Ant utility information about how to compile and deploy yourJava programs and EJBs. You can find the build.xml file in theD:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb folder created by the extraction process.

If you need to know more about the Ant utility, please visit the Ant project at the Jakarta web site athttp://jakarta.apache.org/ant/index.html.

In jreport_ejb folder, there is a folder src, which contains JReport EJB demo source code(workbook/src/main/jreport) and two xml files used in JBoss deployment (workbook/src/resources/META−INF).

Build and Deploy the JReport Demo Program

Perform the following steps:

Copy JREngine.zip to D:\jboss−3.0.7_jakarta−tomcat−4.1.24\client and rename it to JREngine.jar. TheJREngine.zip is located in C:\JReport\lib folder.

1.

In Command Prompt, switch to the D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb folder created bythe extraction process.

2.

Set the JAVA_HOME and JBOSS_HOME environment variables to point to where your JDK and JBoss 3.0.7 areinstalled.

3.

D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb> set JAVA_HOME=C:\j2sdk1.4.1_01D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb> setJBOSS_HOME=D:\jboss−3.0.7_jakarta−tomcat−4.1.24

Add Ant to your execution path.

D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb> set PATH=..\ant\bin;%PATH%Then, issue the command ant and press ENTER key, screen message reads:4. D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb>antBuildfile: build.xml

prepare:

compile: [javac] Compiling 4 source files to

Using JReport Beans in Java IDE

400

Page 413: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb\build\classes

ejbjar: [jar] Building jar:D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb\build\ejb_jrengine.jar [copy] Copying 1 file toD:\jboss−3.0.7_jakarta−tomcat−4.1.24\server\default\deploy

BUILD SUCCESSFULTotal time: 3 seconds

As you can see, ejb_jrengine.jar is successfully built and then deployed toD:\jboss−3.0.7_jakarta−tomcat−4.1.24\server\default\deploy.

Run JREngineClient Application

Perform the following tasks:

Open a Command Prompt window, change to the D:\jboss−3.0.7_jakarta−tomcat−4.1.24\bin folder.1. Invoke JBoss server using run.bat, which is located in %JBossServerRoot%\bin folder, to start jboss.

Note: Before you run the batch file, be sure to add the bold part of the following to the classpath:

2.

set JBOSS_CLASSPATH= C:\JReport\lib\JREngine.zip; C:\JReport\lib\Itext.zip;%JBOSS_CLASSPATH%;%JAVAC_JAR%;%RUNJAR%In another Command Prompt window, run JREngineClient application by invoking ant run.client_jreport.Remember to set your JBOSS_HOME and PATH environment variables.

The output of JREngineClient should look something like this:

3.

D:\jboss−3.0.7_jakarta−tomcat−4.1.24\workbook\jreport_ejb>antrun.client_jreportBuildfile: build.xml

prepare:

compile:

ejbjar:

run.client_jreport: [java] ReportHome: true [java] ReportName: true [java] CatName: true [java] RstName: true [java] getStatus = OK [java] exportToPdf OK [java] Exit

BUILD SUCCESSFULTotal time: 15 seconds

Three files − CustomerList.pdf, CustomerList.rst and JReport.log, specified in JREngineClient.java, aregenerated in the C:\JReport\temp folder.

NOTE: You need a User ID and JReport Runtime Key to run JReport Client application. If you don't have this, pleasecontact Jinfonet Software sales at [email protected] or visit Jinfonet website http://www.jinfonet.com for more

Using JReport Beans in Java IDE

401

Page 414: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

information.

Manage Entity Beans

Every EJB in JBoss is deployed and managed as a JMX MBean. You can view and manage EJBs deployed within JBossthrough your web browser by accessing the JMX manangement console available athttp://localhost:8080/jmx−console/index.jsp.

Index

Using JReport Beans in Novell ConsoleOne

Preparation

Download NovellClient for Windows NT from http://www.novell.com/download, and install NovellClient to logonthe NetWare sever.

1.

Download the release of ConsoleOne from http://www.novell.com/download, run the ConsoleOne installer toinstall ConsoleOne 1.3.2 under D:\Novell\ConsoleOne\1.2\bin.

2.

Download designer.exe from http://www.jinfonet.com/download/novell, execute the installation file and follow theinstallation wizard step by step to install JReport Designer Bean for Novell under D:\Novell\ConsoleOne\1.2.

3.

Logon the NetWare server.Suppose the NetWare server has been started up and you logon Windows NT.

4.

Using JReport Beans in Java IDE

402

Page 415: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Right click the red N icon in the System Tray and click NetWare Login, or right click NetworkNeighborhood and click NetWare Login, or select Novell Login from the Start menu.

In either of ways above, you will get the following dialog:

Enter the user name in the Username text box, please note that the user should be the member of theadministration group. Then enter the password of this user. Click OK to complete the login.

Notes: 1. If you logon the NetWare server for the first time, you should click the Advanced button, and enterthe name of Tree and Context that have been named on the NetWare server. 2. If you have the same nameand password as Windows NT, you will logon Windows NT and NetWare at the same time when you startWindows NT.

Launch Novell ConsoleOne by simply double−clicking the ConsoleOne icon on the desktop.5.

Generating Reports

Create a new object. Right click on Context under the TREE node and select New | Object.1.

Using JReport Beans in Java IDE

403

Page 416: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select Report Catalog from the Class list and click OK to create a new catalog.2.

In the New Report Catalog dialog, input the catalog name, here we input "tutorial", locate the path to store thefile, then check Novell−defined as the data source. Click OK.

3.

The following dialog appears to allow you to add tables. Select tables from the available list, click Add, thenDone.

4.

Using JReport Beans in Java IDE

404

Page 417: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You will get into the Properties dialog. Make sure the Forms tab is selected, then click New.5.

JReport Designer will be launched up. Click Continue on the cover page, the Report Wizard comes up. You can6.

Using JReport Beans in Java IDE

405

Page 418: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

also get the report wizard by right clicking on the catalog "tutorial" in the ConsoleOne window and select theProperties item. Then in the Properties window, select the Form tab, click on the New button.

Now, follow the wizard step by step to finish the form creating. Reference Note: For the details on how tocreate a report form, please refer to the chapter −− Developing Reports with Report Wizard. Save the created form under the same path as catalog "tutorial". 7. Exit JReport Designer by selecting File |Exit to go back the Properties of tutorial frame. If the report form youjust created is not displayed in the Available form list, select the Form tab to refresh the list.

8.

Select the Queries tab in the Properties frame, click on the Generate report button to generate the report. 9.

Using JReport Beans in Java IDE

406

Page 419: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If you want to create a new query, click on the New button. Then you get the report result shown as below.10.

Using JReport Beans in Java IDE

407

Page 420: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Select Save... from the File menu to save the report. Select Export reports... to export the report to different fileformats, such as Text, PDF,....

11.

Go back to Properties frame. Select the Reports tab, you can see the newly generated report shown in theAvailable reports list.

12.

Using JReport Beans in Java IDE

408

Page 421: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using JReport Beans in Java IDE

409

Page 422: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Exporting Report Result to Multiple File Formats

Introduction

JReport makes it easy for you to share the report data with other applications. In JReport Designer, you can export datato various file formats, such as JReport Result, Text, HTML, PDF, Postscript File, Mail, Applet, RTF, Excel File, and XML.

To export the report, on the File menu, point to Export, and then choose a file format.

You can export the report data in both design mode or view mode. If the report is modified, we suggest that you use theview mode to export the report data. To do this, click the View tab, click the Refresh Data button so that the data can berefetched from the database, and then export the report data to the format you desire.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to JReport Result

As you know, one important concept proposed by JReport is the separation of template report file and the report resultfile. The report result file can be viewed by JReport Viewer. Specifically, you can use JReport Viewer for JREntServer toopen local files. You can also display the .rst files in your application by calling JReport Result Viewer Bean.

To export a report to a result file, on the File menu, point to Export, and then click To JReport Result. The Export toJReport Result dialog appears.

410

Page 423: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Type a name for the JReport result file, and then click Save. A .rst file will be generated in the specified directory.

Related Topics

Exporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to Text

To export a text file in JReport Designer, on the File menu, point to Export, and then click To Text. The Export toText dialog appears.

Exporting Report Result to Multiple File Formats

411

Page 424: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The Export To Text dialog includes the following screen elements:

Export toType the file name and directory where you want to store the exported text file or click the Browse button to specify thedirectory.

Standard Data FormatThis section allows you to specify the format in the following options.

FormatYou can specify a delimiter to separate fields. Select one from the drop−down list.

CSV Delimited − Fields in the exported text file will be separated by commas. Tab Delimited − Fields in the exported text file will be separated by tabs. Custom Delimited − Fields in the exported text file will be separated by a user defined delimiter. You can type your owndelimiter in the Delimiter box.

QuoteMarkIf checked, fields in the exported text file will be marked with quotation marks.

Header and FooterIf checked, the exported file will contain all headers and footers in the report, including Report Header/Footer, PageHeader/Footer and Group Header/Footer. Otherwise, the exported file will only contain data in the Detail section.

Repeat last column value if nullIf checked, when a certain field has no value, it will repeat the data of the previous record.

User Define DensityThis section allows you to specify the density for the exported text file content.

Horizontal DensityType a value for each unit of the horizontal density between columns. The density of the result is in direct ratio to thevalue you specified. That is to say, the greater the value is, the smaller the width between columns. The default value is−1.

Exporting Report Result to Multiple File Formats

412

Page 425: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Vertical DensityType a value for each unit of the vertical density between columns. The density of the result is in direct ratio to the valueyou specified. That is to say, the greater the value is, the smaller the height between columns. The default value is −1.

CompressIf checked, there is no clearance between columns. Please note that, this option works only when no any data (includingempty strings) display in a row (since JReport Designer v4.5).

ResolutionSpecify resolution as you desired. When the value is −1, it will use the current resolution of your monitor.

Use Windows end−of−line characters Specifies whether to use Windows end−of−line characters to indicate the start of a new line. If checked, it uses twocharacters at the end of the line: <cr><lf>. Otherwise, it uses Unix EOL character: <lf>, at the end of line.

Example: Exporting a report to CSV File

The following case is a simple example to show you how to export your report to a csv format file:

Open the report to be exported. Here we select the demo report Lesson2.cls under%Intall_Root%\demo\reports.

1.

On the File menu, point to Export, and then click To Text. 2. Specify the destination of the exported file: C:\rptcsv\lesson2.csv. Check Standard Data Format, selectCSV Delimited from the Format drop−down list.

3.

To have records aligned well in the exported file, you are suggested checking QuoteMark. If not, the commas inthe data value like "$78,321.00" will conflict with the delimiter (comma), and may potentially cause the data to beseparated incorrectly when the exported file is further processed by other applications.

"Scarsdale,The Java King,(914) 657−9823,(914) 657−8745,$78,321.00"

As shown above, it's hard to determine whether the value is $78321.00 or $78 and 321.00.

4.

Click OK to perform the exporting operation. 5.

Notes:

In the exported file, you may find that some column names are not aligned with their DBFields. They may displayin different columns. To solve the problem, make both the column name and its DBField left aligned and adjusttheir location with the same Geometry "X" before exporting it to the CSV format.

For example, as the image below:

1. Select both column name "City" and its DBField.

2. On the Format toolbar, click the Left button. This makes the text "City" and "XXXXXXXXXX" align left.

3. On the Format menu, click Align Left. This makes the label and DBField align left.

In step 4 above, you can also use other delimiters such as "|". However, when you do so, you should export to.txt file instead of .csv file. Open it in Excel. In the Text Import wizard, check the Delimited radio button, clickNext to go to the next step. Check Other on the Delimiters panel and key in "|" (quotation marks NOT included),click Finish to view the result.

Exporting Report Result to Multiple File Formats

413

Page 426: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The data of each field should be in one column. If there are no data in the column, empty strings ("")will be putthere automatically. In this case, the empty strings can not be compressed. Only if there are no data in the entireline, can the row be compressed when you check the Compress option.

When exporting a report to CSV file, you may want to export only some of the objects instead of all.

For example, to export only the DBField "Annual Sales" to a CSV file, follow the procedure below:

1. Select DBField "Annual Sales".

2. On the View menu, check the Report Inspector.

3. In Report Inspector, set ExportToCSV to True.

4. In Design view, select all the other objects you don't want to export.

5. In Report Inspector, set ExportToCSV to False.

6. On the File menu, point to Export, click To Text to export the report.

7. In the Export to text dialog, specify the subdirectory and name of the exported file, make sure that you havechecked the Standard Data Format box and selected CSV Delimited format. Click OK.

The exported file will only contain the data of the DBField "Annual Sales". You can control whether to export theother objects to the exported CSV file in the same way. Please note, if you set the ExportToCSV property of asection to be false, all the objects in this section will not be exported regardless of their ExportToCSV properties.

To improve the performance of running report to the Standard Data Format on JReport Enterprise Server

On JReport Enterprise Server, if you want to improve the performance of running a report to the Standard Data Format,such as the CSV format, some settings should be done in JReport Designer first and then deploy the report to JReportEnterprise Server to run it to the Standard Data Format. Please follow the steps below:

Open the report you want to run to the Standard Data Format on the server in JReport Designer. In ReportInspector, browse to the root node of the report, find the two properties FastPass and Columned, and then setthem to true.

1.

Choose the object you want to display in the result file and set where you want them to be shown in the resultfile. To do this, select the object, and find the two properties ColumnIndex and RowIndex. TheColumnIndex refers to which column this object will be in and the RowIndex refers to which row this object willbe in in the result file. The number of the column and the row are started with 0 and counted within its section, forexample, if you want to place the object in the first column and the second row in the detail section, setColumnIndex = 0 and RowIndex = 1 of this object.

Note: This method can also be used in JReport Designer to improve the performance when export the reportresult to Standard Data Format.

2.

Please go to the server.propertise file under %JREntServer_InstallRoot%\bin to change the propertyengine.single_thread = false. This enables the property FastPass to take effect when running the report to theStandard Data Format.

3.

Deploy the report to JReport Enterprise Server, when you run or schedule the report, after you choose the ToText format, please select the Standard Data Format check box, and then click Submit to generate theStandard Data Format file.

4.

Notes:

When the FastPass property is true, in the report header panel, the values of the objects which use the globalparameters to do the calculation will be wrong, and the page level calculation, such as Page Number, Total PageNumber, will also be wrong. So please move these objects from the report header panel to the report footer

Exporting Report Result to Multiple File Formats

414

Page 427: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

panel to avoid these kinds of mistakes. Please do set the positions for the objects with the ColumnIndex and RowIndex properties, otherwise, all theobjects will be at the first column and the first row in the result file.

You can not run the report with Cross Tab to the Standard Data Format in this way.•

Related Topics

Exporting to JReport ResultExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to HTML

To export the current report result to an HTML file, on the File menu, point to Export, click To HTML. The WebWizard dialog appears.

1. Report Tab

Exporting Report Result to Multiple File Formats

415

Page 428: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Web Page NameSpecifies the web page name for the exported HTML file. If there is no name specified, the report name will be used asthe default HTML file name. You do not need to key in the file extension .html, since JReport will automatically tag it.

By default, JReport designates a serial number for each exported HTML page. For example, if you name a 3−page reportas Sales, JReport will create three files called Sales_1.html, Sales_2.html, and Sales_3.html.

ForSpecifies the target internet browser for the exported HTML result files: IE or Netscape.

No MarginIf checked, the exported file has only the margins of browser.

Table FormatThis option changes the code structure of the output file. It doesn't affect the appearance of the exported report.

If checked, the HTML page layout will be structured using Table Elements (TABLE, TD, TH, TR, and so on). By default,the HTML page layout will be structured using Grouping Elements (DIV, SPAN, and so on).

Include Drilldown FileSpecifies whether to generate the drilldown files.

DhtmlSpecifies whether table of contents (TOC) is available in the exported HTML file.

MultifileGenerates a group of HTML files with hyperlinks to each other.

Single FileGenerates a single HTML file instead of multiple files.

AbsoluteIf checked, the font size in the exported HTML file will be fixed, and cannot be adjusted in a web browser.

RelativeIf checked, the font size in the exported HTML file will be relative, and can be adjusted in a web browser.

No HyperlinkSpecifies whether the exported HTML file will contain hyperlinks. This option is enabled only when Single File isselected.

No Page NumberSpecifies whether the exported HTML file will contain page numbers. This option is enabled only when Single File isselected.

Embed CSSSpecifies whether to contain the cascading style sheet (CSS) within the exported HTML files; Otherwise, the CSS file willbe generated individually. This option is enabled only when Multifile is selected.

2. Directory Tab

Exporting Report Result to Multiple File Formats

416

Page 429: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specify a location to place the exported HTML files. Click Browse, navigate to the destination folder, and then clickOpen. Otherwise, JReport will use the default directory.

3. ChartApplet tab

Exporting Report Result to Multiple File Formats

417

Page 430: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Dynamic charts may sometimes be used in your report, they can be still available in the exported HTML file. If Embedchart applet is checked, the dynamic 3D charts will be available in the output HTML file, remaining interactive. If Save inimage is checked, the charts will be converted to images, and also, you can specify the type of the images by choosingfrom the drop−down list (GIF or JPEG, and the default type is JPEG).

4. Note Tab

Exporting Report Result to Multiple File Formats

418

Page 431: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

This tab includes important information about HTML. We recommend you to read the contents on the Note tab beforeyou convert your report to HTML format.

After you complete all the steps above, click Finish to convert your report to HTML file.

Note:When you view the exported HTML file with charts in a web browser, to ensure that the chart can be displayed correctly,please make sure you have enabled the Additional Unsigned Permissions in the Web browser.

To do this in Internet Explorer,

On the Tools menu, click Internet Options.1. Switch to the Security tab, click Custom Level.2. Scroll down Settings, and then set Java Permissions to Custom.3.

Example: Exporting a report to HTML format.

The following case is a simple example to show you how to export your report to an HTML format file:

Open the report to be exported. Here we select %Install_Root%\demo\reports\SummaryData.cls.1. On the File menu, point to Export, and then click To HTML.2. On the Report tab, Make sure Multifile, Include Drilldown File and Dhtml are checked.3. On the Directory tab, specify the path of the files to be exported. 4. On the ChartApplet tab, check Save in gif format. 5. Click Finish to start generating the files.6.

Exporting Report Result to Multiple File Formats

419

Page 432: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You can now view the exported HTML file.

Open the exported file. Table of content (TOC) is displayed in the left pane, including the names of groups andsubgroups. Click a group you are interested in, the content contains data of that specific group will be shown inthe right pane.

1.

Place the cursor over a summary field, when the cursor becomes a hand, double−click to view the details of thesummary.

2.

Browse to the last page that contains a chart, because you have checked Include Drilldown File whenexporting the report, you can drill down on the summaries you are interested.

3.

Exporting Report Result to Multiple File Formats

420

Page 433: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click on any bar in the chart to get detailed information of the summary.

Note: The summary are to be inserted into your report in advance. It cannot be hidden or suppressed, otherwiseyou will not be able to get the drilldown files.

Related Topics

Exporting to JReport ResultExporting to TextExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to PDF

To export a report to PDF file, on the File menu, point to Export, and then click To PDF. The Export to PDF dialogappears.

Exporting Report Result to Multiple File Formats

421

Page 434: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Directory and File nameSpecify the location and the file name. Click Browse to specify the location. JReport will use the report name as thedefault PDF file name if there is no name specified.

No MarginIf checked, there will be no margins in PDF file.

TOCSpecifies whether to contain table of content (TOC) in the generated PDF file.

EncryptIf checked, the report result can be encrypted. Type password to the Enter Password text box and confirm it in theConfirm text box. If you just check the Encrypt check box, and do not specify a password, the report result won't beencrypted.

Drill DownIf checked, the file for drill down will also be created.

Compress ImageIf checked, the size of the images or pictures in the report will be compressed to the specified proportion of its originalsize.

Simulated Printing ModeWhen you export to PDF, JReport will take the result of the whole report as graphic to traverse the report by the methodof simulating printer and generate a PDF file.

Standard ModeThe result of using Standard Mode is the same as the one using Simulated Printing Mode. However, when you export toPDF using Standard Mode, JReport will take the result of the whole report as a data set to traverse the report bysequence and generate a PDF file.

Comparing with the Simulated Printing Mode, using Standard Mode can result in the following advantages:

1. Increased speed and reduced running time (by 20%), because all pages are written to the PDF file at once while inSimulated Printing Mode, JReport writes to the PDF file every time it finishes one page.

2. Decreased file size (by 20%), especially when a report is mainly composed of labels or fields.

Exporting Report Result to Multiple File Formats

422

Page 435: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

3. User Defined Objects (UDO) are changed to be pictures so that more kinds of shapes can be exported to PDF files.

4. Bookmarks can be produced in the PDF files so that users can find the pages they want easily.

5. In Simulated Printing Mode, JReport does not support the transparency property and the Cyclic Liner background.

Check the necessary boxes, Click OK. A file with the extension ".pdf" is generated. If you have a summary in the report,click on the summary in the PDF file, you can get the detailed information about that summary.

Notes:

When you export a chart to PDF, the old method (Simulated Printing) uses the Acrobat!—s built−in method todraw a shape, while the new method (Standard) takes a snapshot of the chart in JReport and repaints it inAcrobat. Therefore, the images generated using the new method may look dimmed and the file size may berelatively large (from 9k to 5,076k). However, you can check Compress Images to make the result file smaller(about 95K) when exporting charts to PDF file. A chart with a dimension of 4x5 (HxW) inch, if not compressed,takes about 1200k size in PDF file, otherwise takes only about 20k.

1.

JReport stores the finished pages in RAM before the pages are finally written to the PDF file. When the resultPDF file is too large, you could be running low on RAM, which often leads to OutOfMemoryError. You can solvethis problem by setting the maximum heap size (−Xmx100m) or just using the old method.

2.

If the color mode of your display adapter is less than 256 colors, when you export to PDF file using standardmethod, the chart can not be compressed. Because JReport catches the image with less than 256 colors as aGIF image, which cannot be compressed.

3.

Before exporting a report using true type fonts, you should select report name in Report Inspector, and then setEmbeddedfonts equal to all true type fonts that you have used in this report, otherwise the PDF files may notdisplay correctly.

4.

In order to get a better effect, Acrobat Reader 6.0 is recommended to be used.

Reference note : JReport Designer Manual | Reference | Report Panel

5.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML Index

Exporting to Fax

Introduction

Since JReport Designer version 7.0, you can export report result to fax. If you want this feature enabled, you need toconfigure your running environment first.

Download Java Communications API (Version 2.0) from the web sitehttp://java.sun.com/products/javacomm/index.html, and put the files in the specified locations:

For Windows•

Exporting Report Result to Multiple File Formats

423

Page 436: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

File Name Location

comm.jar %JReportHome%\lib

javax.comm.properties %JavaHome%\jre\lib

Win32Com.dll %JavaHome%\jre\bin

For Solaris•

File Name Location

comm.jar %JReportHome%/lib

javax.comm.properties %JavaHome%/jre/lib

libSolarisSerialParallel.so LD_LIBRARY_PATH

Exporting Report Result to Fax

To fax the report result to other people, on the File menu, point to Export, and then click To Fax.

Before you can fax the report result, you must have you modem configured; otherwise a warning message will displaywhen you try to export to fax.

To configure the modem,

on the File menu, click Options; or bring out Catalog Browser, on the toolbar, click the Options button.1. On the Report Option dialog, click the Internet tab, set up the options in the Export To Fax panel.2.

Exporting Report Result to Multiple File Formats

424

Page 437: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Once you finish the modem configuration, on the File menu, point to Export, and then click To Fax. The Export to Faxdialog appears.

Exporting Report Result to Multiple File Formats

425

Page 438: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

QualityJReport Designer provides you three levels of quality to choose: Best, Normal, and Fast.

Include Cover SheetSepcifies whether to send a cover in the fax.

The following items are the informations displayed on the fax cover sheet.

Fax NumberThe fax numer of the recipient.

Phone NumberThe phone number of the sender.

ToInformation of the recipient.

FromInformation of the sender.

CompanyInformation of the company.

DateThe day on which the fax is sent.

ReThe subject of the fax.

Exporting Report Result to Multiple File Formats

426

Page 439: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

CommentsThe comments of the fax.

UrgentSpecifies whether the fax is urgent or not.

For ReviewOnly to view the fax is OK.

Please CommentComments is needed for the fax.

Please ReplyA reply is needed for the fax.

Do the above options according to your own requirements, and then click OK on the Export to Fax dialog to dismiss thedialog and send the fax.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to PostScript File

To export the report to PostScript file, on the File menu, point to Export, and then click To Postscript File.

Directory and File nameSpecifies the directory and name of the exported Postscript file. If you do not type the name, JReport will use the reportname as the default Postscript file name.

No MarginIf checked, the margin you set while designing a report will be removed.

Specify the directory and type the file name, and then click Save. JReport will use the report name as the defaultPostScript file name if no name specified. A file with the extension ".ps" is generated.

Exporting Report Result to Multiple File Formats

427

Page 440: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to MailExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to Mail

If you want to send the result of a report to other people, you can send them a mail attached with the result of the report.

To send a mail, on the File menu, point to Export, and then click To Email.

Before you can send a mail, you must have the Report Mail System configured; otherwise, a warning message willdisplay when you try to export to mail.

On the File menu, click Options. On the Internet tab, setup SMTP Server Port, SMTP Server, Mail Box and Default MailFormat.

Reference Note: For details about the Internet tab, please refer to User's Guide | JReport window | Main Menu.

Exporting Report Result to Multiple File Formats

428

Page 441: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Once you finish the Internet configuration, on the File menu, point to Export, and then click To Email.

Exporting Report Result to Multiple File Formats

429

Page 442: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

FromType the e−mail address of the sender. The default mail address is the one you have specified on the Option dialog.

To, Cc, and Bcc Type the e−mail addresses of the recipients, separating the addresses with a comma or a semicolon ( ; ).

Use the CC box to send a copy of the mail.

Use the Bcc box to send a blind carbon copy of the mail.

SubjectType a message title.

CommentType your message in the Comment box. What you write in this text box will be shown in the text part of your mail.

FormatSelect a format to use in your mail.

HTML mail − Both the message and the report will be sent in HTML format. The report will be shown in HTML format inthe mail.Plain text mail − Both the message and the report will be sent in plain text format. The report will be sent as anattachment.HTML file as attachment − The report will be sent in HTML format as an attachment of the mail. PDF file as attachment − The report will be sent in PDF format as an attachment of the mail. JReport .rst file as attachment − The report will be sent in JReport Result file format ( *.rst) as an attachment of the mail.

Exporting Report Result to Multiple File Formats

430

Page 443: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Delimited text as attachment − The report will be sent in delimited text format as an attachment of the mail.

No MarginSpecifies whether to remove the margin you set while designing your report.

Java Archive CompressSpecifies whether to zip the mail sent out.

Once you complete, click OK. The report will be sent to the mail recipient. The recipient can open the mail as normal,using Outlook Express, or any other mail processing product.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to AppletExporting to RTFExporting to Excel FileExporting to XML

Exporting to Applet

JReport Designer can collaborate with a web server by exporting a report as an applet to a server. After having deployedit to the server, you can retrieve it by accessing the server. To export to applet, on the File menu, point to Export, andthen click To Applet.

Key in the the server name and port number, and then click OK. The To Applet dialog box appears.

Exporting Report Result to Multiple File Formats

431

Page 444: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specify the directory and file name. For example, browse to the location you want to save the file, type "exapplet.htm" asthe file name, and then click Save. Then, the file "exapplet.htm" and the report result "exapplet.rst" alike will be generated.

Exporting to applet is used when you want view the report result of JReport using an internet browser. Make sure thatyou have a web server to support applet. Specifically,

Export JReport result to Applet as mentioned above, for example, using A.htm as its name.1. Copy %JReportDesigner_installroot%\lib\viewer12.jar to the documentroot directory of the webserver.

2.

Copy the result file *.rst and *.html just generated to any directory of web server. For example, copy A.rstand A.html into %ServerRoot%\test.

3.

Edit the A.html (with a text editor) to make sure all the paths are valid. For example, change:a). codebase="/" ( which refers to the location of viewer12.jar)b). value = "/test/A.rst" (since we copied A.rst into %ServerRoot%\test. )c). width=800 height=600

4.

Run the browser against the web server to view the result. Before this, make sure you have enabled theAdditional Unsigned Permissions for the Web browser. To do this in Internet Explorer, for example, on theTools menu, click Internet Options, on the Security tab, click Custom Level, scroll down Settings to set JavaPermissions to Custom, click Java Custom Settings, on the Edit Permissions tab, enable Run UnsignedContent.

JReport Enterprise Server also supports to request the report result in an applet in a browser.

5.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to RTF

Exporting Report Result to Multiple File Formats

432

Page 445: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Exporting to Excel FileExporting to XML

Exporting to RTF File

To export the report to the RTF File, on the File menu, point to Export, and then click To RTF. The Export to RTF dialogappears.

Specify the directory and file name, and then click OK. JReport will use the report name as the default RTF file name ifnot specified.

No MarginSpecifies whether to remove the margin set during the report design.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to Excel FileExporting to XML

Exporting to Excel File

To export the report to an Excel File, on the File menu, point to Export, and then click To Excel File. The Export toXLS dialog appears.

Exporting Report Result to Multiple File Formats

433

Page 446: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specify the directory and file name, and then click OK. JReport will use the report name as the default XLS file name ifnot specified. A file with the extension ".xls" is generated.

WordwrapKeep Existing − Keep all the settings of each object's WordWrap property specified in the report.Disable All − Disable the WordWrap property for all objects, the Wordwrap property will be made false for all the objects.Enable All − Enable the WordWrap property for all objects, the Wordwrap property will be made true for all the objects.

Match LayoutSpecifies whether the exported Excel layout should match the original report layout. Normally when a report is exportedto Excel, some of the report elements could probably be severely re−positioned or misplaced. This depends on youractual report design. You can check this option to make sure the exported excel has the same layout as the original file.Please check out the notes using this option.

Has ShapesSpecifies whether to include shapes in the exported xls file.

Excel2000This box is unchecked by default (suggested).

Notes: JReport Designer supports the following features when exporting reports to Excel format,

Multiple colors in the report. Since Excel only can support 56 kinds of colors, so if the report has more than 56colors, some colors will be merged.

Multiple language of the report.• Large report. When exporting a large report to Excel format, users can customize the number of the rows in onesheet of Excel and the size of the buffer.

The report with chart. However, when exporting multiple pie charts to Excel, only the first pie chart will beexported.

When the Columned property is set to be true, the image that is inserted into the text object will not be displayedin the exported Excel document.

Notes for Match Layout

Stock chart and gauge chart don't support matching layout feature. • The arc shape is not supported.• Some shapes could distort when exporting to Excel. For example, a square might appear as a rectangle, and acircle might be changed to an ellipse. All shapes can be repositioned in Excel.

For a report that contains crosstab, it's NOT recommended that you place an object in the crosstab area, sincethis may increase the chance of losing record data. JReport benefits from using layers where the objects can beoverlapped without causing data loss problems in a JReport report. However, when in Excel, only one of theoverlapped objects will be showed correctly, others might be cut off.

Because of the differences between JReport functions and Excel formulas, some string functions that work wellin a CLS file may not work well in a Excel report. For example, the MAX function in JReport will return the longeststring when it's used for a string type field; however, this will lead to a meaningless value (0) when in Excel.

The HorizontalGap and VerticalGap properties for a crosstab should be set to a value as small as possible, suchas 0.01 inch, otherwise in Excel, some empty rows and columns will be used to represent these gaps.

If the total number of records that a summary accumulates exceeds 30, in the exported excel report, the formulawill not be retained, say, only the final result will be shown.

Set the Excel buffer size

You can store the report result in Excel buffer sheets when exporting to Excel format. To do this,

Select the Report node in Report Inspector.1. In the Properties sheet, set the ExcelBufferSize property.2.

Exporting Report Result to Multiple File Formats

434

Page 447: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The default size is 1, which indicates 1 sheet of the report result is allocated to the result buffer; other sheets willbe stored on disk. If you have enough memory, to get better performance, you can increase the Excel buffer sizeto store more sheets in memory of the Excel format report result.

Set the maximal number of rows for every worksheet

You can control the maximal number of rows in every worksheet in the exported Excel report. To do this,

Select the Report node in Report Inspector.1. In the Properties sheet, set the RowsPerSheet property.

The default value is −1, which means a maximal number of 65000 rows is allowed in a single worksheet. Thevalue range is 0 ~ 65000, values out of this range will be considered as 65000.

2.

Set the Excel column width

You can set the width of each column for the to−be−exported report in JReport Designer. To do this,

Select the Report node in Report Inspector.1. In the Properties sheet, set the ColumnWidthList property.

Type the width for the columns in turn, using semicolon (;) to separate each value. If you don't want to specify thewidth for a certain column, omit the value, JReport will use the default value, which is 8, for that column.

This property takes effect only when the Columned property is set to True.

For example, the value list 12;15;;20 makes the first column width 12, the second 15, the third 8, which is thedefault value, and the fourth 20.

2.

Note: The ColumnWidthList property for the subreport is disabled when exporting a report that contains a subreport toExcel.

Realign objects for better appearance in Excel

Normally, when a report is exported to an Excel file, the positions and sizes of the objects in the original report areautomatically rearranged by JReport Designer. However, you can arrange most of objects manually in JReport Designer,specially for exporting to Excel, so that they can be well−aligned in the exported excel file.

Before you can resize or reposition an object, you should set the Columned property to True. Select the report node inReport Inspector, scroll the Properties sheet to find the Columned property, and then set its value to be true. This makesthe object aligned according to the cells in Excel.

To relocate an object for exporting to Excel,

Select the object in Report Inspector.1. In the Properties sheet, set the ColumnIndex and RowIndex properties.

The ColumnIndex and RowIndex properties determine the object's location in the exported XLS file.

2.

PropertyDataType

Description

ColumnIndex IntegerSpecifies the X coordinate of the selectedobject in the exported XLS file, measured incells.

RowIndex Integer

Exporting Report Result to Multiple File Formats

435

Page 448: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specifies the Y coordinate of the selectedobject in the exported XLS file, measured incells.

To resize an object for exporting to Excel,

Select the object in Report Inspector.1. In the Properties sheet, set the ColumnNumber and RowNumber properties.

The ColumnNumber and RowNumber properties determine the objects size in the exported XLS file.

2.

PropertyDataType

Description

ColumnNumber IntegerSpecifies the width of the selected object inthe exported XLS file, measured in cells.

RowNumber IntegerSpecifies the height of the selected object inthe exported XLS file, measured in cells.

Only a few objects, such as images, charts, and user defined objects, have these two properties.

The alignment for the shape objects is different from that for normal objects. To realign a shape object for exporting toExcel,

Select the shape object in Report Inspector.1. In the Properties sheet, set the properties: TopAttachCol, TopAttachRow, BottomAttachCol,BottomAttachRow.

These four properties together determine the coordinates and size of the shape object.

2.

PropertyDataType

Description

TopAttachCol IntegerSpecifies the X coordinate of the upper−leftcorner of the shape in the exported XLS file,measured in cells.

TopAttachRow IntegerSpecifies the Y coordinate of the upper−leftcorner of the shape in the exported XLS file,measured in cells.

BottomAttachCol IntegerSpecifies the X coordinate of the lower−rightcorner of the shape in the exported XLS file,measured in cells.

BottomAttachRow IntegerSpecifies the Y coordinate of the lower−rightcorner of the shape in the exported XLS file,measured in cells.

Actually, the first pair of properties (TopAttachCol, TopAttachRow) locate a cell and use its upper−left corner as theupper−left corner of the shape, while the second pair (BottomAttachCol, BottomAttachRow) locate another cell and useits upper−left corner as the lower−right corner of the shape.

For example, if the properties for an oval is set as:

TopAttachCol: 1TopAttachRow: 2BottomAttachCol: 3BottomAttachRow: 4

Exporting Report Result to Multiple File Formats

436

Page 449: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then, the upper−left cell will be A2 and the lower−right cell will be C4. The exported shape will be like below:

Note: The value you set for the TopAttachCol (TopAttachRow) property should be always larger than that for theBottomAttachCol (BottomAttachRow) property.

Improving the performance when exporting Excel reports

Normally, when a report is being exported to the Excel file, the coordinates (column index and row index) of the reportobjects will be calculated by JReport engine, which may take a great deal of processing time. You can have these reportobjects arranged at design time so that the extra position calculating time can be saved. To do this,

Select the Report node in Report Inspector.1. In the Properties sheet, set the Columned property to true.

This property improves the performance when exporting the report to CSV format or Excel format if its value istrue, in this case, you can define the position of the object in the CSV format file or Excel format by setting thevalues of ColumnIndex and RowIndex.

2.

Example: Exporting a report to Excel file

Open the report to be exported. Here we select <install_root>\demo\reports\Bar_Line.cls. Thereport with a bar_line chart will be shown like this,

1.

On the File menu, point to Export, and then click To Excel File. Finish the Export to XLS dialog. Here, we2.

Exporting Report Result to Multiple File Formats

437

Page 450: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

specify the directory as C:\.Go to C:\ to open the Bar_Line.xls file, the result will be shown like this,3.

In addition, JReport Designer enables you to export only the objects that you need to the Excel file. To do this, beforeexporting, select all the unwanted objects and set their ExportToXLS property to false. After saving the changes, exportthe report to an Excel file. On the Export to XLS dialog, make sure Excel2000 is checked. You will get the result youwant.

Note:

If you select Excel2000 check box and set the ExportToXLS property of a page section (Report Header Section, PageHeader Section, Detail Section, and so on) to False, all the objects in this section will not be exported, regardless of theirExportToXLS properties.

Related Topics

Exporting to TextExporting to HTMLExporting to PDFExporting to Postscript FileExporting to MailExporting to AppletExporting to RTF

Exporting to XML

To export the report to the XML File, on the File menu, point to Export, and then click To XML. The Export toXML dialog appears:

Exporting Report Result to Multiple File Formats

438

Page 451: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Export toType the file name and directory where you want to place the exported XML file, or click on the Browse button to specifya new location.

Base xsdClick on the Browse button to specify the directory and the name of an existing XML schema (.xsd) file. If you specify anexisting XML schema file, the exported XML file will be generated basing on this XML schema file. Otherwise a new XMLschema file will be generated to the same directory as the exported XML file. The new XML schema file and the exportedXML file will have same name with different extension.

Only Data

If checked, the exported XML file will only contain the database column information andthe exported XML schema file will only contain the structure information of the report.

If unchecked, the exported XML file will also contain the elements that controlled by a formula and the exportedXML schema file will contain all the detailed information of the report, including all the property value of eachreport object.

Notes: When you export a report to XML file and specify an existing schema file, please pay attention to the followingtwo things:1. The existing schema file that you specify also must be generated from this report . If you use other schema files, aNullPointerException will be thrown out.2. If the existing schema file that you specify contains only data, but you clear the Only Data check box in the Export toXML window, the exported XML file will contain only database column information. The content of the exported XML filewill be consistent with the schema file it is based on.3. If you delete an element node or an attribute node from the existing schema file, the XML file, which exported basingon it, will not contain the corresponding column. (In the not only data schema file, only the removal of the element thatused in formula control property will affect the XML file exported based on it.)

Example1: Deleting an element node from a schema file affects the exported XML file based on it.

Lets take mcolor.cls as an example.a. Export mcolor.cls to XML file, you will get two files: mcolor.xml and mcolor.xsd.b. Open the mcolor.xsd file, delete "mcolor_PagePanel1_DetailPanel1_DBField3" from the"mcolor_PagePanel1_DetailPanel1".c. Export mcolor.cls to XML file again, specify the modified mcolor.xsd as the base on file.d. The new exported mcolor.xml file will not contain the information about "mcolor_PagePanel1_DetailPanel1_DBField3".

If you do not want to see all the property values in the generated XML file, you can comment out all those unwantedproperties in this way:

Open the file JRXMLTag.properties located in resource.zip under %installroot_Pro%\lib.1.

Exporting Report Result to Multiple File Formats

439

Page 452: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Add a question mark in front of those unwanted properties to comment them out. See below:

Change: Suppressed=SuppressedTo: ?Suppressed=Suppressed

When you export the report to XML, the exported XML file will not contain the property Suppressed for eachreport object.

2.

Save the property file and refresh the one in resource.zip.3.

In addition, when you uncheck Only Data, and add the sign @ in front of the value in JRXMLTag.properties, the propertylisted in the Element node will move to the Attribute node.

For example, in JRXMLTag.properties,

Change: StartYPos=StartYPosTo: StartYPos=@StartYPos

You will find the StartYPos property now listed in the Attribute node as below:

Before adding the sign @ in front of the value, the StartYPos property is listed in the Element node as below.

Related Topics

Exporting to JReport ResultExporting to TextExporting to HTMLExporting to PDFExporting to FaxExporting to Postscript FileExporting to MailExporting to AppletExporting to RTFExporting to Excel File

Exporting Report Result to Multiple File Formats

440

Page 453: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

User Defined Objects (UDO)

Introduction

A User defined object (UDO) is an object inherited from JReport system’s object. You can add and modify newproperties, as well as other existing methods and specify new methods for modifying your UDO. UDOs can be insertedinto JReport system as if they are a regular JReport object. Thus, UDOs have become part of the report created byJReport system.

The following objects and interfaces are necessary to create a UDO. Please refer to JReport Javadoc correspondingclass or interface. You can go to http://www.jinfonet.com/webpage/kbase/kbase.htm to browse the file online ordownload the javadoc.

Jet.report.JRObjectTemplateThis is the object provided by JReport system. It's also the object to derive a UDO.

The JRObjectTemplate contains several predefined properties of the standard JReport Object which is used tocompose a report: X, Y, Height and Width, etc.

You may add more properties (those properties are supported by JReport system) to your own UDO. Thoseproperties can be viewed and modified by Report Inspector at design time.

Note: Only JReport system properties or properties inherited from JReport system properties can be added, likeJetNumber, JetColor, JetString, JetEnumeration, etc. See the jet.controls package.

jet.datastream.JRVisiableResultThis is another object provided by JReport system. You also need to define an object inherited from this object,so that you can specify methods of saving and restoring the UDO object. JRVisiableResult provides methodsfor saving and restoring UDO.

jet.datastream.JRObjectResultIf the UDO you defined is not used for displaying (e.g., it will not appear inside the report result on the screen oron the paper), then it can be inherited from the JRObjectResult object.

jet.udo.JRObjectResultCreatorThis is an interface. It takes JReport system’s JReport Record as input parameters and produces the UDO’sJRObjectResult.

The definition of the JReport Record is in the jet.connect package.

jet.udo.JRObjectRenderThis is another interface. It provides a method which is used to paint the UDO to the report, the report then canbe shown on the screen or printed on a printer.

jet.udo.JRObjectEditorThis is an optional interface. If you specify it, JReport system will use it to handle the interactive event (keyevent, mouse event, paint etc.) at design time. If this interface is not implemented, JReport system will use thedefault one.

jet.udo.JRGroupListenerThis interface is used when you define a UDO whose value is calculated based on a group of data.

Creating a UDO

Creating a UDO Manually

Create a template fileInherit from the class JROblectTemplate to create a template file.

1.

Create a result fileInherit from the class JRVisiableResult or JRObjectResult to create a result file.

2.

441

Page 454: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create a result creator fileImplement JRObjectResultCreator to create a result creator file.

3.

Create a result render fileImplement interface JRObjectRender to create a result render file. If you want to display a UDO in the designpanel, implement interface JRObjectEditor. If your UDO is a group level object, implement interfaceJRGroupListener.

4.

Modify udo.ini file under %InstallRoot%lib directory.Add the following to the file:

Begin name=MyDbFieldtemplate=myudo.MyDbFldresultobject=myudo.MyDbFldRstresultcreator=myudo.MyDbFldCreatorresultviewer=myudo.MyDbFldRender End

5.

Compile the Java file, add the class to the class path of JReport and run JReport Designer.6.

Examples

Example One:

This example describes how to access Record for your UDO and how to register your UDO to the report system.

1. A UDO needs to implement at least four classes from JReport. The four classes are for template, result, creator andrender files respectively.

MyDbFld.java

//Templatepackage myudo;

import jet.report.*;import jet.controls.*;

/*** This class extends form JRObjectTemplate, add two properties "ColumnName" and"TextColor".*/public class MyDbFld extends JRObjectTemplate{ /** * This property is for the column name of MyDbFld. */ public JetColumnName columnName = new JetColumnName(this,"ColumnName");

/** * This property is for the background color of MyDbFld.. */public JetColor backColor = new JetColor(this, "TextColor", null, true);

public MyDbFld(){super(); columnName.setEditable(true);

//set the default size. set("Width",40); //before build575 should be width.set(40);

User Defined Objects (UDO)

442

Page 455: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

set("Height",20); //before build575 should be height.set(20);

//add the property to group then they can displayed in ReportInspector. addPropertyToGroup("ColumnName", "Others"); addPropertyToGroup("TextColor","Color");}

/** * Return the instance name prefix. */ public String getPrefix() { return "MyDbField"; }}

MyDbFldCreator.java

//Creatorpackage myudo;

import java.awt.*;import java.util.*;import jet.report.*;import jet.controls.*;import jet.connect.*;import jet.udo.*;import jet.datastream.*;import guitools.Painter;import jet.util.*;

/*** Implements JRObjectResultCreator for creating JRObjectResult in JReport engine.*/public class MyDbFldCreator implements JRObjectResultCreator{ public MyDbFldCreator() { }

public JRObjectResult createJRObjectResult(JRObjectTemplate rptobj, Record record) { MyDbFld rpt = (MyDbFld)rptobj; MyDbFldRst dsField = new MyDbFldRst(); dsField.setTemplate(rpt);

return dsField; }}

MyDbFldRender.java

//Render

User Defined Objects (UDO)

443

Page 456: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

package myudo;

import java.awt.*;import java.awt.event.*;import java.util.*;

import jet.datastream.*;import jet.connect.DbValue;import jet.connect.Record;import jet.udo.*;

public class MyDbFldRender extends Component implements JRObjectRender{ String text = null; Color color; Color background;

/** * The default constructor. */ public MyDbFldRender() { }

//retrieve property and data from JRObjectResult. public void setProperty(jet.util.PropertySetable dsPropSet) { text = ((MyDbFldRst)dsPropSet).getText(); color = (Color)dsPropSet.getPropertyByName("TextColor").getObject(); background = (Color)dsPropSet.getPropertyByName("Background").getObject(); setBounds(((MyDbFldRst)dsPropSet).getBounds()); }

/** * Paint the text. */ public void paint(Graphics g) { Dimension dim = getSize(); if(background != null) { g.setColor(background); g.fillRect(0,0,dim.width,dim.height); }

if (text != null) { if(color == null) color = Color.black;

g.setColor(color);

g.drawString(text,10,10); }

User Defined Objects (UDO)

444

Page 457: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

}}

Note: Since the compiling process of JReport Designer differentiates with that of JReport Enterprise Server, when yourun UDOs in these two applications, you should pay attention to some minor differences. For example, to get width andheight, in JReport Designer, you should use

w =guitools.toolkit.Unit.convertUnitToPixel(((Integer)propertySetable.getPropertyByName("Width").getObject()).intValue());h =guitools.toolkit.Unit.convertUnitToPixel(((Integer)propertySetable.getPropertyByName("Height").getObject()).intValue());

While in JReport Enterprise Server, you should use the following instead:

JRObjectResult obj = (JRObjectResult)propertySetable;w = guitools.toolkit.Unit.convertUnitToPixel(obj.getTemplate().getWidth(obj));h = guitools.toolkit.Unit.convertUnitToPixel(obj.getTemplate().getHeight(obj));

MyDbFldRst.java

//Resultpackage myudo;

import jet.connect.Record;import jet.connect.DbValue;

import jet.util.*;import jet.datastream.*;

public class MyDbFldRst extends JRVisiableResult{ public MyDbFldRst() { }

// retrieve value from column. DbValue getValue() { //get the column name. String colName = (String)getPropertyByName("ColumnName").getObject();

//get the report record. Record record = getRecord();

//return the column value. return record.getCell(colName); }

//make the text will be displayed. String getText() { String sRet;

DbValue value = getValue();

if ( value != null && !value.isNull() )

User Defined Objects (UDO)

445

Page 458: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

{ sRet = value.toString(); } else { sRet = "NULL"; }

return sRet; }}

2. Compiling.To compile these four Java files, you should add the report.zip and JREngine.zip with their path into the classpath. Forexample, use the following command. Javac −classpath "d:\JReport\lib\JRengine.zip;d:\JReport\lib\report.zip;d:\test" MyDbFld.javaHere we assume that JReport is installed under d:\JReport, java files for the example is in d:\test\myudo.

3. Modify udo.ini file under %InstallRoot%lib directory to append the four classes as follows:

Beginname=MyDbFieldtemplate=myudo.MyDbFldresultobject=myudo.MyDbFldRstresultcreator=myudo.MyDbFldCreatorresultviewer=myudo.MyDbFldRenderEnd

4. Edit %installroot%\bin\JReport.bat to append these four classes to the classpath:

Change: ... −classpath "d:\JReport\lib\report.zip; ...d:\temp" ...To : ... −classpath "d:\JReport\lib\report.zip;d:\test; ... d:\temp" ...

5. Start JReport. Selecting File | Insert, you will find a new UDO object named MyDbFld in the drop down list in thepopped up window.

Example Two:

This example describes how to make a group based on UDO. This sample is similar as a summary field. Thisexample includes the implementation of four classes and shares a class with example one.

Create the template, result, creator and rendor files as below:

MySumFld.java

//Templatepackage myudo;

import jet.report.*;import jet.controls.*;

/*** This class extends form JRObjectTemplate, add two properties "ColumnName" and"TextColor".*/

User Defined Objects (UDO)

446

Page 459: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

public class MySumFld extends MyDbFld{public MySumFld(){super();}

/** * Return the instance name prefix. */ public String getPrefix() { return "MySumField"; }

public boolean isGroupListener() { return true; }}

MySumFldRst.java

//Resultpackage myudo;

import jet.connect.Record;import jet.connect.DbValue;

import jet.util.*;import jet.datastream.*;import java.io.*;

public class MySumFldRst extends MyDbFldRst{ double value = 0; public MySumFldRst() { }

//make the text will be displayed. String getText() { return ""+value; }

/** * Read the data from DataInput. UDO can override this method to restore its own data. */ protected void readProperties(DataInput in, DSDataStreamable ds) throws IOException { super.readProperties(in, ds); value = in.readDouble(); }

User Defined Objects (UDO)

447

Page 460: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

/** * Write the data to DataInput. UDO can override this method to save its own data. */ protected void writeProperties(DataOutput out) throws IOException { super.writeProperties(out); out.writeDouble(value); }}

MySumFldCreator.java

//Creatorpackage myudo;

import java.awt.*;import java.util.*;import jet.report.*;import jet.controls.*;import jet.connect.*;import jet.udo.*;import jet.datastream.*;import guitools.Painter;import jet.util.*;

/*** Implements JRObjectResultCreator for creating JRObjectResult in JReport engine.*/public class MySumFldCreator implements JRObjectResultCreator, JRGroupListener// this interface must implement by JRObjectCreator{ MySumFld rpt; //MySumFldRst dsField; double value; public MySumFldCreator() { }

public void setTemplate(JRObjectTemplate rptobj) { rpt = (MySumFld)rptobj; }

public JRObjectResult createJRObjectResult(JRObjectTemplate rptobj, Record record) { rpt = (MySumFld)rptobj; MySumFldRst dsField = new MySumFldRst(); dsField.setTemplate(rpt); dsField.value = value;

return dsField; }

/**

User Defined Objects (UDO)

448

Page 461: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

* This method will be called before the first record. */ public void prepareFetchRecords() { value = 0; }

/** * This method will be called after the last record. */ public void finishFetchRecords() { }

/** * This method will be called each record. */ public void fetchNewRecord(Record record) { String colName = (String)rpt.getPropertyByName("ColumnName").getObject();

//return the column value. DbNumber num = (DbNumber)record.getCell(colName); if(!num.isNull()) { value += num.intValue(); } }}

MyDbFldRender.java

//RenderShare the class with example one.

2. Compile these four Java files in the same way as example one.

3. Modify %installroot%\lib\udo.ini to append these four classes as below.

Beginname=MySumFldtemplate=myudo.myudo/MySumFldresultobject=myudo.myudo/MySumFldRstresultcreator=myudo.MySumFldCreatorresultviewer=myudo.MyDbFldRenderEnd

4. Edit %installroot%\bin\Jreport.bat to append these four classes to the classpath, assume the four classes are locatedin d:\test\myudo,

Change: ... −classpath "d:\JReport\lib\report.zip; ...d:\temp" ...To : ... −classpath "d:\JReport\lib\report.zip;d:\test; ... d:\temp" ...

5. Start JReport. Selecting File | Insert UDO, you will find a new UDO object named MySumFld in the drop down list inthe popped up window.

User Defined Objects (UDO)

449

Page 462: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Creating UDO with UDO Maker

UDO Maker is another way of generating UDOs for you, but it is only used for importing a bean into JReport System. UDO Maker is actually an automatic code generator. You may modify its framework, compile it and add the UDO to thecatalog for later design use.

Starting UDO Maker

When you install JReport Designer, you have also installed JReport UDO Maker. Under the %installroot%\bin, there is abatch file named UDOMaker.bat. UDO Maker can be started by running this batch file. From the desktop, double clickMy Computer, then go to %installroot%\bin\UDOMaker.bat, run UDOMaker.bat

Or, from an MS−DOS command prompt, issue the following commands (assume that JReport is installed underC:\jreport):

c:\> cd\jreport\binc:\jreport\bin\>UDOMaker

Creating a UDO with UDO Maker

Here is a list of the brief steps you should follow to generate UDO code with UDO maker. We will have a case study in alater chapter with the step by step instructions.

Start UDO Maker. 1. Open Jar, select one bean and double click it to get the properties editor. 2. In the properties editor, type the UDO name in the UDO Name box. 3. Group the UDO properties 4. Click Add to add a new property group and modify the type of the properties. 5. Click File | Option, modify the option. 6. Save the UDO. Modify the automatically generated code under %JReportProfessional_installroot%\bin ifnecessary.

7.

Compile the Java file and run JReport Designer to insert the UDO into the catalog.8.

UDO Maker

After starting UDO Maker, the following window will appear.

File Menu

Open JarOpen the jar file that contains java beans.

Open File Open the saved property file. UDO maker will save the UDO as two kinds of files, one is a properties file

User Defined Objects (UDO)

450

Page 463: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

(abc.properties), the other is a java source file. Save Save the bean to UDO.

Option Change the UDO generation options.

Use bean size (autofit): Some beans have their preferred sizes (like javax.JLabel). If this option is checked, thepreferred size of the bean will be used while paging JReport.

Html: Default JReport will generate a GIF file for the UDO while creating an html report. If you do not like thissolution, select Html. You can write your own codes in XXXRndr.java after saving.

Text: The same as html.

Group: If the bean needs a group of data record, add codes in XXXCrtr.java.

Chart: If the bean needs chart data set, add codes for converting JReport chart data set to the bean data set.

Container: If the bean can contain other UDO or JReport objects, select this.

2. View Menu

Click View, the following window is displayed.

User Defined Objects (UDO)

451

Page 464: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

After opening a jar, a beans tool pallet will pop up. Selecting View | Show Beans Frame can also bring it up.

3. Properties editor

Double click an item in beans frame, the bean’s properties editor will appear.

User Defined Objects (UDO)

452

Page 465: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

All default properties are in others group. Click add, you can add a new group, choose properties from OthersProperties to add them to Current Group Properties. Also, you can delete and modify groups.

4. Properties sheet

User Defined Objects (UDO)

453

Page 466: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Bean Propname: Names of properties.

JReport Property: Default type of JReport property.

Is NoUse: Default one is false. If it is checked, the UDO will not contain the property.

Case: Chart API

JReport Enterprise Chart API is the basic interface of ChartDataset provided by JReport Engine. Any user defined chartobject can get data freely, and JReport internal chart uses this also.

To guide you to learn how to use this API, we make the following demo report. In our demo, we use JClass chart as ourchart object. For detail information of JClass, please visit http://www.klgroup.com/jclass. To view our demo report, youneed first to download JClass Chart 4.0.1 from their web site http://www.klgroup.com/store. Then follow the steps tofinish the demo report.

Generating Frame Code with UDO maker

1. Import the table stock market.xls into our demo.mdb which will be used as the data of the chart.

2. Use UDO Maker to generate the udo.ini file. Before running UDO maker, you need to modify the batch fileudomaker.bat located at %installroot%\bin first. Add the two jar files jcchart400K.jar and jcchart400Kds.jar under the

User Defined Objects (UDO)

454

Page 467: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

%installroot_JClass%\lib into the classpath of udomaker.bat. Then run this batch file for the UDO Maker window:

3. Click File | Open Jar, select jcchart400k.jar located at %installroot_root%\lib. Then the beans window appears asbelow:

4. In this window, list all the available beans you can import into JReport. Selectcom.klg.jclass.chart.beans.SimpleChart, double click on the name, the bean properties editor will appear:

User Defined Objects (UDO)

455

Page 468: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

5. Input jet.udodemo.JCandle into the text box of UDO Name.

6. Click File | Options... to open the options dialog as shown below, check the box Chart:

User Defined Objects (UDO)

456

Page 469: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

7. Click OK to close this dialog. Then click File | Save to save the bean to UDO.

8. Then find that under %installroot%_JReportProfessional%\lib, an udo.ini file is generated after you save the beans. In the udo.ini file, you will see

Beginname=JCandletemplate=jet.udodemo.JCandleTmplresultobject=jet.udodemo.JCandleRsltresultcreator=jet.udodemo.JCandleCrtrresultviewer=jet.udodemo.JCandleRndrobjecteditor=jet.udodemo.JCandleDsgnEnd

9. At the same time, find under %installroot%_JReportProfessional%\bin the following files generated:JCandle.udoJCandleCrtr.javaJCandleDsgn.javaJCandleRndr.javaJCandleRslt.javaJCandleTmpl.java

10. These files are just the frame work of the code, you may call the methods provided in the API to further edit thecode. See the API definition in the later part of this section.

11. Compile these java files using javac. Then zip all the generated class files and save as a jar file namedudodemo.jar.

12. Save this udo.ini file and then modify the JReport.bat which is used to start JReport Designer. Add the two jarfiles jcchart400K.jar and jcchart400Kds.jar under the %installroot_JClass%\lib into the classpath of JReport.bat. Andalso you need to add the udodemo.jar into the classpath. By the way, we suppose you are using jdk1.2.x.

Inserting the UDO

13. Then start JReport Designer using modified JReport.bat.

User Defined Objects (UDO)

457

Page 470: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

14. Add the table Stock Market into the Catalog Browser.

15. Create a report using the table Stock Market.

16. In the design mode, click Insert on the menu bar, then click UDO to open the Insert UDO dialog. Then click on thedrop−down arrow, select JCandle in the drop−down list as shown below:

17. Click the OK button, then you will be able to insert a UDO graph into your report. At first, the graph may be a plotgraph rather than a candle graph, as you can see in the following screen:

18. Select the UDO chart, open Report Inspector, click the button beside the text box of the property ChartDataSet,then a ChartDataSet dialog will pop us to prompt you select the data for X−Axis and Y−Axis as below, in this demo, weselect ID for X−Axis and Stock Market_Date for Y−Axis:

User Defined Objects (UDO)

458

Page 471: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

19. Select relative database column for the property High, Low, Open, Close.

20. Specify the property ChartType to be Candle, then you will see the draft of the graph in design mode:

User Defined Objects (UDO)

459

Page 472: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

21. Click the view mode, notice that the graph becomes nearly a solid line as below. This is because the data of theStock Market is from one year's record. Too many data are displayed in one graph, and you cannot see the candlesclearly:

22. We specify two parameters Start Date and End Date to make the graph just display records of a certain period, forexample, one month. We then see a clear Candle graph in the view mode:

JReport Enterprise Chart API Definition

JReport Enterprise Chart API is the basic interface of ChartDataset provided by JReport Engine. Any user definingchart object can get data freely, and JReport internal chart uses this also.

package jet.udo.chart;public interface SingleChartDataset{ /** * Get the X−Axis values; */ public Object[] getX();

/** * Get the Z−Axis values; */ public Object[] getZ();

User Defined Objects (UDO)

460

Page 473: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

/** * Get the Z−Axis values for each point on it; */ //public Object[] getZ(int zindex);

/** * Get the Y−Axis values for each point on it; If the chart is not 3D chart, return all x points *values, theparameter is useless. */ public Object[] getY(int zindex);

/** * If the chart is a 3D chart, this function returns values of the colName for each point. */ public Object[] getValues(int zindex, String colName);

/** * If the chart is not a 3D chart, this function returns values of the colName for all points. */ public Object[] getValues(String colName);

/** * Test if the chart is 3D; */ public boolean is3D();

}

The known implementation class:

package jet.report; public class ChartDefine implements java.io.Serializable { public String x; public String y; public String z; public boolean xGroup = true; public boolean zGroup = true; public boolean b3D = false; public transient Object owner = null;//JetChartProperty

/** * Constuctions * @Param x trhe column name of the X−Axis * @Param y trhe column name of the Y−Axis * @Param z trhe column name of the Z−Axis * @Param xGroup if the X−Axis is a group value. * @Param zGroup if the Z−Axis is a group value. * @Param b3D if the chart is a 3D chart. * @Param owner Used in design mode, system automatic assign. */ public ChartDefine(String x,String y,String z,boolean xGroup,boolean zGroup,boolean b3D,Object owner) }

package jet.datastream; public class DSChartDataset extends jet.report.ChartDefine implements SingleChartDataset; { public DSChartDataset(String x,String y,String z,boolean xGroup,boolean zGroup,boolean b3D,Object owner); public DSChartDataset(jet.report.ChartDefine d); }

package jet.report; /** * This class is the chart dataset property. */ public class JetChartProperty;

Tools:

/** * This class is getting chart dataset from a result object. */ public class ChartDataTool { public static final DSChartDataset getChartDataset(JRObjectResult ds, String propName); }

User Defined Objects (UDO)

461

Page 474: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

An Example:

According to the above Api definition, now we develop a program to generate the following chart:

First, let's explain the chart:

This chart is a 2D chart. Corresponding to each date on X−Axis, there are four values: High, Low, Open and Close.

You can write a program to fetch data to generate the chart:

{SingleChartDataset data = …;….

Object[] xaxis = data .getX();Object[] open = data .getValues("Open");Object[] close = data .getValues("Close");Object[] high = data .getValues("High");Object[] low = data .getValues("Low");}

In JReport Designer, you can see the properties of their charts from Report Inspector:

Property designer:

User Defined Objects (UDO)

462

Page 475: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

2D chart usage

2D detail level chart: •

2D Group level chart:•

3D Group Level chart:

User Defined Objects (UDO)

463

Page 476: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Adding a UDO to a Report

Inserting a UDO

Before inserting an UDO into a report, please make sure that the file udo.ini is under <install_root>\lib.

Start JReport Designer. 1. Create a new report or open an existing report. 2. Click on the Insert menu, select UDO. 3. Select your UDO and insert it just like a regular JReport object.4.

Building Hyperlinks by Inserting Built−in UDOs

JReport includes a built−in UDO object − JHyperlink. In this example we will insert a JHyperlink into a report to see howto use it.

Sometimes you will build a number of reports and each of them contains different information on the same subject. Inthis case, you may need to build a summary report to organize these reports together. For example, Report A hasSummary Information of City Wise while Report B is an Account List of City Wise. When you click on the city in Report A,it should go to the page of that city in Report B. Using the hyperlink feature of JReport Designer, you can buildhyperlinks between reports. In addition, you can also insert any hyperlink to invoke which could be part of yourapplication unrelated to reporting. In any case, a browser will pop up to view the referenced pages.

Start JReport Designer and open the report in which you want to build a hyperlink. 1. Click on the Insert menu and select a UDO item. 2. The Insert UDO dialog will pop up as follows, select JHyperLink from the drop−down menu.3.

Click OK, you will be allowed to insert a hyperlink in the report. 4. Double click the object to pop up Report Inspector. Input URL as a JReport Enterprise Server addresshttp://localhost:8888/jrserver/hsqlDemo/Tutorial.cat/ParameterUsage.cls and make surejet.udos.IEExecuter is the ExecClassName, type Customer Orders Report in the displayValue property as the

5.

User Defined Objects (UDO)

464

Page 477: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

display name of the hyperlink. When you click the hyperlink, it will pop up browser session to connect withJReport Enterprise Server for the report; therefore, before clicking this hyperlink, you should have JReportEnterprise Server started.

Insert another hyperlink into this report. Double click the object to pop up Report Inspector. Input URL ashttp://www.jinfonet.com and make sure jet.udos.IEExecuter is the ExecClassName, type Web Site as thedisplay name of the hyperlink in the displayValue property.

Two hyperlinks are successfully built in the report.

6.

In the view mode of the report, click on the Customer Orders Report hyperlink you just made and it will link tothe page you pointed to in the URL. Make sure that you have launched JReport Enterprise Server and specifythe URL corresponds with your Server configuration.

7.

Click Submit to get the report result shown.8.

User Defined Objects (UDO)

465

Page 478: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Web Site hyperlink, you will see the http://www.jinfonet.com home page in a browser.9.

Example: Using JHyperlink to Link Reports as Master−Detail Reports

JHyperlink can be used to link reports as master and detail reports to show related information in a hierarchy, such asOrders and Line Items. You can use the JHyperlink object with JavaScript called in formulas to control the URL on−clickevent to show the information in the detail reports on JReport Enterprise Server. For how to use JHyperlink to link reportsas master−detail reports, JReport Designer provides an example for your better understanding.

All the needed materials for this example, including the reports and catalog and the JavaScript pages are compressed inthe file JHyperlink_Master−detail.zip under <install_root>\help\pro−material. ExtractJHyperlink_Master−detail.zip to <install_root>\help, and do the following steps:

Start JReport Designer and open the catalog for this example, Tutorial.cat.1. Select one of the existing reports and ensure the reports in this catalog can run. If there is a problem, open theCatalog Browser, highlight the connection node, and in the Properties sheet, modify the value of the URL toconnect to JReport demo database, it is jdbc:hsqldb:<install_root>\Demo\db\demo.

2.

Copy the three JavaScript pages master_detail_dhtml.jsp, master_detail_closeall.jsp, andremoveReport.jsp to <server_install_root>\public_html\dhtmljsp.

These three JavaScript pages mainly contain the functions that are used to show the specified contents in the detail reports,♦ the functions that show a header on the top of the page for you to drill up and down.♦

3.

User Defined Objects (UDO)

466

Page 479: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Linking the master report to the detail report

Formulas will be used to control the property values URL and displayValue of JHyperlink to make it link the master anddetail reports. Please see the following steps.

In JReport Designer, open the master report − mainreport.cls.1. On the Insert menu, select UDO, and from the dropdown list, choose JHyperlink. Drop the JHyperlink into thedetail section to replace the Employee Name database field.

2.

Highlight the JHyperlink, and in the Report Inspector, specify the value of URL and displayValue as follows:

URL: Select the formula linkToSalesYearly

linkToSalesYearly is defined like this:

String url ="jrs.report=/master_detail_sample/SalesPerformancebyYear.cls&jrs.catalog=/master_detail_sample/Tutorial.cat&jrs.path=/master_detail_sample/SalesPerformancebyYear.cls&jrs.param$pEmployeeID="+@"Employee_Employee ID";return"javascript:window.top.createSubReport('"+@EmployeeName+"','"+url+"')";

where, the url is used to access the detail report SalesPerformancebyYear.cls, and the records of thedetail report are filtered by the parameter pEmployeeID; creatSubReport() is a function defined inmaster_detail_dhtml.jsp to add a link on the top of the page.

3.

User Defined Objects (UDO)

467

Page 480: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

This URL value enables you to drill down to the detail report and also make a link for this detail report onthe top of the page for you to drill up and down.displayValue: Select the database field EmployeeName from the dropdown list to show the EmployeeName in the master report.

Open the detail report SalesPerformancebyYear.cls, in the ReportHeaderPanel, the value of the Total is aJHyperlink, whose property values URL and displayValue are both controlled by formulas.

URL: Controlled by the formula linkToQuarter, which is defined as follows:

String url ="jrs.report=/master_detail_sample/SalesYearPerformancebyQuarter.cls&jrs.catalog=/master_detail_sample/Tutorial.cat&jrs.path=/master_detail_sample/SalesYearPerformancebyQuarter.cls&jrs.param$pEmployeeID="+@"Employee_EmployeeID"+"&jrs.param$pYear="+@getYear;return "javascript:window.top.createSubReport('"+@getYear+"','"+url+"')";

where, the url is used to access the detail report SalesYearPerformancebyQuarter.cls, and the records ofthe detail report are filtered by the parameters pEmployeeID and pYear; creatSubReport() is a functiondefined in master_detail_dhtml.jsp to add a link on the top of the page.

displayValue: Controlled by the formula getSalesByYear, which is defined as follows:

"$"+ToText(@Sum_TotalSales0)

This formula returns the total sales amount for the year.

4.

Running the master−detail reports on JReport Enterprise Server

This example requires you to access the report by URL, and with the help of the functions provided in the JavaScriptpages, you can drill the reports up and down. Please see the following steps:

After copying master_detail_dhtml.jsp, master_detail_closeall.jsp, and removeReport.jsp to<server_install_root>\public_html\dhtmljsp, start JReport Enterprise Server.

1.

Create a resource node master_detail_sample under Public Reports on the server, and deploy the reportsand catalog to /master_detail_sample.

2.

Use the following URL to run the master report:

http://localhost:8888/dhtmljsp/master_detail_dhtml.jsp?jrs.report=/master_detail_sample/mainreport.cls&jrs.catalog=/master_detail_sample/Tutorial.cat&jrs.path=/master_detail_sample/mainreport.cls&jrs.linkname=New

In the above URL, jrs.linkname=New is used to create a link named New on the top of the page for themaster report.

3.

Click any name in the Employee Name column, the year's performance of the employee will be displayed.4.

User Defined Objects (UDO)

468

Page 481: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click the Total number, it will drill down to the next detail report, and click New on the top of the page, it will drillup to the master report.

Index

User Defined Objects (UDO)

469

Page 482: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

True Type Font

JReport Font System

Users might find that reports which are designed well in Designer are truncated in the JREntServer running in a differentplatform. The reason is that different platforms have different font systems, and by mapping the fonts to different platformby JDK, the report result is shown with the discrepancy. To solve this problem, Java provides a True Type Font (TTF)administrative system, so that fonts can be deployed together with the report into the runtime environment independentof platform fonts.

Note: Prior to JReport Version 7.0, JReport provides its own TTF administrative system. Since JDK 1.3, Java resolvesthe cross−platform problem with TTF, and we turn to JDK TTF since JReport Version 7.0. One thing to note is that JDKhas problem in printing reports with rs_song.ttf (some characters are screwed), we strongly recommend you to use otherChinese ttf fonts like SimSun.ttf, PMingLiu.ttf, LF_FangSong.ttf.

In addition, in case that the end users do not have the fonts used in the report, to make them to view the report well,JReport provides the pdf embedded fonts solution. In other words, the fonts are embedded in the pdf file and end usersdo not need to install the fonts to their local machines.

To sum up, when you start to design reports and these reports are going to be on the production to a different platform,you are strongly recommended to design reports with TTF fonts.

Designing Reports with TTF

Copy True Type Font files *.ttf to the %JReportHome%\Font subdirectory. You can get the ttf fonts from the yoursystem's Font directory or from the Internet.

1.

Running JReport Designer, on the Design mode, click on the drop−down arrow of the font, scroll down to thebottom part of the list, you will find the fonts with * before them, they are the True Type fonts you have deployed.

2.

Click the View tab to review the report result. Save the report until you are satisfied with the report design.3.

Deploying TTF to Production Environment

If you want to deploy Report files (.cls) that use True Type Font to other operating system, you need to bring the relevantFont files (other files under the Font path) simultaneously to %JREntServerHome%\font directory. Please make sure thatyou copy or ftp (in binary mode) the .ttf files to that directory.

Delivering the Result in Excel/RTF/HTML/Txt

For files of HTML/RTF/Excel formats, they will go to find the fonts from system font directory. Therefore, usually if youwant to deliver the report result in the above formats to the end users, choose the ttf fonts which are commonly used onWindows systems for your reports.

If you have to use some fonts which are not in clients' systems, please consider the embedded ttf font solution for goodprint result in PDF format

Delivering the Result in PDF

To view pdf with Chinese fonts, for example, you need to install the special language packages. Or, when you design thereports with some fonts which are not within the Acrobat's internal fonts, the fonts will be mapped differently. The abovetwo cases will make troubles to the end users to view or print the report in Acrobat Reader. However, different from thehtml/RTF, pdf allows to embed the font description within the file. Therefore, JReport provides the embedded ttf fontsolution for pdf result, and you will find it extremely helpful when

you select the ttf fonts to design the report and those fonts are not in the client's font systems;•

470

Page 483: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

you have used the ttf and Acrobat Reader has to be updated with the language extension package to view theresult. However, you do not want the end users to take trouble to do that.

To take advantage of pdf embed ttf font feature,

Select the ttf to design reports as specified previously. 1. Open the report, go to Report Inspector, under the top node, find a property called EmbededFonts. Thedrop−down list will show all the ttf fonts used by the report. You can select multiple ones by pressing the Ctrl orShift key.

2.

Save the report and catalog. Deploy them to the server side. Also make sure to deploy the ttf fonts to the%JREntServerHome%\font folder.

3.

Of course, by embedding ttf fonts, the file size is increased a little bit. But they are of reasonable size to transfer over thenetwork.

True Type Font

471

Page 484: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Report Template

Introduction

Report template is a report sample in which font, color and layout are defined. It has some placeholders for lines, labelsand database fields. By replacing the placeholders with actual ones, you can generate a lot of reports which are similar tothe template.

JReport provides you with some built−in templates, such as Standard, Table, Invoice, and Left Alignment. In addition,you can design your own templates.

How does a Template Work

Relationships among templates, template items and template groups

A template is a .tpl file, which defines the layout of the report. Each template corresponds to an item, because if you wantto use the template to control the layout of your report, you must put the template into a template group. The templategroups are displayed on the New tab of the Open Report dialog for you to create reports. One template group maycontain more than one template items. By default, the first template item will be used to control your report layout.

JReport Designer uses a file named template.xml, which is under %InstallRoot%\template, to define thetemplate information. Open it and you can find the relationship among the templates, template items, and templategroups in the file easily.

Each template item and template group can have an image as its icon. Group image should be 42 pixels in width and 44pixels in height, and will be displayed on the New tab of the Open Report dialog. Item image should be 200 pixels inwidth and 160 pixels in height, and will be displayed on the Style tab of the Report Wizard. All these images must beunder the directory %InstallRoot%/template.

Each template item has a name, which must be unique, and a long description. A template item points to a template file.More than one template item can point to the same template file. Template files must be under directory%InstallRoot%/template.

Each template group has a name, which must be unique, and a long description. The members of the template group arethe template items.

The file template.xml can be edited manually. When you save a template file and this template file does not exist inthis file, a dialog will popup to guide you to edit this file automatically.

In JReport Designer, you can create templates, template items, and template groups with GUI tools.

Controlling report layout by template items

Each .tpl file should be pointed to a template item and then put it into a template group. You can put any multipletemplate items together as one group, but to make a template group useable, please follow the below principles:

Report Wizard always uses the first template item in the template group. Of course, you can select anothertemplate item in the group on the Style tab before clicking on the Finish button. The generated report will bedetermined by both the first template item and the selected template item.

If a template has no group section, the generated report has no group section either. If a template has one groupsection, the generated report can have any number of group sections. If a template has multiple group sections,the generated report can have no group section or exactly that number of group sections.

Here is an example. The first template item has a line in the report header section and the selected template itemhas a line in report footer section. If styleTitles of these two lines are different, the generated report will have a

472

Page 485: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

line in both the report header section and report footer section. But if the two lines of the two templates have thesame styleTitle, then the generated report will have only one line in the report footer section. Report Wizardidentifies only styleTitles.

Note : styleTitle is a property of the objects in the template file. Please see it at the section of Objects in atemplate file.

Template items in a template group should have some close relationships. The styleTitle in the template itemsshould be the same. For example, all template items of invitation letter templates can be grouped together andthe styleTitle of Address in the templates should be the same.

If you want a report to be completely controlled by a template item, make the template item be the first in atemplate group or create a new group for this template item.

Saving a Report as a Template

In JReport Designer, when you finished designing your report, you can save the report as a template, so that you cancreate similar reports easily later. It is the most common way to generate a .tpl file. To do so,

Open the report you like.1. On the file menu, click Save Template, and the Save Template As dialog appears.2. Specify a name for the template.

By default, the report name will be used as the template name, and you can also type in a new name for thetemplate in the Template Name text box.

3.

Click Save to save the template. The Item Properties dialog pops up.

A .tpl file must be defined as an item, and then it can be used in creating report.

Specify a name for the item. By default, the template name will be used as the item name. You can also type in anew name in the text box.

Choose an image for the item, and give it a description if you like. The image specified here will be displayed onthe Style tab of Report Form Creation Wizard.

Click the ... button, the Select an Image dialog appears. All the images under %InstallRoot%\template are displayed on the dialog for you to choose.

If you want to use your own images, please copy them to the directory %Install Root%\template.

4.

Click OK to close the dialog and generate the template item, and then you should specify a template group forthe newly created item. It can be a new group or an existing template group.

5.

If you select Yes on the Warning message, the Template Group Properties dialog pops up for you to create anew group.

Specify a name for the new template group. By default, the item name will be used as the group name. You canalso type in a new name in the text box.

Choose an icon for the new template group, and give it a description if you like. The icon specified here will bedisplayed on the New tab of Open Report dialog.

Click the ... button, the Select an Image dialog appears. All the images under %InstallRoot%\template are displayed on the dialog for you to choose.

If you want to use your own images, please copy them to the directory %Install Root%\template.

If you do not specify an image, the default image will be used on the New tab of the Open Report dialog.

6.

Report Template

473

Page 486: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click OK to generate the template group.If you click No on the Warning message box, the Select Group dialog will pop up.

Select a template group in the list.

If you want to make the newly created item as the first one in the selected group, select the As the firstmember check box.

Click OK to add it to the template group.

7.

Open the template.xml file, you will find that the file have been modified. The newly created template, template item,and template group have been added to the file automatically.

Managing Templates

Now, you have lots of templates, template items, and template groups, so you should manage them, such as pointing atemplate to an item, or adding an existing item to a template group. To do this managing tasks, please go to theFile menu, click Manage Template, the Manage Template dialog appears. You can do the following works with the helpof the Manage Template dialog.

Adding or removing template groups

All the template groups are listed in the Groups panel.

To add a new group, click the plus button on the list, the Add Group dialog pops up for you to give a name for the newgroup. Click OK to generate the group. You can find the group in the list.

To remove a group, select a group in the list, and then click the cross button on the list.

Adjusting the order of the template groups

The order of the template groups in the list will be the order of template groups displayed on the New tab of the OpenReport dialog.

To adjust the order, select a group in the list, and then click the upward arrow button and the downward arrow button tomove the selected template up or down.

Modifying properties of the template groups

Adding or removing template items to the template group

You can add any existing template items to the selected template group. In addition, you can also create a new templateitem and then add it to the selected template group.

When you select a group in the Groups list, all the template items in the group will be displayed in the Items list. Theorder of the template items in the list will be the order they displayed on the Style tab of the Report Form CreationWizard. And JReport Designer always use the first item to control the report layout. You can use the Up andDown buttons to adjust the order of the template groups.

To add an existing template item to the selected template group,

Select a template group in the Groups list on the Manage Template dialog.1. In the Items panel, click the Add Item button, and the Add Items To Group dialog appears. All the availableitems are listed. Select the items you want and then click OK.

2.

In the Items list, the selected items are appended.3.

Report Template

474

Page 487: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

To add a newly created template item to the selected template group,

Click the Items button on the Manage Template dialog, and the Items Properties dialog appears. 1. All the existing items are listed on the left panel and their properties are shown on the right panel. You canmodify the properties if you like.

2.

Click the New button on the Items Properties dialog. Specify a name for the new item, and then click OK.3. In the Items list, select the item you have just created.4. Specify an image for the item. Click the button beside the Item Image text box, and select the image you want onthe Select an Image dialog.

5.

Give a description if you like.6. In the Template text box, specify a template file for the item. Click the button beside the text box, select thetemplate you want.

7.

Click OK on the Items Properties dialog and save the changes.8. Select a group. Click the Add Items button, you can find the item you have just created. Select it and click OK toadd it to the selected template group.

9.

Modifying a Template File

Usually, you are not allowed to modify the template file, because you may make the template work incorrectly. However,if you really need to modify the template, please refer to the following information to make your changes.

Objects in a template file

Report template contains objects, such as DB Fields, Labels and so on. Each object in the template is given a set ofproperties, and the object with the properties are called Style, which is used to define how to design these objects ingenerating a report from this template. The properties are listed below:

styleTitleThe name of the style. It must be unique.

canDupThis property specifies whether the style can be duplicated.

IncreaseOrientationThe orientation of the instances generated from the same style.

Vertical − Instances are arranged from top to bottom.Horizontal − Instances are arranged from left to right.

styleStatuesThis option specifies whether the style can be used in multiple instances, for more than one object in the report.

Fixed − The style can not be used in multiple instances.Increasable − The style can be used in multiple instances.

lineSwapNormally if instances generated from a style extend beyond the paper border, the width of these instances will beshortened to fit the paper. If the lineSwap is true, the instances will move to the next line.

descriptionA description of the style.

attachedObjThe object attached to. If its attached object exists, it exists. If its attached object does not exist, it cannot existeither.

AttachedBorderThe border of the object attached. The object and its attached border will keep the same distance as in thetemplate.

Top − Attach to the top border of the attached object.Bottom − Attach to the bottom border of the attached object.Left − Attach to the left border of the attached object.

Report Template

475

Page 488: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Right − Attach to the right border of the attached object. increaseIntervalThe spaces between the objects generated using the same style.

How do the object styles take effect in the report

Each style in a template file has a property called styleTitle to identify it. The value of the styleTitle is a unique string. Itdesignates the style in Report Wizard. The layout of the generated report is determined by the style. When you insert anobject, for example a database field, you must select which style to use. Please see the following examples:

Example One•

Assume that IncreaseOrientation of style DBField is Horizontal, Line1, Line2, Line3 and Line4 attach to DBField,styleStatus of DBField is Increasable, styleStatus of Line1, Line2 and Line4 is Fixed, Line3 is Increasable.

After inserting three fields, ID, Name and City, using style DBField, the result will be shown as below.

If IncreaseOrientation of style DBField is Vertical, StyleStatus of Line1, Line2 and Line3 is Fixed, Line4 isIncreasable, the result will be:

Example Two•

Assume that IncreaseOrientation of style DBField is Horizontal, Total is attached to DBField, StyleStatus of Totalis Fixed, DBField is Increasable.

Insert fields ID, Name and City, using style DBField, and insert field Summary, using total, the result will be:

If IncreaseInterval of style DBField is 0, the result will be:

Report Template

476

Page 489: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Example Three•

Assume that IncreaseOrientation of style DBField is Horizontal, Total is attached to DBField, styleStatus of Totalis Fixed, DBField is Increasable.

Insert fields ID, Name and City, using style DBField, and insert field Summary, using total. The result will be:

If Total does not attach to DBField, the result will be

If IncreaseOrientation of style DBField is Vertical, the result will be:

Modifying a Template File

To modify a template file,

On the File menu, click Open Template, the Open Template dialog appears.1. Select a template and click Open.2. In the template file, select the object you want to modify. Bring out the Report Inspector, the properties of thetemplate are listed in the style section. Modify the properties values.

3.

On the File menu, click Save Template to save the changes of the template.4.

Index

Report Template

477

Page 490: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Writing and Using Formulas

Introduction

A formula is a symbolic statement of the manipulations you want to perform on certain data. JReport provides a numberof built−in functions for you to build your formula. Also it provides user−defined formula (UDF) functions that allow you todesign your own formula functions according to your requirements. Generally, formulas can be used:

to calculate information you can not obtain directly from database data fields, • to compare data, • to join text with data, • to convert data from one form to another, • to enhance the formatting options with text strings, and • to do a number of other things to customize your reports.•

Operations on a Formula

Creating and Modifying a Formula

You can use the following three methods to create and modify a formula.

Reference Note: User Reference | Formula Syntax.

Editor ToolbarClick on the Insert Formula button on the Editor Toolbar. The Insert DBField dialog will appear with theFormulae tab. Select a formula and click Modify to edit or click New to create a formula.

MenuClick DBField on the Insert menu. The Insert DBField dialog will appear. Click on the Formulae tab. Select aformula and click on the Modify to edit or click New to create a formula.

In Resource Viewer

To create a new formula, select the Formulas node, right click and then click Add Formula on the pop−upmenu.

To edit an existing formula, select a formula under the Formulas node, right click and then click Edit Formula onthe pop−up menu.

After the above steps, the Formula Editor will appear, then you can edit the selected formula with it.

Reference Note: User's Guide | Editing a Report | DBFields, Formulas

Formula Examples

All the following examples can be found in tutorial.cat file.

Example 1•

Name: salesregion

Text:

if (isnull( @"Customers_Region" ) )@"Customers_Country" else if (@"Customers_Region" in ["IA", "IL", "IN" ,"ME", "MA", "MD", "MI", "MN",

478

Page 491: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

"MO", "ND", "NE", "NH", "NJ", "NY", "OH", "PA", "RI", "SD", "VT", "WI"])"North East, USA"else if ( @"Customers_Region" in ["AL", "AZ", "FL", "GA", "KY", "KS", "LA", "MS","NC", "OK", "SC", "TN", "TX", "VA", "VI", "WV"])"South East, USA"else if ( @"Customers_Region" in ["AK", "AR", "CA", "CO", "HI", "ID", "MT", "NM","NV", "OR", "UT", "WA", "WY", "KS" ])"West, USA"

Purpose:In your sales report, you want JReport to print out which region the customer belongs to according theabbreviated state names stored in Customers_Region field.

Explanation:If the customer does not live in the US, Customers_Region will be null in the database, we use isnull() function tomake the formula return the country name of this customer.

In the three else−if statements, JReport will retrieve the value of Customers_Region field, and compare it withthe values in brackets []. If it is found to be the same value, the formula will return the region name.

• Example 2

Name: date

Text:

Number m = Month ( @"Order Date" ) ; String str = ""; if ( m == 1) str = " January Sales"else if( m == 2) str = " February Sales"else if ( m == 3) str = " March Sales"else if( m == 4 ) str = " April Sales"else if( m == 5 ) str = " May Sales"else if ( m == 6) str = " June Sales"else if ( m == 7) str = " July Sales"else if( m == 8 ) str = " August Sales"else if ( m == 9) str = " September Sales"else if( m == 10 ) str = " October Sales"else if ( m == 11) str = " November Sales"else if ( m == 12 ) str = " December Sales"

Purpose:In your sales report, you want JReport to print out the month name of the orders, so that you can compare the

Writing and Using Formulas

479

Page 492: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

orders of each month in a year.

Explanation:Since the database field "order date" is a timestamp type of data, we first use the built−in function Month(DateTime) to extract the month portion of "order date". Then we use the else−if statement to decide the monthaccording to the return value of the function and assign a string value which contains relative month name to thepre−declared string variable str.

• Example 3

Name: sectioninvisible

Text:

boolean s;if (pagenumber==1){s=true}else s=false

Purpose:This formula is used to control the property Suppressed of a certain section such as Page Header so that thissection will be suppressed on the first page of a report.

Explanation:Because you just want to suppress the section on the first page, if you only set the property Suppressed of thissection to be true in Report Inspector, then this section will be suppressed on each page. In this formula, we firstdeclare a boolean type variable s. Then we use the following else−if statement to decide whether the page is thefirst page. If the statement is true, we assign true to "s", otherwise, assign false to "s". In this formula,pagenumber is a special field.

Using Formulas

Inserting a Formula into a Report

You can insert formulas as DBfields into your report. There are three ways to insert formulas.

Resource ViewerSelect a formula under the Formulas node, and drag it to the a proper position of the report.

Editor ToolbarClick on the Insert Formula button on the Editor toolbar. The Insert DBField dialog will appear with theFormulae tab. Select a formula and click Insert. Drag your mouse cursor into the Design area. A box should beattached to the cursor. Click the area where you would like to place this label, a formula is inserted in the report.

MenuClick DBField on the Insert menu. The Insert DBField dialog will appear. Click on the Formulae tab and selecta formula and click Insert. Drag your mouse cursor into the Design area. A box should be attached to the cursor.Click the area where you would like to place this label, a formula is inserted in the report.

Controlling the Property Values

You can use formulas to control the property values of fields, objects, grouppanel, pagepanel, reportpanel etc.

When you design a report, you may notice that if you click some properties in Report Inspector, there will be a button appearing on the right of the drop−down arrow , and when you click on this button, it will change to be another

button and also the section will become empty. Then when you click on the drop−down arrow, a drop−down menu will

Writing and Using Formulas

480

Page 493: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

be listed as follows:

If you select one item in the list, the property will be modified according to the return value of the formula. This is calledcondition format in JReport.

Here is an example.

Assume that you have created a formula named "mcolor".

In Formula Editor dialog, you can see the text of formula "mcolor " as below:

1.

Writing and Using Formulas

481

Page 494: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Open a report in which you want to control the properties with a formula. Click Report Inspector on theView menu to bring out Report Inspector, select DetailPanel, click on the button on the right of theBackground Color section, and click on the drop−down arrow, then select mcolor.

2.

Click the View tab to view the report, the screen will show as below3.

Writing and Using Formulas

482

Page 495: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Another thing you should pay attention to is that if the value of the property is Boolean, that is to say, the value is true orfalse, when you create a formula, the return value should also be true or false. Otherwise, the formula is useless for thecondition format.

Usually when you open the drop−down menu of this kind of property, there is no formula to be selected directly unlessyou have created a formula in Catalog Browser before building the report, so you can click on Create Formula on the topof the drop−down menu to activate Formula Editor in order to create a new formula.

User−defined Formula Functions (UDF)

When the built−in functions cannot satisfy your needs, you can design your own formula functions. JReport providesuser−defined formula (UDF) functions to implement it. You can first write codes to implement a function you need, thenimport it as a class when you build a formula.

When you develop a java file to implement the function, this class should belong to packagejet.formula.javaformula.

When you develop a java file to implement the function, only the following data type can be used to interact withJReport products (pass parameters and return parameters):

DbBigInt, DbDouble, fCurrency, DbBit (using for boolean type), DbChar(using for String), DbDate, DbTime,DbTimestamp, DbBinary, fText (using for Long VarChar), fImage (using for long VarBinary), fIntArray,fNumArray, fCurArray, fBoolArray, fStrArray, fDateArray, fTimeArray, fDateTimeArray, fBinaryArray, fTextArray,fImageArray, fIntRange, fNumRange, fCurRange, fBoolRange, fStrRange, fDateRange, fTimeRange,fDateTimeRange.

All the data types which start with 'f' belong to the package jet.formula.*. Other data types belong to the packagejet.connect.*. Refer to JReport Javadoc jet.formula and jet.connect packages, and you can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to browse the Javadoc online or download the javadoc.

Writing and Using Formulas

483

Page 496: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Below is an example for using user−defined formula functions.

Create a java file to implement a function. You are provided one demo program named Myfunctions.java, youcan get it at http://www.jinfonet.com/webpage/kbase/kbase.htm from the manual related materials.

1.

Compile this java file to generate the class file.

javac −classpath d:\JReport\lib\JREngine.zip;d:\JReport\lib\report.zip;MyFunctions.java

2.

Edit the batch file starting JReport. Assume the class file is located underc:\test\jet\formula\javaformula, you can append c:\test into the classpath set in this batch file.

3.

Start JReport Designer. 4. Create a new formula to load this class and call the methods in MyFunctions.java by the following statement:

import myfunc from "MyFunctions";

"myfunc" is the instance name that you give when you load the class. It is a global variable, you can use it in yourformulas in the current catalog.

myfunc.MethodName(parameters);

MethodName is the method name in MyFunctions.java. You can call methods in your java file as many times asyou want, but it is enough for you to load this class only one time. For example, using our demo, we define theformula to load the class and call the method to open a temp file:

global integer filehandle = myfunc.openfile("e:\\test\\data.txt", false);

Then call the method to write data into the temp file:

string contents ="";contents = @"Customer Name"+"\t"+ @Customers_Country+"\t"+ @Customers_Phone +"\t"+ PageNumber + "\n";myfunc.write(filehandle, contents);

The return value of the last statement will be the formula result.

And we have defined the formula to close the temp file:

PageNumber;myfunc.closefile(filehandle);

If you add the statement PageNumber to your formula, this formula will be calculated after page break. That is tosay, it can control the calculation point.

Finish writing the above statements, Formula Editor looks like this:

5.

Writing and Using Formulas

484

Page 497: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Now in Catalog Browser, you can find the formula you just created which you can use in the report as a normalone.

6.

Note: If you return DbChar as following:

return new DbChar(cWord + " : " + cWord2 + " : " + cWord3 + " : " + cWord4);

the value will not be returned properly, because JReport Engine deals with strings using 8859_1 encoding. So youshould change your UDF code like below:

try{String a =cWord + " : " + cWord2 + " : " + cWord3 + " : " + cWord4;return new DbChar(new String(a.getBytes(), "8859_1"));}catch (Exception y7){return new DbChar("error");}

then it will match JReport Engine's code and return a string with 8859_1 encoding.

It is recommended to return a string with 8859_1 encoding when you use different encoding, such as Chinese ortraditional Chinese.

Index

Writing and Using Formulas

485

Page 498: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Parameter and its Applications

Introduction

A parameter in JReport is a variable whose value is supplied at run time. The run−time parameter helps a lot when youwant to dynamically control your report result.

Operations on a Parameter

There are two methods to begin operations on a parameter:

Catalog Browser

To create a new parameter, select the Parameters node, right click and on the pop−up menu click AddParameter.

To edit a parameter, expand the Parameters node, select a parameter, right click and on the pop−up menu clickEdit Parameter.

Edit ToolbarClick the Insert Parameter button on the Edit toolbar to open Insert DBField dialog with the Parameter tabshown. Click Modify to edit an existing parameter, click New to create a new parameter or click Insert to insertan existing parameter into the report.

Creating or Modifying a Parameter

Let us have a look at the Create Parameter dialog or Modify Parameter dialog. Actually this two dialogs are the samething in different names.

486

Page 499: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Where,

Parameter Name: Create or edit the name of the parameter. • Prompting Text: Enter some prompting text to indicate the user to supply the value of the parameter. • Value Type: Specify the data type of the parameter. Select one from the drop−down list, such as Integer,Number, String, Currency, and so on.

Prompting Values: Enter values as examples to show the user how the value should be like and give the useran option to select an item from the drop−down list. There can be more than one prompting value. The one in thetext box will be used as the default value for the parameter unless the user replace it with another one. All theprompting values must be of the same type as specified in the Value Type.

Add Button − Type a new value in the Prompting Values text box, and then click the plus button above the textbox. The value will be added to the drop−down list as a prompting value.Remove Button − Select the value from the drop−down list, and then click the cross button above the text box.The value will be removed from the drop−down list.

Minimum Value: Enter the minimum value allowed for this parameter.• Maximum Value: Enter the maximum value allowed for this parameter.

Note: At run time the prompting value you supply must be between the minimum value and the maximum value,or an error message will pop up. You may leave the two fields empty.

User Defined Format: For certain types of parameters, the value format supplied by JReport may not satisfyyour requirement. Take Date type as an example, JReport supplies only the following parameter value formats:

M/d/yyMMM d, yyyyMMMM d, yyyyEEEE, MMMM d, yyyy

However, you prefer MMM−dd−yy to all of the above. In this case, you can define your own particular format inthis field. When you have defined the value format, all the values you supply at run time should base on it.Otherwise there will be an error message.

Note: The letters that stand for the user defined format should follow JDK standard. In addition, the user definedformat only limit the format of your input value, and it does not mean that your display value will be in the sameformat. To change display format, specify the format property of this parameter in Report Inspector.

Reference Notes: User Reference | JReport Objects | Parameter

Bind with Column: If checked, you can specify a column name to list all its values in the database in the EnterParameter Value dialog at runtime.

JReport Parameter and its Applications

487

Page 500: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

When you have set bound column for the report, click the SQL button to see the SQL statements.Distinct: When viewing the report which contains parameters, the Enter Parameter Values dialog will pop up. Ifthe Distinct option is checked, in the Enter Parameter Values dialog, identical values will appear only once andno duplicate values will be listed.

For example, you created a parameter and unchecked Distinct. When you insert the parameter into a report andview the report, the following dialog will pop up:

You can find duplicate values display more than once in the drop−down list, such as "CA". But if you checked theDistinct option when creating the parameter, duplicate values of the column display only once in the drop−downlist in the Enter Parameter Values dialog.

Required: A parameter can be required or optional.•

JReport Parameter and its Applications

488

Page 501: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If the Required box is checked, this parameter will be treated as a required parameter. A required parametermust be fulfilled, which means you must supply a value in the Enter Parameter Values dialog before the reportcan run.

If not checked, this parameter will be treated as an optional parameter. An optional parameter can be left blank,which means you can either type a value, or leave it as it is.

In Enter Parameters Value dialog, the prompting text of a required parameter will be marked with a * sign.

Note: If the parameter is optional and you do not expect it to take effect in your report, in the Enter ParameterValues dialog, clear the content of the field. Otherwise, the value you leave in the field will function in report.

Sorting Parameters

If there are several parameters used in the report, for example, PToday, enddate, startdate, Editor, PCoutry,Cus_Region, P, P1, when you run the report, the parameter tabs will display in a random sequence, for example, thewindow may be like below:

But sometimes you may want to have the parameters displayed in a certain order. JReport provides a sorting parameterfunction to enable you to edit the parameter sequence. To use this feature, follow the steps below:

Start JReport Designer and open the report with parameters. 1. Click SortParameter on the Edit menu to open the Sort Parameter dialog box, in this dialog, all the parametersyou used in the current query will be displayed as below:

2.

JReport Parameter and its Applications

489

Page 502: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click to select a parameter to highlight it, and then click MoveUp and MoveDown to adjust the sequence. Forexample, we make the parameter displayed in ascending order. You can also drag them up and down directly.

3.

Click on OK button to close the Sort Parameter dialog box. 4. Run the report again, you will find that the parameters displayed in the sequence you specified:5.

Parameter Application Cases

We can summarize Parameter's applications as below:

Directly insert the parameter in a report (a section or in text object) to display its value.• Call the parameter in a formula.• Dynamic group.• Dynamic sort.• Most important, filter data set.• Parameter binding• Group Parameters•

JReport Parameter and its Applications

490

Page 503: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Inserting a Parameter Directly into a Report

This is the most simple and common use of a parameter. The example parameter we created below allows the lastperson who edited the report to place his name on it.

On the Edit Toolbar, click the Insert Parameter button and click New.1. In the Parameter Name text box, type "Editor" as a name for the parameter.

In the Prompting Text box, enter the message that will display as screen prompt, in this case: "Please type thename of the last person who edited:"Note: you can only create a one line statement.

Finally, place an example in the Prompt Value box as default value so that you have a format to follow. We useJohn Smith in this case.

2.

Click OK.3. Select the new parameter and click the Insert button. Place this new field in your report. In this case we put itinside the PageHeader section to show it on every page.

4.

After that, click on the View tab to view your report. 5. The Enter Parameter Values dialog appears when you view the report.

Type Jenny in the text box. To use the default value, click Default.

6.

The report result is shown as below.

Part of the Design

Part of the View

7.

Referencing a Parameter in a Formula

Reference a parameter field in a formula using the syntax: @ParameterName

This example we will create a formula which will display the URL for a company. The URL will be based on the value forthe parameter Company.

On the Edit toolbar, click the Insert parameter button and click New. Complete the dialog as below, click OKwhen you finish.

1.

JReport Parameter and its Applications

491

Page 504: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Switch to the Formulae tab, click New to create a new formula and enter "URL" as the formula name.

In the Formula Text panel, type the below line:"http://www." + @Company + ".com"Where, @Company can be keyed manually, or selected from the Parameter tree in the Field panel and the @sign will be automatically inserted.

Click the Check button to make sure there are no errors found. Click OK.

2.

Click Insert to insert the formula into the report.3. Click View, and then click ok to use the default value Jinfonet when prompted to enter company name. Thereport result is shown as below.

Part of the Design

Part of the View

4.

JReport Parameter and its Applications

492

Page 505: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: This is just a simple case of referencing a parameter in a formula. In this example, we place the formula directly inthe report. You will find its great application when using the formula in the Condition Format to control the properties ofan object.

Dynamic Group

As we have learned we can make a multi−level group report by selecting a field as grouping criterion under theGroup/Sort tab in Report Wizard. However, because the grouping criteria are definite, if you want to group several timesaccording to different grouping criteria but based on the same table in the database, (for example, you want to makethree employee list reports with different grouping criteria, the first one is grouped by their first name, the second one isby the hire date and the third one is by their salary), then you have to repeat the steps of setting query, selecting fields asgrouping criteria, and so on, in Report Form Creation Wizard, which is lack of efficiency.

To save your time, we implemented a new feature called "dynamic grouping", which means selecting grouping criteriahas become a dynamic process. You don't need to repeat the same steps to make multiple reports with differentgrouping criteria. You can just predefine a parameter using string value type and add it to the group list. Then when yourun the report, the parameter dialog will prompts you to select a field to group by. All the acceptable group− by fields arelisted in a drop−down list. You can select any of them as grouping criterion.

Let us take a simple report as an example:

Create a parameter of String type. Type "GroupBy" as the parameter name and leave other fields empty.1. We first build a report "groupsort.cls" based on Order table. On the Group tab, select the parameter GroupBy.We also use the default alphabetical ascending order to arrange the groups.

2.

JReport Parameter and its Applications

493

Page 506: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specify details on other tabs and then finish the report. 3. View the report, you will be prompted to enter the parameter value. Different from the above examples, you willfind all the the DB−Fields used in the query for the report (not just the displayed fields) in the parameterdrop−down list. We select "Ship Via" as the group−by criterion.

4.

The result is obvious, first group is Express Delivery, then Federal Shippers, then Federal Shipping etc. You canselect other fields to group your records.

5.

JReport Parameter and its Applications

494

Page 507: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Dynamic Sort

The Sort tab allows you to organize the information within the group by sorting records. Like dynamic group, the sortcriteria can also be defined at run time.

Let us continue with the report "groupsort.cls", which we created in the Dynamic Group section.

Create another parameter "SortBy" of String type. Leave other fields empty.1. On the Edit Toolbar, click Insert group/sort; or on the Insert menu, click Group/sort. 2. Switch to the Sort tab, and select parameter SortBy in descending order.3.

JReport Parameter and its Applications

495

Page 508: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click OK.Click View, this time we select "Order Date" as sort−by criterion.4.

Now view the report result.5.

JReport Parameter and its Applications

496

Page 509: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

See each group Order Date field. Obviously, the records are arranged within each group in descending orderaccording to Order Date.

Using Parameter(s) to Filter Data Set

You can use parameter(s) in a where clause, so that filtering conditions for records vary according to your parametervalue(s) entered each time.

First, define the parameter in Catalog Browser. The type of a parameter should be set according to the column type andthe manner with which you use the parameter. Second, include the parameter in the criteria. For example, if the columnis a number, define a parameter to be number type also. In the Query Editor frame, define the conditionTableName.Column Name = @ParameterName. Please refer to the demo report file Invoice.cls.

If you set the parameter format to be @ParameterName, then JReport Engine will parse the parameter value. Forexample, if you input parameter value with the single quotation mark (like 'BJOHNSON'), the quotation mark will berecognized as parts of the parameter value. However, if you use the format like :ParameterName, for example, using thesymbol ':' instead of '@', JReport Engine will not parse the parameter value, it will replace the original one with theparameter value you input at run time directly. That is, if ':' is used and the parameter type is a string, the system willsimply substitute <ParameterName> with the parameter value string. In this case, you need to key in a parameter valuelike:'asdfsakdf','aksdfashdlf','asdfjkasdfalk'...if the data type is a number, the parameter value should be like:12,34,56,...

As usual, let us start off with an example.

JReport Parameter and its Applications

497

Page 510: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Create a parameter IDSet.1.

While you are creating a report, or when editing a report, go to the Condition tab.

Select Customer ID to be in the parameter values (:IDSet).

2.

View the report, use the default value. You can see the records whose Customer IDs are 1, 10 and 15 areretrieved.

3.

View the report again. This time, we enter parameter IDSet value as 3, 7, 9, 11, 15, 25. Only the records of thosecustomer IDs are displayed.

4.

Using Parameters to Filter Records (also fetch all records if no parameter value is entered)

This case is similar to the previous example, but this time we have a further requirement that if no parameter value is

JReport Parameter and its Applications

498

Page 511: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

entered, all the records will be fetched out. This simple condition will let us make formulas besides parameter.

Finish designing your report. 1. Create a parameter called PARAM1 with the string data type, you can leave its default value as empty. 2. Create a new formula FORMU1 as below:

string s = Trim(@PARAM1 ); integer len = Length(s);string cos = Trim(@"Contact First Name"); string coL = "," + cos; string co = coL + "," ; string coF = cos + "," ; integer lenF = Length(coF);integer lenL = Length(coL);

if (len <1)return trueelse if (s == cos)return trueelse if (InStr(co, s) >= 0)return trueelse if (Right(s,lenL) == coL)return trueelse if (Left(s,lenF) == coF)return trueelse return false

Where, PARAM1 is the parameter just created, and Contact First Name is the DBField you want to filter recordswith.

3.

Click the Open Data Set button on the toolbar, and let us add the condition. Add a line to express:FORMU1=true as in this screen shot:

4.

Click Finish to apply your changes. 5. Now view the report, you are prompted to enter parameter value:You can enter Joan, then the record whose Contact First Name is Joan is fetched out.You can enter Joan,Robert,Joseph, then the records whose Contact First Name is Joan, Robert and Josephare fetched out respectively. Please note Joan,Robert,Joseph is separated with a comma without any space.Or, you can enter nothing, then all the records are displayed.

6.

Supplementing Where Portion

When a report is saved, it is only a report file not the result. At run time when you call JReport Engine Bean, we have amethod setWherePortion(), which will replace the original where portion (except joins) in your query (only at run time).But what if you want to append it instead of replacing it?

This issue can be solved with a parameter.

JReport Parameter and its Applications

499

Page 512: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If there are NO conditions for your original report, then you can set where portion, so that there is no whereportion replacement problem. But if there are conditions in your original report, and you want to append thedynamic whereportion, you need to use the parameter in JReport to dynamically set the whereportion. Follow thesteps below:

1.

In JReport Designer, create a parameter of string type, say Param1. 2. Modify the conditions for the report. Click the Open Data Set button on the toolbar. Imagine that you have manyother conditions, and in the last line, click AND to add a new line. Then in the new row write :Param1 in the leftexpression. The colon is to append the parameter value (of string type) to the where portion instead of replacingit.

3.

Then click OK to apply your changes. 4. Save the report and catalog. 5. Now when you view the report with JReport Designer, or use the function setParamValues() with JReport EngineBean, you can write a where potion in standard SQL syntax for the parameter value, say,Param1="Orders.`Payment Received` =true."

6.

Supplement Where Portion (also for a sub−report)

In addition to the previous example, what if we need to append the dynamic whereportion to both my main report and thesubreport?

You can also apply the previously suggested parameter feature for your sub−report. Link the parameter in the sub−reportto the main report, so that you can set the parameter value in the main report.

Specifically,

JReport Parameter and its Applications

500

Page 513: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

you have added and :Param1 in your main report. At the same time, also create another parameter namedmain (string type) in the catalog.

1.

Repeat and:SubParam2 in your sub−report as you do for your main report. 2. While inserting a sub−report into the main report. You will find the tab Parameters in the sub−report. The left oneis SubParam2, and you should select the main parameter for the parameters in the main report.

3.

Click OK. Insert the sub−report. 4. Now when you view the report, you will be prompted with two parameters: Param1, and main. You can enter thewhereportions for Param1 and main. The value for main will be sent to the SubParam2.

5.

While you view the report with JReport Designer, or use the function setParamValues() with JReport EngineBean, you need to give the values in standard SQL syntax for the TWO parameters.

6.

Parameter Binding

JReport provides such a mechanism that link each field value of Display Column with the exact value of Bind Column.When you select the field value from Display Column, the field value of Bind Column is actually sent to the query andfilter the query result.

For example, you specify Customer ID to query data, but you would like to select Customer Name not Customer ID in thedialog box popped up at runtime. To do so, you can use the functionality "Parameter Binding"

Below is an example which illustrates how to use Parameter Binding.

Create a parameter named "bindcolumn" and specify Customer_ID as Bind Column, which will be used to querydata, choose Customer_Name in the drop−down list of Display Column to get a list of Customer_Name values inthe prompted dialog at runtime.

1.

JReport Parameter and its Applications

501

Page 514: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Use the parameter in the query. 2.

3. View your report, all the customer names from database will be listed in the popped up dialog:

JReport Parameter and its Applications

502

Page 515: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then you can select a value from the list to query data with the Customer ID instead of Customer name.

Note: When you check Bind with column with a different type with the defined parameter, for example, you defined astring type parameter "pstring", and bind it with a integer type, then the parameter "pstring" will be changed to a integertype, but its format will not be changed. So you need to change the parameter format to integer in Report Inspector.

Group Parameters

Multiple Parameters Control

Sometimes, multiple parameters are used in a report, when you run the report, you have to specify the values of theparameters one by one. However, you may just want to specify values of part of the parameters used in the report, anduse the default values of the left ones. In this case, you can use the Parameters type parameter to implement thisfunction.

The Parameters type parameter is used to divide the parameters into different groups. Insert the Parameters typeparameter into a report, and when you run the report, you can just specify the values of the parameters in the group thatyou selected, and the default values will be used for other parameters.

For the detailed usage, please see the example below:

In this example, in a report, which shows the customers' information, the following parameters are used: IDSet (used inthe filtering condition, and please refer to the section Using Parameter(s) to Filter Data Set above), Editor, PToday,and PCountry (these three parameters are in the Tutorial.cat of our demo reports). You just want to enter the values forthe parameters IDSet and PToday when running the report. Please do as follows:

Create a report as described in the section Using Parameter(s) to Filter Data Set above.1. Create a new parameter named GroupParam. Select the Parameters type from the Value Type drop−down list.2. In the Value panel, add the following parameters as the values of GroupParam: @IDSet, @PToday and@Editor, @Country. Please see the image below:

3.

JReport Parameter and its Applications

503

Page 516: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

As shown in the image above, the parameters are divided into two groups, "Editor, PCountry" and "IDSet,PToday". Please note that the parameters in each group are fixed, say, you can not change the parameters inthe group. Open the report, insert the parameters PToday, PCountry, Editor, and GroupParam into the report.

On the Edit menu, select the Sort Parameter item, and then on the Sort Parameter dialog, move the parameterGroupParam up to the first of the list.

4.

Run the report, the Enter Parameter Values dialog appears. From the drop−down list, select a value forGroupParam. Here we select "@IDSet, @PToday". And you can see that the parameter IDSet andPToday are displayed follow GroupParam. Now you can specify value for the parameter IDSet and PToday.

5.

Click IDSet, and input 1,2 as its value; click PToday, and input 2004−5−1 as its value.6. Click OK on the Enter Parameter Values dialog, you can see that only the records whose Customer ID is 1 and2 are displayed, and the retrun values of the parameters PToday, PCountry, and Editor are 05/01/04, USA (thedefault value), and John Smith (the default value).

7.

JReport Parameter and its Applications

504

Page 517: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Note: You'd better make the parameter GroupParam invisible before you view the report. Otherwise, the value"@IDSet,@PToday" of GroupParam will also be displayed.

Parameter Filter

You can use the value of one parameter to filter another one. For example, a report has three parameters:ParamCountry, ParamRegion, and ParamCity. When you run the report, the value of ParamCounty filters the value ofParamRegion, and the value of ParamRegion filters the value of ParamCity. To do this, please see the steps below:

Create a parameter named ParamCountry, check the Bind with Column check box, and then selectCustomers_Country as the value of Bind Column and Display Column.

Click the SQL button, the Import SQL dialog appears, and SELECT CUSTOMERS.Country FROMCUSTOMERS is displayed in the text box.

1.

Create a parameter named ParamRegion, check the Bind with Column check box, and then selectCustomers_Region as the value of Bind Column and Display Column.

Click the SQL button, and the Import SQL dialog appears. In the text box, type in the following statement:WHERE (Customers.Country=@ParamCountry).

Now the statements in the text box are: SELECT CUSTOMERS.Region FROM CUSTOMERS WHERE(Customers.Country=@ParamCountry).

2.

Create a parameter named ParamCity, check the Bind with Column check box, and then selectCustomers_City as the value of Bind Column and Display Column.

Click the SQL button, and the Import SQL dialog appears. In the text box, type in the following statements:WHERE (Customers.Country=@ParamCountry and Customers.Region=@ParamRegion).

Now the statements in the text box are: SELECT CUSTOMERS.City FROM CUSTOMERS WHERE(Customers.Country=@ParamCountry and Customers.region=@ParamRegion).

3.

Create a report, set a condition Customers.CITY = @ParamCity on the Conditions tab.4. View the report, the Enter Parameter Values appears.

On the ParamCountry tab, select a country, go to the ParamRegion tab, only the regions in the selected countrywill be displayed in the drop−down list, choose a region, and go to ParamCity, only the cities in the selectedregion are displayed.

Note: If the three parameters are not displayed in the sequence as ParamCountry, ParamRegion, andParamCity, please go to the Edit menu of JReport Designer, and select Sort Parameter to adjust theirsequences.

5.

Click OK on the Enter Parameter Values dialog, only the specified record will be shown. 6.

JReport Parameter and its Applications

505

Page 518: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Importing Parameter Values

Introduction

In previous versions of JReport Designer, when a report is invoked, a default JReport dialog box pops up showing theparameters the report used for you to input a value. The default value(s) shown are fixed during development time.However, showing a default, fixed value which is dated many months ago will make no sense to users.

Therefore, we provide an interface for importing different default values from an outside class file so that the defaultvalues can be specified flexibly.

There is only one method for this interfacepublic Hashtable promptValues(String paramsName[]);See also: JReport Javadoc jet.util.ImportParamValues interface. You can go tohttp://www.jinfonet.com/webpage/kbase/kbase.htm to browse the file online or download the javadoc.

Importing Parameter Values

1. Define a Java class file. See our demo code ParamTest.java and TestParamList which can be found athttp://www.jinfonet.com/webpage/kbase/kbase.htm with the manual related materials.

To import parameter values, implement the interface jet.util.ImportParamValues in your java file. The class definition is

package help.;import java.util.*;import jet.util.*;

public class ParamTest implements ImportParamValues{

public ParamTest() { ; }

public Hashtable promptValues(String paramsName[])

{ //Class body

}

}

The following explains the code:

The package name can be defined by yourself, in our sample code, we use "help" as the package name.• Since the interface ImportParamValues is in the package jet.util, you must import the class package jet.util.*.• A public constructor method without parameters is needed.•

2. Compile the Java file to generate the its class file.

3. Append the class path to the classpath variable of the batch file you used to start JReport Designer.

4. Start JReport Designer. Open the report whose parameter value will be imported. In Report Inspector, set the reportproperty ImportParamValues to be the class name you just generated with its package name, and set ParaListAuto to

JReport Parameter and its Applications

506

Page 519: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

be false.

Example One: Importing Parameter Values from a Database

This example shows how to import parameter value from a database, so you needn't type the values one by one whilespecifying the parameter default value. In our sample code ParamTest.java, we assign different values to the parameters"PToday" by access values from a MS Access database. In our demo reports, report Invoice.cls used the parameter inthe query condition. We just take this report as an example.

Compile ParamTest.java to generate ParamTest.class.1. Append the class path to the classpath variable in the JReport.bat under %Install_Root%\bin.2. Start JReport Designer with the batch file JReport.bat.3. Open Invoice.cls and activate Report Inspector, find the report property ImportParamValues, input the the classname with the full package name, in this example, you should input help.ParamTest, then set the propertyParaListAuto to be false.

4.

5. Save the report and catalog, then view the report, the parameter dialog will pop up, click on the drop−down list ofthe parameter, you will find that all the values you specified in the ParamTest.java have been imported into thelist:

JReport Parameter and its Applications

507

Page 520: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then you can select one of the values to view the report.6. In JReport Enterprise Server, after appending the path where the ParamTest class locates to the classpathvariable of the batch file you used to start JReport Enterprise Server, start JReport Enterprise Server.

7.

Deploy the saved report Invoice.cls to JReport Enterprise Server.

See also: User's Guide | Deploying Reports section.

8.

Load I.E. browser to access the Server page, you will get the same parameter values as you see in JReportDesigner.

9.

Example Two: Specifying Parameter Default Values

Another case to apply the feature of Importing Parameter Values is to specify your desired default values. For example, ifyou want to group/sort dynamically with a parameter, when you view the report, a dialog box is popped up, and you canfind a lot of default values in the drop−down list. Sometimes you don't need so many values to group/sort, and you won'tlike to select a value among a large quantity of values. To do this, you can specify the default values you desired in yourjava class, then import these values you defined in this class. Please refer to the sample code TestParamList.java.

Compile TestParamList.java and append the generated class path to the classpath variable in JReport.bat under%Install_Root%\bin.

1.

Start JReport Designer and create a report with dynamic group/sort using parameter "importpara".2. When you set the property ParaListAuto to be true in Report Inspector, many values will be listed in the poppedup dialog box.

3.

Set ParaListAuto = false, and set the property ImportParamValue to be "help.TestParamList", then view the4.

JReport Parameter and its Applications

508

Page 521: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

report, the following dialog will be popped up. You can see that only four values displayed as we defined inTestParamList.java.

Notes:

When you want to use a parameter as a grouping/sorting criteria (example 2), you need to make sure theparameter values are within the columns used in the report's query, in addition, the name should be consistentwith the column names defined in the catalog. For example, the query of the report joins two tables: Orders andOrders_Details. In Catalog Browser, expand the query used by the report, you will see all the column under thetwo tables. Make sure the values returned are within them and the consistent with the column names.

In the sample ParamTest.java, we used the method compareToIgnoreCase( ) to compare the parameter name inthe class file with the one in your report. This method is not case sensitive when doing the comparison.

You should ensure the parameter format in the class file is consistent with that in JReport. Specifically, theparameter format used in the class file should be parsed when viewing the report so that correct data records willreturn.

When you implement the interface jet.util.ImportParamValues and use the function promptValues( ) of theinterface, you should pay attention that the parameter of this function must be a string array which containsnames of the parameters.

When you implement the interface jet.util.ImportParamValues and use the function promptValues( ) of theinterface, you should pay attention that the return value of this method must be a Hashtable, whose keys areparameter names used in the report and values are vector objects which contain the parameter values.

When there are sub−reports in a main report, setting for ImportParamValue and ParaListAuto does not affectsub−reports, that is to say you have to set these properties in the main report and sub−reports separately.

JReport Parameter and its Applications

509

Page 522: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Exit Functions

Exit Functions

JReport includes three exit functions you can call: BeforeRun, AfterInitParameter and AfterRun. These functionsenable you to develop an action to be called before, during and after the process of report running. Your applications willreturn true or false. For true, JReport Engine will continue running. For false, JReport Engine will stop execution.

In Report Inspector, you can find the three properties: BeforeRun, AfterRun and AfterInitParameter.

BeforeRunCall a method that you develop just before running the report.

AfterInitParameterWhen running the report, after you enter parameters in the parameter dialog, this method you develop will becalled.

AfterRunAllows you to call your own method after running the report.

Reference Note : For the API information, please refer to JReport Javadoc jet.util package and jet.exception package.You can go to http://www.jinfonet.com/kbase.htm to browse the file online. In addition, go to User Reference | ReportingFeatures | Report Panel for more information.

510

Page 523: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Using Exit Functions

In this section, we provide you simple example for you to further understand the Exit Function. In this example, weprovide a simple application which will run at all the three times, BeforeRun, AfterInitParameter, and AfterRun.

Develop your java files to implement the methods. In this case, please copy the following code and save it to<install_root>\help.

import java.io.*;import java.awt.*;import java.net.*;import jet.util.*;

public class testa implements JURLExecuter{ public boolean exec(String[] params) { System.out.println("testa : "); for(int i = 0;i<params.length;i++) { System.out.print("\"" + params[i] + "\","); } System.out.println();

return true; }}

1.

Compile testa.java to generate the testa.class under <install_root>\help. 2. Add the path <install_root>\help to the classpath of the files used to start JReport Designer. Therecommended way is to edit the file setenv.bat (setenv.sh on Unix) located in the <install_root>\bindirectory.

set ADDCLASSPATH=C:\oracle\jdbc\lib\ojdbc14.jar;C:\JReport\Designer\help

3.

Start JReport Designer, open the Invoice.cls report in the Tutorial.cat catalog which uses the parameterPToday. In Report Inspector, specify the class and give parameters for the three functions. Please see thescreen shot below:

4.

Exit Functions

511

Page 524: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JURL:/ − The standard format, and followed by the class name.testa − The class name in this example.aa;bb;cc and 123;234;345 − The string type parameters of the class, which are divided by semicolons.PToday − A pre−defined JReport parameter used in the current report, which is introduced by the symbol @.

As shown above, two types of exit function parameters are supported, they are String type parameters, such as aa, C:\ and so on. In this case, the string will be passed directly to theexit function.

JReport per−defined parameters used in the current report, which are introduced by the @ symbol. Inthis case, the parameter value will be passed to the exit function.

Run the report, the report engine will call the class that you specified in Report Inspector. In the console windowof JReport Designer, you will see the returned values are:

testa :"aa","bb","cc", (the return value of BeforeRun)testa :"May 21, 1998", (the return value of AfterInitParameter)testa :"123","234","345", (the return value of AfterRun)

5.

Notes:

When a JReport parameter is used as the parameter of the BeforeRun function, no JReport parameter value willbe returned, and the returned value will be the JReport parameter name with the @ symbol.

For the JReport parameter that are used as exit function parameters, they must be used in the report. Otherwise,no value will be returned.

Running the Exit Function Report on JReport Enterprise Server

To run the reports which include the exit function on JReport Enterprise Server,

Deploy the report with its catalog to the JReport Enterprise Server.1. Add the path of the class file to the file which is used to start the server. If you are using the JReport standaloneserver, it is JREntServer.bat in <install_root>\bin. If you are using a Java Application Server, add theclasses to the WAR or EAR file and re−deploy the application.

2.

Exit Functions

512

Page 525: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Run the deployed report.3.

Exit Functions

513

Page 526: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

National Language Support

Introduction

Since Version 3.1, JReport products implemented the National Language Support (NLS) feature. By enabling NLS indesign mode, reports can run in different languages. When you design and save the report, the language−dependent textof Label objects will be abstracted to a resource file (.properties). You can duplicate the resource file for other languagesand modify the text in the file. When JReport is running, JReport Engine will retrieve the language−dependent textaccording to the current locale, then you will get a report result that matches your locale setting. Regardless of thesesettings, report data will always be displayed in the language corresponding to your database information.

Note: User interface of JReport Designer, including menus, icons, dialog boxes, and so on, can also be changed to anynational language. Java language supports a mechanism called "resource bundle" that separates language dependentstrings into isolated files. By working on those specific files, the translation work is greatly simplified, and can be doneby any customer or retailer into any language. However, you need to get permission from us since we have thecopyright of the material. We need to have you release the rights to us for any translated derivative work. JReportcurrently supports English and Chinese versions.

Using National Language Support

Create a report in a certain language. For example, create a report in English that may look like below:1.

Open Report Inspector, set the property nationalLanguageSupport to true.2.

514

Page 527: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

On the File menu, click Save NLS to save this report, you will find that a new property file with the nameReportName_LocaleID.properties is automatically generated under the directory where the report is saved.

For example, suppose that English (United States) is set as the default system locale, a file namedReportName_en_US.properties will be generated.

3.

Open this property file using any text editor, you will see all the label text has been extracted as below:

#JReport Reports Resources#Thu Nov 16 17:16:23 CST 2000LBL_TXT_Last_sName=Last\ NameLBL_TXT_Position=PositionLBL_TXT_First_sName=First\ NameLBL_TXT_Employee_sInformation=Employee\ Information

4.

If you want to display the report in German, you should make a copy of the properties file above in the samedirectory, rename the new file as ReportName_de_DE.properties, and then modify its content as below, note thatat the end of the property file, you should write the encoding you use.

#JReport Reports Resources#Thu Nov 16 17:16:23 CST 2000LBL_TXT_Last_sName=Letzter NameLBL_TXT_Position=in Position bringenLBL_TXT_First_sName=VornameLBL_TXT_Employee_sInformation=AngestelltInformationen

encoding=Cp1252

5.

National Language Support

515

Page 528: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Save the file. Start JReport Designer. JReport Engine automatically bundles the report with the property fileReportName_de_DE.properties and the report will be displayed in German if your current locale is set to German.

6.

Note: To view the report in the language you specified in JReport Designer, please make sure that default system localeis set to the corresponding language.

NLS for JREntServer

If National Language Support is enabled for your report in design mode, it will also be available after the report has beendeployed to JReport Enterprise Server. On JReport Enterprise Server, reports are running in the client/server scenario,where different clients select different languages for the corresponding rendering of the report.

To use NLS for JReport Enterprise Server, you should:

Create and design a report in JReport Designer as mentioned in preceding procedure. 1. Deploy the report and catalog to JReport Enterprise Server using Deployment Wizard in JReport Designer, andthe NLS properties files will be deployed to the server as well.

2.

Start JReport Enterprise Server, and then access the catalog and reports using the IE browser.

Click Advanced Run or Schedule of the deployed report, you will see that there is a new option called UsingLanguage. This option will list all the available languages of this report in the drop−down list, the number ofwhich depends on how many types of locale properties file you defined for this report. In this example, becausethere are only two languages defied, you will only see two languages list in the drop−down list, en and de.

3.

Select Language, Region, select ISO 8859−1 as the Encoding. Meanwhile, on the View menu of IE browser,select corresponding Encoding.

4.

National Language Support

516

Page 529: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

5. Click the Submit button, then you will see the report displayed in English:

6. Select de as the language and Windows Eastern European as the encoding, and then click the Submit button,the report will be displayed in German:

National Language Support

517

Page 530: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Notes:

• When you deploy NLS reports from a remote computer, please also compress the NLS properties files togetherwith the catalog and report, and then deploy the zip file to the sever.

• If resource from real path is used, please also copy the NLS properties files to the real path together with thecatalog and report.

Appendix I: Language

Two−letter lower−case symbols Language

aa Afar

ab Abkhazian

af Afrikaans

am Amharic

ar Arabic

as Assamese

ay Aymara

az Azerbaijani

ba Bashkir

be Byelorussian

bg Bulgarian

National Language Support

518

Page 531: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

bh Bihari

bi Bislama

bn Bengali; Bangla

bo Tibetan

br Breton

ca Catalan

co Corsican

cs Czech

cy Welsh

da Danish

de German

dz Bhutani

el Greek

en English

eo Esperanto

es Spanish

et Estonian

eu Basque

fa Persian

fi Finnish

fj Fiji

fo Faroese

fr French

fy Frisian

ga Irish

gd ScotsGaelic

gl Galician

gn Guarani

gu Gujarati

ha Hausa

he Hebrew (formerly iw)

hi Hindi

hr Croatian

hu Hungarian

hy Armenian

ia Interlingua

id Indonesian (formerly in)

ie Interlingue

National Language Support

519

Page 532: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ik Inupiak

is Icelandic

it Italian

iu Inuktitut

ja Japanese

jw Javanese

ka Georgian

kk Kazakh

kl Greenlandic

km Cambodian

kn Kannada

ko Korean

ks Kashmiri

ku Kurdish

ky Kirghiz

la Latin

ln Lingala

lo Laothian

lt Lithuanian

lv Latvian, Lettish

mg Malagasy

mi Maori

mk Macedonian

ml Malayalam

mn Mongolian

mo Moldavian

mr Marathi

ms Malay

mt Maltese

my Burmese

na Nauru

ne Nepali

nl Dutch

no Norwegian

oc Occitan

om (Afan) Oromo

or Oriya

pa Punjabi

National Language Support

520

Page 533: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

pl Polish

ps Pashto, Pushto

pt Portuguese

qu Quechua

rm Rhaeto−Romance

rn Kirundi

ro Romanian

ru Russian

rw Kinyarwanda

sa Sanskrit

sd Sindhi

sg Sangho

sh Serbo−Croatian

si Sinhalese

sk Slovak

sl Slovenian

sm Samoan

sn Shona

so Somali

sq Albanian

sr Serbian

ss Siswati

st Sesotho

su Sundanese

sv Swedish

sw Swahili

ta Tamil

te Telugu

tg Tajik

th Thai

ti Tigrinya

tk Turkmen

tl Tagalog

tn Setswana

to Tonga

tr Turkish

ts Tsonga

tt Tatar

tw Twi

ug Uighur

National Language Support

521

Page 534: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

uk Ukrainian

ur Urdu

uz Uzbek

vi Vietnamese

vo Volapuk

wo Wolof

xh Xhosa

yi Yiddish (formerly ji)

yo Yoruba

za Zhuang

zh Chinese

zu Zulu

Appendix II: Region

Region A2

AFGHANISTAN AF

ALBANIA AL

ALGERIA DZ

AMERICAN SAMOA AS

ANDORRA AD

ANGOLA AO

ANGUILLA AI

ANTARCTICA AQ

ANTIGUA AND BARBUDA AG

ARGENTINA AR

ARMENIA AM

ARUBA AW

AUSTRALIA AU

AUSTRIA AT

AZERBAIJAN AZ

BAHAMAS BS

BAHRAIN BH

BANGLADESH BD

BARBADOS BB

BELARUS BY

BELGIUM BE

BELIZE BZ

BENIN BJ

National Language Support

522

Page 535: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

BERMUDA BM

BHUTAN BT

BOLIVIA BO

BOSNIA AND HERZEGOWINA BA

BOTSWANA BW

BOUVET ISLAND BV

BRAZIL BR

BRITISH INDIAN OCEAN TERRITORY IO

BRUNEI DARUSSALAM BN

BULGARIA BG

BURKINA FASO BF

BURUNDI BI

CAMBODIA KH

CAMEROON CM

CANADA CA

CAPE VERDE CV

CAYMAN ISLANDS KY

CENTRAL AFRICAN REPUBLIC CF

CHAD TD

CHILE CL

CHINA CN

CHRISTMAS ISLAND CX

COCOS (KEELING) ISLANDS CC

COLOMBIA CO

COMOROS KM

CONGO, Democratic Republic of (was Zaire) CD

CONGO, People's Republic of CG

COOK ISLANDS CK

COSTA RICA CR

COTE D'IVOIRE CI

CROATIA (local name: Hrvatska) HR

CUBA CU

CYPRUS CY

CZECH REPUBLIC CZ

DENMARK DK

DJIBOUTI DJ

DOMINICA DM

DOMINICAN REPUBLIC DO

EAST TIMOR TL

ECUADOR EC

EGYPT EG

EL SALVADOR SV

National Language Support

523

Page 536: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

EQUATORIAL GUINEA GQ

ERITREA ER

ESTONIA EE

ETHIOPIA ET

FALKLAND ISLANDS (MALVINAS) FK

FAROE ISLANDS FO

FIJI FJ

FINLAND FI

FRANCE FR

FRANCE, METROPOLITAN FX

FRENCH GUIANA GF

FRENCH POLYNESIA PF

FRENCH SOUTHERN TERRITORIES TF

GABON GA

GAMBIA GM

GEORGIA GE

GERMANY DE

GHANA GH

GIBRALTAR GI

GREECE GR

GREENLAND GL

GRENADA GD

GUADELOUPE GP

GUAM GU

GUATEMALA GT

GUINEA GN

GUINEA−BISSAU GW

GUYANA GY

HAITI HT

HEARD AND MC DONALD ISLANDS HM

HONDURAS HN

HONG KONG HK

HUNGARY HU

ICELAND IS

INDIA IN

INDONESIA ID

IRAN (ISLAMIC REPUBLIC OF) IR

IRAQ IQ

IRELAND IE

ISRAEL IL

ITALY IT

National Language Support

524

Page 537: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JAMAICA JM

JAPAN JP

JORDAN JO

KAZAKHSTAN KZ

KENYA KE

KIRIBATI KI

KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF KP

KOREA, REPUBLIC OF KR

KUWAIT KW

KYRGYZSTAN KG

LAO PEOPLE'S DEMOCRATIC REPUBLIC LA

LATVIA LV

LEBANON LB

LESOTHO LS

LIBERIA LR

LIBYAN ARAB JAMAHIRIYA LY

LIECHTENSTEIN LI

LITHUANIA LT

LUXEMBOURG LU

MACAU MO

MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF MK

MADAGASCAR MG

MALAWI MW

MALAYSIA MY

MALDIVES MV

MALI ML

MALTA MT

MARSHALL ISLANDS MH

MARTINIQUE MQ

MAURITANIA MR

MAURITIUS MU

MAYOTTE YT

MEXICO MX

MICRONESIA, FEDERATED STATES OF FM

MOLDOVA, REPUBLIC OF MD

MONACO MC

MONGOLIA MN

MONTSERRAT MS

MOROCCO MA

MOZAMBIQUE MZ

MYANMAR MM

National Language Support

525

Page 538: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

NAMIBIA NA

NAURU NR

NEPAL NP

NETHERLANDS NL

NETHERLANDS ANTILLES AN

NEW CALEDONIA NC

NEW ZEALAND NZ

NICARAGUA NI

NIGER NE

NIGERIA NG

NIUE NU

NORFOLK ISLAND NF

NORTHERN MARIANA ISLANDS MP

NORWAY NO

OMAN OM

PAKISTAN PK

PALAU PW

PALESTINIAN TERRITORY, Occupied PS

PANAMA PA

PAPUA NEW GUINEA PG

PARAGUAY PY

PERU PE

PHILIPPINES PH

PITCAIRN PN

POLAND PL

PORTUGAL PT

PUERTO RICO PR

QATAR QA

REUNION RE

ROMANIA RO

RUSSIAN FEDERATION RU

RWANDA RW

SAINT KITTS AND NEVIS KN

SAINT LUCIA LC

SAINT VINCENT AND THE GRENADINES VC

SAMOA WS

SAN MARINO SM

SAO TOME AND PRINCIPE ST

SAUDI ARABIA SA

National Language Support

526

Page 539: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

SENEGAL SN

SEYCHELLES SC

SIERRA LEONE SL

SINGAPORE SG

SLOVAKIA (Slovak Republic) SK

SLOVENIA SI

SOLOMON ISLANDS SB

SOMALIA SO

SOUTH AFRICA ZA

SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS GS

SPAIN ES

SRI LANKA LK

ST. HELENA SH

ST. PIERRE AND MIQUELON PM

SUDAN SD

SURINAME SR

SVALBARD AND JAN MAYEN ISLANDS SJ

SWAZILAND SZ

SWEDEN SE

SWITZERLAND CH

SYRIAN ARAB REPUBLIC SY

TAIWAN TW

TAJIKISTAN TJ

TANZANIA, UNITED REPUBLIC OF TZ

THAILAND TH

TOGO TG

TOKELAU TK

TONGA TO

TRINIDAD AND TOBAGO TT

TUNISIA TN

TURKEY TR

TURKMENISTAN TM

TURKS AND CAICOS ISLANDS TC

TUVALU TV

UGANDA UG

UKRAINE UA

UNITED ARAB EMIRATES AE

UNITED KINGDOM GB

UNITED STATES US

UNITED STATES MINOR OUTLYING ISLANDS UM

URUGUAY UY

UZBEKISTAN UZ

National Language Support

527

Page 540: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

VANUATU VU

VATICAN CITY STATE (HOLY SEE) VA

VENEZUELA VE

VIET NAM VN

VIRGIN ISLANDS (BRITISH) VG

VIRGIN ISLANDS (U.S.) VI

WALLIS AND FUTUNA ISLANDS WF

WESTERN SAHARA EH

YEMEN YE

YUGOSLAVIA YU

ZAMBIA ZM

ZIMBABWE ZW

National Language Support

528

Page 541: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Page Level Security

Introduction

Security in the report is a kind of privileged control. Beginning with Version 4.0, we support page level security whichcreates a security mechanism for controlling access to the report.

Page Level Security is implemented with two security properties on the group panel: Grant and Cascade. By utilizingthese two properties, you can specify which group should be displayed in your reports. The feature enables differentusers to view different groups according to their access privilege. It also applies to the nested group.

Setting Page Level Security

The Grant and Cascade properties are provided to build a report with Page Level Security. The Grant property is astring type variable, which can be controlled by a formula. Its value contains one or more security identifiers (SID). TheCascade property is a boolean type variable. If it is true, the group's Detail or sub−groups can be viewed according tothe SID. Otherwise display group header and footer .

Below we will follow an example to illustrate how to set Page Level Security.

Start up JReport Designer. Create a report for customer information. Group the report by the Customer_Regionfield.

1.

Create a formula to control the Grant property value. The formula will return a string value, which indicateswhich user has the privilege to access the JReport Enterprise Server.

For example, we write the following formula named "security" to set the SID.

"admin" and "jennifer" are two users assigned by the server administrator. By the above formula, the user"admin" is authorized to view only the CA group and MN group, and the user "jennifer" can only view the BC

2.

529

Page 542: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

group. If the formula is written as below:

if ( @Customers_Region =="BC")return "user1|user2|user3";

then user1, user2, and user3 can view the BC group. Further more, if user1, user2 and user3 are the membersin one group specified in the server, then the group can only view the BC group.

Note: The returned value must be same as user ID defined in the server, and the user ID is case sensitive. Go to the group panel properties in Report Inspector. Set Grant equal to the formula "security", and propertyCascade to true.

3.

Viewing a Report in JReport Enterprise Server

Since the control of report access is not possible without a user ID, the significance of this function is only apparent afterreports are deployed to JReport Enterprise Server and other users access it.

When a client views the report with Page Level Security in JReport Enterprise Server, the corresponding group displayaccording to the SID. You can export the report with page level security to PDF, HTML, TXT etc., but the RST andApplet format is not supported with this feature.

Deploy the report and catalog to JReport Enterprise Server. In this case, deploy the report with the Page LevelSecurity we just created.

1.

Access JReport Enterprise Server via the browser IE. 2. Logon to the server with the user ID "admin" 3. Click the Report button to get the report to be viewed. The report displays the CA and MN groups as wespecified in the formula in a separated page.

4.

Page Level Security

530

Page 543: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

If you logon to the server with the user ID "jennifer", the report will display only the BC group.5.

Notes:

The Cascade property will not work if you do not set the Grant property.• If the Cascade property is set to be false, the specified group will display only its group header and footer.•

Scheduling a Report in JReport Enterprise Sever

You can set up a schedule on a page−level−security report as a normal report. When you schedule a task to publish itto email, there is a slight difference. JReport Enterprise Server supports Multiple Mail feature which enables to sendresults of page−level−security reports directly to each user who is authorized to view the report. Below we will illustratehow to schedule a task on the page−level−security report to publish to e−mail.

Assume the catalog and report have been deployed to the server. User "admin" and "jennifer" have permissionto view the report.

1.

Log on the server with user ID "admin" or "jennifer", and set up a schedule on the report. 2. Check Publish to E−mail and check This report has Page Level Security, send an email to each user whoviews it. Type the subject and select the result format, then click Submit.

3.

Page Level Security

531

Page 544: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport Enterprise Server will get e−mail addresses from the user accounts and send the report result to user"admin" and "jennifer" with the contents according to their access right to the report.

Note: Before publishing to e−mail, make sure you have input the e−mail addresses of users when configuring theserver. To do this, access JReport Enterprise Server with port 8889 (default port of remote administration). On theSecurity page, click User tab. Choose the user name which you want to edit in the User ID column and click it. Then youcan type in the e−mail address of the user.

Example: Email Billing Reports

Sometimes, sending pertinent report data to corresponding mail recipient is required. JReport Enterprise Server allowsyou to send the scheduled report result to the e−mail addresses accordingly, based on the page level security settings ofthe report and the user information stored on JReport Enterprise Server (e.g., e−mail address information). Therefore,each recipient will be able to view only certain part of the report data. However, using email information of server users isnot reliable, because the user ID that is ok for the report doesn't always exist in JReport Enterprise Server, and in caseslike this, mails will not be sent successfully. The best way to solve this is to use external e−mail information source, usingthe UserMailList API that JReport provides.

JReport provides two interfaces for you to retrieve user and e−mail information from a customized source:

jet.server.api.UserMailListFactoryUsed to get the UserMailList instance implemented by the user.

jet.server.api.UserMailListUsed to get e−mail information from a customized source.

You can implement multiple classes of interface UserMailList, each of them may refer to a particular report. By usingthe getInstance() method in the jet.server.api.UserMailListFactory interface, you can get oneimplementation of UserMailList. For more information on these two interfaces, please refer to JReport EnterpriseServer API Documentation.

Let's take the following simple example:.

Here, we have a Customers table with customer names and their e−mail addresses, as illustrated below. Youcan design a report this table and others. Then apply the page level security for this report, so that later in the

1.

Page Level Security

532

Page 545: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

server side, we can schedule this report and send the pertinent data to different recepients saved in thisCustomers table.

In JReport Designer, design a report and set the page level security for it. In this case, group the report data by"Customer Name", and then grant a formula − "FPageLevel" to it. The content of the formula FPageLevel is likebelow:

@"Customer Name";

This means only the records of the specified group will be shown at run time when you enter with the different ID−− Customer Name, in this example.

2.

Then in the server side, we are going to implement the two interfaces to import email list saved in the Customerstable. Specifically, implement the jet.server.api.UserMailListFactory interface. ThegetInstance() method should be implemented in this interface to get an instance ofjet.server.api.UserMailList. Please take the following implementation as a reference, where theimplementing class name of the UserMailList interface are formated as "UserMailList_" + report + "_Impl", suchas "UserMailList_Invoice_cls_Impl".

public class DemoUserMailListFactoryImpl implements UserMailListFactory {

3.

public UserMailList getInstance(ServerInfo serverInfo) {if (serverInfo == null) {return null;}String rpt = null;try {rpt = serverInfo.getTaskProperties().getProperty(APIConst.TAG_REPORT);} catch (RptServerException e) {e.printStackTrace();return null;}rpt = rpt.substring(rpt.lastIndexOf("/") + 1);rpt = rpt.replace('.', '_');rpt = rpt.replace(' ', '_');String clsName = "UserMailList_" + rpt + "_Impl";try {UserMailList mailList = (UserMailList)Class.forName(clsName).newInstance();return mailList;} catch (InstantiationException e1) {e1.printStackTrace(); } catch (IllegalAccessException e1) {e1.printStackTrace();} catch (ClassNotFoundException e1) {e1.printStackTrace();}return null;}}

Page Level Security

533

Page 546: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Then implement the jet.server.api.UserMailList interface, which gets the user and e−mail informationfrom the customized data source. The following implementation gets e−mail list from the Customers table, whichcontains "Customer Name" and "Customer Email" columns.

public class UserMailList_Invoice_cls_Impl implements UserMailList {

4.

public static Hashtable userEmails = new Hashtable();private String curRealmName = "defaultRealm";

public UserMailList_Invoice_cls_Impl(){loadData();}

private void loadData (){try{ String jdbcDriver = "sun.jdbc.odbc.JdbcOdbcDriver";DriverManager.registerDriver((Driver)Class.forName(jdbcDriver).newInstance()); Connection conn = DriverManager.getConnection("jdbc:odbc:jinfonet4");Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("select * from Customers");String userName = null;String userEmail = null;while(rs.next()){userName = rs.getString("Customer Name");userEmail = rs.getString("Customer Email");if (userEmail != null) {userEmails.put(userName, userEmail);}}}catch(Exception e){e.printStackTrace();}

}public java.util.Enumeration getAllMailAddresses(String realmName){if (realmName.equals(curRealmName)) {return userEmails.elements();}else{return null;} }

public java.util.Enumeration getGroupMailAddresses(String realmName, StringgroupName) { if (realmName.equals(curRealmName) && userEmails.containsKey(groupName)) {Vector groupEmails = new Vector();groupEmails.addElement(userEmails.get(groupName)); return groupEmails.elements() ;}else{return null;}}

public java.lang.String getMailAddress(String realmName, String userName) {

Page Level Security

534

Page 547: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

if (realmName.equals(curRealmName) && userEmails.containsKey(userName)) { return (String)userEmails.get(userName);}else{return null;}}}

Register the above classes to the server before JReport Enterprise Server is started: Add the −Dcom.jinfonet.mailListFactory=UserMailListFactoryImplName parameter to thecommand line/batch file that starts JReport Enterprise Server, where theUserMailListFactoryImplName indicates the implementation of thejet.server.api.UserMailListFactory interface.

In this case, the parameter should be−Dcom.jinfonet.mailListFactory=DemoUserMailListFactoryImpl.

Add the path of the implementation classes to the classpath of the command line/batch file.♦

5.

Start JReport Enterprise Server and then deploy the report and catalog.6. Schedule the report, publish to e−mail, check the option This report has Page Level Security. Send an emailto each user who views it. Provide the necessary information and then submit the schedule.

7.

The report will be processed and sent to the corresponding recipients with pertinent report data.

Index

Page Level Security

535

Page 548: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Record Level Security and Column Level Security

Introduction

Record level security (RLS) and Column Level Security (CLS) of JReport Designer allow you to control the user accessto different subsets of data, which ensures that people only see what they are supposed to see. This lets you providedifferent users with accordingly different, but appropriate contents.

What are record level security & column level security?In short, record level security allows you to define what records are to be revealed to a certain user, while column levelsecurity allows you to define which report column is revealed to a certain user.

No matter to whom you need to provide information, a plant manager or thousands of customers, JReport Designerallows you to control the access to information according to your needs.

Both record level security and column level security of JReport Designer are based on catalog, in this way, you don'tneed to set security information for every report.

JReport products have two types of the security policies, one is the security policies based on catalog (Catalog ScopeSecurity Policy), while the other is the security policies based on single report (Report Scope Security Policy):

Catalog Scope Security PolicyYou can build your catalog scope security policy, with each security policy referring to a data source in thecatalog, so that if you want to implement the same security policy in a group of reports, you can simply apply anexisting security policy to the report, without repeatedly building the security information for each report. BothRLS and CLS can be catalog scope security.

Report Scope Security Policy Additionally, the record level security can be report scope, which is based on security information file, say, youcan use security information file to set the security policies for a report. Report scope security policy doesn'tsupport column level security.

Both of these two types of policies (for record level security only) can be applied simultaneously in the catalog and report.Please note, if a report scope security policy has already been applied to a report, it will override the catalog securitypolicy applied to the catalog, say, the report scope security policies have higher priorities than the catalog securitypolicies.

User, Role, and Group ManagementYou can both import the users/groups/roles from JReport Enterprise Server and define new user/group/role in designer.

Import/export Security Policy to XMLSecurity policy information can be imported from TXT (for Report Scope Security only) and XML (for Catalog ScopeSecurity) formats. You can export the security policy to XML files.

Catalog Scope Security

You can build your catalog scope security policy, with each security policy referring to a data source in the catalog, sothat if you want to implement the same security policy in a group of reports, you can simply apply an existing securitypolicy to the report, without repeatedly building the security information for each report.

536

Page 549: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

UserThe users for catalog scope security falls into two categories: UserDefiend and Server. The user defined user is createdin JReport Designer, while the Server user is imported from JReport Enterprise Server.

RoleThe roles for catalog scope security falls into two categories: UserDefiend and Server. The user defined role is created inJReport Designer, while the Server role is imported from JReport Enterprise Server.

GroupThe groups for catalog scope security falls into two categories: UserDefiend and Server. The user defined role is createdin JReport Designer, while the Server role is imported from JReport Enterprise Server.

Security PolicyThe permissions can be assigned to users, roles, and groups. A role/group can have more than one user, and a user canbelong to more than one role/group. The permissions that a user may have depends on the permissions of theroles/groups it belongs to and its own permissions. The inheritance relationship is logic OR.

For example, if a user U1 belongs to two roles, two groups, such as R1, R2, G1, and G2, the permissions the user U1will eventually have are the permission collection of the roles and itself, which is P1, P2, P3, P4, and P5, as shown in thefollowing diagram.

Record Level Security and Column Level Security

537

Page 550: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The group and role relationships are the same, let's see another example, if a group G1 has two roles, R1 and R2, andtogether with its own permissions, the users in group G1 will have P1, P2, P3, and permissons assigned directly to theusers.

When calculating a user's permissions, the permission collections of its roles and groups are firstly calculated, usinglogical OR. If the calculation result conflicts against the user permissions, the user's permissions have higher priority,say, if one access right is permitted for the user's groups and roles but denied by the user's permissions, the user stilldoesn't have this access right.

The major procedures for using RLS and CLS with catalog scope securtiy policy is as described below:

Set up security policies. You use this step to set up security policy for different report categories. These predined security policies workwithin catalog range, which means you can reuse a security policy in multiple reports, instead of repeating thesecurity policies in each report.

1.

Apply the security policies to your reportsAfter you have the security policies defined, you can apply these security policies to your report respectively.

2.

Deploy these reports with RLS (CLS) to JReport Enterprise Server and run.3.

Setting up Security Policy

Before you can apply the security policy to a report, you must have the security policy created.

To add a security policy,

Record Level Security and Column Level Security

538

Page 551: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Open Catalog Browser, select the data source upon which you would like to build the security policy.1. Select the Security Controller.2. Click the New Security button.3. To apply the record level security, check the Valid RLS box. To apply the column level security, check the ValidCLS box.

4.

Tip: To open a security dialog, on Catalog Browser, click New Security to create a new one, or right−click an existingsecurity policy, and then choose Edit Security.

Using the security dialog, you can

Add/edit a user, role, or group• Delete a user, role, or group• Edit permissions for a user, role, or group• Synchronize user/role information with server• Import/export security information•

Add/edit a user, role, or group

To add a new user,

Open the Security dialog, on the User tab, click the Add button.1. Provide username, title, email information respectively in their fields.2. Select the roles/groups that you want apply to this user from the All Roles/All Groups list, click the Add (rightarrow) button to add it to the Belongs to list.

3.

To add a new role,

Open the Security dialog, on the Role tab, click the Add button.1. Provide name for the role.2. Select the users/groups that you want add to this role from the All Users/All Groups list, click the Add (rightarrow) button to add it to the Assign to list.

3.

To add a new group,

Open the Security dialog, on the User tab, click the Add button.1. Provide name for the group.2. Select the users/roles that you want add to this group from the All Users/All Roles list, click the Add (rightarrow) button to add it to the Users/Roles list.

3.

To edit a user, role, or group, on the Security dialog, select the user, role, or group, and then click Property.

Note: The name of a user/role should be unique in the users/roles list. The user name can be the same as the rolename.

Delete a user, role, or group

To delelte a user, role, or group, on the Security dialog, selelct the user, role, or group, and then click Delete.

Edit permissions for a user, role, or group

This operation can be done when you add or edit a user, role, or group. To edit permissions,

On the Security dialog, select the user, role, or group you want to edit, click Property, and then clickPermissions.

1.

On the Security Permissions Settings dialog, specify the policy settings.2.

Record Level Security and Column Level Security

539

Page 552: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You should select the Policy Settings option. If you have the Policy No Limit option selected, you will not beable to specify the policy settings for this user, role, or group. Policy no limit means all the records and columnsare available for this user/role/group.

There are two tabs on this dialog, Record Level Security and Column Level Security.

On the Record Level Security tab, specify the security conditions for this user, role, or group.

Build your own condition statements. Specify the expression in the first field, which can be DBFields, formulas,parameters, and some special fileds. Select an operator from the Operator drop down list, and then specify thevalue to complete editing a row. If you want to append a new row, in the More drop down list, select AND or OR.

Values Description

AND

Specifies the relationship between two expression statements aslogical AND. If this line is the last line in the expression list, when youselect AND or OR, and new line will be append to the end of the list aswell.

OR

Specifies the relationship between two expression statements aslogical OR. If this line is the last line in the expression list, when youselect AND or OR, and new line will be append to the end of the list aswell.

Insert Row Inserts a new line behind the current line.

Delete Row Delete the current line.

New Group Add a new expression group to the list. The relation ships between twogroups can be:

AND − Logical AND relationship between two groups. Recordssatisfying both condition groups will be retrieved.

Record Level Security and Column Level Security

540

Page 553: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

OR − Logical OR relationship between two groups. Records satisfyingeither one of the condition groups will be retrieved. AND NOT − Records satisfying the first condition group and notsatisfying the second condition group will be retrieved. OR NOT − Records satisfying the first condition group or not satisfyingthe second condtion group will be retrieved.

On the Column Level Security tab, check the boxes to select the dbfields, formulas, parameters, or summaries.You can set the selected items to be shown to (allowed) or hidden (denied) from that specific user, role, or group.

Choose Allow all to show all the columns, choose Deny all to hide all the columns from this user (role, or group).

You can change the select type by checking Allow or Deny. When Allow is checked, all the selected items areto be shown, and vice versa.

3.

Synchronize user/role information with server

Besides defining user and roles in JReport Designer, you can also use the users and roles defined on JReport EnterpriseServer.

To use users and roles defined on server,

On Security menu of the Security dialog, click Synchronize with Server.1. Make sure JReport Enterprise Server is started. Provide the information like the following:

HostThe host name or ip where server runs, such as "localhost" or "192.168.1.1".

PortThe service port of JReport Enterprise Server, such as "8888".

Full Path

2.

Record Level Security and Column Level Security

541

Page 554: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The server full path, such as "/jrserver".

User NameThe user name to log in, such as "admin".

PasswordThe password for the user.

ReplaceUse the server users/roles to override the user defined ones, if the names of the user/role are the same on bothserver and local. Note: Your permission settings for the user defined users or roles will be lost once they arereplaced.

MergeMerge the server user/roles with the user defined ones, the permission settings for the user defined users orroles will be retained after synchronization even though the user/role names of both server and local are thesame.Click OK to start synchronization.3.

Notes:

You must use a user in the administrators group to log in can you do the synchronization.• The users/roles from server will be marked as Server in the Source field on the Security dialog, while othersdefined in JReport Designer are marked UserDefined.

A user from server can't be reassigned to (or removed from) a role from server. Similarly, a role from server can'tbe re−assigned to (or removed from) a user from server. Namely, if both users and roles are obtained fromserver, you will not be able to change their parental relationships. The only way to do this is to synchronize withserver.

Record Level Security and Column Level Security

542

Page 555: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

A role from server is not able to be assigned to a local user (UserDefined), while a user from server can beassigned to a local role. During synchronization, if the users/ roles, whose source names are Server, have the same names with those onserver, their properties will be refreshed using new information on server, such as user, role, or group informationand parental relationships. However, their permission settings will be reserved. Specially, if a user from serverhas been assigned to some roles defined in Designer, these roles will be reserved in its members list.

Import/export security information

You can import or export your security information from/to external XML files (*.acl.xml). To do this, on the Securitymenu, click Import or Export.

The security information contained in the XML file is shown as the below diagram:

Record Level Security and Column Level Security

543

Page 556: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

You can create your own XML format security information files according to the above structure. However, the best wayto generate an XML security information file is to use the Security dialog to edit the security informaiton, and then exportit to an external XML file.

For instance, if we set up a simple security policy like below:

USER

User Name: d_d_u1

Belongs to Role: d_d_r1

Record Level Security and Column Level Security

544

Page 557: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Permissions: (@"Customer ID">=5 AND @"Customer ID"<=10) AND @"AnnualSales"<=65000

ROLE

Role Name: d_d_r1

Belongs to User: d_d_u1

The corresponding XML code will be:

<ACL version="1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema−instance" xsi:noNamespaceSchemaLocation="C:/JReport/template/Acl.xsd"> <ACLEntry> <User> <Roles>d_d_r1</Roles> <UserName>d_d_u1</UserName> <SourceName>UserDefined</SourceName> </User> <Permission> <PermissionType>RLS</PermissionType> <PermissionName>visible</PermissionName> <Policy> <SCGroup> <AndCondition> <logic>AND</logic> <Left>@&quot;Customer ID&quot;</Left> <operator>&gt;=</operator> <Right>5</Right> </AndCondition> <AndCondition> <logic>AND</logic> <Left>@&quot;Customer ID&quot;</Left> <operator>&lt;=</operator> <Right>10</Right> </AndCondition> </SCGroup> <SCGroup> <AndCondition> <logic>End</logic> <Left>@&quot;Annual Sales&quot;</Left> <operator>&lt;=</operator> <Right>65000</Right> </AndCondition> </SCGroup> </Policy> </Permission> </ACLEntry> <ACLEntry> <Role> <RoleName>d_d_r1</RoleName> <Users>d_d_u1</Users> <SourceName>UserDefined</SourceName> </Role> <Permission> <PermissionType>RLS</PermissionType> <PermissionName>visible</PermissionName> <Policy></Policy> </Permission>

Record Level Security and Column Level Security

545

Page 558: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

</ACLEntry></ACL>

Notes:

Please note that if you want to use the XML security information, you are supposed to purchase a special licensefor this feature, for more, please contact Jinfonet Support ([email protected]).

Before you can import from the external XML file, you should make surexsi:noNamespaceSchemaLocation= is set to %JReportRoot%/template/Acl.xsd, such as"C:/JReport/template/Acl.xsd"; this file is available only if you purchase the license key for XML feature.

Applying a Security Policy to the Report

To apply a security policy to the report,

On Report Inspector, select the DataSource node.1. In the Properties sheet, select the security policy you desire for the SecurityName property.2.

When you preview the report, the SID dialog will pop up. Type the user name, and then click OK to see the result.

Notes:

You will not be able to view any records if the user ID you enter on the SID dialog doesn't exist in the securitypolicy defined.

Security policies for main report and sub−report can be set and applied individually, different conjunctions willcause different results, the relationships between the security policy settings and the try−viewing results are asshown in the following table:

main sub Users in Policy Users NOT in Policy

Ð ÐIn this case, no security policy is applied to either main or sub report, so all theusers can view all the records in both main and sub report.

Ï ÐCan view specified records in main reportand all records in sub report.

Can view no records in mainreport and all records in sub report.

Ð ÏCan view all records in main report andspecified records in sub report.

Can view all records in main reportand no records in sub report.

Ï ÏCan view specified records in both mainand sub report.

Can view no records in either mainor sub report.

Ï − Security policy has been set and appliedÐ − Security policy has not been set and appliedThe report scope security has high priority than catalog scope security, say, if in one report, both catalog scope security and reportscope security (which is set by the RecordSecurity property) are applied, the report scope security will take effect, other than thecatalog scope security.

Deploying to JReport Enterprise Server

After you have set up the record level security (RLS) for the reports in JReport Designer, you can deploy the reports toJReport Enterprise Server as normal.

Log on to JReport Enterprise Server as different users, you will find that the record level security settings are applied tothe report; different users will only see the data they are supposed to see.

Note: The user defined user and roles may not be recognized by JREntServer, if your security policies contain suchusers/roles, please create these users and roles respectively on server, and then in JReport Designer, synchronize thesecurity information with server, using the Merge option.

Record Level Security and Column Level Security

546

Page 559: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Report Scope Security

The report scope security applies to record level security (RLS) only.

Setting up Record Level Security

Since the record−level−security rules are file−based, you do not need to do extra work on your current reports; justcreate a new .txt file, add security settings, and then link the file to your report.

Set up the security information

You can set up the security information in JReport Designer using the Record Level Security Info dialog.

To set up the security information,

Open a report file in JReport Designer. Here we open the report file customerlist.cls. 1. Open Report Inspector, select the DataSource node. 2. Click the ... button to the right of the RecordSecurity property entry.3.

Edit the security information on the dialog, or you can import a .txt file that contains the same information. Forexample, the security info may be like the following. Click OK to dismiss the dialog.

4.

Record Level Security and Column Level Security

547

Page 560: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Click View to preview the report. You will be prompted to provide security ID (SID), which refers to the user namein the security file. Type user1 as the SID, and then click OK.

Only the records satisfies the conditions will be displayed.

5.

Record Level Security and Column Level Security

548

Page 561: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Use user2 and user3 as the SID to view the report.

User2:

6.

Record Level Security and Column Level Security

549

Page 562: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

User3:

Notes:

If the Date/Time format in your reports differentiates from that in your database, please change the format usingthe Date Format tab on the Get JDBC Connection Information dialog, which can be accessed in the CatalogBrowser.

If you want to use more values in one cell, use "|" to separate them. Applies to User, E−mail, and Title column.This is useful when you want to apply the same conditions to multiple users. For example, if you want user1,user2, and user3 to share the same security setting, list user1, user2, and user3 in the same cell, separated by"|", and then define the security conditions.

Record Level Security and Column Level Security

550

Page 563: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In current version of JReport Designer you cannot save the security information to a file. • The relationship between each condition line (if they are possessed by one user) is logic OR. • For information about each column headings, please refer to JReport Designer User Reference | JReportWindows and Dialogs | Record Level Security Info dialog

Edit the security information in a text file

You can also import the security information from a text file. Use TAB to separate each column. Please always keep theheadings (User, Role, Column, and so on) in the first line of the text file.

The relationship between each condition line (if they are possessed by one user) is logic OR.

The text file used in the preceding example is like below:

User Role Column Operator Value Email Title

admin admin

user1Customers_CustomerID

>= 10 [email protected] Mr.

user1 Customer Name = 'Absolute Java'

user2 Customer Name IN('Absolute Java','AmericanCoffee, Inc.')

[email protected] Miss

user3 Customers_Phone IN('(212) 946−3462','(317)942−1274')

[email protected] Mrs.

UserThe user ID to whom the security settings will be applied.

RoleThe role of the user. More than one user can share one role; for one role, you only need to define once, and other userscan share this role without type the same conditions again.

If a role should contain more than one condition, append the conditions in multiple lines, and then add the role name infront of each line.

In the case below, RoleA contains two conditions, user1 and user2 share RoleA. The two users has the samepermissions, and neither of them can see the record where Customers_Customer ID=10.

User Role Column Operator Value

user1 RoleA Customers_Customer ID > 10

user2 RoleA Customers_Customer ID < 10

ColumnThe condition expression is comprised of three parts − Column, Operator, and Value.

The column name, can be the name of a DBField in the current query, the name of a formula (summary) based on anyDBField in the current query, and the name of a parameter. You do not need to quote the name when the name containsspaces. However, you must make sure the names you type actually exist.

OperatorThe operator can be one of the following operators: =, <>, <, >, <=, >=, and IN.

ValueThe value part of the condition expression.

Record Level Security and Column Level Security

551

Page 564: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

For String type values, use single quotation mark (') to quote the values, e.g., 'Absolute Java';For Boolean type values, use 0 (false) or 1 (true).For Date type values, please make sure the format of the value you enter is consistent with that of your database.

Note: On the Record Level Security Info dialog, the date values provided on the drop down list may not be valid for youractual database, because they are date values that have already been reformatted using your date format settings inJReport. For detailed information on how to set the date format in JReport Designer, please refer to the Date Formatsection of the document at http://www.jinfonet.com/manualpro/userguide/connect.htm.

For the values of other types, type them in their original form.

E−mailThe e−mail address of the user. A user can have only one E−mail address. If there are more than one E−mail addressdefined for one user, the first one will be actually used.

TitleThe title for the user. A user can have only one title. If there are more than one title defined for one user, the first one willbe actually used.

Compound conditions

If you want to apply more than one condition expression to one user, edit the condition expressions in several individuallines, typing the same user name for each line. For such compound conditions, the relationships among them are logicalOR.

For example, Customer_Customer ID >= 10 and Customer Name = 'Absolute Java' together will cause JReport Designerto bring back records whose customer ID is larger than or equals to 10 and the record whose customer name is AbsoluteJava together.

If you want to use logical AND for the relationship between each condition expression, please use a formula that returnsa Boolean value to filter the records. To specify the formula name for the report, open Report Inspector, select DataSource node, select or type the formula name in the Function property entry.

For example, if user1 should only see the records satisfying the condition Customers_Region = 'CO' andCustomers_Customer ID >= 10, the formula should be like below:

if ( @Customers_Region == 'CO' && @"Customers_Customer ID">= 10 )return "user1"

If both Record Level Security Info dialog and formula are used to control the security information, both of the two will takeeffect, and the relationship between them is logical OR.

Running Reports with RLS on Server

After you have set up the record level security (RLS) for the reports in JReport Designer, you can deploy the reports toJReport Enterprise Server as normal.

Log on to JReport Enterprise Server as different users, you will find that the record level security settings are applied tothe report; different users will only see the data they are supposed to see.

Record Level Security and Column Level Security

552

Page 565: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Security Context

Table of Contents

1. Security Context Overview

2. Configuration

2.1. Designer

2.2. Server

3. Security Context APIs

3.1. JReport Designer API

3.1.1. JRSecurityContextFactory

3.1.2. JRSecurityUserDataSource

3.1.3. JRSecurityHierarchicalDataSource

3.2. JReport Enterprise Server API

3.2.1. SecurityContextFactory

3.2.2. SecurityContext

4. JReport Designer

4.1. Formula Editor

4.2. Deployment

4.2.1. Deploy wizard Overview

4.2.2. Working Principle

4.3. View Report

553

Page 566: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Security Context OverviewSecurity Context support refers to a set of new functionalities that JReport products provides to support the NXJ SecurityContext. Other than using the security system of JReport, Security Context support allows NXJ developers to write codethat obtains user profile information from the security database.

554

Page 567: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Configuration

Designer

By default, JReport products use their own security system. If you want enable the security context support, you need toconfigure the config.xml ( %reporthome%\bin) file first.

Add the elements <SecurityContextFactory value=""/> and <DeployWizardFactory value=""/> as the child of theelement <Option> .

1.

Specify the implementing classes to the attribute values. For example, part of the config.xml file might be likebelow:

<Option>

<SecurityContextFactory value="com.utify.JRSecurityContextFactoryImpl"/><DeployWizardFactory value="com.utify.JRDeployWizardFactoryImpl"/></Option>

2.

Add the root path of the implementing class packages to the classpath of JReport.bat from which you startJReport products.

3.

Server

Security Context interfaces in JReport Enterprise Server is different with that for JReport Designer; therefore you willhave to implement server interfaces separately.

The same as designer, before you use the security context feature, you must have the server.properties(%serverhome\bin%) file configured.

Open the server.properites file, modify (add if it doesnt exist) the value of this property:

com.jinfonet.securityContextFactory=mypackage.myclass

Add your SecurityContextFactory implementing class package and name.

Alternatively,

You can add D com.jinfonet.securityContextFactory =mypackage.myclass parameters to start server.

1.

Add the root path of the implementing class packages to the classpath of JREntServer.bat from which you startJReport products.

2.

555

Page 568: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Security Context APIsJReport provides a set of APIs to support Security Context feature.

JReport Designer API

JRSecurityContextFactory

Package: jet.acl.api

Usage: This interface is used to help the user to create an instance of SecurityContext.

Method:getSecurityContext(javax.swing.JFrame frame, java.util.Vector roles)

Parameters:

frame − The parent window

roles − The role list defined by RLS (Record Level Security)

Returns:

The SecurityContext object

JRSecurityUserDataSource

Package: jet.datasource

Usage: A JRSecurityUserDataSource provides data for JReport for generating reports. JRSecurityUserDataSource classis developed by user of JReport, and it can provide data from flat file, non−relational database, or application data.The data returned by this class is in ResultSet object, so user need create ResultSet instance and JReport will use theinstance to fetch data. Users can also create their own ResultSet class.

Method:getResultSet(SecurityContext sc, java.lang.String param)

Method description:Gets the data in ResultSet according to parameters.

Parameters:sc − A SecurityContext object, which is implemented by the userparam − The parameter that the user wants to use for UDS

Returns:The ResultSet object

JRSecurityHierarchicalDataSource

Package: jet.datasource

Usage: A JRSecurityHierarchicalDataSource provides data for JReport for generating reports.JRSecurityHierarchicalDataSource class is developed by user of JReport, and it can provide data from flat file,non−relational database, or application data.

556

Page 569: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

The data returned by this class is in JRHierarchicalDataset object, so user need create JRHierarchicalDataset instanceand JReport will use the instance to fetch data. Users can also create their own JRHierarchicalDataset class.

Method:getHierarchicalDataset(SecurityContext sc, java.lang.String param)

Method description: Gets the data in JRSecurityHierarchicalDataset according to security context and parameters

Parameters:sc − A SecurityContext object, which is implemented by the userparam − The parameter that the user wants to use for HDS

Returns:The JRHierarchicalDataset object

JReport Enterprise Server API

SecurityContextFactory

Package: jet.server.api

Usage: SeucurityContextFactory is an interface that is used to help you implement security context.

Method:getSecurityContext(java.lang.String realmName, java.lang.String userName, java.lang.String resource, intversionNumber)

Method description:Return the SecurityContext of specified resource.

Parameters:realmName − the realm name of current active realm of server.userName − the user name, for a shedule task it means submitter,for advance run task it means login user.resource − the resource of server, now it is only limited to report resource in server for example:"/AccessDemo/CustomersAddress.cls"versionNumber − the version number of resource.

Returns:

the SecurityContext of specify resource.

SecurityContext

Package: jet.server.api

Usage: SecurityContext is an interface that is used to help you implement security context.

Methods:getEmail() − Return the user name.getRoles() − Return roles the user belong to.getSalutation() − Return the salutation of the user(e.g., Mr., Mrs., etc).getUserName() − Return the user name.

Security Context APIs

557

Page 570: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

JReport DesignerParts of JReport Designer are updated to support the security context.

Formula Editor

The formula editor now allows you to pass the security context to a user−defined formula (UDF) function.

You can call getSecurityContext () in your formula, which will pass the object it returns to your UDF function. The methodgetSecurityContext() returns a DbSecurityContext type object, which provides the method get() to get the SecurityContext instance transfer from Server or Designer.

DbSecurityContext is a new data type for the SecurityContext object, because all the data types of variables used in UDFfunctions should be DbValue.

The following is an example.

Import userClass from UserFunction;

userClass.getData(getSecurityContext(), @country, );

Deployment

JReport provides you with two API methods in order to offer you chances to pop up your own deployment tool wizard.

DeploymentWizard

Package: jet.builder.deployment.api

Usage: DeploymentWizard is an interface that is used to implement customize deploy wizard.

Methods:deploy (Frame frame, String catFullPathName, String reporthome)

Parameters:frame − the frame of the deployment box

catalogFullPath − the full path name of the catalog file

reporthome − the report home path.

DeploymentWizardFactory

Package: jet.builder.deployment.api

Usage: DeploymentWizardFactory is an interface that is used to implement customize deploy wizard.

Methods:getDeploymentWizard()

Method decription:Return the DeploymentWizard.

558

Page 571: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Working Principle

Loading DeployWizardFactory class name from configuration information:

In JReport designer, there is a config.xml file under /%reporthome%/bin since version 7. This file iscorresponding with Report Option dialog. You can make it configurable by modifying this xml file. Designer loadsinformation from this xml file and configure Report Option dialog when designer is starting up.

Getting DeployWizardFactory class name and show customized deployment wizard:

When you click Deploy to JReport Enterprise Server menu in designer, it will first check if there isdeployWizardFactory in the ReportOption and try to create new instance by the class name. If the class of thecustomized deployWizard is successfully loaded, its wizard will be shown, otherwise the default deploy wizardwill be shown.

View Report

When you click on the View tab to view a report that requires the security context to run, JReport Designer will use theimplemented JRSecurityContextFactory to instantiate the SecurityContext instance it will use to execute the report.

The value should be your own class package.

The value should be your own class package.

Index

JReport Designer

559

Page 572: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Converting Crystal Reports to JReport Reports

Introduction

A tool called Crystal Converter is provided for you to convert Crystal reports to JReport reports, so as to open and modifythem in JReport Designer.

Installing Crystal Converter

Installation

To install Crystal Converter, please install the following products:

Install Crystal Reports 8.5 or above.1. For Crystal Reports 8.5, please install cr85dev.zip.For Crystal Reports 9, please install Crystal Report 9 Report Creation API License; For Crystal Reports 10, please use Crystal Reports Advanced Developer Edition with the Report CreationAPI license.

Note: For Crystal Report 9 and Crystal Report 10, if no Report Creation API is installed, some simple reports(reports that do not contain cross−tab, chart, sub−report, and Group by Field in specified order) can also beconverted.

2.

Contact Jinfonet Sales ([email protected]) to get the Crystal Converter installation program jrconverter.exe.

Install the Crystal Converter under the installation root of JReport Designer.

Please make sure that there is no space in the name of the folder, in which JReport Designer is installed, forexample, the path C:\Program Files is not allowed. Otherwise, when you convert reports, the error messageRun−time error '13' Type mismatch may be thrown.

According to different version of Crystal Reports on your machine, different Crystal Converter can be installed.The installer will list all the available Crystal Converters for you to choose.

3.

After installing the Crystal Converter, a folder named convertcryXX (e.g. convertcry9 for Crystal Converter ofCrystal Reports 9) including all the resources of Crystal Converter will be generated under the installation root ofJReport Designer.

4.

Notes:

The Crystal Converter of the higher version can convert Crystal reports that created by the lower version directly.For example, the converter for Crystal Reports 9 can convert reports that are created by Crystal Reports 8.5directly, without opening and saving them in Crystal Reports 9 first before conversion. But if you use theconverter of Crystal 8.5 to convert a report that created by Crystal Reports 9, the error message an invalidTLV record will pop up.

If the Crystal report to be converted was created by Crystal Reports version that lower than 8.5, you arerecommended to open and save it in the version corresponding to the converter before converting it.

System Properties

After you have installed the Crystal Converter, four system variables are added to your machine automatically forconversion. They are listed in the table below:

SystemVariables

Description

ConverterPath

560

Page 573: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Specifies the location of convert.exe (the executable file that is used toconvert Crystal report to JReport report).

JReportClassPath Specifies the .zip files of JReport Designer that will be used for conversion.

JReportPath Specifies the location of JReport Designer.

JVMPATH Specifies the location of the jvm.dll file.

Suppose that JReport Designer is installed under C:\JReport and the Crystal Converter of Crystal Reports 9 is installed,open System in the Control Panel, on the Advanced tab, click Environment Variables, and the four system variablesare displayed like this:

Converting Crystal Reports to JReport Reports

Before using the Crystal Converter in JReport Designer, please add the system variable ConverterPath(%install_root%\convertcryXX) to the classpath of the file JReport.bat or setevn.bat under%install_root%\bin in order to load convert.exe when launching JReport Designer.

In JReport Designer, two methods are provided for you to convert Crystal reports: convert more than one Crystal reportat one time, or convert Crystal report one by one.

Converting More Than One Crystal Reports At One Time

Launch JReport Designer, on the File menu, select Import and then click Crystal to bring out the ImportCrystal Report dialog. Please look at the screen shot below:

1.

Converting Crystal Reports to JReport Reports

561

Page 574: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

In the Select Catalog to Save Imported Reports section, click the Browse button to specify a catalog amongthe existing catalogs in your disk for the converted reports, or click the New Catalog button to create a newcatalog for the converted reports using the Input New Catalog Name dialog.

In the Name text box, specify a name for the new catalog, and then click the button beside the Directory textbox to specify a directory for the new catalog. Click OK to create the new catalog.

2.

In the Select Reports section, click the Browse button to bring out the Get Directory dialog. Select the folderwhich contains the Crystal reports you want to convert, and click OK. Now, the folder name with its full path isdisplayed in the Look in text box, and all the Crystal reports under that folder are listed in the CrystalReports list.

3.

Highlight the Crystal reports you want to convert and click to add the selected Crystal reports to the Import

to JReport list.

4.

Click the Convert button to convert the selected Crystal reports to JReport reports.5. After conversion, a message box will pop up to ask you whether to open an converted report.6.

Converting Crystal Reports to JReport Reports

562

Page 575: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Converting One Crystal Report At One Time

Launch JReport Designer, go to the File menu, and click Open, or click the Open button on the standard toolbarto bring out the Open Report dialog.

1.

On the Existing tab, select the Other report types check box.2. Click the Browse button beside the Report Name text box, and the Open other types of report dialog pops up.

Open the folder which contains the Crystal reports, highlight the report you want and click Open. The selectedreport will be displayed in the Report Name text box with its full path.

3.

Click Open to convert the selected report and it will be opened automatically after conversion in JReportDesigner.

4.

Of course, you can also convert one report through the Import Crystal Reports dialog.

Note: If the Access database is used for the Crystal report to be converted, you can use the Crystal Converter to convertit easily. However, if some other database are used, you should do more work to make the conversion task completesuccessfully. For more information, please refer to the section Connecting to the Databases.

Converting a Report with Sub−report

In Crystal, the main report and sub−report are saved as one report, but in JReport Designer, they are saved separately.So when you convert a report that contains sub−reports, please follow the steps below:

In Crystal Reports, save the sub−report as a single report, using the name specified in the main report.1. In JReport Designer, convert the sub−report.2. Convert the main report. 3.

Notes:

The sub−reports must be converted before the main report. • Sometimes, two Crystal reports may contain a sub−report that has the same name but different report contents,•

Converting Crystal Reports to JReport Reports

563

Page 576: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

when you convert such reports, please make sure the two sub−reports can be used after conversion.

Converting Formulas

Sometimes, you have to convert the Crystal formulas syntax to JReport formulas syntax manually, because someformulas can not be correctly converted by the converter.

For detailed JReport formula syntax, please refer to JReport Designer User Reference | JReport Formula.

When manually converting the formulas, please note that:

The keyword Like in Crystal should be changed to LooksLike.• When a DBField has no record, different default value will be gotten in JReport report and Crystal report. InCrystal Report, we will get a value, while in JReport Designer, some codes should be added to get the samevalue, for example,

In Crystal Report{@Accessory Price}+{@Bicycle Price}

In JReport Designer, you should add codes like this manually,if (isnull(@"@Accessory Price")) return @"@Bicycle Price"else if (isnull(@"@Bicycle Price")) return @"@Accessory Price"else return @"@Accessory Price"+@"@Bicycle Price

If a summary is based on a formula whose syntax is not converted successfully, the summary cannot be insertedin the JReport report.

You'd better not use Formula as the variable name in Crystal report. If there is one, please change the namebefore conversion.

JReport Designer does not support While and Case statement in Crystal, so change While to For statement,and change Case to If else statement.

After the Crystal's condition formula is being converted into the formula which controls the property values inJReport, the formula will be checked wrong because it cannot be interpreted in JReport, so you have to modify itmanually. To help the user get the formula information, JReport Designer provides the detailed message in thedesg_log.txt file for your reference, which is the log file in the same folder as the converted report. For example,in Chart.rpt of Crystal samples,

In Crystal,if CurrentFieldValue < 10000 then Color (10, 19, 200)

The message shows in desg_log.txt:setControlFields("Chart.PagePanel1.GroupPanel #1.DetailPanel2.Customer_Last Year'sSales","Foreground","Field7_Color"): Illegal field name Field7_Color

In JReport,if (@"Customer_Last Year's Sales" < 10000 ) then "0x0a13c8"

Note: To obtain the value of Crystal color functions, such as Color (r, g, b) and RGB (r, g, b), you can use thefunction Integer.toHexString(new Color(r, g, b).getRGB()), use the real value to replace theparameters − r, g, and b.

In Crystal, calculation can be done between DateTime and Date, but it is not allowed in JReport Designer. In thiscase, you should use the ToDate formula in JReport to change DateTime to Date.

Functions that do not match in JReport Designer can not be converted.• When save the Crystal reports which have the formulas with the same name but different contents to onecatalog, the firstly inserted formula will be saved with the original name, but the later inserted formula will besaved with a changed name (an index will be added, e.g., the former formula will be saved with the name region,and the later one will be saved with a name region0).

Converting Crystal Reports to JReport Reports

564

Page 577: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

References

After you have installed JReport Designer with Crystal Converter, go to %JReportDesigner_InstallRoot%, and youwill find a folder called convertcryXX (XX: version number of Crystal Reports), which contains the conversion files forCrystal Reports. In this folder, there is a file named config.txt, open it and you will see all the conversion parameters.You can change the values of the parameters in this file if necessary. Below is the functions of each parameter in this file:

CRYSTAL_FILEThe default Crystal reports file path or name.

LOG_FILESets a name for the generated log files while converting reports. Meanwhile, the converting formula log(desg_log.txt), and JReport Catalog API log (cat_log.txt) will be generated. All the log files are located under thepath specified by the JREPORT_PATH parameter.

DETAIL_LOGA boolean value specifies whether to log the detailed information and whether to show the Java Console whenconverting reports. When the conversion is failed, the Java Console can show some tips about the problems.

After conversion, four log files have been generated at the location where the catalog of the converted reportsexists. The log files are cat_log.txt, desg_log.txt, fml_log.txt, and log.txt. If DETAIL_LOG is true,all the log information will be recorded into the log.txt file.

DB_PASSWORDSets a password, which is used to connect the database of Crystal reports, because we fail to get the passwordthrough Crystal API.

DB_SCHEMASpecifies the schema in database of the Crystal report if it hasn't been specified in Crystal. Please note that theschema name is case sensitive. The name specified in this option has higher priority than the name you get fromCrystal API.

DB_NAMESometimes, Crystal Converter cannot get the information of the database used by the crystal report, for example,when SQL Server database is used. This option is provided for you to specify the name of the databasemanually. The name specified in this option has higher priority than the name you get from Crystal API.

FORMULA_SYNTAXSpecifies the syntax type to parse the formula. Sets C for Crystal syntax, d B for BASIC syntax, otherwise, ignoreit.

Please note: If the syntax type is incorrectly specified, some errors will come up. If you cannot confirm the typeof the syntax, specify All or ignore it.

TABLE_CONNECTORSpecifies the connector sign between table name (it is not the name in the database but the name defined byCrystal) and column name in the converted catalog and reports.

Note: After reports are successfully converted, a catalog will be generated under the same directory. When youconvert the reports with another type of connector sign, the reports cannot be converted to this existed catalogunder the same directory. So if you want to use another connector sign, please create a new catalog in adifferent path first and then convert the reports to this new catalog.

ADVCHARTIf true, Crystal Advanced charts will be converted as Group charts.

The following types of charts can be converted, The group charts.♦ The advanced charts that are created in the form of For each record.♦ The advanced charts that are created in the form of On change of and show values of summaries, canbe converted as the group charts, if you have set the value of the parameter ADVCHART as true in theconfig.txt file.

Converting Crystal Reports to JReport Reports

565

Page 578: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Tips

For the reason of Crystal Report (Cannot get information from the Crystal API)

For the Default property value of some objects, the information can not be converted.• Hyperlink information for a field can not be converted.• If the query of the Crystal report is Distinct, because JReport Designer can not get the Select Distinct optionthrough Crystal API, after conversion, you will get the duplicate values. To get the unique value, please selectthe Select Distinct option manually in Query Editor of JReport Designer after conversion.

For the reason of JReport Designer

Some features, such as OLAP, and Alerting, can not be converted.• Crystal supports the report that has a date type row, which can be grouped by for each year, for eachquarter and printed the first date in the period or the last date in the period. In JReport, this function isimplemented by formulas. The CrossTab.rpt of Crystal samples is an example of this case.

For the join information among the tables, only the following two types can be converted: inner joins orjoins linked by =.

For the reason of the different implementation of the two products

OLE and MAP objects can not be converted.• The converted layout of Chart and Crosstab may be slightly different from the original layout.• If there is no embedded field in the Text Object, it is converted to a Label in JReport, but the line feed informationwill be lost. If there is embedded field in the Text Object, it is converted to a formula in JReport, but the formatinformation of the Text Object will be lost. If you want to remain the format information, you have to modify theformula in JReport Designer manually.

For example, in Crystal demo report Customer Profile.rpt, the Text Object Q1 Total Sales: Sum ofOrders.Order Amount will be converted in the formula like this: "Q1 Total Sales: " + @"Sum({Orders.Order Amount}, {@region})".

When you view the report, the format of the value returned by Orders.Order Amount is lost. Then you have tochange the formula to "Q1 Total Sales: " + Totext(@"Sum ({Orders.OrderAmount},{@region})","##,###.##").

Some objects in Crystal report can cross the page edge. JReport can convert this kind of report, but some errorswill occur. Thus you are strongly recommended that before conversion, do not make the Crystal report cross overthe page edge.

Trouble Shootings

After the installation of Crystal Converter, in JReport Designer, if the Crystal menu item and the Other reporttypes section on the Open Report dialog are still not available, please check whether%install_root%\convertcryXX has been added to the classpath of the file JReport.bat orsetevn.bat under %install_root%\bin.

• Sometimes, Crystal Converter may fail to convert some reports. The following ways are provided to help you tofigure out the problems:

Check whether you have installed the required products:

For Crystal Reports 8.5, please install cr85devwin.zip, which can be downloaded from the website ofCrystal Reports; For Crystal Reports 9, please install Crystal Report 9 Report Creation API License; For Crystal Reports 10, please use Crystal Reports Advanced Developer Edition with the ReportCreation API license.

1.

Converting Crystal Reports to JReport Reports

566

Page 579: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Please try to convert a Crystal demo report first to see whether your environment is ok. Please check that whether the version of the report you are going to convert is consistent with theversion of the converter.

2.

In config.txt file, which is under %JReportHome%\convertcryXX (XX: version number of CrystalReports), set the property DETAIL_LOG to true. During conversion, the Java Console will appear andwhen the conversion is failed, some tips of the problem will be shown in the javaConsole. Also, moredetailed log information will be recorded in the log.txt file, which is at the same location as the catalogof the converted reports.

3.

Launch JReport Designer from the Command Prompt window with the command line arguments−vDebug and −log.

For example, if you have installed JReport Designer under C:\JReport, use the commands listed belowto launch JReport Designer:

C:\cd JReport\binC:\JReport\bin>JReport −vDebug −log

−vDebug: Enables JReport Designer to output debug messages.−log: Enables JReport Designer to generate log file to record debug, error or other messages. Bydefault, the log file is named JReport.log under %JReportHome%\bin.

To launch JReport Designer in this way, you can also change the property of the JReport Designershortcut on the desktop and then launch it with the modified shortcut.

To change the property, right click the shortcut, click Properties on the pop−up menu, select theShortcut tab on the JReport Designer Properties dialog, and then in the Target text box, change theargument from −vError to −vDebug −log.

4.

If you really cannot resolve the problems, you can contact Jinfonet support. Please send as muchinformation as you can, such as the report has problems with, the database structure, the log files(generated when DETAIL_LOG=true) and so on.

5.

Index

Connecting to the Databases

The Crystal reports to be converted may use various databases through different connections, and when you convert thereport to JReport, you can also specify which database and which kind of connection to use. Thus, you have to do somework in advance to make the conversion work complete successfully. Please look at the table below:

Crystal Reports JReport Designer Convert Description

ODBC ODBC Automatically Configure Config.txt if necessary.

Non−ODBC ODBC AutomaticallySet up an ODBC driver to connect to thedatabase that has the same name with theCrystal reports'.

Any connections Non−ODBC ManuallySet up a database with the same name asthe Crystal reports' in the catalog which isused to save the converted report.

Note: The ODBC mentioned in the table refer to the ODBC that can be accessed bysun.jdbc.odbc.JdbcOdbcDriver.

As shown in the table above, it can be divided into the following cases:

Converting Crystal Reports to JReport Reports

567

Page 580: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

ODBC to ODBC

When you convert a report that uses ODBC to connect to its database, and you still want to use ODBC after conversion,you can convert the report directly, such as Microsoft Access database.

However please note that for some database, you have to specify some parameter values in config.txt under%JReport_InstallRoot%\convertcryXX before conversion. The parameters are DB_PASSWORD, DB_NAME, andDB_Schema.

DB_PASSWORD − The password of the database which is used by the report.DB_NAME − The name of the database which is used by the report.DB_Schema − The schema name in the database of the report.

Specify the values for the parameters that used by the database. For example, for the SQL Server database, you shouldspecify the DB_NAME and DB_PASSWORD, and for the Sybase database, you should only specify theDB_PASSWORD.

Note: When the next time you convert reports, please make sure these values have been modified or removed accordingto database the Crystal reports used, otherwise, the connection may fail to be added.

Non−ODBC to ODBC

When you convert a report that uses other connections not ODBC, and you want to use ODBC in JReport Designer afterconversion, before conversion, you have to set up an ODBC driver to connect to the database that has the same nameas the Crystal reports use. However, you'd better firstly check the default database whether is the database you used incurrent reports in ODBC Data Source Administrator Dialog.

For example, if the database name of the Crystal report is DBTest, and when you set up the ODBC driver for the system,in the Data Source Name text box, please type in DBTest.

If a password has been set for the database, before conversion, please also specify the value of DB_PASSWORD inconfig.txt.

Any Connections to Non−ODBC

No matter which kind of connection is used by the Crystal report, before conversion, you can set up a database with thesame name as the Crystal reports' in the catalog which is used to save the converted report.

However, before conversion, you must add the driver of the database the reports used in jreport.bat under%JReportHome%\bin.

Please follow the steps below to get the name of the database used by the Crystal report:

Set DETAIL_LOG=True in the config.txt file.1. Convert the report based on an existing catalog. The Crystal Converter will tell you that the conversion is failed. 2. Open the log.txt file at the directory, where the catalog exists, to get the database information.

For example, you may get information like this,

Find Connection == Fail to find connection:[DBTest] at [test.cat]Connection info == UserID:test; dbPsw:

In the log file above, the DBTest in the square brackets is the database name.

3.

To create the database in the catalog,

Converting Crystal Reports to JReport Reports

568

Page 581: JReport Designer - User's Guide · Table of Contents Editing a Report by Inserting Objects.....108

Open the catalog which is used to save the converted reports.1. Select a database node on the resource tree and then click the New DataSource button on the catalog toolbar(please do not use the Default database node).

2.

On the Input Data Source Name dialog, type the name of the database, and then click OK.3. Now you can convert the report.4.

Converting Crystal Reports to JReport Reports

569