├── settings.gradle ├── .gitignore ├── logo.png ├── salmosReport_SQL_Hibernate.jpg ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── java │ │ └── io │ │ └── github │ │ └── birddevelper │ │ └── salmos │ │ ├── setting │ │ ├── SummaryType.java │ │ ├── XmlReportElementType.java │ │ └── HtmlReportTemplate.java │ │ ├── db │ │ └── JdbcQueryExcuter.java │ │ ├── ObjectFactory.java │ │ ├── ReportMaker.java │ │ ├── XmlReportMaker.java │ │ ├── HtmlReportMaker.java │ │ └── GeneralReportMaker.java └── test │ └── java │ └── io │ └── github │ └── birddevelper │ └── salmos │ ├── XmlReportMakerTest.java │ ├── HtmlReportMakerTest.java │ └── GeneralReportMakerTest.java ├── .idea ├── vcs.xml ├── .gitignore ├── jpa-buddy.xml ├── modules.xml ├── runConfigurations.xml ├── misc.xml ├── compiler.xml ├── salmos-report-spring-boot-starter.iml ├── gradle.xml ├── jarRepositories.xml └── uiDesigner.xml ├── .github └── workflows │ └── gradle-publish.yml ├── pom.xml ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'salmos-report-spring-boot-starter' 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Project exclude paths 2 | /.gradle/ 3 | /build/ 4 | /build/classes/java/main/ -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/birddevelper/salmos-report-spring-boot-starter/HEAD/logo.png -------------------------------------------------------------------------------- /salmosReport_SQL_Hibernate.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/birddevelper/salmos-report-spring-boot-starter/HEAD/salmosReport_SQL_Hibernate.jpg -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/birddevelper/salmos-report-spring-boot-starter/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/setting/SummaryType.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos.setting; 2 | 3 | public enum SummaryType { 4 | SUM, 5 | AVERAGE, 6 | COUNT 7 | } 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | # Editor-based HTTP Client requests 8 | /httpRequests/ 9 | -------------------------------------------------------------------------------- /.idea/jpa-buddy.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/setting/XmlReportElementType.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos.setting; 2 | 3 | public enum XmlReportElementType { 4 | 5 | RecordColumnAsElementAttribute, 6 | RecordColumnAsElementChild 7 | 8 | } 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/db/JdbcQueryExcuter.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos.db; 2 | 3 | import org.springframework.jdbc.core.support.JdbcDaoSupport; 4 | 5 | import javax.sql.DataSource; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | 10 | public class JdbcQueryExcuter extends JdbcDaoSupport { 11 | 12 | 13 | public JdbcQueryExcuter(DataSource dataSource) { 14 | setDataSource(dataSource); 15 | } 16 | 17 | 18 | public List> getResultList(String sql){ 19 | 20 | return getJdbcTemplate().queryForList(sql); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/salmos-report-spring-boot-starter.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/ObjectFactory.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import lombok.AccessLevel; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import java.util.*; 8 | 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | 11 | @Getter 12 | @Setter 13 | public class ObjectFactory { 14 | 15 | protected Map reportFields; 16 | 17 | @Setter(value= AccessLevel.NONE) 18 | protected List> listOfObjects; 19 | 20 | public void loadObjects(List objects){ 21 | if(reportFields==null) 22 | throw new IllegalArgumentException("No field specified to be shown in report, first set report fields in reportFields "); 23 | listOfObjects = new ArrayList<>(); 24 | ObjectMapper objectMapper = new ObjectMapper(); 25 | for(T obj: objects){ 26 | Map objectMapping = objectMapper.convertValue(obj, Map.class); 27 | Map reportRow = new HashMap<>(); 28 | for (Map.Entry field : reportFields.entrySet()) 29 | reportRow.put(field.getValue(), objectMapping.get(field.getKey())); 30 | listOfObjects.add(reportRow); 31 | 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/io/github/birddevelper/salmos/XmlReportMakerTest.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.*; 7 | 8 | public class XmlReportMakerTest { 9 | 10 | 11 | public class Student { 12 | 13 | public String name; 14 | public int age; 15 | public List skills; 16 | 17 | 18 | } 19 | 20 | @Test 21 | public void generateXmlFromListOfObjectTest(){ 22 | List studentList = new ArrayList<>(); 23 | for(int i=1; i<3;i++) { 24 | Student student = new Student(); 25 | student.name = "John Be - "+i; 26 | student.age = 34+i; 27 | student.skills = Arrays.asList("java", "node"); 28 | studentList.add(student); 29 | } 30 | 31 | ObjectFactory objectFactory = new ObjectFactory(); 32 | Map fieldMap = new HashMap<>(); 33 | fieldMap.put("name", "Full Name"); 34 | fieldMap.put("age", "Age"); 35 | 36 | objectFactory.setReportFields(fieldMap); 37 | objectFactory.loadObjects(studentList); 38 | XmlReportMaker xmlReportMaker = new XmlReportMaker(objectFactory); 39 | Assertions.assertNotEquals("",xmlReportMaker.generate()); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/io/github/birddevelper/salmos/HtmlReportMakerTest.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.junit.jupiter.api.Assertions; 5 | 6 | import java.util.*; 7 | 8 | public class HtmlReportMakerTest { 9 | 10 | 11 | public class Student { 12 | 13 | public String name; 14 | public int age; 15 | public List skills; 16 | 17 | 18 | } 19 | 20 | @Test 21 | public void generateHtmlFromListOfObjectTest(){ 22 | 23 | List studentList = new ArrayList<>(); 24 | for(int i=1; i<3;i++) { 25 | Student student = new Student(); 26 | student.name = "Jessi Je - "+i; 27 | student.age = 34+i; 28 | student.skills = Arrays.asList("java", "node"); 29 | studentList.add(student); 30 | } 31 | 32 | ObjectFactory objectFactory = new ObjectFactory(); 33 | Map fieldMap = new HashMap<>(); 34 | fieldMap.put("name", "Full Name"); 35 | fieldMap.put("age", "Age"); 36 | 37 | objectFactory.setReportFields(fieldMap); 38 | objectFactory.loadObjects(studentList); 39 | HtmlReportMaker htmlReportMaker = new HtmlReportMaker(objectFactory); 40 | Assertions.assertNotEquals("",htmlReportMaker.generate()); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/io/github/birddevelper/salmos/GeneralReportMakerTest.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.*; 7 | 8 | public class GeneralReportMakerTest { 9 | 10 | public class Student { 11 | 12 | public String name; 13 | public int age; 14 | public List skills; 15 | 16 | 17 | } 18 | 19 | @Test 20 | public void generateHtmlFromListOfObjectTest(){ 21 | List studentList = new ArrayList<>(); 22 | for(int i=1; i<3;i++) { 23 | Student student = new Student(); 24 | student.name = "John Be - "+i; 25 | student.age = 34+i; 26 | student.skills = Arrays.asList("java", "node"); 27 | studentList.add(student); 28 | } 29 | 30 | ObjectFactory objectFactory = new ObjectFactory(); 31 | Map fieldMap = new HashMap<>(); 32 | fieldMap.put("name", "FullName"); 33 | fieldMap.put("age", "Age"); 34 | 35 | objectFactory.setReportFields(fieldMap); 36 | objectFactory.loadObjects(studentList); 37 | GeneralReportMaker htmlReportMaker = new GeneralReportMaker(objectFactory,"::FullName --- ::Age
"); 38 | System.out.println(htmlReportMaker.generate()); 39 | Assertions.assertNotEquals("",htmlReportMaker.generate()); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/gradle-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created 6 | # For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle 7 | 8 | name: Gradle Package 9 | 10 | on: 11 | release: 12 | types: [created] 13 | 14 | jobs: 15 | build: 16 | 17 | runs-on: ubuntu-latest 18 | permissions: 19 | contents: read 20 | packages: write 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up JDK 11 25 | uses: actions/setup-java@v3 26 | with: 27 | java-version: '11' 28 | distribution: 'temurin' 29 | server-id: github # Value of the distributionManagement/repository/id field of the pom.xml 30 | settings-path: ${{ github.workspace }} # location for the settings.xml file 31 | 32 | - name: Build with Gradle 33 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 34 | with: 35 | arguments: build 36 | 37 | # The USERNAME and TOKEN need to correspond to the credentials environment variables used in 38 | # the publishing section of your build.gradle 39 | - name: Publish to GitHub Packages 40 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 41 | with: 42 | arguments: publish 43 | env: 44 | USERNAME: ${{ github.actor }} 45 | TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | io.github.birddevelper 6 | salmos-report-spring-boot-starter 7 | 2.1.1 8 | Salmos Report 9 | 10 | Salmos Report is a spring boot library that helps make beautiful html table, xml document, pdf document or any other format you wish from SQL query or Arrays and Lists. Until now, it can produce Html, xml, pdf document and custom format report . 11 | 12 | https://github.com/birddevelper/salmos-report-spring-boot-starter 13 | 14 | 15 | The Apache License, Version 2.0 16 | http://www.apache.org/licenses/LICENSE-2.0.txt 17 | 18 | 19 | 20 | 21 | 22 | 23 | M.Shaeri 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | ossrh 32 | https://s01.oss.sonatype.org/content/repositories/snapshots 33 | 34 | 35 | ossrh 36 | https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 37 | 38 | 39 | 40 | 41 | 42 | 43 | scm:git:git@github.com:birddevelper/salmos-report-spring-boot-starter.git 44 | scm:git:ssh://github.com:birddevelper/salmos-report-spring-boot-starter.git 45 | https://github.com/birddevelper/salmos-report-spring-boot-starter/tree/master 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/ReportMaker.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import io.github.birddevelper.salmos.db.JdbcQueryExcuter; 4 | import io.github.birddevelper.salmos.setting.SummaryType; 5 | import lombok.AccessLevel; 6 | import lombok.Getter; 7 | import lombok.Setter; 8 | 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.regex.Pattern; 15 | 16 | import com.fasterxml.jackson.databind.ObjectMapper; 17 | 18 | @Getter 19 | @Setter 20 | @Accessors(fluent = false, chain = true) 21 | public abstract class ReportMaker { 22 | 23 | protected boolean summaryCommaSeperatedNumbers = false; 24 | protected int summaryDecimalPrecision = 0; 25 | 26 | @Setter(value= AccessLevel.NONE) 27 | protected String sqlQuery; 28 | 29 | protected ObjectFactory objectFactory; 30 | 31 | 32 | @Getter(value= AccessLevel.NONE) 33 | @Setter(value= AccessLevel.NONE) 34 | protected HashMap summaryColumns; 35 | 36 | @Getter(value= AccessLevel.NONE) 37 | @Setter(value= AccessLevel.NONE) 38 | protected JdbcQueryExcuter jdbcQueryExcuter; 39 | 40 | 41 | public void setSqlQuery(String sqlQuery){ 42 | if(objectFactory!=null) 43 | throw new IllegalStateException("You can not set sql query when you built your report maker with ObjectFactory."); 44 | this.sqlQuery = sqlQuery; 45 | } 46 | 47 | public void addSummaryColumn(String columnName, SummaryType summaryType){ 48 | this.summaryColumns.put(columnName,summaryType); 49 | } 50 | 51 | public void removeSummaryColumn(String columnName){ 52 | this.summaryColumns.remove(columnName); 53 | } 54 | 55 | protected String roundOff(double val, int decimalPlace, boolean summaryCommaSeperatedNumbers) 56 | { 57 | return String.format("%"+(summaryCommaSeperatedNumbers ? ",": "")+"." + decimalPlace + "f", val); 58 | } 59 | 60 | 61 | 62 | protected boolean isNumeric(String strNum) { 63 | Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?"); 64 | if (strNum == null) { 65 | return false; 66 | } 67 | return pattern.matcher(strNum).matches(); 68 | } 69 | 70 | abstract public String generate(); 71 | 72 | abstract public File generateFile(String filePathName) throws IOException; 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/setting/HtmlReportTemplate.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos.setting; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import java.util.List; 7 | 8 | @Getter 9 | @Setter 10 | @Accessors(fluent = false, chain = true) 11 | @Builder 12 | public class HtmlReportTemplate { 13 | 14 | public HtmlReportTemplate() { 15 | this.rowIndexVisible = false; 16 | this.rightToLeft = false; 17 | this.tableCssClass = ""; 18 | this.oddRowCssClass = ""; 19 | this.evenRowCssClass = ""; 20 | this.titleBarCssClass = ""; 21 | this.headerRowCssClass = ""; 22 | this.rowIndexHeader = ""; 23 | this.footerRowCssClass = ""; 24 | 25 | this.tableCssStyle = ""; 26 | this.oddRowCssStyle = ""; 27 | this.evenRowCssStyle = ""; 28 | this.titleBarCssStyle = ""; 29 | this.headerRowCssStyle = ""; 30 | this.footerRowCssStyle = ""; 31 | 32 | 33 | 34 | } 35 | 36 | public HtmlReportTemplate(boolean RowIndexVisible, String tableCssClass, boolean rightToLeft, 37 | String oddRowCssClass, String evenRowCssClass, String titleBarCssClass, String headerRowCssClass, 38 | String rowIndexHeader, String footerRowCssClass) { 39 | this.rowIndexVisible = RowIndexVisible; 40 | this.tableCssClass = tableCssClass; 41 | this.rightToLeft = rightToLeft; 42 | this.oddRowCssClass = oddRowCssClass; 43 | this.evenRowCssClass = evenRowCssClass; 44 | this.titleBarCssClass = titleBarCssClass; 45 | this.headerRowCssClass = headerRowCssClass; 46 | this.rowIndexHeader = rowIndexHeader; 47 | this.footerRowCssClass = footerRowCssClass; 48 | } 49 | 50 | 51 | 52 | 53 | private boolean rowIndexVisible; 54 | private List summaryColumns; 55 | private String tableCssClass; 56 | private boolean rightToLeft; 57 | private String oddRowCssClass; 58 | private String evenRowCssClass; 59 | private String titleBarCssClass; 60 | private String headerRowCssClass; 61 | private String rowIndexHeader; 62 | private String footerRowCssClass; 63 | 64 | private String oddRowCssStyle; 65 | private String evenRowCssStyle; 66 | private String titleBarCssStyle; 67 | private String headerRowCssStyle; 68 | private String footerRowCssStyle; 69 | private String tableCssStyle; 70 | } 71 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/XmlReportMaker.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import io.github.birddevelper.salmos.setting.SummaryType; 4 | import io.github.birddevelper.salmos.setting.XmlReportElementType; 5 | import io.github.birddevelper.salmos.db.JdbcQueryExcuter; 6 | import lombok.AccessLevel; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | import org.springframework.beans.factory.annotation.Configurable; 10 | 11 | import javax.sql.DataSource; 12 | import java.io.File; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.nio.charset.Charset; 16 | import java.util.*; 17 | 18 | 19 | @Getter 20 | @Setter 21 | @Configurable 22 | @Accessors(fluent = false, chain = true) 23 | public class XmlReportMaker extends ReportMaker{ 24 | 25 | 26 | 27 | String rootElementName = "root"; 28 | String childElementName = "child"; 29 | XmlReportElementType xmlReportElementType = XmlReportElementType.RecordColumnAsElementChild; 30 | String newLine = "\n"; 31 | 32 | 33 | public XmlReportMaker(DataSource datasource) { 34 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 35 | summaryColumns = new HashMap(); 36 | 37 | } 38 | 39 | public XmlReportMaker(ObjectFactory objectFactory) { 40 | this.objectFactory = objectFactory; 41 | summaryColumns = new HashMap(); 42 | 43 | } 44 | 45 | 46 | 47 | 48 | 49 | public String generate(){ 50 | if(xmlReportElementType == XmlReportElementType.RecordColumnAsElementChild) 51 | return generateXMLRecordColumnAsElementChild( ); 52 | else 53 | return generateXMLRecordColumnAsElementAttribute( ); 54 | } 55 | 56 | 57 | @Override 58 | public File generateFile(String filePathName) throws IOException { 59 | File file = new File(filePathName); 60 | FileOutputStream outputStream = new FileOutputStream(file); 61 | String fileContent = generate(); 62 | outputStream.write(fileContent.getBytes(Charset.forName("UTF-8"))); 63 | return file; 64 | } 65 | 66 | 67 | 68 | private String generateXMLRecordColumnAsElementAttribute( ){ 69 | 70 | 71 | List> rows = jdbcQueryExcuter.getResultList(this.sqlQuery); 72 | 73 | String xmlRoot = "<"+ rootElementName +" ::sumAttr >" + this.newLine ; 74 | 75 | String bodyXml = ""; 76 | 77 | boolean gotColumnName = false; 78 | String[] columnsNames = null; 79 | int NumberOfcolumns = 0; 80 | HashMap summaryValue = new HashMap<>(); 81 | 82 | int Index=0; 83 | for(String column : summaryColumns.keySet()) 84 | summaryValue.put(column,0.0); 85 | 86 | 87 | 88 | for(Map row:rows){ 89 | Index++; 90 | 91 | /// Getting the Columns name from first row 92 | String childElement ="\t<"+ childElementName + " ::childAttr />"+this.newLine ; 93 | /// Getting data and making row 94 | if(!gotColumnName) { 95 | Set columns = row.keySet(); 96 | Iterator column = columns.iterator(); 97 | NumberOfcolumns = columns.size() ; 98 | gotColumnName = true; 99 | columnsNames = new String[NumberOfcolumns]; 100 | columns.toArray(columnsNames); 101 | } 102 | 103 | String Attributes = ""; 104 | for(int i=0; i< NumberOfcolumns; i++ ){ 105 | 106 | String ColumnName= columnsNames[i]; 107 | Object RawData = row.get(ColumnName); 108 | String data = String.valueOf(RawData); 109 | 110 | Attributes += String.format("%s = \"%s\" ", ColumnName, data) ; 111 | 112 | if(summaryValue.containsKey(ColumnName) && RawData!= null){ 113 | 114 | 115 | switch(summaryColumns.get(ColumnName)) 116 | { 117 | case SUM: 118 | if(isNumeric(data.replace(",",""))) 119 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ Double.parseDouble(data.replace(",",""))); 120 | break; 121 | case AVERAGE: 122 | if(isNumeric(data.replace(",",""))) 123 | summaryValue.put(ColumnName, (summaryValue.get(ColumnName) * ( Index -1 ) + Double.parseDouble(data.replace(",","")))/Index ); 124 | break; 125 | case COUNT: 126 | if( data!=null && data!="") 127 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ 1); 128 | break; 129 | default: 130 | System.out.println("no match"); 131 | } 132 | 133 | 134 | } 135 | } 136 | 137 | childElement = childElement.replace("::childAttr",Attributes); 138 | 139 | bodyXml+= childElement; 140 | 141 | 142 | } 143 | 144 | String sumAttr=""; 145 | if(summaryColumns.size()>0) { 146 | 147 | for (String column : columnsNames) { 148 | if(summaryValue.containsKey(column)) 149 | sumAttr += column + "=\"" + roundOff( summaryValue.get(column), this.summaryDecimalPrecision, this.summaryCommaSeperatedNumbers ) + "\" "; 150 | 151 | } 152 | } 153 | xmlRoot = xmlRoot.replace("::sumAttr",sumAttr); 154 | xmlRoot+= bodyXml; 155 | xmlRoot += "" + this.newLine ; 156 | 157 | 158 | 159 | 160 | 161 | return xmlRoot; 162 | } 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | private String generateXMLRecordColumnAsElementChild( ){ 171 | 172 | List> rows=null; 173 | 174 | if(this.objectFactory!=null){ 175 | if(objectFactory.getListOfObjects()!=null ) 176 | rows = objectFactory.getListOfObjects(); 177 | else 178 | throw new IllegalArgumentException("Please load objects list in objectFactory before making report"); 179 | } 180 | else if(this.sqlQuery!=null && this.sqlQuery.length()>0) { 181 | rows = jdbcQueryExcuter.getResultList(this.sqlQuery); 182 | } 183 | else { 184 | throw new IllegalArgumentException("Neither Objects List Nor Sql query is given to report maker."); 185 | } 186 | 187 | 188 | String xmlRoot = "<"+ rootElementName +" ::sumAttr >" + this.newLine ; 189 | 190 | String bodyXml = ""; 191 | 192 | boolean gotColumnName = false; 193 | String[] columnsNames = null; 194 | int NumberOfcolumns = 0; 195 | HashMap summaryValue = new HashMap<>(); 196 | 197 | int Index=0; 198 | for(String column : summaryColumns.keySet()) 199 | summaryValue.put(column,0.0); 200 | 201 | 202 | 203 | for(Map row:rows){ 204 | Index++; 205 | 206 | /// Getting the Columns name from first row 207 | String childElement ="\t<"+ childElementName + " >"+this.newLine ; 208 | /// Getting data and making row 209 | if(!gotColumnName) { 210 | Set columns = row.keySet(); 211 | Iterator column = columns.iterator(); 212 | NumberOfcolumns = columns.size() ; 213 | gotColumnName = true; 214 | columnsNames = new String[NumberOfcolumns]; 215 | columns.toArray(columnsNames); 216 | } 217 | 218 | for(int i=0; i< NumberOfcolumns; i++ ){ 219 | 220 | String ColumnName= columnsNames[i]; 221 | Object RawData = row.get(ColumnName); 222 | String data = String.valueOf(RawData); 223 | 224 | childElement += String.format("\t\t<%s>%s%s", ColumnName, data, ColumnName, this.newLine) ; 225 | 226 | if(summaryValue.containsKey(ColumnName) && RawData!= null){ 227 | switch(summaryColumns.get(ColumnName)) 228 | { 229 | case SUM: 230 | if(isNumeric(data.replace(",",""))) 231 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ Double.parseDouble(data.replace(",",""))); 232 | break; 233 | case AVERAGE: 234 | if(isNumeric(data.replace(",",""))) 235 | summaryValue.put(ColumnName, (summaryValue.get(ColumnName) * ( Index -1 ) + Double.parseDouble(data.replace(",","")))/Index ); 236 | break; 237 | case COUNT: 238 | if( data!=null && data!="") 239 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ 1); 240 | break; 241 | default: 242 | System.out.println("no match"); 243 | } 244 | 245 | 246 | } 247 | } 248 | 249 | childElement +="\t" + this.newLine ; 250 | 251 | bodyXml+= childElement; 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | } 263 | 264 | String sumAttr=""; 265 | if(summaryColumns.size()>0) { 266 | 267 | for (String column : columnsNames) { 268 | if(summaryValue.containsKey(column)) 269 | sumAttr += column + "=\"" + roundOff( summaryValue.get(column), this.summaryDecimalPrecision, this.summaryCommaSeperatedNumbers ) + "\" "; 270 | 271 | } 272 | } 273 | xmlRoot = xmlRoot.replace("::sumAttr",sumAttr); 274 | xmlRoot+= bodyXml; 275 | xmlRoot += "" + this.newLine ; 276 | 277 | 278 | return xmlRoot; 279 | } 280 | 281 | 282 | 283 | 284 | 285 | } 286 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | What is SalmosReport 2 | ====== 3 | [![Maven Central](https://img.shields.io/maven-central/v/io.github.birddevelper/salmos-report-spring-boot-starter.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22io.github.birddevelper%22%20AND%20a:%22salmos-report-spring-boot-starter%22) 4 | 5 | SalmosReport is a spring boot library that facilitates the creation of HTML reporting tables and documents in various formats such as HTML, XML, PDF, and custom formats from SQL queries, arrays, and lists. Presently, the tool can generate HTML, XML, PDF documents, and customized format reports.other custom formats. 6 | 7 | ![Salmos Report](https://raw.githubusercontent.com/birddevelper/salmos-report-spring-boot-starter/master/salmosReport_SQL_Hibernate.jpg) 8 | 9 | 10 | ### Features 11 | 12 | * Read data from List of Objects and Entities 13 | * Read data from database by sql query 14 | * Aggregation functions (Sum, Average, Count) 15 | * Generate HTML Report 16 | * Generate XML document 17 | * Generate PDF document 18 | * Generate custom structure report 19 | * Generate TEXT file from report 20 | * Css Classes for HTML report 21 | * Embedded Css Style for HTML report 22 | 23 | ### Getting started 24 | 25 | 26 | Current Version of the plugin is 2.1.0 27 | 28 | Gradle : 29 | ```shell 30 | implementation 'io.github.birddevelper:salmos-report-spring-boot-starter:2.1.0' 31 | ``` 32 | 33 | 34 | Maven : 35 | ```shell 36 | 37 | io.github.birddevelper 38 | salmos-report-spring-boot-starter 39 | 2.1.0 40 | 41 | ``` 42 | 43 | ### Usage 44 | 45 | There exist 3 classes in this plugin to make amazing things for you. 46 | 47 | * HtmlReportMaker : A class that generates HTML table from records retrieved from sql query or from list of objects. 48 | * XmlReportMaker : A class that generates XML document from records retrieved from sql query or from list of objects. 49 | * GeneralReportMaker : This class generates output in any given structure and format from sql query or list of objects. 50 | 51 | #### HtmlReportMaker Sample code 52 | 53 | ```java 54 | import io.github.birddevelper.salmos.HtmlReportMaker; 55 | import io.github.birddevelper.salmos.setting.HtmlReportTemplate; 56 | import io.github.birddevelper.salmos.setting.SummaryType; 57 | 58 | 59 | @Service 60 | public class ReportService { 61 | 62 | @Autowired 63 | DataSource dataSource; 64 | 65 | public String generateReport() { 66 | 67 | // Creating instance of HtmlReportMaker 68 | HtmlReportMaker hrm = new HtmlReportMaker(dataSource); 69 | // specify columns of data that must be summarized in table footer row 70 | hrm.addSummaryColumn("Age", SummaryType.AVERAGE); 71 | hrm.addSummaryColumn("Salary", SummaryType.SUM); 72 | 73 | // template specifies the report table appearance 74 | HtmlReportTemplate myTemplate = new HtmlReportTemplate(); 75 | myTemplate.setTableCssClass("tblReport"); 76 | myTemplate.setEvenRowCssClass("myEvensRow"); 77 | myTemplate.setOddRowCssClass("myOddsRow"); 78 | myTemplate.setHeaderRowCssClass("myheader"); 79 | myTemplate.setRightToLeft(true); 80 | myTemplate.setRowIndexHeader("#"); 81 | myTemplate.setRowIndexVisible(true); 82 | 83 | hrm.setTemplate(myTemplate); 84 | 85 | // summary section numbers decimal point setting 86 | hrm.setSummaryDecimalPrecision(1); 87 | 88 | // summary section numbers seperated by comma 89 | hrm.setSummaryCommaSeperatedNumbers(true); 90 | 91 | // show row's index 92 | hrm.isRowIndexVisible(true); 93 | 94 | // set the query retrieving data from database 95 | hrm.setSqlQuery("select fullname as 'Name', age as 'Age', salary as 'Salary' from chamber limit 0,10"); 96 | 97 | return hrm.generate(); 98 | 99 | 100 | 101 | } 102 | } 103 | ``` 104 | 105 | 106 | 107 | 108 | #### XmlReportMaker Sample Code 109 | 110 | ```java 111 | import io.github.birddevelper.salmos.XmlReportMaker; 112 | import io.github.birddevelper.salmos.setting.SummaryType; 113 | import io.github.birddevelper.salmos.setting.XmlReportElementType; 114 | @Service 115 | public class ReportService { 116 | 117 | @Autowired 118 | DataSource dataSource; 119 | 120 | public String generateXMLReport() { 121 | // Creating instance of XmlReportMaker 122 | XmlReportMaker xrm = new XmlReportMaker(dataSource); 123 | 124 | // specify columns of data that must be summarized (they will put in root element as attribute) 125 | xrm.addSummaryColumn("Age", SummaryType.AVERAGE); 126 | xrm.addSummaryColumn("Salary", SummaryType.SUM); 127 | 128 | // summary section numbers decimal point setting 129 | xrm.setSummaryDecimalPrecision(0); 130 | 131 | xrm.setRootElementName("Persons"); 132 | xrm.setChildElementName("person"); 133 | 134 | // this line set the generator to put row data in attributes of row element 135 | xrm.setXmlReportElementType(XmlReportElementType.RecordColumnAsElementAttribute); 136 | 137 | // set the query retrieving data from database 138 | xrm.setSqlQuery("select fullname as 'Name', age as 'Age', salary as 'Salary' from chamber limit 0,10"); 139 | 140 | return xrm.generate(); 141 | } 142 | } 143 | ``` 144 | 145 | 146 | 147 | 148 | 149 | 150 | #### GeneralReportMaker Sample code 151 | 152 | ```java 153 | import org.log.carvan.utils.GeneralReportMaker; 154 | import io.github.birddevelper.salmos.setting.SummaryType; 155 | 156 | @Service 157 | public class ReportService { 158 | 159 | @Autowired 160 | DataSource dataSource; 161 | 162 | public String generateUniversalReport() { 163 | 164 | GeneralReportMaker grm = new GeneralReportMaker(dataSource); 165 | // load template from file located in resources 166 | grm.loadTemplateBodyFromFile("templates/salmosTemplates/template1.html"); 167 | 168 | // set the query retrieving data from database 169 | grm.setSqlQuery("select fullname as 'Name', age as 'Age', salary as 'Salary' from chamber limit 0,10"); 170 | 171 | // specify columns of data that must be summarized 172 | grm.addSummaryColumn("Age", SummaryType.AVERAGE); 173 | grm.addSummaryColumn("Salary", SummaryType.SUM); 174 | 175 | // set footer template with String (to have a column summary in footer, you should use ::[column name]Summary in template 176 | grm.setTemplateFooter("

CityCount >> ::AgeSummary ---- Capacity Average >> ::SalarySummary

"); 177 | 178 | 179 | return grm.generate(); // return String containing the produced report 180 | 181 | 182 | } 183 | } 184 | ``` 185 | 186 | ### Generate PDF report 187 | ```java 188 | import io.github.birddevelper.salmos.HtmlReportMaker; 189 | import io.github.birddevelper.salmos.setting.HtmlReportTemplate; 190 | import io.github.birddevelper.salmos.setting.SummaryType; 191 | 192 | 193 | @Service 194 | public class ReportService { 195 | 196 | @Autowired 197 | DataSource dataSource; 198 | 199 | public File generatePDFReport() { 200 | 201 | // Creating instance of HtmlReportMaker 202 | HtmlReportMaker hrm = new HtmlReportMaker(dataSource); 203 | // specify columns of data that must be summarized in table footer row 204 | hrm.addSummaryColumn("Age", SummaryType.AVERAGE); 205 | hrm.addSummaryColumn("Salary", SummaryType.SUM); 206 | 207 | 208 | // summary section numbers decimal point setting 209 | hrm.setSummaryDecimalPrecision(1); 210 | 211 | // summary section numbers seperated by comma 212 | hrm.setSummaryCommaSeperatedNumbers(true); 213 | 214 | // show row's index 215 | hrm.isRowIndexVisible(true); 216 | 217 | //sql query to retrieve data rows 218 | String sql = "select fullname as 'Name', age as 'Age', salary as 'Salary' from chamber limit 0,10"; 219 | // set the query retrieving data from database 220 | hrm.setSqlQuery(sql); 221 | String[] fonts = {"fonts/ArialBold.ttf", "fonts/MyOtherFont.ttf"}; // path to fonts that you want embed in pdf document 222 | String baseUri = "the base uri"; 223 | 224 | return hrm.generatePDF("D:/mypdf.pdf",fonts,baseUri); 225 | 226 | 227 | 228 | } 229 | } 230 | ``` 231 | 232 | 233 | 234 | 235 | #### Generate from list of objects ( for example : hibernate output ) 236 | 237 | ```java 238 | import io.github.birddevelper.salmos.XmlReportMaker; 239 | import io.github.birddevelper.salmos.setting.SummaryType; 240 | import io.github.birddevelper.salmos.setting.XmlReportElementType; 241 | import lombok.Getter; 242 | import lombok.Setter; 243 | @Service 244 | public class ReportService { 245 | 246 | @Getter 247 | @Setter 248 | public class Student { 249 | private String name; 250 | private int age; 251 | private Date birthDate; 252 | private List skills; 253 | 254 | } 255 | 256 | @AutoWired 257 | StudentRepository studentRepository; 258 | 259 | public String generateHTMLReport() { 260 | 261 | 262 | List studentList = studentRepository.findAll(); 263 | 264 | 265 | // Mapping the class fields to report columns (here we want only name and age, the reset of entity fields will be ignored) 266 | Map fieldMap = new HashMap<>(); 267 | fieldMap.put("name", "Full Name"); 268 | fieldMap.put("age", "Age"); 269 | 270 | // buidling instance of ObjectFactory class 271 | ObjectFactory objectFactory = new ObjectFactory(); 272 | 273 | // setting mapping fields 274 | objectFactory.setReportFields(fieldMap); 275 | // setting entity lists 276 | objectFactory.loadObjects(studentList); 277 | 278 | // building instance of HtmlReportMaker with ObjectFactory as input parameter 279 | HtmlReportMaker htmlReportMaker = new HtmlReportMaker(objectFactory); 280 | 281 | // generate report 282 | return htmlReportMaker.generate(); 283 | } 284 | } 285 | ``` 286 | 287 | 288 | 289 | 290 | 291 | ### Change Logs : 292 | 293 | 2.1.1 : 294 | - Maven modelVersion changed to 4.0.0 295 | - builder pattern 296 | 297 | 2.1.0 : 298 | - Embedded css style attribute for HTML report 299 | 300 | 2.0.0 : 301 | - Generate reports from list of objects (for example: list of entities retrieved by hibernate) 302 | 303 | 1.2.0 : 304 | - Export to PDF and TEXT files added. 305 | 306 | 1.1.0 : 307 | 308 | - GeneralReportMaker class added. 309 | - Bugs fixed. 310 | 311 | 1.0.0 : 312 | - First release. 313 | - Generate Reports from Sql Query 314 | - Generate HTML and XML reports 315 | 316 | 317 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/HtmlReportMaker.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import io.github.birddevelper.salmos.setting.HtmlReportTemplate; 4 | import io.github.birddevelper.salmos.setting.SummaryType; 5 | import io.github.birddevelper.salmos.db.JdbcQueryExcuter; 6 | import lombok.AccessLevel; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | import org.jsoup.Jsoup; 10 | import org.jsoup.nodes.Document; 11 | import org.xhtmlrenderer.layout.SharedContext; 12 | import org.xhtmlrenderer.pdf.ITextRenderer; 13 | 14 | import javax.sql.DataSource; 15 | import java.io.File; 16 | import java.io.FileOutputStream; 17 | import java.io.IOException; 18 | import java.io.OutputStream; 19 | import java.nio.charset.Charset; 20 | import java.util.*; 21 | 22 | 23 | @Getter 24 | @Setter 25 | @Accessors(fluent = false, chain = true) 26 | /** 27 | * A class that makes HTML table from records retrieved by given sql query. 28 | * 29 | * @param dataSource jdbc data source that usually is configured in application.properties and can be autowired anywhere in application. 30 | * @param sqlQuery SQL query to retrieve records from database 31 | * @param title Optional Table title that will be shown on top of table 32 | * @param rightToLeft Indicates the table direction, default value is false 33 | * @param rowIndexVisible Indicates whether the table have index column or not, default value is false 34 | * @param tableCssClass Optional table css class name 35 | * @param oddRowCssClass Optional odd rows class name 36 | */ 37 | public class HtmlReportMaker extends ReportMaker { 38 | 39 | boolean rowIndexVisible; 40 | boolean rightToLeft; 41 | String oddRowCssClass; 42 | String evenRowCssClass; 43 | String titleBarCssClass; 44 | String headerRowCssClass; 45 | String footerRowCssClass; 46 | String tableCssClass; 47 | 48 | String oddRowCssStyle; 49 | String evenRowCssStyle; 50 | String titleBarCssStyle; 51 | String headerRowCssStyle; 52 | String footerRowCssStyle; 53 | String tableCssStyle; 54 | 55 | String title; 56 | String rowIndexHeader; 57 | 58 | 59 | 60 | public HtmlReportMaker(ObjectFactory objectFactory) { 61 | summaryColumns = new HashMap(); 62 | this.objectFactory = objectFactory; 63 | this.rowIndexVisible = false; 64 | this.rightToLeft = false; 65 | this.tableCssClass = ""; 66 | this.oddRowCssClass = ""; 67 | this.evenRowCssClass = ""; 68 | this.titleBarCssClass = ""; 69 | this.headerRowCssClass = ""; 70 | this.footerRowCssClass = ""; 71 | this.tableCssStyle = ""; 72 | this.oddRowCssStyle = ""; 73 | this.evenRowCssStyle = ""; 74 | this.titleBarCssStyle = ""; 75 | this.headerRowCssStyle = ""; 76 | this.footerRowCssStyle = ""; 77 | this.rowIndexHeader = ""; 78 | this.title=""; 79 | this.summaryCommaSeperatedNumbers = false; 80 | } 81 | 82 | 83 | public HtmlReportMaker(DataSource datasource) { 84 | summaryColumns = new HashMap(); 85 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 86 | this.rowIndexVisible = false; 87 | this.rightToLeft = false; 88 | this.tableCssClass = ""; 89 | this.oddRowCssClass = ""; 90 | this.evenRowCssClass = ""; 91 | this.titleBarCssClass = ""; 92 | this.headerRowCssClass = ""; 93 | this.rowIndexHeader = ""; 94 | this.footerRowCssClass = ""; 95 | this.tableCssStyle = ""; 96 | this.oddRowCssStyle = ""; 97 | this.evenRowCssStyle = ""; 98 | this.titleBarCssStyle = ""; 99 | this.headerRowCssStyle = ""; 100 | this.footerRowCssStyle = ""; 101 | 102 | 103 | 104 | this.title=""; 105 | this.summaryCommaSeperatedNumbers = false; 106 | } 107 | 108 | public void setTemplate(HtmlReportTemplate template){ 109 | this.rowIndexVisible = template.isRowIndexVisible(); 110 | this.tableCssClass = template.getTableCssClass(); 111 | this.rightToLeft = template.isRightToLeft(); 112 | this.oddRowCssClass = template.getOddRowCssClass(); 113 | this.evenRowCssClass = template.getEvenRowCssClass(); 114 | this.titleBarCssClass = template.getTitleBarCssClass(); 115 | this.headerRowCssClass = template.getHeaderRowCssClass(); 116 | this.rowIndexHeader = template.getRowIndexHeader(); 117 | this.footerRowCssClass = template.getFooterRowCssClass(); 118 | 119 | // setting embedded style attribute 120 | this.tableCssStyle = template.getTableCssStyle(); 121 | this.oddRowCssStyle = template.getOddRowCssStyle(); 122 | this.evenRowCssStyle = template.getEvenRowCssStyle(); 123 | this.titleBarCssStyle = template.getTitleBarCssStyle(); 124 | this.headerRowCssStyle = template.getHeaderRowCssStyle(); 125 | this.footerRowCssStyle = template.getFooterRowCssStyle(); 126 | 127 | 128 | } 129 | 130 | 131 | public void addSummaryColumn(String columnName, SummaryType summaryType){ 132 | this.summaryColumns.put(columnName,summaryType); 133 | } 134 | 135 | public void removeSummaryColumn(String columnName){ 136 | this.summaryColumns.remove(columnName); 137 | } 138 | 139 | 140 | 141 | 142 | public String generate(){ 143 | return generateHTML(); 144 | } 145 | 146 | @Override 147 | public File generateFile(String filePathName) throws IOException { 148 | File file = new File(filePathName); 149 | FileOutputStream outputStream = new FileOutputStream(file); 150 | String fileContent = generateHTML(); 151 | outputStream.write(fileContent.getBytes(Charset.forName("UTF-8"))); 152 | return file; 153 | } 154 | 155 | public File generatePDF(String filePathName,String[] fonts, String baseUri, boolean printable, boolean interactable) throws IOException { 156 | Document doc = Jsoup.parse(generateHTML(),baseUri); 157 | doc.outputSettings().syntax(Document.OutputSettings.Syntax.html); 158 | File file = new File(filePathName); 159 | try(OutputStream outputStream = new FileOutputStream(file)){ 160 | ITextRenderer renderer = new ITextRenderer(); 161 | SharedContext sharedContext = renderer.getSharedContext(); 162 | if(fonts!=null){ 163 | for(String font:fonts){ 164 | renderer.getFontResolver().addFont(font,true); 165 | } 166 | } 167 | sharedContext.setPrint(printable); 168 | sharedContext.setInteractive(interactable); 169 | String fileContent = doc.html(); 170 | renderer.setDocumentFromString(fileContent,baseUri); 171 | renderer.layout(); 172 | renderer.createPDF(outputStream); 173 | return file; 174 | } 175 | catch(Exception e){ 176 | System.out.println("generate PDF error : "+ e.getMessage()); 177 | return null; 178 | 179 | } 180 | 181 | 182 | } 183 | 184 | 185 | public File generatePDF(String filePathName,String[] fonts, String baseUri) throws IOException { 186 | Document doc = Jsoup.parse(generateHTML(),baseUri); 187 | doc.outputSettings().syntax(Document.OutputSettings.Syntax.html); 188 | File file = new File(filePathName); 189 | try(OutputStream outputStream = new FileOutputStream(file)){ 190 | ITextRenderer renderer = new ITextRenderer(); 191 | SharedContext sharedContext = renderer.getSharedContext(); 192 | if(fonts!=null){ 193 | for(String font:fonts){ 194 | renderer.getFontResolver().addFont(font,true); 195 | } 196 | } 197 | sharedContext.setPrint(true); 198 | sharedContext.setInteractive(true); 199 | String fileContent = doc.html(); 200 | renderer.setDocumentFromString(fileContent,baseUri); 201 | renderer.layout(); 202 | renderer.createPDF(outputStream); 203 | return file; 204 | } 205 | catch(Exception e){ 206 | System.out.println("generate PDF error : "+ e.getMessage()); 207 | return null; 208 | } 209 | 210 | } 211 | 212 | 213 | 214 | private String generateHTML(){ 215 | List> rows=null; 216 | 217 | if(this.objectFactory!=null){ 218 | if(objectFactory.getListOfObjects()!=null ) 219 | rows = objectFactory.getListOfObjects(); 220 | else 221 | //Throw exception if object factory is passed to generator and object list is not loaded. 222 | throw new IllegalArgumentException("Please load objects list in objectFactory before making report"); 223 | } 224 | else if(this.sqlQuery!=null && this.sqlQuery.length()>0) { 225 | //working with query 226 | rows = jdbcQueryExcuter.getResultList(this.sqlQuery); 227 | } 228 | else { 229 | //if neither Objects List Nor Sql query is given to report generator, Throw exception 230 | throw new IllegalArgumentException("Neither Objects List Nor Sql query is given to report maker."); 231 | } 232 | 233 | 234 | 235 | 236 | String table=""; 237 | boolean gotColumnName = false; 238 | Integer NumberOfcolumns = 0; 239 | String headerofTable = (!this.title.equals("") ? "" : "") + "" + (this.rowIndexVisible ? "" : "" ); 240 | String bodyOfTable = ""; 241 | String footerOfTable = ""; 242 | String[] columnsNames = null; 243 | HashMap summaryValue = new HashMap<>(); 244 | int Index=0; 245 | for(String column : this.summaryColumns.keySet()) 246 | summaryValue.put(column,0.0); 247 | 248 | 249 | for(Map row:rows){ 250 | Index++; 251 | 252 | 253 | 254 | /// Get the Columns name from first row 255 | if(!gotColumnName) { 256 | Set columns = row.keySet(); 257 | Iterator column = columns.iterator(); 258 | NumberOfcolumns = columns.size() ; 259 | 260 | while (column.hasNext()) { 261 | 262 | String colName = column.next(); 263 | //System.out.println(colName); 264 | headerofTable+= String.format("") ; 265 | } 266 | 267 | headerofTable+=""; 268 | gotColumnName = true; 269 | 270 | columnsNames = new String[NumberOfcolumns]; 271 | columns.toArray(columnsNames); 272 | 273 | headerofTable = headerofTable.replace("::colspan", String.valueOf(NumberOfcolumns + (this.rowIndexVisible ? 1:0 )) ); 274 | table += headerofTable ; 275 | } 276 | 277 | /// Getting data and making row 278 | String singleRow ="" + (this.rowIndexVisible ? "": ""); 279 | 280 | for(int i=0; i< NumberOfcolumns; i++ ){ 281 | 282 | String ColumnName= columnsNames[i]; 283 | Object RawData = row.get(ColumnName); 284 | String data = String.valueOf(RawData); 285 | String dataType = RawData.getClass().getSimpleName(); 286 | singleRow += String.format("") ; 287 | 288 | /// accumulate in summary 289 | if(summaryValue.containsKey(ColumnName) && RawData!= null){ 290 | 291 | 292 | switch(this.summaryColumns.get(ColumnName)) 293 | { 294 | case SUM: 295 | if(isNumeric(data.replace(",",""))) 296 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ Double.parseDouble(data.replace(",",""))); 297 | break; 298 | case AVERAGE: 299 | if(isNumeric(data.replace(",",""))) 300 | summaryValue.put(ColumnName, (summaryValue.get(ColumnName) * ( Index -1 ) + Double.parseDouble(data.replace(",","")))/Index ); 301 | break; 302 | case COUNT: 303 | if( data!=null && data!="") 304 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ 1); 305 | break; 306 | default: 307 | System.out.println("no match"); 308 | } 309 | 310 | 311 | } 312 | } 313 | 314 | bodyOfTable+= singleRow + ""; 315 | 316 | 317 | } 318 | 319 | table+=bodyOfTable; 320 | 321 | 322 | 323 | if(this.summaryColumns.size()>0) { 324 | footerOfTable = ""+ (this.rowIndexVisible ? "" : "" ); 325 | for (String column : columnsNames) { 326 | if(summaryValue.containsKey(column)) 327 | footerOfTable += ""; 328 | else 329 | footerOfTable += ""; 330 | } 331 | } 332 | footerOfTable += ""; 333 | table+= footerOfTable + "
" + this.title + "
" + this.rowIndexHeader + " %s %s", colName ,"
"+ String.valueOf(Index) + " %s %s", data ,"
" + roundOff( summaryValue.get(column), this.summaryDecimalPrecision, this.summaryCommaSeperatedNumbers ) + " -
"; 334 | 335 | return table; 336 | } 337 | 338 | 339 | 340 | 341 | } 342 | -------------------------------------------------------------------------------- /src/main/java/io/github/birddevelper/salmos/GeneralReportMaker.java: -------------------------------------------------------------------------------- 1 | package io.github.birddevelper.salmos; 2 | 3 | import io.github.birddevelper.salmos.db.JdbcQueryExcuter; 4 | import io.github.birddevelper.salmos.setting.SummaryType; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | import org.jsoup.Jsoup; 8 | import org.jsoup.nodes.Document; 9 | import org.xhtmlrenderer.layout.SharedContext; 10 | import org.xhtmlrenderer.pdf.ITextRenderer; 11 | 12 | import javax.sql.DataSource; 13 | import java.io.*; 14 | import java.nio.charset.Charset; 15 | import java.util.*; 16 | import java.util.stream.Collectors; 17 | 18 | @Getter 19 | @Setter 20 | public class GeneralReportMaker extends ReportMaker { 21 | 22 | 23 | String templateBody =""; 24 | String templateHeader = ""; 25 | String templateFooter = ""; 26 | String itemSeparator =""; 27 | 28 | 29 | 30 | 31 | @Override 32 | public String generate() { 33 | return mixTemplateWithData(); 34 | } 35 | 36 | @Override 37 | public File generateFile(String filePathName) throws IOException { 38 | File file = new File(filePathName); 39 | FileOutputStream outputStream = new FileOutputStream(file); 40 | String fileContent = mixTemplateWithData(); 41 | outputStream.write(fileContent.getBytes(Charset.forName("UTF-8"))); 42 | return file; 43 | } 44 | 45 | public File generatePDF(String filePathName,String[] fonts, String baseUri, boolean printable, boolean interactable) throws IOException { 46 | Document doc = Jsoup.parse(mixTemplateWithData(),baseUri); 47 | doc.outputSettings().syntax(Document.OutputSettings.Syntax.html); 48 | File file = new File(filePathName); 49 | try(OutputStream outputStream = new FileOutputStream(file)){ 50 | ITextRenderer renderer = new ITextRenderer(); 51 | SharedContext sharedContext = renderer.getSharedContext(); 52 | if(fonts!=null){ 53 | for(String font:fonts){ 54 | renderer.getFontResolver().addFont(font,true); 55 | } 56 | } 57 | sharedContext.setPrint(printable); 58 | sharedContext.setInteractive(interactable); 59 | String fileContent = mixTemplateWithData(); 60 | renderer.setDocumentFromString(fileContent,baseUri); 61 | renderer.layout(); 62 | renderer.createPDF(outputStream); 63 | return file; 64 | } 65 | catch(Exception e){ 66 | System.out.println("generate PDF error : "+ e.getMessage()); 67 | return null; 68 | 69 | } 70 | 71 | 72 | } 73 | 74 | public File generatePDF(String filePathName,String[] fonts, String baseUri) throws IOException { 75 | Document doc = Jsoup.parse(mixTemplateWithData(),baseUri); 76 | doc.outputSettings().syntax(Document.OutputSettings.Syntax.html); 77 | File file = new File(filePathName); 78 | try(OutputStream outputStream = new FileOutputStream(file)){ 79 | ITextRenderer renderer = new ITextRenderer(); 80 | SharedContext sharedContext = renderer.getSharedContext(); 81 | if(fonts!=null){ 82 | for(String font:fonts){ 83 | renderer.getFontResolver().addFont(font,true); 84 | } 85 | } 86 | sharedContext.setPrint(true); 87 | sharedContext.setInteractive(true); 88 | String fileContent = mixTemplateWithData(); 89 | renderer.setDocumentFromString(fileContent,baseUri); 90 | renderer.layout(); 91 | renderer.createPDF(outputStream); 92 | return file; 93 | } 94 | catch(Exception e){ 95 | System.out.println("generate PDF error : "+ e.getMessage()); 96 | return null; 97 | } 98 | 99 | } 100 | 101 | 102 | 103 | public GeneralReportMaker(DataSource datasource) { 104 | summaryColumns = new HashMap(); 105 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 106 | } 107 | 108 | public GeneralReportMaker(DataSource datasource, String sqlQuery, String templateBody) { 109 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 110 | summaryColumns = new HashMap(); 111 | this.sqlQuery = sqlQuery; 112 | this.templateBody = templateBody; 113 | } 114 | 115 | public GeneralReportMaker(DataSource datasource, String sqlQuery, String templateBody, String templateHeader, String templateFooter) { 116 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 117 | summaryColumns = new HashMap(); 118 | this.sqlQuery = sqlQuery; 119 | this.templateBody = templateBody; 120 | } 121 | 122 | public GeneralReportMaker(DataSource datasource, String sqlQuery, InputStream templateBodyInputStream) { 123 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 124 | summaryColumns = new HashMap(); 125 | this.sqlQuery = sqlQuery; 126 | this.templateBody = getStringFromInputStream(templateBodyInputStream); 127 | 128 | } 129 | 130 | public GeneralReportMaker(DataSource datasource, String sqlQuery, InputStream templateBodyInputStream, InputStream templateHeaderInputStream, InputStream templateFooterInputStream ) { 131 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 132 | summaryColumns = new HashMap(); 133 | this.sqlQuery = sqlQuery; 134 | this.templateBody = getStringFromInputStream(templateBodyInputStream); 135 | this.templateHeader = getStringFromInputStream(templateHeaderInputStream); 136 | this.templateFooter = getStringFromInputStream(templateFooterInputStream); 137 | 138 | } 139 | 140 | public GeneralReportMaker(DataSource datasource, String sqlQuery, String templateFilePath, String itemSeparator) { 141 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 142 | summaryColumns = new HashMap(); 143 | this.sqlQuery = sqlQuery; 144 | this.templateBody = getResourceFileAsString(templateFilePath); 145 | this.itemSeparator = itemSeparator; 146 | 147 | } 148 | 149 | public GeneralReportMaker(DataSource datasource, String sqlQuery, String templateBodyFilePath, String templateHeaderFilePath, String templateFooterFilePath, String itemSeparator) { 150 | jdbcQueryExcuter = new JdbcQueryExcuter(datasource); 151 | summaryColumns = new HashMap(); 152 | this.sqlQuery = sqlQuery; 153 | this.templateBody = getResourceFileAsString(templateBodyFilePath); 154 | this.templateHeader = getResourceFileAsString(templateHeaderFilePath); 155 | this.templateFooter = getResourceFileAsString(templateFooterFilePath); 156 | this.itemSeparator = itemSeparator; 157 | 158 | } 159 | 160 | 161 | ////// Constructors with List of Objects 162 | public GeneralReportMaker(ObjectFactory objectFactory) { 163 | summaryColumns = new HashMap(); 164 | this.objectFactory = objectFactory; 165 | } 166 | 167 | public GeneralReportMaker(ObjectFactory objectFactory, String templateBody) { 168 | this.objectFactory = objectFactory; 169 | summaryColumns = new HashMap(); 170 | this.sqlQuery = sqlQuery; 171 | this.templateBody = templateBody; 172 | } 173 | 174 | public GeneralReportMaker(ObjectFactory objectFactory, String templateBody, String templateHeader, String templateFooter) { 175 | this.objectFactory = objectFactory; 176 | summaryColumns = new HashMap(); 177 | this.sqlQuery = sqlQuery; 178 | this.templateBody = templateBody; 179 | } 180 | 181 | public GeneralReportMaker(ObjectFactory objectFactory, InputStream templateBodyInputStream) { 182 | this.objectFactory = objectFactory; 183 | summaryColumns = new HashMap(); 184 | this.sqlQuery = sqlQuery; 185 | this.templateBody = getStringFromInputStream(templateBodyInputStream); 186 | 187 | } 188 | 189 | public GeneralReportMaker(ObjectFactory objectFactory, InputStream templateBodyInputStream, InputStream templateHeaderInputStream, InputStream templateFooterInputStream ) { 190 | this.objectFactory = objectFactory; 191 | summaryColumns = new HashMap(); 192 | this.sqlQuery = sqlQuery; 193 | this.templateBody = getStringFromInputStream(templateBodyInputStream); 194 | this.templateHeader = getStringFromInputStream(templateHeaderInputStream); 195 | this.templateFooter = getStringFromInputStream(templateFooterInputStream); 196 | 197 | } 198 | 199 | public GeneralReportMaker(ObjectFactory objectFactory, String templateFilePath, String itemSeparator) { 200 | this.objectFactory = objectFactory; 201 | summaryColumns = new HashMap(); 202 | this.sqlQuery = sqlQuery; 203 | this.templateBody = getResourceFileAsString(templateFilePath); 204 | this.itemSeparator = itemSeparator; 205 | 206 | } 207 | 208 | public GeneralReportMaker(ObjectFactory objectFactory, String templateBodyFilePath, String templateHeaderFilePath, String templateFooterFilePath, String itemSeparator) { 209 | this.objectFactory = objectFactory; 210 | summaryColumns = new HashMap(); 211 | this.sqlQuery = sqlQuery; 212 | this.templateBody = getResourceFileAsString(templateBodyFilePath); 213 | this.templateHeader = getResourceFileAsString(templateHeaderFilePath); 214 | this.templateFooter = getResourceFileAsString(templateFooterFilePath); 215 | this.itemSeparator = itemSeparator; 216 | 217 | } 218 | 219 | 220 | 221 | public void loadTemplateBodyFromFile(String templateBodyFilePath){ 222 | 223 | this.templateBody = getResourceFileAsString(templateBodyFilePath); 224 | } 225 | 226 | public void loadTemplateHeaderFromFile(String templateHeaderFilePath){ 227 | 228 | this.templateHeader = getResourceFileAsString(templateHeaderFilePath); 229 | } 230 | 231 | public void loadTemplateFooterFromFile(String templateFooterFilePath){ 232 | 233 | this.templateFooter = getResourceFileAsString(templateFooterFilePath); 234 | } 235 | 236 | 237 | 238 | private String mixTemplateWithData() { 239 | 240 | List> rows=null; 241 | 242 | if(this.objectFactory!=null){ 243 | if(objectFactory.getListOfObjects()!=null ) 244 | rows = objectFactory.getListOfObjects(); 245 | else 246 | throw new IllegalArgumentException("Please load objects list in objectFactory before making report"); 247 | } 248 | else if(this.sqlQuery!=null && this.sqlQuery.length()>0) { 249 | rows = jdbcQueryExcuter.getResultList(this.sqlQuery); 250 | } 251 | else { 252 | throw new IllegalArgumentException("Neither Objects List Nor Sql query is given to report maker."); 253 | } 254 | 255 | 256 | String output = ""; 257 | int Index=0; 258 | boolean gotColumnName = false; 259 | int NumberOfcolumns = 0; 260 | String[] columnsNames = null; 261 | HashMap summaryValue = new HashMap<>(); 262 | 263 | for(String column : summaryColumns.keySet()) 264 | summaryValue.put(column,0.0); 265 | 266 | 267 | for(Map row:rows){ 268 | String tempTemplate = this.templateBody; 269 | Index++; 270 | 271 | if(!gotColumnName) { 272 | Set columns = row.keySet(); 273 | Iterator column = columns.iterator(); 274 | NumberOfcolumns = columns.size() ; 275 | gotColumnName = true; 276 | columnsNames = new String[NumberOfcolumns]; 277 | columns.toArray(columnsNames); 278 | } 279 | 280 | String Attributes = ""; 281 | for(int i=0; i< NumberOfcolumns; i++ ){ 282 | 283 | String ColumnName= columnsNames[i]; 284 | Object RawData = row.get(ColumnName); 285 | String data = String.valueOf(RawData); 286 | tempTemplate = tempTemplate.replace("::"+ColumnName, data) ; 287 | 288 | if(summaryValue.containsKey(ColumnName) && RawData!= null){ 289 | switch(summaryColumns.get(ColumnName)) 290 | { 291 | case SUM: 292 | if(isNumeric(data.replace(",",""))) 293 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ Double.parseDouble(data.replace(",",""))); 294 | break; 295 | case AVERAGE: 296 | if(isNumeric(data.replace(",",""))) 297 | summaryValue.put(ColumnName, (summaryValue.get(ColumnName) * ( Index -1 ) + Double.parseDouble(data.replace(",","")))/Index ); 298 | break; 299 | case COUNT: 300 | if( data!=null && data!="") 301 | summaryValue.put(ColumnName, summaryValue.get(ColumnName)+ 1); 302 | break; 303 | default: 304 | System.out.println("no match"); 305 | } 306 | 307 | 308 | } 309 | 310 | 311 | } 312 | 313 | output += tempTemplate + this.itemSeparator; 314 | 315 | 316 | } 317 | 318 | if(summaryColumns.size()>0) { 319 | 320 | for (String columnName : columnsNames) { 321 | if(summaryValue.containsKey(columnName)) { 322 | this.templateHeader = this.templateHeader.replace("::" + columnName + "Summary", roundOff(summaryValue.get(columnName), this.summaryDecimalPrecision, this.summaryCommaSeperatedNumbers)); 323 | this.templateFooter = this.templateFooter.replace("::" + columnName + "Summary", roundOff(summaryValue.get(columnName), this.summaryDecimalPrecision, this.summaryCommaSeperatedNumbers)); 324 | } 325 | } 326 | } 327 | 328 | return this.templateHeader + output+ this.templateFooter; 329 | } 330 | 331 | 332 | 333 | 334 | private String getStringFromInputStream(InputStream inputStream) { 335 | InputStream is = inputStream; 336 | if (is != null) { 337 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 338 | return (String) reader.lines().collect(Collectors.joining(System.lineSeparator())); 339 | } else { 340 | throw new RuntimeException("not valid stream"); 341 | } 342 | } 343 | 344 | 345 | private String getResourceFileAsString(String fileName) { 346 | InputStream is = getResourceFileAsInputStream(fileName); 347 | if (is != null) { 348 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 349 | return (String) reader.lines().collect(Collectors.joining(System.lineSeparator())); 350 | } else { 351 | throw new RuntimeException("resource not found"); 352 | } 353 | } 354 | 355 | private InputStream getResourceFileAsInputStream(String fileName) { 356 | ClassLoader classLoader = this.getClass().getClassLoader(); 357 | return classLoader.getResourceAsStream(fileName); 358 | } 359 | 360 | 361 | 362 | 363 | } 364 | --------------------------------------------------------------------------------