Friday 16 June 2017

Movendo Média Jfreechart Exemplo


2009-08-06: liberação de 0.6.0 é liberada 2009-05-22: liberação de 0.5.0 é liberada 2009-03-16: liberação de 0.5.0 beta. 2008-06-20: lançamento de 0.4.1, relançamento do site Wiki e inclusão dos fóruns como páginas incorporadas: Fórum de Usuários e Fórum de Desenvolvedores. Enjoy 2008-05-04 Appendium Ltd e LavaBlast têm o prazer de anunciar o lançamento da versão 0.4.0 do StatSVN. Mais detalhes sobre este blog e o changelog. 2007-03-10 Notícia. Como parte do lançamento 0.3.1, lançamos uma série de demos para alguns projetos conhecidos: Subversion, Ant, Log4J, Spring Rich Client, Hibernate 3, Joda Time, Ruby, Groovy, Grails e Felix para começar. Vá em frente, admita, você sempre quis saber quem fez o quê e quando sobre esses projetos. Atenção . Se você não estiver usando uma localidade em inglês, defina a variável de ambiente LANG para enUS ao executar o aplicativo até resolvermos alguns problemas de i18n com o StatSVN (a chamada para svn diff retorna uma string localizada que pode resultar em alguns resultados não sendo armazenados em cache, os resultados Estão corretas, mas o StatSVN pedirá novamente na próxima vez). 2007-02-07: Quer ajudar Estamos considerando a substituição de nossas invocações de linha de comando com chamadas para SVNKit (anteriormente JavaSVN). Queremos escrever a implementação do protótipo e ver o quão bem ela funciona? Deixe-nos saber 2007-01-12: Versão 0.3.0 está em SVN e adiciona 2 relatórios (RepoMap e LOCChurn), bem como corrigir uma série de problemas com arquivos em movimento, diretórios E eliminação desses. Mais detalhes nesta página. 2006-11-28: Versão 0.2.0 está para fora e suporta agora a geração de Html e de XDoc para facilitar a integração com Maven (veja relatórios aqui). Também ficamos satisfeitos em mencionar que existe um plugin Maven 2 usando o StatSVN, ele está disponível no stat-scm. sourceforge. Tweet Estatísticas do SVN O StatSVN recupera informações de um repositório do Subversion e gera várias tabelas e gráficos descrevendo o desenvolvimento do projeto, p. Linha de tempo para as linhas de código Linhas de código para cada desenvolvedor Atividade por Hora do relógio Autores Atividade Atividade do autor por Módulo Autor Mais recentes Compromete com links para ViewVc Estatísticas por diretório Número de arquivos Tamanho médio do arquivo Maiores arquivos Arquivos com a maioria das revisões Tamanho do diretório Repositório Tags Número de LOC, por versão. Árvore de repositório com contagem de arquivos e linhas de código LOC e Churn a evolução de LOC ea quantidade de mudança por dia Repo Mapear a visão hierárquica dinâmica de seu repo para os últimos 30 dias A versão atual do StatSVN gera um conjunto estático de documentos HTML contendo Tabelas e imagens de gráfico. O StatSVN é um software de código aberto, lançado sob os termos da LGPL, baseado no StatCVS. O StatSVN usa JFreeChart para gerar gráficos. Onde está o manual O manual está disponível on-line como um Wiki e é tão atualizado e abrangente como você quer que ele seja. Exemplo rápido para Maven 1 Antes de executar o site maven (ou simplesmente maven xdoc), você pode gerar os arquivos XDOC executando: (não esqueça - v). Este exemplo irá gerar xdoc no diretório sitestatsvn, tag 0.2.0, 0.1.3, 0.1.2, 0.0.9, excluir qalab. xml e outros. Depois disso, o XDOC seria apanhado pelo site maven ou pelo maven xdoc. Observe que para usar as tags, você deve usar um arquivo de log não no nível do tronco, mas logo acima, para incluir o diretório de tags. No momento, o StatSVN só funciona com o diretório tags. Exemplo rápido de novo despejo Existe uma nova facilidade de despejo (não esqueça - v). Isso irá gerar uma grande quantidade de saída, mas no final isso, se mostra OK para tudo, é provável que o StatSVN entendeu corretamente seu repositório: JasperReports - Guia Rápido JasperReports - Começando JasperReports - Ambiente JasperReports - Ciclo de Vida JasperReports - Designs JasperReports - Compilando o Projeto de Relatórios JasperReports - Relatórios de Preenchimento Relatório Jasper - Relatórios de Impressão de Amperes JasperReports - Exportação de Relatórios Relatórios Parâmetros Se definido como java. lang. Boolean. TRUE o relatório será gerado em uma página longa e não ocorrerá quebra de página. Passemos ReportTitle e Author para o relatório (gerado por JasperReportFill. java). Arquivo revisado C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java é como segue minus O conteúdo do arquivo POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java são como abaixo minus O conteúdo do arquivo C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java são como Dado abaixo menos Permite adicionar parâmetros ao lt ReportTitle gt e lt Author gt ao nosso modelo de relatório existente (Chapter Report Designs). O título e o autor do relatório serão exibidos no início do relatório. O modelo de relatório revisado (jasperreporttemplate. jrxml) é o seguinte. Salve-o em C: toolsjasperreports-5.0.1 diretório de teste menos Geração de relatório Vamos compilar e executar o arquivo acima usando nosso processo regular de construção ANT. O conteúdo do arquivo build. xml (salvo no diretório C: toolsjasperreports-5.0.1test) são como abaixo. O arquivo de importação - baseBuild. xml é escolhido a partir do capítulo Configuração do Ambiente e deve ser colocado no mesmo diretório que o build. xml. Em seguida, vamos abrir janela de linha de comando e ir para o diretório onde build. xml é colocado. Por fim, execute o comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport é o destino padrão) da seguinte forma minus Como resultado da compilação acima, uma janela do JasperViewer se abre como mostrado na seguinte tela menos Aqui, vemos que, a ReportTitle lista de contatos e autor preparado pelo Manisha são exibidos no início do relatório. Fontes de dados de relatório Fontes de dados são contêineres de dados estruturados. Ao gerar o relatório, o mecanismo JasperReports obtém dados dos datasources. Os dados podem ser obtidos nos bancos de dados, arquivos XML, matrizes de objetos e coleção de objetos. Vimos no capítulo Relatórios de preenchimento. O método fillReportXXX () espera receber uma fonte de dados do relatório, que tem de preencher, sob a forma de net. sf. jasperreports. engine. JRDataSource objeto ou um java. sql. Connection (quando os dados do relatório são encontrados em um Banco de dados relacional). A interface JRDataSource tem apenas dois métodos, que devem ser implementados menos booleano público next () lança JRException No momento de preenchimento do relatório, esse método é chamado no objeto de fonte de dados pelo mecanismo de relatório ao iterar pelos dados. Public Object getFieldValue (JRField jrField) lança JRException Este método fornece o valor para cada campo de relatório no registro de fonte de dados atual. A única maneira de recuperar dados da fonte de dados é usando os campos de relatório. Há várias implementações padrão da interface JRDataSource, dependendo da maneira, os registros na fonte de dados são adquiridos. Implementações de Datasource A tabela abaixo resume as datasources e suas classes de implementação menos JDBC Data Sources Classe JRResultSetDataSource craps um objeto java. sql. ResultSet. Esta é a implementação de fontes de dados mais comumente usada quando dados de relatório são extraídos de um banco de dados relacional. Se um java. sql. Connection é passado para o mecanismo em vez disso, ele executa primeiro a consulta relacionada e armazena o objeto java. sql. ResultSet retornado em uma instância JRResultSetDataSource. Classes de fontes de dados JavaBean JRBeanArrayDataSource e JRBeanCollectionDataSource representam implementações que podem envolver matrizes e coleções de objetos JavaBean. Cada objeto dentro da matriz ou a coleção será visto como um registro neste tipo de fonte de dados. O mapeamento entre uma determinada propriedade JavaBean e o campo de relatório correspondente é feito por convenções de nomenclatura. O campo do nome do relatório deve ser o mesmo que o nome da propriedade JavaBean conforme especificado pelas especificações do JavaBeans. Em todos os exemplos deste tutorial, usamos JRBeanCollectionDataSource. Fontes de dados baseadas em mapas As classes de implementação JRMapArrayDataSource e JRMapCollectionDataSource são úteis se o aplicativo pai já armazenar os dados de relatório disponíveis na memória como objetos java. util. Map. Cada objeto de mapa na matriz ou coleção wrapped é considerado um registro virtual na fonte de dados eo valor de cada campo de relatório é extraído do mapa usando o campo de relatório nomeado como a chave. Fontes de Dados TableModel Em muitos aplicativos do lado do cliente, os dados são exibidos em formato tabular. Um requisito comum em muitas aplicações é permitir que o usuário imprima este formato tabular como um relatório. A classe de implementação JRTableModelDataSource torna a tarefa de gerar relatórios de formato tabular trivial para aplicativos Swing. Essa classe envolve um objeto javax. swing. table. TableModel. Colunas no objeto TableModel wrapped podem ser acessadas por seus nomes ou por seus índices baseados em 0. Classe de fontes de dados XML JRXmlDataSource é uma implementação de origem de dados baseada no DOM, que usa expressões XPath para selecionar dados do documento XML. Registros na origem de dados XML são representados por elementos de nó selecionados através da expressão XPath. Os valores de campo são recuperados de cada registro usando a expressão XPath fornecida pela descrição do campo (elemento ltfieldDescriptiongt em JRXML). XPath é uma linguagem usada para navegar através de atributos e elementos de documentos XML. Mais informações sobre XPath podem ser encontradas em w3.orgTRxpath. Fontes de dados CSV O JRCsvDataSource representa uma implementação para fontes de dados, que recuperam seus dados de arquivos de texto estruturados geralmente CSVs. Os valores de campo são recuperados usando seu índice de coluna. Fontes de dados XLS O JRXlsDataSource representa uma implementação para fontes de dados, que recuperam seus dados de documentos do Excel. O mapeamento de campo de relatório para esta implementação de origem de dados também se baseia no índice de coluna de campo. Origens de dados vazias A classe JREmptyDataSource. Simula uma fonte de dados com um dado número de registros vazios virtuais dentro. Ele é usado pelas ferramentas da interface do usuário para oferecer funcionalidade de visualização básica do relatório, ou em modelos de relatório especiais, ou para fins de teste e depuração. Fontes de dados rebobináveis ​​O net. sf. jasperreports. engine. JRRewindableDataSource estende a interface JRDataSource básica. Ele adiciona apenas um método, chamado moveFirst (), para a interface. Este método destina-se a mover o cursor para o primeiro elemento na origem de dados. Fontes de dados rebobináveis ​​são úteis quando se trabalha com sub-relatórios colocados dentro de uma banda que não é permitida a divisão devido à configuração isSplitAllowedfalse e não há espaço suficiente na página atual para o sub relatório a ser processado. Todas as implementações de origem de dados acima são rebobináveis, exceto para o JRResultSetDataSource. Como ele não suporta mover o ponteiro de registro para trás. Isso representa um problema somente se essa fonte de dados for usada manualmente para envolver um java. sql. ResultSet antes de passá-lo para o sub-relatório. Não há problema, se a consulta SQL reside no modelo de sub-relatório, como o mecanismo irá executá-lo novamente ao reiniciar o sub-relatório na próxima página. Provedores de fontes de dados A biblioteca JasperReports tem uma interface net. sf. jasperreports. engine. JRDataSourceProvider. Isso ajuda na criação e disposição de objetos de origem de dados. Ao criar um modelo de relatório usando ferramentas GUI, uma ferramenta especial para personalizar a fonte de dados de relatórios é necessária. JRDataSourceProvider é a maneira padrão para conectar fontes de dados personalizadas em uma ferramenta de design. Uma implementação personalizada desta interface deve implementar os seguintes métodos que permitem a criação e disposição de objetos de fonte de dados e também métodos para listar os campos de relatório disponíveis dentro da fonte de dados, se possível menos Campos de relatórios Campos de relatório são elementos, que representam mapeamento de dados entre datasource E modelo de relatório. Os campos podem ser combinados nas expressões do relatório para obter a saída desejada. Um modelo de relatório pode conter zero ou mais elementos ltfieldgt. Ao declarar campos de relatório, a fonte de dados deve fornecer dados correspondentes a todos os campos definidos no modelo de relatório. Declaração de Campo A declaração de campo é feita como mostrado abaixo minus O Atributo de Nome O atributo de nome do elemento ltfieldgt é obrigatório. Faz referência ao campo em expressões de relatório por nome. O atributo de classe O atributo de classe especifica o nome da classe para os valores de campo. Seu valor padrão é java. lang. String. Isso pode ser alterado para qualquer classe disponível em tempo de execução. Independentemente do tipo de um campo de relatório, o mecanismo cuida da moldagem nas expressões de relatório em que o token F é usado, tornando desnecessários os modelos manuais. Campo Descrição O elemento ltfieldDesciptiongt é um elemento opcional. Isso é muito útil ao implementar uma fonte de dados personalizada. Por exemplo, podemos armazenar uma chave ou alguma informação, através da qual podemos recuperar o valor do campo da fonte de dados personalizada no tempo de execução. Usando o elemento ltfieldDesciptiongt em vez do nome do campo, você pode facilmente superar restrições de convenções de nomeação de campos ao recuperar os valores de campo da fonte de dados. A seguir está um pedaço de código de nosso arquivo JRXML existente (Designs de relatórios de capítulo). Aqui, podemos ver o uso de nome. classe . E elementos fieldDescription. Campos de ordenação Nos momentos em que a classificação de dados é necessária e a implementação de fonte de dados não o suporta (por exemplo, fonte de dados CSV), o JasperReports suporta a classificação de origem de dados baseada em campo na memória. A classificação pode ser feita usando um ou mais elementos ltsortFieldgt no modelo de relatório. Se pelo menos um campo de classificação for especificado, durante o processo de preenchimento do relatório, a fonte de dados será passada para uma instância do JRSortableDataSource. Isso, por sua vez, obtém todos os registros da origem de dados, executa na classificação de memória de acordo com os campos especificados e substitui a origem de dados original. O nome do campo de classificação deve ser idêntico ao nome do campo do relatório. Campos utilizados para classificação devem ter tipos que implementam java. utilparable. A classificação de ordem natural é executada para todos os campos, exceto os do tipo java. lang. String (para o tipo String, o collator correspondente ao local de preenchimento do relatório é usado). Quando são especificados vários campos de ordenação, a ordenação será executada utilizando os campos como chaves de ordenação na ordem em que aparecem no modelo de relatório. O exemplo a seguir demonstra o recurso de classificação. Sorted Report Example Permite adicionar o elemento lt sortField gt ao nosso modelo de relatório existente (desenhos de relatórios de capítulo). Permite ordenar o país do campo em ordem decrescente. O modelo de relatório revisado (jasperreporttemplate. jrxml) é o seguinte. Salve-o em C: toolsjasperreports-5.0.1 diretório de teste menos Os códigos java para preenchimento de relatório permanece inalterado. O conteúdo do arquivo C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java são como dados abaixo minus O conteúdo do arquivo POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java são como dados abaixo minus O conteúdo do arquivo C: toolsjasperreports-5.0. 1testsrccomtutorialspointDataBeanList. java são como dados abaixo menos geração de relatório Vamos compilar e executar o arquivo acima usando nosso processo regular de construção ANT. O conteúdo do arquivo build. xml (salvo no diretório C: toolsjasperreports-5.0.1test) são os dados abaixo. O arquivo de importação - baseBuild. xml é escolhido do capítulo Configuração do Ambiente e deve ser colocado no mesmo diretório que o build. xml. Em seguida, vamos abrir janela de linha de comando e ir para o diretório onde build. xml é colocado. Finalmente, execute o comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport é o destino padrão) da seguinte forma minus Como resultado da compilação acima, uma janela do JasperViewer se abre como mostrado na tela abaixo abaixo Aqui, podemos ver que Os nomes de países são organizados em ordem decrescente em ordem alfabética. As expressões Report Expression Report são os poderosos recursos do JasperReports, que nos permitem exibir dados calculados em um relatório. Dados calculados são os dados que não são dados estáticos e não são passados ​​especificamente como um parâmetro de relatório ou campo de fonte de dados. As expressões de relatório são construídas a partir da combinação de parâmetros de relatório, campos e dados estáticos. A linguagem Java é usada para escrever expressões de relatório por padrão. Outros linguagens de script para expressões de relatório como linguagem de script Groovy, JavaScript ou script BeanShell são suportados por compiladores do JasperReports. Este capítulo irá explicar-lhe menos como funcionam as expressões de relatório, supondo que tenham sido escritas utilizando apenas a linguagem Java. Em um modelo de relatório JRXML, existem vários elementos que definem expressões como menos ltvariableExpressiongt ltinitialValueExpressiongt ltgroupExpressiongt ltprintWhenExpressiongt ltimageExpressiongt lttextFieldExpressiongt Expressão Declaração Basicamente, todas as expressões de relatório são expressões Java, que podem fazer referência aos campos de relatório, variáveis ​​de relatório e parâmetros de relatório. Referência de campo na expressão Para usar uma referência de campo de relatório em uma expressão, o nome do campo deve ser colocado entre F e seqüências de caracteres, como mostrado abaixo. - Seguir é um pedaço de código de nosso arquivo JRXML existente Referência em Expression Para referenciar uma variável em uma expressão, devemos colocar o nome da variável entre V e como mostrado no exemplo abaixo. Minus Referência de parâmetro em Expression Para fazer referência a um parâmetro em uma expressão, o nome do parâmetro deve ser colocado Entre P e como mostrado no exemplo abaixo abaixo Seguir é um pedaço de código de nosso arquivo JRXML existente, que demonstra o referenciamento de parâmetro em uma expressão. (JRXML from Chapter Report Designs) minus Como você viu acima, as referências de parâmetro, campo e variável são de fato objetos Java reais. Conhecendo sua classe a partir da declaração de parâmetro, campo ou variável feita no modelo de relatório, podemos até chamar métodos nessas referências de objeto nas expressões. O exemplo a seguir mostra menos como extrair e exibir a primeira letra do campo de relatório java. lang. String Nome menos Referência do conjunto de recursos na expressão Para fazer referência a um recurso em uma expressão, a chave deve ser colocada entre R e conforme mostrado no exemplo fornecido Abaixo menos Com base na localidade fornecida pelo tempo de execução e na chave report. title, o bundle de recursos associado ao modelo de relatório é carregado. Assim, o título do relatório é exibido extraindo o valor String do bundle de recursos. Mais informações sobre internacionalização podem ser encontradas no capítulo Internacionalização. Calculadora A Calculadora é uma entidade no JasperReports, que avalia expressões e incrementa variáveis ​​ou conjuntos de dados no momento do preenchimento do relatório. Durante o processo de compilação, as informações são produzidas e armazenadas no relatório de compilação pelo compilador. Essas informações são usadas durante o tempo de preenchimento do relatório para criar uma instância da classe net. sf. jasperreports. engine. fill. JRCalculator. O arquivo de origem Java é gerado e compilado por compiladores de relatórios baseados em Java. Essa classe gerada é uma subclasse do JRCalculator eo bytecode produzido pela compilação é armazenado dentro do objeto JasperReport. Esse bytcode é carregado no tempo de preenchimento do relatório e a classe resultante é instanciada para obter o objeto calculador necessário para a avaliação da expressão. Expressões Condicionais O JasperReports não suporta declarações if-else ao definir expressões variáveis. Em vez disso, você pode usar os operadores ternários. . . Esse operador pode ser aninhado dentro de uma expressão Java para obter a saída desejada com base em várias condições. Exemplo de expressões condicionais no relatório Permite modificar o modelo de relatório existente (Designs de relatórios de capítulo) e adicionar uma expressão condicional para o país de campo. O modelo de relatório revisado (jasperreporttemplate. jrxml) é o seguinte. Salve-o em C: toolsjasperreports-5.0.1 diretório de teste menos Os códigos java para preenchimento de relatório são os seguintes. O conteúdo do arquivo C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java são como menos O conteúdo do arquivo POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java são como menos Vamos adicionar um novo registro com campo country como vazio em nosso Java bean Lista. O conteúdo do arquivo C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList. java são como menos Report Generation Vamos compilar e executar o arquivo acima usando o nosso processo regular de construção ANT. O conteúdo do arquivo build. xml (salvo no diretório C: toolsjasperreports-5.0.1test) é dado abaixo. O arquivo de importação - baseBuild. xml é escolhido do capítulo Configuração do Ambiente e deve ser colocado no mesmo diretório que o build. xml. Em seguida, vamos abrir janela de linha de comando e ir para o diretório onde build. xml é colocado. Finalmente, execute o comando ant - Dmain-class com. tutorialspoint. JasperReportFill (viewFullReport é o destino padrão) como menos Como resultado da compilação acima, uma janela JasperViewer se abre como mostrado na tela abaixo abaixo Aqui, podemos ver, Para o último registro, não tínhamos passado quaisquer dados para o país de campo, NENHUM PAÍS está sendo impresso. Variáveis ​​de relatório As variáveis ​​de relatório são objetos especiais construídos na parte superior da expressão do relatório. As variáveis ​​de relatório simplificam as seguintes tarefas menos expressões de relatório, que são fortemente utilizadas em todo o modelo de relatório. Essas expressões podem ser declaradas apenas uma vez usando as variáveis ​​de relatório. As variáveis ​​de relatório podem executar vários cálculos com base nos valores de expressões correspondentes, como contagem, soma, média, menor, maior, variância, etc. Se as variáveis ​​forem definidas em um design de relatório, estas podem ser referenciadas por novas variáveis ​​nas expressões. Assim, a ordem em que as variáveis ​​são declaradas em um projeto de relatório é importante. Declaração de variável Uma declaração de variável é a seguinte minus Como visto acima, o elemento ltvariablegt contém o número de atributos. Esses atributos são resumidos a seguir menos The Name Attribute Similar to parameters and fields. O atributo name do elemento ltvariablegt é obrigatório. Permite referenciar a variável pelo seu nome declarado nas expressões do relatório. O atributo de classe O atributo de classe também é obrigatório que especifica o nome da classe para os valores da variável. Seu valor padrão é java. lang. String. Isso pode ser alterado para qualquer classe disponível no classpath, tanto no momento da compilação do relatório quanto no tempo de preenchimento do relatório. O motor cuida do tipo de fundição em expressões de relatório que o token V é usado, portanto, a fundição de tipo manual não é necessária. Cálculo Este atributo determina menos o cálculo a executar na variável ao preencher o relatório. As subseções a seguir descrevem todos os valores possíveis para o atributo de cálculo do elemento ltvariablegt. Média menos O valor da variável é a média de cada valor não nulo da expressão da variável. Válido apenas para variáveis ​​numéricas. Contagem menos O valor da variável é a contagem de instâncias não nulas da expressão da variável. Primeiro menos O valor da variável é o valor da primeira instância da expressão da variável. Valores subseqüentes são ignorados. Maior menos O valor da variável é o valor mais alto para a expressão da variável. Menor menos O valor da variável é o valor mais baixo para a expressão da variável no relatório. Nada menos Nenhum cálculo é realizado na variável. StandardDeviation menos O valor da variável é o desvio padrão de todos os valores não nulos que correspondem à expressão do relatório. Válido apenas para variáveis ​​numéricas. Soma menos O valor da variável é a soma de todos os valores não nulos retornados pela expressão do relatório. Sistema menos O valor da variável é um cálculo personalizado (calculando o valor para essa variável você mesmo, usando a funcionalidade scriptlets do JasperReports). Variância menos O valor da variável é a variância de todos os valores não nulos retornados pela avaliação da expressão das variáveis ​​de relatório. Incrementer FactoryClass Esse atributo determina a classe usada para calcular o valor da variável ao preencher o registro atual no relatório. O valor padrão seria qualquer classe implementando net. sf. jasperreports. engine. fill. JRIncrementerFactory. A classe de fábrica será usada pelo mecanismo para instanciar objetos de incremento em tempo de execução, dependendo do atributo de cálculo definido para a variável. IncrementType Isso determina quando recalcular o valor da variável. Este atributo utiliza valores, como abaixo menos Coluna menos O valor da variável é recalculado no final de cada coluna. Grupo menos O valor da variável é recalculado quando o grupo especificado pelo incrementoGroup muda. Nenhum menos O valor da variável é recalculado com cada registro. Page minus O valor da variável é recalculado no final de cada página. Relatório minus O valor da variável é recalculado uma vez, no final do relatório. IncrementGroup Isso determina o nome do grupo no qual o valor da variável é recalculado, quando incrementType for Group. Isso leva o nome de qualquer grupo declarado no modelo de relatório JRXML. Isso determina quando o valor de uma variável é redefinido. Este atributo utiliza valores, como abaixo menos Coluna menos O valor da variável é reposto no início de cada coluna. Grupo menos O valor da variável é redefinido quando o grupo especificado pelo incrementoGroup muda. Nenhum menos O valor da variável nunca é redefinido. Page minus O valor da variável é reposto no início de cada página. Relatório minus O valor da variável é reposto apenas uma vez, no início do relatório. ResetGroup Isso determina o nome do grupo no qual o valor da variável é redefinido, quando resetType for Group. Os valores para esse atributo seriam o nome de qualquer grupo declarado no modelo de relatório JRXML. Variáveis ​​de relatório incorporadas Existem algumas variáveis ​​de sistema integradas, prontas para usar em expressões, da seguinte forma minus Variável Nome e Descrição Este valor de variáveis ​​é o número da página atual. Ele pode ser usado para exibir o número da página atual eo número total de páginas usando uma característica especial dos elementos de campo de texto JasperReports, o atributo evaluationTime. O nome dessa variável é derivado do nome do grupo ao qual ele corresponde, sufixado com a seqüência COUNT. Esta variável contém o número de registros no grupo atual. Permite adicionar uma variável (countNumber) ao nosso modelo de relatório existente (Designs de Relatórios de Capítulos). Iremos prefixar a contagem para cada registro. O modelo de relatório revisado (jasperreporttemplate. jrxml) é o seguinte. Salve-o em C: toolsjasperreports-5.0.1 diretório de teste menos Os códigos java para preenchimento de relatório permanece inalterado. O conteúdo do arquivo C: toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill. java são como dados abaixo minus O conteúdo do arquivo POJO C: toolsjasperreports-5.0.1testsrccomtutorialspointDataBean. java são como dados abaixo minus O conteúdo do arquivo C: toolsjasperreports-5.0. 1testsrccomtutorialspointDataBeanList. java são como dados abaixo menos Report Generation Vamos compilar e executar o arquivo acima usando nosso processo regular de construção ANT. O conteúdo do arquivo build. xml (salvo no diretório C: toolsjasperreports-5.0.1test) são os dados abaixo. O arquivo de importação - baseBuild. xml é escolhido a partir do capítulo Configuração do Ambiente e deve ser colocado no mesmo diretório que o build. xml. Em seguida, vamos abrir janela de linha de comando e ir para o diretório onde build. xml é colocado. Por fim, execute o comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport é o destino padrão) como menos Como resultado da compilação acima, uma janela JasperViewer abre como na tela abaixo menos Aqui, vemos que a contagem é prefixada Para cada registro. Seções de relatório Discutimos a estrutura de um modelo de relatório simples no capítulo Primeiros passos. Em linhas semelhantes, o JasperReports estrutura o modelo de relatório em várias seções. As seções são partes do relatório que têm uma altura especificada e podem conter objetos de relatório como linhas, retângulos, imagens ou campos de texto. O mecanismo de relatório itera através dos registros virtuais da fonte de dados de relatório fornecida, no momento do preenchimento do relatório. Dependendo do comportamento definido por cada seção, o mecanismo processa cada seção de relatório quando apropriado. Por exemplo, a seção de detalhes é processada para cada registro na fonte de dados. Quando quebras de página ocorrem, as seções de cabeçalho de página e rodapé de página são processadas conforme necessário. No JasperReports, terminologia e seções de relatório também são chamados como bandas de relatório. As seções são constituídas por uma ou mais faixas. Essas seções são preenchidas repetidamente no momento da geração do relatório e preparam o documento final. Seções Principais Um modelo de relatório no JasperReports tem as seguintes seções principais menos A tabela a seguir resume cada uma das seções menos Altura da seção especifica a altura em pixels para essa seção específica e é muito importante no projeto geral do relatório. Print When Expression Uma expressão booleana que determina se a seção deve ser impressa ou não. Split Allowed Uma bandeira indicando se a seção pode ser dividida quando não cabe na página atual. Se true, a seção será transferida para a próxima página. Observe que no caso, a seção não se encaixa na próxima página, então a seção será dividida independentemente do valor de sinalizadores. SplitType pode ter os seguintes valores minus splitTypeStretch: Divide o conteúdo esticado. Se a seção se estica na página atual (se o espaço disponível for menor que a altura declarada), a região que é adicionada à altura original é permitida para dividir na próxima página. SplitTypePrevent: Prevenção de divisão na primeira tentativa. Se a seção não se encaixa na próxima página, a divisão ocorre normalmente, uma vez que a prevenção de divisão de banda é efetiva somente na primeira tentativa de divisão. SplitTypeImmediate: Dividir imediatamente. A banda é permitida para dividir em qualquer lugar, exceto acima, o seu elemento mais alto. Para demonstrar cada seção, vamos gravar o modelo de relatório (jasperreporttemplate. jrxml). Salve este arquivo no diretório C: toolsjasperreports-5.0.1test. Neste arquivo, estaríamos exibindo um texto em cada uma das seções (discutimos acima). O conteúdo do arquivo é como indicado abaixo minus O código java para preencher e gerar o relatório é dado abaixo. Permite salvar este arquivo JasperReportFill. java para o diretório C: toolsjasperreports-5.0.1testsrccomtutorialspoint. Aqui, usamos uma instância de JREmptyDataSource ao preencher relatórios para simular uma fonte de dados com um registro nele, mas com todos os campos neste único registro sendo nulo. Geração de Relatórios Vamos compilar e executar o arquivo acima usando nosso processo regular de criação de ANT. O conteúdo do arquivo build. xml (salvo no diretório C: toolsjasperreports-5.0.1test) são como abaixo. O arquivo de importação - baseBuild. xml é retirado do capítulo Configuração do Ambiente e deve ser colocado no mesmo diretório que o build. xml. Em seguida, vamos abrir janela de linha de comando e ir para o diretório onde build. xml é colocado. Finalmente, execute o comando ant - Dmain-classcom. tutorialspoint. JasperReportFill (viewFullReport é o destino padrão) da seguinte forma minus Como resultado da compilação acima, uma janela do JasperViewer abre como na tela abaixo menos Aqui, podemos ver em cada um 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