Monday 21 August 2017

Moving Media Jfreechart Example


2009-08-06: liberazione di 0.6.0 viene rilasciato 2009-05-22: rilascio di 0.5.0 viene rilasciato 2009-03-16: rilascio della 0.5.0 beta. 2008-06-20: liberazione di 0.4.1, ri-lancio del sito Wiki e l'inclusione dei forum come pagine incorporate: User Forum e Developers Forum. Godetevi 2008-05-04 Appendium Ltd e LavaBlast sono lieti di annunciare il rilascio della versione 0.4.0 di StatSVN. Maggiori dettagli su questo blog e il changelog. 2007-03-10 Notizie. Come parte del rilascio 0.3.1, abbiamo avviato una serie di demo per alcuni progetti noti: Subversion, Formica, Log4J, Primavera Rich Client, Hibernate 3, Joda Tempo, Ruby, Groovy, Grails e Felix per iniziare. Vai avanti, ammettilo, hai sempre voluto sapere chi ha fatto cosa e quando su quei progetti. Avvertimento . se non sei utilizzando un locale inglese, impostare la variabile d'ambiente LANG per enUS quando si esegue l'applicazione fino a quando non risolvere alcuni problemi i18n con StatSVN (la chiamata a svn rendimenti diff una stringa localizzata che può portare a qualche risultato non essere memorizzati nella cache, i risultati sono corretti ma StatSVN chiederà loro di nuovo la prossima volta). 2007-02-07: Vuoi aiutare stavano prendendo in considerazione la sostituzione nostre invocazioni riga di comando con le chiamate a svnkit (ex JavaSVN). Vuoi scrivere la realizzazione del prototipo e vedere come si comporta Fateci sapere 2007-01-12: La versione 0.3.0 è in SVN e aggiunge 2 rapporti (RepoMap e LOCChurn), così come la fissazione di un certo numero di problemi con lo spostamento di file, directory e la cancellazione di quelli. Maggiori dettagli su questa pagina. 2006-11-28: La versione 0.2.0 è fuori e ora supporta HTML e la generazione xdoc per facilitare l'integrazione con Maven (vedi report qui). Sono stati inoltre lieta di dire che vi è un plugin Maven 2 usando StatSVN, è disponibile presso stat-scm. sourceforge. Tweet Tweet dagli Autori Quindi, qual è StatSVN Grandi statistiche per SVN StatSVN recupera informazioni da un repository Subversion e genera varie tabelle e grafici che descrivono lo sviluppo del progetto, ad esempio Timeline per le linee di righe di codice di codice per ogni sviluppatore durante il giorno Clock attività Autori Attività Autore per modulo Autore impegna Più recenti con collegamenti alle Statistiche ViewVC per directory del file contare dimensione del file file media file più grandi con la maggior parte delle revisioni Directory Taglie Repository Tag Numero di LOC per la versione. albero repository con conteggio dei file e righe di codice LOC e churn l'evoluzione del LOC e la quantità di cambiamento al giorno Repo Mappa la vista gerarchica dinamica del pronti contro termine per gli ultimi 30 giorni La versione corrente di StatSVN genera una serie statica di documenti HTML contenenti tabelle e immagini grafico. StatSVN è un software open source, rilasciato sotto i termini della licenza LGPL, sulla base di StatCVS. StatSVN utilizza JFreeChart per generare charts. Where è il manuale Il manuale è disponibile on-line come un wiki ed è come up-to-date e completa come si vuole che sia. Esempio rapido per Maven 1 Prima di eseguire sito Maven (o semplicemente xdoc Maven), è possibile generare i file xdoc eseguendo: (non dimenticate - v). Questo esempio genererà xdoc nella directory sitestatsvn, tag 0.2.0, 0.1.3, 0.1.2, 0.0.9, escludere qalab. xml e altri. Dopo che il xdoc sarebbe stata ripresa da sito Maven o Maven xdoc. Si prega di notare che per poter utilizzare i tag, è necessario utilizzare un file di registro non a livello del tronco, ma appena al di sopra, al fine di includere la directory tag. Al momento, StatSVN funziona solo con directory tag. Esempio veloce di nuova discarica C'è un nuovo impianto di scarico (non dimenticare - v). Questo genererà una grande quantità di output, ma alla fine questo, se mostra OK per tutto ciò che è probabile che StatSVN correttamente inteso proprio repository: JasperReports - Guida rapida JasperReports - Come JasperReports introduttiva - JasperReports configurazione dell'ambiente - JasperReports del ciclo di vita - Designs JasperReports - Compilazione report di progettazione JasperReports - riempimento report Jasper report - Visualizza amp stampare report JasperReports - Esportazione report report Parameters Se impostato java. lang. Boolean. TRUE il rapporto sarà generato in una pagina lunga e interruzione di pagina non si verificherà. Passiamo ReportTitle e autore della relazione (generato da JasperReportFill. java). Revised file C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java è la seguente meno i contenuti del file POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java è come qui sotto meno il contenuto del file C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java sono i dato inferiore a meno Consente di aggiungere i parametri ReportTitle gt lt e lt Autore GT al nostro modello di report esistente (Capitolo rapporto disegni). Il Rapporto titolo e autore verranno visualizzati all'inizio del rapporto. Il modello di relazione modificata (jasperreporttemplate. jrxml) è il seguente. Salvarlo in C: directory toolsjasperreports-5.0.1test meno Generazione di report Vi compilare ed eseguire il file di cui sopra utilizzando il nostro normale processo di compilazione ANT. Il contenuto del file di build. xml (salvato nella directory C: toolsjasperreports-5.0.1test) sono le seguenti. Il file di importazione - baseBuild. xml viene prelevata dal Setup Ambiente capitolo e deve essere collocato nella stessa directory del build. xml. Avanti, lascia finestra della riga di comando di apertura e passare alla directory in cui è collocato build. xml. Infine, eseguire il comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport è la destinazione predefinita) come segue meno Come risultato della compilazione sopra, una finestra JasperViewer apre come mostrato nella seguente schermata minus Qui, vediamo che la ReportTitle elenco di contatti e autore Preparato da Manisha vengono visualizzati all'inizio del rapporto. Origini dati del report Datasources sono contenitore di dati strutturati. Mentre la generazione del rapporto, il motore JasperReports ottiene i dati dalle origini dati. I dati possono essere ottenuti dai database, file XML, array di oggetti, e la raccolta di oggetti. Abbiamo visto nelle relazioni capitolo riempimento. il metodo fillReportXXX () si aspetta di ricevere una fonte di dati del rapporto, che deve compilare, in forma di oggetto o di un net. sf. jasperreports. engine. JRDataSource java. sql. Connection (quando i dati del report si trova in una database relazionale). L'interfaccia JRDataSource ha solo due metodi, che dovrebbe essere attuato meno public boolean successivo () genera JRException Al rapporto riempire il tempo, questo metodo viene chiamato sull'oggetto di origine di dati da parte del motore di reporting quando scorrendo i dati. Oggetto pubblico GetFieldValue (JRField jrField) getta JRException Questo metodo fornisce il valore di ogni campo del report nel record origine dati corrente. L'unico modo per recuperare i dati dall'origine dati è quello di utilizzare i campi del report. Ci sono diverse implementazioni di default dell'interfaccia JRDataSource, a seconda del modo in cui, i record nell'origine dati vengono acquisiti. Implementazioni DataSource tabella riportata di seguito riassume i origini dati e le loro classi di implementazione meno JDBC Data Sources Classe JRResultSetDataSource craps un oggetto java. sql. ResultSet. Questo è il più comunemente usato implementazioni origine dati quando i dati del report sono estratti da un database relazionale. Se un java. sql. Connection viene passato al motore, invece, viene eseguito prima della relativa query e memorizza l'oggetto java. sql. ResultSet restituito in un'istanza JRResultSetDataSource. Fonti dati JavaBean classi JRBeanArrayDataSource e JRBeanCollectionDataSource rappresentano implementazioni che può avvolgere gli array e collezioni di oggetti JavaBean. Ogni oggetto all'interno della matrice o la raccolta sarà visto come un record in questo tipo di origine dati. La mappatura tra una particolare proprietà JavaBean e il campo corrispondente relazione è fatta da convenzioni di denominazione. Il nome del campo del report deve essere lo stesso del nome della proprietà JavaBean come specificato dalle specifiche JavaBeans. In tutti gli esempi di questo tutorial, abbiamo utilizzato JRBeanCollectionDataSource. Mappa a base Origini dati Le classi di implementazione JRMapArrayDataSource e JRMapCollectionDataSource sono utili se l'applicazione principale memorizza già i dati di reporting disponibili in memoria come oggetti java. util. Map. Ogni oggetto Map nella matrice o la raccolta avvolto è considerato un record virtuale nella fonte di dati, e il valore di ogni campo del report viene estratto dalla mappa utilizzando il campo report denominato come la chiave. TableModel origini dati In molte applicazioni sul lato client, i dati viene visualizzato in formato tabulare. Un requisito comune in molte applicazioni è quello di permettere all'utente di stampare questa tabella come rapporto. classe di implementazione JRTableModelDataSource rende il compito di generare report dal formato tabellare banale per applicazioni Swing. Questa classe avvolge un oggetto javax. swing. table. TableModel. Colonne nell'oggetto TableModel avvolto è possibile accedere sia con il loro nome o dai loro indici 0-based. Origini dati XML Class JRXmlDataSource è un'implementazione fonte di dati sulla base di DOM, che utilizza espressioni XPath per selezionare i dati dal documento XML. Record nell'origine di dati XML sono rappresentati da elementi nodo selezionato attraverso l'espressione XPath. I valori dei campi vengono recuperati da ogni record utilizzando l'espressione XPath fornito dalla descrizione del campo (elemento ltfieldDescriptiongt in jrxml). XPath è un linguaggio utilizzato per navigare attraverso un documento XML attributi ed elementi. Maggiori informazioni su XPath può essere trovato alla w3.orgTRxpath. CSV Origini dati JRCsvDataSource rappresenta un'implementazione per fonti di dati, il quale recuperare i propri dati da file di testo strutturati di solito CSV. I valori dei campi vengono recuperati utilizzando il loro indice di colonna. XLS Origini dati JRXlsDataSource rappresenta un'implementazione per fonti di dati, che recuperano i dati da documenti di Excel. mappatura Report-campo per questa implementazione origine dati si basa anche su l'indice di colonna campo. Vuote Fonti dei dati La classe JREmptyDataSource. simula una sorgente di dati con un determinato numero di record vuoti virtuali all'interno. E 'utilizzato dagli strumenti di interfaccia utente per offrire funzionalità di base rapporto anteprima, o in modelli di report speciali, o per scopi di test e debug. Riavvolgibile Fonti dei dati La net. sf. jasperreports. engine. JRRewindableDataSource estende l'interfaccia di base JRDataSource. Si aggiunge solo un metodo, chiamato moveFirst (), all'interfaccia. Questo metodo è destinato per spostare il cursore sul primo elemento nell'origine dati. fonti di dati riavvolgibili sono utili quando si lavora con sotto-report posizionati all'interno di una band che non è consentito di dividere a causa dell'impostazione isSplitAllowedfalse e non c'è abbastanza spazio nella pagina corrente per il rapporto di sub per essere reso. Tutte le suddette implementazioni delle origini dati sono riavvolgibile ad eccezione del JRResultSetDataSource. in quanto non supporta spostando il puntatore del record indietro. Ciò pone un problema solo se questa fonte di dati sono utilizzati manualmente per avvolgere una java. sql. ResultSet prima di passarlo al sub-report. Non c'è nessun problema, se la query SQL risiede nel modello di sub-report, come il motore eseguirà nuovamente quando si riavvia il sub-report nella pagina successiva. Provider origine dati La biblioteca JasperReports ha un net. sf. jasperreports. engine. JRDataSourceProvider interfaccia. Questo aiuta nella creazione e lo smaltimento di oggetti di origine dei dati. Quando si crea un modello di report utilizzando strumenti grafici, è necessario uno speciale strumento per personalizzare la fonte riporta dati. JRDataSourceProvider è il modo standard per collegare sorgenti di dati personalizzate in uno strumento di progettazione. Una implementazione personalizzata di questa interfaccia deve implementare i seguenti metodi che permettono di creare e lo smaltimento di oggetti di origine dei dati e anche i metodi per elencare i campi del report disponibili all'interno della sorgente di dati, se possibile, meno Rapporti campi Campi report sono elementi che rappresentano la mappatura dei dati tra datasource e riferire modello. I campi possono essere combinati nelle espressioni del report per ottenere il risultato desiderato. Un modello di rapporto può contenere zero o più elementi ltfieldgt. Quando si dichiara campi del report, l'origine dei dati deve fornire i dati corrispondenti a tutti i campi definiti nel modello di rapporto. dichiarazione Campo Dichiarazione campo è fatto come illustrato di seguito meno il nome dell'attributo L'attributo nome dell'elemento ltfieldgt è obbligatoria. Si fa riferimento al campo nelle espressioni del report per nome. La classe Attributo L'attributo class specifica il nome della classe per i valori del campo. Il suo valore di default è java. lang. String. Questo può essere cambiato in qualsiasi classe disponibile in fase di esecuzione. Indipendentemente dal tipo di un campo rapporto, il motore si occupa di fusione nelle espressioni del report in cui viene utilizzato il token F, rendendo quindi inutile manuale getta. Campo Descrizione L'elemento ltfieldDesciptiongt è un elemento opzionale. Questo è molto utile quando si implementa una fonte di dati personalizzato. Ad esempio, siamo in grado di memorizzare una chiave o di alcune informazioni, con la quale siamo in grado di recuperare il valore del campo dall'origine dati personalizzati in fase di esecuzione. Utilizzando l'elemento ltfieldDesciptiongt al posto del nome del campo, si può facilmente superare le restrizioni di convenzioni campo di denominazione quando si recuperano i valori dei campi dalla sorgente dati. Di seguito è un pezzo di codice dal nostro file jrxml esistente (Capitolo Rapporto disegni). Qui, possiamo vedere l'uso del nome. classe . e gli elementi fieldDescription. Ordina campi nei momenti in cui è richiesto l'ordinamento dei dati e l'implementazione origine dati pretende lo supporta (per esempio CSV origine dati), JasperReports supporta in memoria fonte di dati di campo basati su ordinamento. L'ordinamento può essere fatto utilizzando uno o più elementi ltsortFieldgt nel modello di rapporto. Se non viene specificato almeno un campo di ordinamento, durante il processo di rapporto di riempimento, l'origine dei dati viene passato a un'istanza JRSortableDataSource. Questo a sua volta, recupera tutti i record dall'origine dati, si esibisce in memoria di ordinamento in base ai campi specificati, e sostituisce l'origine dati originale. Il nome del campo di ordinamento deve essere identico al nome del campo del report. I campi utilizzati per l'ordinamento dovrebbe avere tipi che implementano java. utilparable. ordinamento ordine naturale viene eseguita per tutti i campi ad eccezione di quelli di tipo java. lang. String (per il tipo String, raccoglitrice corrispondente al locale rapporto di riempimento è utilizzato). Quando vengono specificati diversi campi di ordinamento, l'ordinamento verrà eseguita utilizzando i campi come chiavi di ordinamento nell'ordine in cui compaiono nel modello di rapporto. Seguendo l'esempio dimostra la funzione di ordinamento. Ordinati Relazione Esempio Consente aggiungere l'elemento gt lt SortField al nostro modello di report esistente (Capitolo Rapporto disegni). Consente di campo di ordinamento Paese in ordine decrescente. Il modello di relazione modificata (jasperreporttemplate. jrxml) è il seguente. Salvarlo in C: directory toolsjasperreports-5.0.1test meno i codici Java per il riempimento rapporto rimane invariato. Il contenuto del file C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java sono come indicato di seguito meno il contenuto del file POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java sono come indicato di seguito meno il contenuto del file C: toolsjasperreports-5.0. 1testsrccomtutorialspointDataBeanList. java sono come indicato di seguito meno Relazione generazione Vi compilare ed eseguire il file di cui sopra utilizzando il nostro normale processo di compilazione ANT. Il contenuto del file di build. xml (salvato nella directory C: toolsjasperreports-5.0.1test) sono come indicato di seguito. Il file di importazione - baseBuild. xml viene prelevato dal capitolo Configurazione ambiente e deve essere collocato nella stessa directory del build. xml. Avanti, lascia finestra della riga di comando di apertura e passare alla directory in cui è collocato build. xml. Infine, eseguire il comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport è la destinazione predefinita) come segue meno Come risultato della compilazione sopra, una finestra JasperViewer si apre, come mostrato nella schermata indicato di seguito meno Qui, possiamo vedere che i nomi dei paesi sono disposti in ordine decrescente in ordine alfabetico. Espressione report report espressioni sono le potenti funzionalità di JasperReports, che ci permettono di visualizzare i dati calcolati in un report. dati calcolati sono i dati che non è un dato statico e non è specificamente passato come parametro di report o un campo di origine dati. espressioni report vengono costruite dalla combinazione di parametri del report, campi e dati statici. Il linguaggio Java è utilizzato per la scrittura di espressioni di report per impostazione predefinita. Altri linguaggi di scripting per le espressioni di report come Groovy linguaggio di scripting, JavaScript, o uno script BeanShell sono supportati da JasperReports compilatori. In questo capitolo vi spiegherà meno come si fa riferire le espressioni di lavoro, partendo dal presupposto che essi sono stati scritti utilizzando solo il linguaggio Java. In un modello di rapporto jrxml, ci sono diversi elementi che definiscono espressioni come meno ltvariableExpressiongt ltinitialValueExpressiongt ltgroupExpressiongt ltprintWhenExpressiongt ltimageExpressiongt lttextFieldExpressiongt Dichiarazione Espressione In sostanza, tutte le espressioni del report sono espressioni Java, che possono fare riferimento i campi del report, le variabili di report e parametri del report. Il campo di riferimento in un'espressione Per utilizzare un riferimento campo del report in un'espressione, il nome del campo deve essere messo tra F e carattere sequenze, come illustrato di seguito meno seguito è un pezzo di codice dal nostro file esistente jrxml (capitolo Rapporto disegni) meno variabile Riferimento in Expression fare riferimento a una variabile in un'espressione, occorre mettere il nome della variabile tra il V e come illustrato nell'esempio di sotto di meno parametri di riferimento in Expression fare riferimento a un parametro in un'espressione, il nome del parametro deve essere messo tra P e come illustrato nell'esempio di sotto di meno seguito è un pezzo di codice dal nostro file jrxml esistente, che dimostra il riferimento del parametro in un'espressione. (Jrxml dal capitolo Rapporto Design) meno Come avete visto sopra, il parametro di campo, e riferimenti variabili sono in veri e propri oggetti Java fatto. Conoscendo la loro classe dal parametro, campo, o dichiarazione di variabile fatta nel modello di rapporto, possiamo anche chiamare i metodi su tali riferimenti agli oggetti nelle espressioni. L'esempio seguente mostra meno come estrarre e visualizzare la prima lettera da java. lang. String campo del report Nome meno riferimento risorsa Bundle in Expression Per fare riferimento a una risorsa in un'espressione, la chiave deve essere messo tra R e, come mostrato nell'esempio dato inferiore a meno Basato sul locale runtime-in dotazione e la chiave report. title, il raggruppamento di risorse associato al modello di report viene caricato. Da qui, il titolo del report viene visualizzato estraendo il valore stringa dal pacchetto di risorse. Altro su internazionalizzazione possono essere trovate nel capitolo Internazionalizzazione. Calcolatrice Calcolatrice è un'entità in JasperReports, che valuta le espressioni e gli incrementi variabili o insiemi di dati in fase di rapporto di riempimento. Durante il processo di compilazione, l'informazione viene prodotto e conservato nella relazione di compilazione dal compilatore. Questa informazione viene utilizzata durante il tempo di rapporto di riempimento di costruire un'istanza della classe net. sf. jasperreports. engine. fill. JRCalculator. file sorgente Java viene generato e compilato dai compilatori del rapporto basati su Java al volo. Questa classe generato è una sottoclasse del JRCalculator, e il bytecode prodotto dalla compilazione viene memorizzato all'interno dell'oggetto JasperReport. Questo bytcode viene caricato il rapporto tempo di riempimento e la classe risultante viene creata un'istanza per ottenere l'oggetto calcolatrice necessario per la valutazione delle espressioni. Le espressioni condizionali JasperReports doesnt supporto if-else la definizione delle espressioni variabili. Invece, è possibile utilizzare gli operatori ternari. . . Questo operatore può essere nidificato all'interno di un'espressione Java per ottenere il risultato desiderato in base a più condizioni. Esempio di espressione condizionale in rapporto consente modificare modello di report esistente (Capitolo Relazione disegni) e aggiungere una espressione condizionale per il paese campo. Il modello di relazione modificata (jasperreporttemplate. jrxml) è il seguente. Salvarlo in C: directory toolsjasperreports-5.0.1test meno i codici Java per il riempimento rapporto sono i seguenti. Il contenuto del file C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java sono i meno Il contenuto del file di POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java sono i meno Noi aggiungeremo un nuovo record con il campo di paese vuoto nel nostro bean Java Elenco. Il contenuto del file C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java sono i meno generazione di report Vi compilare ed eseguire il file di cui sopra utilizzando il nostro normale processo di compilazione ANT. Il contenuto del file di build. xml (salvato nella directory C: toolsjasperreports-5.0.1test) sono riportati di seguito. Il file di importazione - baseBuild. xml viene prelevato dal capitolo Setup ambiente e deve essere collocato nella stessa directory del build. xml. Avanti, lascia finestra della riga di comando di apertura e passare alla directory in cui è collocato build. xml. Infine, eseguire il comando ant - Dmain classe com. tutorialspoint. JasperReportFill (viewFullReport è la destinazione predefinita) come meno Come risultato della compilazione sopra, una finestra JasperViewer si apre, come mostrato nella schermata indicato di seguito meno Qui, possiamo vedere, per l'ultimo record, non avevamo superato tutti i dati per il paese campo, nessun paese è in fase di stampa. Rapporto variabili del report variabili sono oggetti speciali costruite in cima alla un'espressione del report. variabili del report semplificano i seguenti compiti meno espressioni di report, che sono pesantemente utilizzati in tutto il modello di rapporto. Queste espressioni possono essere dichiarate solo una volta, utilizzando le variabili del report. variabili del report possono eseguire vari calcoli in base ai valori corrispondenti espressioni quali conteggio, somma, media, bassa, alta, varianza, ecc Se le variabili sono definite in un design rapporto, allora questi possono essere referenziati da nuove variabili nelle espressioni. Quindi, l'ordine in cui le variabili sono dichiarate in un disegno relazione è importante. Variabile Dichiarazione Una dichiarazione di variabile è il seguente meno Come visto in precedenza, elemento ltvariablegt contiene il numero di attributi. Questi attributi sono riassunte qui di seguito meno il nome dell'attributo Simile ai parametri e campi. l'attributo nome dell'elemento ltvariablegt è obbligatoria. Permette riferimento alla variabile con il suo nome dichiarato nelle espressioni del report. La classe Attributo L'attributo class è anche obbligatorio che specifica il nome della classe per i valori delle variabili. Il suo valore di default è java. lang. String. Questo può essere cambiato in qualsiasi classe disponibile nel classpath, sia al momento rapporto-compilazione e il rapporto tempo di riempimento. Il motore si prende cura di tipo-casting nelle espressioni di report cui viene utilizzato il token V, non è necessario, quindi, manuale di tipo-casting. Calcolo Questo attributo determina meno quello di calcolo per eseguire sulla variabile durante il riempimento del rapporto. Le seguenti sottosezioni descrivono tutti i valori possibili per l'attributo calcolo dell'elemento ltvariablegt. minus medio Il valore della variabile è la media di ogni valore non nullo della espressione variabile. Valido solo per le variabili numeriche. Count meno il valore della variabile è il conteggio delle istanze non nulli dell'espressione variabile. In primo luogo meno il valore della variabile è il valore della prima istanza dell'espressione variabile. I valori successivi vengono ignorati. Massima meno il valore variabile è il valore più alto per l'espressione variabile. Più basso meno il valore variabile è il valore più basso per l'espressione variabile nel rapporto. Niente meno Nessun calcolo vengono eseguiti sulla variabile. Standarddeviation meno il valore della variabile è la deviazione standard di tutti i valori non nulli che corrispondono l'espressione del report. Valido solo per le variabili numeriche. Somma meno il valore della variabile è la somma di tutti i valori non Null restituiti dall'espressione rapporto. Sistema di meno il valore della variabile è un calcolo personalizzato (il calcolo del valore di tale variabile da soli, utilizzando le funzionalità scriptlet di JasperReports). Varianza meno il valore della variabile è la varianza di tutti i valori non Null restituiti dalla valutazione dell'espressione variabili del report. Incrementer factoryClass Questo attributo determina la classe utilizzata per calcolare il valore della variabile durante il riempimento del record corrente sulla relazione. Il valore di default sarebbe qualsiasi classe che implementa net. sf. jasperreports. engine. fill. JRIncrementerFactory. La classe di fabbrica sarà utilizzato dal motore per istanziare oggetti incrementatore in fase di esecuzione in base al calcolo di attributi per la variabile. IncrementType Ciò determina quando ricalcolare il valore della variabile. Questo attributo utilizza valori, come sotto meno Colonna meno il valore della variabile viene ricalcolato alla fine di ogni colonna. Gruppo meno il valore della variabile viene ricalcolato quando il gruppo specificato dal incrementGroup cambia. Nessuno meno il valore della variabile viene ricalcolato con ogni record. Pagina meno il valore della variabile viene ricalcolato alla fine di ogni pagina. Relazione meno il valore della variabile viene ricalcolato volta, alla fine della relazione. IncrementGroup Questo determina il nome del gruppo in cui il valore della variabile viene ricalcolato, quando incrementType è Gruppo. Questo prende nome di un gruppo dichiarato nel modello di rapporto jrxml. Questo determina quando il valore di una variabile viene ripristinata. Questo attributo utilizza valori, come sotto meno Colonna meno il valore della variabile viene azzerato all'inizio di ogni colonna. Gruppo meno il valore della variabile viene resettato quando il gruppo specificato dai cambiamenti incrementGroup. Nessuno meno il valore della variabile non viene mai azzerato. Pagina meno il valore della variabile viene azzerato all'inizio di ogni pagina. Relazione meno il valore della variabile viene azzerato solo una volta, all'inizio del report. ResetGroup Questo determina il nome del gruppo in cui il valore della variabile viene azzerato, quando resetType è Gruppo. I valori di questo attributo sarebbe il nome di un gruppo dichiarato nel modello di rapporto jrxml. Built-In variabili del report Ci sono alcune variabili di sistema built-in, pronti per l'uso nelle espressioni, come segue meno Nome variabile e descrizione Questo valore delle variabili è il suo numero di pagina corrente. Può essere utilizzato per visualizzare sia il numero di pagina corrente e il numero totale di pagine utilizzando una speciale funzione di JasperReports elementi di campo di testo, l'attributo evaluationTime. Il nome di questa variabile è derivato dal nome del gruppo corrisponde a, suffisso con la sequenza COUNT. Questa variabile contiene il numero di record nel gruppo corrente. Consente di aggiungere una variabile (NumeroConteggio) al nostro modello di report esistente (Capitolo Rapporto disegni). Noi prefisso il conteggio di ogni record. Il modello di relazione modificata (jasperreporttemplate. jrxml) è il seguente. Salvarlo in C: directory toolsjasperreports-5.0.1test meno i codici Java per il riempimento rapporto rimane invariato. Il contenuto del file C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java sono come indicato di seguito meno il contenuto del file POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java sono come indicato di seguito meno il contenuto del file C: toolsjasperreports-5.0. 1testsrccomtutorialspointDataBeanList. java sono come indicato di seguito meno generazione di report Vi compilare ed eseguire il file di cui sopra utilizzando il nostro normale processo di compilazione ANT. Il contenuto del file di build. xml (salvato nella directory C: toolsjasperreports-5.0.1test) sono come indicato di seguito. Il file di importazione - baseBuild. xml viene prelevata dal Setup Ambiente capitolo e deve essere collocato nella stessa directory del build. xml. Avanti, lascia finestra della riga di comando di apertura e passare alla directory in cui è collocato build. xml. Infine, eseguire il comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport è la destinazione predefinita) come meno Come risultato della compilazione sopra, una finestra si apre JasperViewer come nella schermata sotto di meno Qui, si vede che il conteggio è prefissato per ogni record. Rapporto Sezioni Abbiamo discusso la struttura di un semplice modello di rapporto nel capitolo Per iniziare. Sulle linee simili, strutture JasperReports il modello di report in più sezioni. Le sezioni sono parti del rapporto che hanno un'altezza specificata e può contenere oggetti report come linee, rettangoli, immagini o campi di testo. I itera motore di reporting attraverso i registri virtuali della sorgente dati del report fornito, in rapporto di tempo di riempimento. A seconda di ogni sezioni comportamento definito, il motore poi rende ogni sezione del report al momento opportuno. Ad esempio, la sezione particolare è reso per ogni record nell'origine dati. Quando si verificano le interruzioni di pagina, le sezioni pagina intestazione e piè pagina sono resi in base alle esigenze. In JasperReports, sezioni terminologia e report sono anche chiamati come bande di report. Le sezioni sono costituite da una o più bande. Queste sezioni sono riempiti più volte al momento di relazioni, e preparare il documento finale. Le sezioni principali un modello di rapporto in JasperReports ha le seguenti sezioni principali minus La tabella seguente riassume ciascuna delle sezioni meno Altezza della sezione specifica l'altezza in pixel per quella sezione particolare ed è molto importante nel disegno complessivo rapporto. Stampa Quando Espressione Un'espressione booleana che determina se la sezione deve essere stampato o meno. Split consentito un flag che indica se la sezione è permesso di dividere quando non si adatta nella pagina corrente. Se fosse vero, la sezione sarà trasferito alla pagina successiva. Si noti che nel caso in cui, la sezione non si adatta alla pagina successiva, quindi la sezione sarà divisa indipendentemente dal valore bandiere. splitType può assumere i seguenti valori meno splitTypeStretch: Divide allungato contenuti. Se la sezione si estende sulla pagina corrente (se lo spazio disponibile è inferiore altezza dichiarato), la regione che viene aggiunto l'altezza originale è permesso di dividere nella pagina successiva. splitTypePrevent: Impedire diviso al primo tentativo. Se la sezione non si adatta alla pagina seguente, la scissione avviene normalmente, come la prevenzione banda split è efficace solo al primo tentativo di divisione. splitTypeImmediate: Split immediatamente. La band è permesso di dividere ovunque tranne sopra, il suo elemento più in alto. Per dimostrare ogni sezione, consente di modello di rapporto di scrittura (jasperreporttemplate. jrxml). Salvare il file di directory C: toolsjasperreports-5.0.1test. In questo file, ci sarebbe la visualizzazione di un testo in ciascuna delle sezioni (abbiamo discusso in precedenza). Il contenuto del file sono come indicato di seguito meno il codice Java per compilare e generare il report è riportata qui sotto. Consente di salvare il file JasperReportFill. java di directory C: toolsjasperreports-5.0.1testsrccomtutorialspoint. Qui, si usa un'istanza di JREmptyDataSource durante la compilazione report per simulare una fonte di dati con un record in esso, ma con tutti i campi di questo singolo record di essere nullo. Generazione di rapporti Vi compilare ed eseguire il file di cui sopra utilizzando il nostro normale processo di compilazione ANT. Il contenuto del file di build. xml (salvato nella directory C: toolsjasperreports-5.0.1test) sono le seguenti. Il file di importazione - baseBuild. xml viene prelevato dal Setup Ambiente capitolo e deve essere collocato nella stessa directory del build. xml. Avanti, lascia finestra della riga di comando di apertura e passare alla directory in cui è collocato build. xml. Infine, eseguire il comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport è la destinazione predefinita) come segue meno Come risultato della compilazione sopra, una finestra si apre JasperViewer come nella schermata sotto di meno Qui, possiamo vedere in ciascuna delle the sections a text is printed. It is to be noted that as JRXML contains a ltlastPageFootergt element, it will be displayed in the last page of the report instead of the ltpageFootergt element being displayed. The ltcolumnHeadergt and ltcolumnFootergt elements will only be displayed on the report, if it has more than one column. Report Groups Groups in JasperReports help to organize data on report in a logical manner. A report group represents a sequence of consecutive records in the data source, which have something in common, such as the value of a certain report fields. A report group is defined by the ltgroupgt element. A report can have any number of groups. Once declared, groups can be referred throughout the report. A report group has three elements minus Group expression minus This indicates the data that must change to start a new data group. Group header section minus Helps place label at the beginning of the grouped data. Group footer section minus Helps place label at the end of the grouped data. During the iteration through the data source at report-filling time if the value of the group expression changes, a group rupture occurs and the corresponding ltgroupFootergt and ltgroupHeadergt sections are inserted in the resulting document. Report group mechanism does not perform any sorting on the data supplied by the data source. Data grouping works as expected only when the records in the data source are already ordered according to the group expressions used in the report. Group Attributes The ltgroupgt element contains attributes that allow us to control how grouped data is laid out. The attributes are summarized in table below minus Attribute and Description This is mandatory. It references the group in report expressions by name. It follows the same naming conventions that we mentioned for the report parameters, fields, and report variables. It can be used in other JRXML attributes when you want to refer a particular report group. When set to true . each data group will begin on a new column. Default value is false . When set to true . prevents the group from splitting on its first break attempt. Lets add a group ( CountryGroup ) to existing report template (Chapter Report Designs ). Occurrence of each country is counted and the count is displayed as the group footer. In the group header, the count of each record is prefixed. The revised report template (jasperreporttemplate. jrxml) is as follows. Save it to C:toolsjasperreports-5.0.1test directory minus The java codes for report filling remains unchanged. The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java are as given below minus The contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java are as below minus The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java are as given below minus Report Generation We will compile and execute the above file using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as below. The import file - baseBuild. xml is picked up from chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport is the default target) as minus As a result of above compilation, a JasperViewer window opens up as in the screen below minus Here, we see that the each country is grouped and the count of occurrence of each country is displayed at the footer of each group. Report Fonts A report contains text elements and each of these can have its own font settings. These settings can be specified using the lt font gt tag available in the lttextElementgt tag. A report can define a number of fonts. Once defined, they can be used as default or base font settings for other font definitions throughout the entire report. Report Fonts A report font is a collection of font settings, declared at the report level. A report font can be reused throughout the entire report template when setting the font properties of text elements. Report fonts are now deprecated. Do not use ltreportFontgt elements declared within the document itself. Use the ltstylegt element instead. Font Attributes Table below summarizes the main attributes of the lt font gt element minus The flag that specifies whether the font should be embedded into the document itself. It defaults to false. If set to true, helps view the PDF document without any problem. Font Types In JasperReports fonts can be categorized as minus Logical Fonts minus Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are minus Serif, SansSerif, Monospaced, Dialog, and DialogInput . These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system. Physical Fonts minus These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts. Font Extensions minus The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales. As described in the table above we need to specify in the attribute fontName the name of a physical font, the name of a logical font, or the name of a font family from the registered JasperReports font extensions. PDF Font Name JasperReports library uses the iText library, when exporting reports to PDF(Portable Document Format). PDF files can be viewed on various platforms and will always look the same. This is partially because in this format, there is a special way of dealing with fonts. fontName attribute is of no use when exporting to PDF. Attribute pdfFontName exist where we need to specify the font settings. The iText library knows how to deal with built-in fonts and TTF files and recognizes the following built-in font names minus Courier Courier-Bold Courier-BoldOblique Courier-Oblique Helvetica Helvetica-Bold Helvetica-BoldOblique Helvetica-Oblique Symbol Times-Roman Times-Bold Times-BoldItalic Times-Italic ZapfDingbats As per iText library pre-requisite, to work with fonts, we need to specify one of the following as the font name minus A built-in font name from the above list. The name of a TTF (True Type Font) file, which it can locate on disk. The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered. Based on the above pre-requisites, the pdfFontName attribute can contain one of the following values minus The name of a built-in PDF font from the above list. The name of a TTF file that can be located on disk at runtime when exporting to PDF. The real name of a registered font. The suffix of the key (the part after net. sf. jasperreports. export. pdf. font ) for a font registered with iText as a font file. Default Fonts and Inheritance Each text element inherits font and style attributes from its parent element, which in turn inherits these attributes from its parent. If no styles andor fonts are defined for elements, the default style (andor font - but this is now deprecated) declared in the ltjasperReportgt root element will be applied. Defining default styles or fonts in JasperReports is not mandatory. If no font is defined for a given element, the engine looks either for the inherited font attributes, or, if no attributes are found on this way, it looks for the net. sf. jasperreports. default. font. name property in the srcdefault. jasperreports. properties file. Its value defines the name of the font family to be used when font properties are not explicitly defined for a text element or inherited from its parent. The main default font properties and their values defined in the srcdefault. jasperreports. properties file are in the table below minus By default PDF fonts are not embedded. To demonstrate using fonts and font attributes in order to get a particular text appearance, lets write new report template (jasperreporttemplate. jrxml). The contents of the JRXML are as below. Save it to C:toolsjasperreports-5.0.1test directory. Here, we will display a text in the title of the report in various font formats. The java code to fill and generate the report is as given below. Lets save this file JasperFontsReportFill. java to C:toolsjasperreports-5.0.1testsrccomtutorialspoint directory. Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields being null . Report Generation We will compile and execute the above file using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as given below. The import file - baseBuild. xml is picked from chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. JasperFontsReportFill (viewFullReport is the default target) as minus As a result of above compilation, a JasperViewer window opens up as shown in the screen given below minus Here, we can see that the text Welcome to TutorialsPoint is displayed in different font formats. Unicode Support In JasperReports, working with texts needs some dedicated tools to process both the character representations and the text formatting properties. Any text can be considered as a character sequence with a particular representation structure. The text appearance consists in both layout (and paragraph) and font settings. But while in most cases, the text layout remains invariant, font settings may change when running the report in different Locales. We know that different languages need different character sets with respect to specific characters representation. Therefore, working with texts means working with fonts. However, a detailed discussion about how to use fonts in JasperReports is available in the chapter Report Fonts . One of the main features concerning the text content in a given report is the possibility to internationalize it. It means, we can run the report in different localized environments, using different languages and other localization settings without any hardcoded modification. Character encoding is an important feature when a report is intended to be internationalized. Character Encoding A character is the smallest unit of writing conveying a meaningful information. It is an abstract concept, a character does not have a visual appearance. Uppercase Latin A is a different character from lowercase Latin a and from uppercase Cyrillic A and uppercase Greek Alpha. A visual representation of a character is known as a glyph . A certain set of glyphs is called a font . Uppercase Latin A, uppercase Cyrillic A and uppercase Greek Alpha may have identical glyphs, but they are different characters. At the same time, the glyphs for uppercase Latin A can look very different in Times New Roman, Gill Sans and Poetica chancery italic, but they still represent the same character. The set of available characters is called a character repertoire . The location (index) of a given character within a repertoire is known as its code position, or code point. The method of numerically representing a code point within a given repertoire is called the character encoding . Encodings are normally expressed in terms of octets. An octet is a group of eight binary digits, i. e. eight ones and zeros. An octet can express a numeric range between 0 and 255, or between 0x00 and 0xFF, to use hexadecimal notation. A Unicode is a character repertoire that contains most of the characters used in the languages of the world. It can accommodate millions of characters, and already contains hundreds of thousands. Unicode is divided into planes of 64K characters. The only one used in most circumstances is the first plane, known as the basic multilingual plane, or BMP. UTF-8 is the recommended encoding. It uses a variable number of octets to represent different characters. In a JRXML file, the encoding attribute is specified in the header. It is used at report compilation time to decode the XML content. For instance, if the report contains French words only and characters such as ccedil, eacute, acirc, then the ISO-8859-1 (a. k.a Latin-1) encoding is sufficient minus As seen above, ideally we can choose the encoding fit to the minimal character set, which can correctly represent all the characters in the document. But in case of Multilanguage documents (i. e. documents containing words spelled in several languages), one should choose the encoding adapted to the minimal character set, able to correctly represent all the characters in the document, even if they belong to different languages. One of the character encodings able to handle multilingual documents is the UTF-8 . used as default encoding value by JasperReports. The texts are usually kept in resource bundle files rather than within the document during internationalization. So, there are cases where the JRXML itself looks completely ASCII-compatible, but generated reports at runtime do contain texts unreadable with ASCII. As a result, for a certain type of document export formats (such as CSV, HTML, XHTML, XML, and text) one has to know the encoding for the generated document too. Different languages are supported by different character encodings. So each time, we need to run a report in a localized environment. Further, we have to know, which is the most appropriate character encoding for the generated document language. In this case, the encoding property defined in the JRXML file itself might be no more useful. To solve this kind of issues we can use an export customer property known as net. sf. jasperreports. export. character. encoding . This export custom property is default to UTF-8 and is present in JasperReports. This default value is set in the default. jasperreports. properties file. For more specific options at export time, the CHARACTERENCODING export parameter is also available. To demonstrate using unicode support in Jasperreports, lets write new report template (jasperreporttemplate. jrxml). Save it to C:toolsjasperreports-5.0.1test directory. Here, we will display a text in different languages using the Unicode characters (uXXXX). Any character encoded with UTF-8 can be represented using only its 4-digits hexadecimal code. For instance, the Greek letter can be written as u0393. When such a notation is encountered, the engine calls for the appropriate character representation in the character set, and only that particular character will be printed out. The contents of the JRXML are as below minus In the above file, we can see the presence of the UTF-8 encoding. Also the localized Unicode pieces of text are stored in document parameters. The java code to fill and generate the report is as below. Lets save this file JasperUnicodeReportFill. java to C:toolsjasperreports-5.0.1testsrccomtutorialspoint directory. Here we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields in this single record being null . Report Generation We will compile and execute the above file using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as below. The import file - baseBuild. xml is picked from chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. JasperUnicodeReportFill (viewFullReport is the default target) as follows minus As a result of above compilation, a JasperViewer window opens up as shown in the screen given below minus Here, we can see that the text being displayed is in different languages. Also we see that the languages are grouped together on the same page and also mixed into the same text element. Report Styles JasperReports has a feature ltstylegt which helps to control text properties in a report template. This element is a collection of style settings declared at the report level. Properties like foreground color, background color, whether the font is bold, italic, or normal, the font size, a border for the font, and many other attributes are controlled by ltstylegt element. Styles can extend other styles, and add to, or override properties of the parent style as well. Style Properties A ltstylegt element has many attributes. Some of the most commonly used are listed in the table given below minus Attribute and Description Conditional Styles In some situations, a style should be applied only when certain condition is met (for example, to alternate adjacent row colors in a report detail section). This can be achieved using conditional styles. A conditional style has two elements minus a Boolean condition expression a style The style is used only if the condition evaluates to true . Applying Styles to Report Elements Any type of report element can reference a report style definition using the style attribute. Hence, all the style properties declared by the style definition that are applicable to the current element will be inherited. To override the inherited values, style properties specified at the report element level can be used. Style Templates We can make a set of reports with a common look by defining the style at a common place. This common style template can then be referenced by the report templates. A style template is an XML file that contains one or more style definitions. Style template files used by convention the. jrtx extension, but this is not mandatory. A style template contains following elements minus ltjasperTemplategt minus This is the root element of a style template file. lttemplategt minus This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file. ltstylegt minus This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition. References to style templates are included in JRXML reports as lttemplategt elements. The style templates are loaded at report fill time, and style name references are resolved once all the templates have been loaded. When loading style templates and resolving style names to styles, a treegraph of style templates is created, the top of the tree being the set of styles defined in the report. On this tree, style name references are resolved to the last style that matches the name in a depth-first traversal. Lets try out the conditional styles and style templates. Lets add the lt style gt element alternateStyle to our existing report template (Chapter Report Designs ). Based on the condition, font color changes to blue for even count. We have also included a style template styles. jrtx . The revised report template (jasperreporttemplate. jrxml) is as follows. Save it to C:toolsjasperreports-5.0.1test directory minus The contents of style template styles. jrtx are as follows. Save it to C:toolsjasperreports-5.0.1test directory. The java codes for report filling remain unchanged. The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java are as given below minus The contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java are as below minus The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java are as below minus Report Generation We will compile and execute the above file using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as given below. The import file - baseBuild. xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport is the default target) as minus As a result of above compilation, a JasperViewer window opens up as shown in the screen given below minus Here, we can see that the color of the font is changed to blue for even count (in column country). In the column name, the font color is changed to green (this style is referenced from the style template). Report Scriptlets We have seen in our previous chapters, data displayed on the report is usually fetched from report parameters and report fields. This data can be processed using the report variables and their expressions. There are situations when a complex functionality cannot be achieved easily using report expressions or variables. Examples of this may be complex String manipulations, building of Maps, or Lists of objects in memory or manipulations of dates using 3rd party Java APIs. For such situations, JasperReports provides us with a simple and powerful means of doing this with Scriptlets . Scriptlets are sequences of Java code that are executed every time a report event occurs. Values of report variables can be affected through scriptlets. Scriptlet Declaration We can declare a scriptlet in two ways minus Using lt scriptlet gt element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly. Using the attribute scriptletClass of the element lt jasperReport gt, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the predefined name REPORT. Scriptlet class A scriptlet is a java class, which must extend either of the following classes minus net. sf. jasperreports. engine. JRAbstractScriptlet minus This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods. net. sf. jasperreports. engine. JRDefaultScriptlet minus This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods heshe needs for hisher project. The following table lists the methods in the above class. These methods will be called by the report engine at the appropriate time, during report filling phase. Method and Description public void afterDetailEval() Called after each record in the detail section of the report is evaluated. Any number of scriptlets can be specified per report. If no scriptlet is specified for a report, the engine still creates a single JRDefaultScriptlet instance and registers it with the built-in REPORTSCRIPTLET parameter. We can add any additional methods that we need to our scriptlets. Reports can call these methods by using the built-in parameter REPORTSCRIPTLET. Global Scriptlets We can associate scriptlets in another way to reports, which is by declaring the scriptlets globally. This makes the scriptlets apply to all reports being filled in the given JasperReports deployment. This is made easy by the fact that scriptlets can be added to JasperReports as extensions. The scriptlet extension point is represented by the net. sf. jasperreports. engine. scriptlets. ScriptletFactory interface. JasperReports will load all scriptlet factories available through extensions at runtime. Then, it will ask each one of them for the list of scriptlets instances that they want to apply to the current report that is being run. When asking for the list of scriptlet instances, the engine gives some context information that the factory could use in order to decide, which scriptlets actually apply to the current report. Report Governors Governors are just an extension of global scriptlets that enable us to tackle a problem of report engine entering infinite loop at runtime, while generating reports. Invalid report templates cannot be detected at design time, because most of the time, the conditions for entering the infinite loops depend on the actual data that is fed into the engine at runtime. Report Governors help in deciding whether a certain report has entered an infinite loop and they can stop it. This prevents resource exhaustion for the machine that runs the report. JasperReports has two simple report governors that would stop a report execution based on a specified maximum number of pages or a specified timeout interval. They are minus net. sf. jasperreports. governors. MaxPagesGovernor minus This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are minus net. sf. jasperreports. governors. TimeoutGovernor minus This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not. The configuration properties are minus The properties for both governors can be set globally, in the jasperreports. properties file, or at report level, as custom report properties. This is useful because different reports can have different estimated size or timeout limits and also because you might want turn on the governors for all reports, while turning it off for some, or vice-versa. Lets write a scriptlet class ( MyScriptlet ). The contents of file C:toolsjasperreports-5.0.1testsrccomtutorialspointMyScriptlet. java are as follows minus Details of the above scriptlet class are as follows minus In the afterReportInit method, we set a value to the variable someVar this. setVariableValue(someVar, new String(This variable value was modified by the scriptlet.)). At the end of the class, an extra method called hello has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable. Next, we will add the scriptlet class reference in our existing report template (Chapter Report Designs ). The revised report template (jasperreporttemplate. jrxml) are as follows. Save it to C:toolsjasperreports-5.0.1test directory minus The details of the revised report template is given below minus We have referenced the MyScriptlet class in the attribute scriptletClass of ltjasperReportgt element. Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar . which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet . The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ( P. hello() ) The java codes for report filling remain unchanged. The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java are as given below minus The contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java are as given below minus The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java are as given below minus Report Generation We will compile and execute the above file using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as given below. The import file - baseBuild. xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport is the default target) as minus As a result of above compilation, a JasperViewer window opens up as shown in the screen given below minus Here we see two messages are displayed from MyScriptlet class minus In title section minus This variable value was modified by the scriptlet At the bottom minus Hello Im the reports scriptlet object. Create SubReports Subreports are one of the nice features of the JasperReports. This feature allows incorporating a report within another report, that is, one report can be a subreport of another. Subreports help us keep report designs simple, as we can create many simple reports and encapsulate them into a master report. Subreports are compiled and filled just like normal reports. Any report template can be used as a subreport when incorporated into another report template, without anything changed inside (of the report template). Subreports are like normal report templates. They are in fact net. sf. jasperreports. engine. JasperReport objects, which are obtained after compiling a net. sf. jasperreports. engine. design. JasperDesign object . ltsubreportgt Element A ltsubreportgt element is used when introducing subreports into master reports. Here is the list of sub-elements in the ltsubreportgt JRXML element. ltparametersMapExpressiongt minus This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTSPARAMETERSMAP parameter to pass the parent reports parameters to the subreport. This expression should always return a java. util. Map object in which the keys are the parameter names. ltsubreportParametergt minus This element is used to pass parameters to the subreport. It has an attribute name . which is mandatory. ltconnectionExpression gt minus This is used to pass a java. sql. Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase. ltdataSourceExpressiongt minus This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORTDATASOURCE parameter to pass the parent reports datasource to the subreport. The elements ( connectionExpression and dataSourceExpression ) cannot be present at the same time in a ltsubreportgt element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it. ltreturnValuegt minus This is used to assign the value of one of the subreports variables to one of the master reports variables. This sub element has attributes as follows minus subreportVariable minus This attribute specifies the name of the subreport variable whose value is to be returned. toVariable minus This attribute specifies the name of the parent report variable whose value is to be copiedincremented with the value from the subreport. calculation minus This attribute can take values. Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is Nothing. incrementerFactoryClass minus This attribute specifies the factory class for creating the incrementer instance. ltsubreportExpressiongt minus This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java. lang. String, java. io. File, java. URL, java. io. InputStream, net. sf. jasperreports. engine. JasperReport. Default value is java. lang. String . isUsingCache minus This is an attribute of the ltsubreportgt element. This is a Boolean, when set to true . the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java. lang. String objects as the subreport template source, representing file names, URLs, or classpath resources. Let take up a simple example to demonstrate creation of subreports using JRDataSource. Lets first write two new report templates, one being subreport and the other Master report. The contents of the subreport (addressreporttemplate. jrxml) template is as given below. Save it to C:toolsjasperreports-5.0.1test directory. As we use a data source, we need to write a corresponding POJO file SubReportBean. java as shown below. Save it to directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint minus Here, we have declared two fields city and street and respective getter and setter methods are defined. Now, lets update our existing DataBean file. We will add a new field subReportBeanList . which is a java. util. List. This field will hold the list of SubReportBean objects. The contents of the file DataBean are as below. Save it to directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. Lets now update the file C:toolsjasperreports-5.0.1testsrccomtutorialspoint DataBeanList. java . The contents of this file are as minus In the method produce() in the above file, we are setting the list of SubReportBean. Now, lets write a new master report template (jasperreporttemplate. jrxml). Save this file to directory C:toolsjasperreports-5.0.1test . The contents for this file are as below minus In the above template, we have defined a new parameter SUBREPORTDIR, which defines the path of the subreport. We have defined a field subReportBeanList of type java. util. List, which corresponds to property in the file DataBean. The element ltsubreportgt has sub-element ltdataSourceExpressiongt. We have put the list subReportBeanList in an instance of JRBeanCollectionDataSource. In the sub-element ltsubreportExpressiongt, we have given the subreport name (AddressReport. jasper). Now, lets write a new class CreateReport to compile and execute our report template. The contents of file C:toolsjasperreports-5.0.1testsrccomtutorialspointCreateReport. java are as given below minus Here, we see that we are compiling both the master and sub report templates and passing the master report (.jasper) file for the report filling. Report Generation Now, all our files are ready, lets compile and execute them using our regular ANT build process. The contents of the file build. xml (saved under directory C:toolsjasperreports-5.0.1test) are as given below. The import file - baseBuild. xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build. xml. Next, lets open command line window and go to the directory where build. xml is placed. Finally, execute the command ant - Dmain-classcom. tutorialspoint. CreateReport (viewFullReport is the default target) as follows minus As a result of above compilation, a JasperViewer window opens up as shown in the screen given below minus Here, we can see that the attributes Name, Country, and Address are displayed. Creating Charts Earlier people had to rely on scriptlets to gather the chart data and render the chart using an image element in the report template. JasperReports makes it simple now, as it has a built-in support for charts using the new chart component. Using a new chart component, user needs to apply only the visual settings and define expressions that will help build the chart dataset. JasperReports uses JFreeChart as the underlying charting library. When configuring a new chart component, following three components are involved minus The overall chart component. The chart dataset (which groups chart data-related settings). The chart plot (which groups visual settings related to the way the chart items are rendered). JasperReports currently supports the following types of charts: Pie, Pie 3D, Bar, Bar 3D, XY Bar, Stacked Bar, Stacked Bar 3D, Line, XY Line, Area, XY Area, Stacked Area, Scatter, Bubble, Time Series, High-Low-Open-Close, Candlestick, Multiple Axis, Meter, Thermometer, and Gantt. Chart Properties Charts are normal report elements, so they share some of their properties with all the other report elements. There is a JRXML element called lt chart gt, used to create all type of charts. This element groups special chart-specific settings that apply to all types of charts. Chart Sub-Elements The sub-elements of ltchartgt element are minus ltreportElementgt minus These are displayable objects like static texts, text fields, images, lines, and rectangles that you put in your report template sections. ltBoxgt minus This element is used to surround charts by a border thats customizable on each side. ltchartTitlegt minus This element is used to place the title of the chart. The position attribute decides the title position of the chart in the report. This element has attributes - Position (Values could be Top . Bottom . Left . Right . Deafult value is Top ), color . ltchartTitlegt has font and titleExpression as subelements. ltchartSubtitlegt minus This element is used to place the subtitle of the chart. This element has attribute - color . ltchartSubtitlegt has font and subtitleExpression as subelements. ltchartLegendgt minus The element can control the font-related properties as well as the text color and the background color of the chart legend using this element. This element has attributes - textColor and backgroundColor . ltanchorNameExpressiongt minus This element creates the target for the anchor. lthyperlinkReferenceExpressiongt minus This element contains a report expression indicating the name of the external resource (usually a URL). lthyperlinkAnchorExpressiongt minus Hyperlink points to an anchor in an external resource. lthyperlinkPageExpressiongt minus Hyperlink points to a page in the current report. lthyperlinkTooltipExpressiongt minus This element controls the ToolTip of hyperlink. The type of the expression should be java. lang. String . lthyperlinkParametergt minus This element when present generates a final hyperlink depending on the parameter values. Chart attributes Attributes in the ltchartgt element available for all chart types are minus isShowLegend minus This attribute is used to determine, if a chart legend will be displayed on the report. Values could be true . or false . Default value is true . evaluationTime minus Determines when the charts expression will be evaluated. Values could be Now . Report . Page . Column . Group . Band . Default value is Now . evaluationGroup minus This attribute determines the name of the group to be used to evaluate the charts expressions. The value for this attribute must match the name of the group, we would like to use as the charts evaluation group. hyperlinkType minus This attribute can hold any text value. Default value is None . This means, neither the text fields nor the images represent hyperlinks, even if the special hyperlink expressions are present. hyperlinkTarget minus This attribute helps to customize the behavior of the specified link when it is clicked in the viewer. Values could be Self . or Blank . Default value is Self . bookmarkLevel minus This attribute when set to a positive integer, generates bookmarks in the reports exported to PDF. Default value is 0 . customizerClass minus This is the name of a class (optional) that can be used to customize the chart. The value for this element must be a String containing the name of a customizer class. Chart customization As mentioned above, JasperReports uses JFreeChart as the underlying charting library. JFreeChart contains features that are directly not supported by JasperReports. We can take advantage of these features by supplying a customizer class via the customizerClass attribute in ltchartgt element. A customizer class is nothing, but an implementation of the net. sf. jasperreports. engine. JRChartCustomizer interface. The easiest way to implement this interface is by extending the net. sf. jasperreports. engine. JRAbstractChartCustomizer class and thus having access to parameters, fields, and variables for more flexible chart customization based on report data. Chart Datasets One of the common properties across all chart types is lt dataset gt element. Chart datasets help mapping report data and retrieving chart data at runtime. Each chart type contains different sub-elements to define charts expressions. These expressions define the data used to generate the chart. All of these sub-elements contain a ltdatasetgt element that defines when the charts expressions are evaluated and reset. Several types of chart datasets are available in JasperReports because each type of chart works with certain datasets: Pie, Category, XY, Time Series, Time Period, XYZ, and High-Low. Each of these dataset types implements net. sf. jasperreports. engine. JRChartDataset interface that define chart datasets. All chart datasets initialize and increment in the same way however, they differ only in the type of data or data series they map. Dataset Properties Table given below summarizes the attributes of the element ltdatasetgt minus JasperReports - Crosstabs JasperReports - Internationalization

No comments:

Post a Comment