Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,13 @@
*
* <li><b>location (default)</b> - the location where the compiled jasper report
* definition is (foo.jasper), relative from current URL.</li>
* <li><b>dataSource (required)</b> - the EL expression used to retrieve the
* datasource from the value stack (usually a List).</li>
* <li><b>dataSource</b> - the EL expression used to retrieve the
* datasource from the value stack (usually a List). When neither dataSource
* nor connection is set the report is filled from its parameters alone,
* so a data supplier expected by the report's query executer (e.g.
* <code>HIBERNATE_SESSION</code>, <code>CSV_INPUT_STREAM</code>,
* <code>JSON_INPUT_STREAM</code>) or a ready <code>REPORT_DATA_SOURCE</code> /
* <code>REPORT_CONNECTION</code> can be handed over via reportParameters.</li>
* <li><b>parse</b> - true by default. If set to false, the location param will
* not be parsed for EL expressions.</li>
* <li><b>format</b> - the format in which the report should be generated. Valid
Expand Down Expand Up @@ -258,7 +263,6 @@ public void setConnection(String connection) {
}

protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
// Will throw a runtime exception if no "datasource" property. TODO Best place for that is...?
initializeProperties(invocation);

LOG.debug("Creating JasperReport for dataSource = {}, format = {}", dataSource, format);
Expand All @@ -284,7 +288,7 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro
ValueStackDataSource stackDataSource = null;

Connection conn = (Connection) stack.findValue(connection);
if (conn == null) {
if (conn == null && dataSource != null) {
boolean evaluated = parsedDataSource != null && !parsedDataSource.equals(dataSource);
boolean reevaluate = !evaluated || isAcceptableExpression(parsedDataSource);
if (reevaluate) {
Expand Down Expand Up @@ -338,10 +342,13 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro
// Fill the report and produce a print object
try {
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(new File(systemId));
if (conn == null) {
if (conn != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
} else if (stackDataSource != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
} else {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
LOG.debug("No dataSource or connection set, filling {} from report parameters only", systemId);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
}
} catch (JRException e) {
LOG.error("Error building report for uri {}", systemId, e);
Expand Down Expand Up @@ -460,11 +467,6 @@ private void writeReport(HttpServletResponse response, ByteArrayOutputStream out
* @throws Exception on initialization error.
*/
private void initializeProperties(ActionInvocation invocation) {
if (dataSource == null && connection == null) {
String message = "No dataSource specified...";
LOG.error(message);
throw new RuntimeException(message);
}
if (dataSource != null) {
parsedDataSource = conditionalParse(dataSource, invocation);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
import org.apache.struts2.junit.StrutsTestCase;

import jakarta.servlet.ServletException;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -169,6 +171,21 @@ public void testReportParametersExpressionAccepted() throws Exception {
assertTrue(response.getContentAsString().contains("Qux Report"));
}

public void testFillFromReportParametersWithoutDataSourceOrConnection() throws Exception {
stack.push(new Object() {
public Map<String, Object> getReportParameters() {
return Map.of("CSV_INPUT_STREAM",
new ByteArrayInputStream("Foo,Bar\n".getBytes(StandardCharsets.UTF_8)));
}
});
result.setReportParameters("reportParameters");
compileAndUseReport("csv.jrxml");

result.execute(this.invocation);

assertTrue(response.getContentAsString().contains("Hello Foo Bar!"));
}

public void testExportParametersNotAccepted() throws Exception {
result.setDataSource("{#{'firstName':'ignore', 'lastName':'ignore'}}");

Expand Down Expand Up @@ -234,12 +251,17 @@ protected void setUp() throws Exception {

result = new JasperReportsResult();
container.inject(result);
URL url = ClassLoaderUtil.getResource("org/apache/struts2/views/jasperreports/simple.jrxml", this.getClass());
JasperCompileManager.compileReportToFile(url.getFile(), url.getFile() + ".jasper");
result.setLocation("org/apache/struts2/views/jasperreports/simple.jrxml.jasper");
compileAndUseReport("simple.jrxml");
result.setFormat(JasperReportConstants.FORMAT_XML);
}

private void compileAndUseReport(String jrxml) throws Exception {
String resource = "org/apache/struts2/views/jasperreports/" + jrxml;
URL url = ClassLoaderUtil.getResource(resource, this.getClass());
JasperCompileManager.compileReportToFile(url.getFile(), url.getFile() + ".jasper");
result.setLocation(resource + ".jasper");
}


private static final Map<String, String>[] JR_MAP_ARRAY_DATA_SOURCE = new Map[]{
new HashMap<String, String>() {{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name="csv" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802">
<property name="net.sf.jasperreports.csv.column.names" value="firstName,lastName"/>
<queryString language="csv"><![CDATA[]]></queryString>
<field name="firstName" />
<field name="lastName" />
<detail>
<band height="16">
<textField>
<reportElement x="0" y="0" width="100" height="16" />
<textFieldExpression>"Hello " + <![CDATA[$F{firstName}]]> + " " + <![CDATA[$F{lastName}]]> + "!"</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,13 @@
*
* <li><b>location (default)</b> - the location where the compiled jasper report
* definition is (foo.jasper), relative from current URL.</li>
* <li><b>dataSource (required)</b> - the EL expression used to retrieve the
* datasource from the value stack (usually a List).</li>
* <li><b>dataSource</b> - the EL expression used to retrieve the
* datasource from the value stack (usually a List). When neither dataSource
* nor connection is set the report is filled from its parameters alone,
* so a data supplier expected by the report's query executer (e.g.
* <code>HIBERNATE_SESSION</code>, <code>CSV_INPUT_STREAM</code>,
* <code>JSON_INPUT_STREAM</code>) or a ready <code>REPORT_DATA_SOURCE</code> /
* <code>REPORT_CONNECTION</code> can be handed over via reportParameters.</li>
* <li><b>parse</b> - true by default. If set to false, all the parameters will
* not be parsed for EL expressions.</li>
* <li><b>format</b> - the format in which the report should be generated. Valid
Expand Down Expand Up @@ -161,7 +166,7 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro
ValueStack stack = invocation.getStack();
Connection reportConnection = (Connection) stack.findValue(connection);
ValueStackDataSource reportDataSource = null;
if (reportConnection == null) {
if (reportConnection == null && dataSource != null) {
reportDataSource = prepareDataSource(stack);
}

Expand All @@ -185,10 +190,13 @@ protected void doExecute(String finalLocation, ActionInvocation invocation) thro
// Fill the report and produce a print object
try {
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(new File(systemId));
if (reportConnection == null) {
if (reportConnection != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, reportConnection);
} else if (reportDataSource != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, reportDataSource);
} else {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, reportConnection);
LOG.debug("No dataSource or connection set, filling {} from report parameters only", systemId);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
}

if (invocation.getAction() instanceof JasperReport7Aware action) {
Expand Down Expand Up @@ -305,11 +313,6 @@ private HttpServletResponse prepapreHttpServletResponse(ActionInvocation invocat
* @param invocation Current invocation.
*/
private void initializeProperties(ActionInvocation invocation) {
if (dataSource == null && connection == null) {
String message = "No dataSource specified...";
LOG.error(message);
throw new RuntimeException(message);
}
if (dataSource != null) {
parsedDataSource = conditionalParse(dataSource, invocation);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
import org.apache.struts2.util.ClassLoaderUtil;
import org.apache.struts2.util.ValueStack;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -195,6 +197,25 @@ public Map<String, String> getReportParameters() {
assertThat(response.getContentAsString()).contains("Baz Report");
}

public void testFillFromReportParametersWithoutDataSourceOrConnection() throws Exception {
// given
stack.push(new Object() {
public Map<String, Object> getReportParameters() {
return Map.of("CSV_INPUT_STREAM",
new ByteArrayInputStream("Foo,Bar\n".getBytes(StandardCharsets.UTF_8)));
}
});
result.setReportParameters("reportParameters");
compileAndUseReport("csv.jrxml");

// when
result.execute(this.invocation);

// then
assertThat(response.getContentType()).isEqualTo("text/xml");
assertThat(response.getContentAsString()).contains("Hello Foo Bar!");
}

public void testExportToXml() throws Exception {
// given
result.setDataSource("{#{'firstName':'ignore', 'lastName':'ignore'}}");
Expand Down Expand Up @@ -295,12 +316,17 @@ protected void setUp() throws Exception {

result = new JasperReport7Result();
container.inject(result);
URL url = ClassLoaderUtil.getResource("org/apache/struts2/views/jasperreports7/simple.jrxml", this.getClass());
JasperCompileManager.compileReportToFile(url.getFile(), url.getFile() + ".jasper");
result.setLocation("org/apache/struts2/views/jasperreports7/simple.jrxml.jasper");
compileAndUseReport("simple.jrxml");
result.setFormat(JasperReport7Constants.FORMAT_XML);
}

private void compileAndUseReport(String jrxml) throws Exception {
String resource = "org/apache/struts2/views/jasperreports7/" + jrxml;
URL url = ClassLoaderUtil.getResource(resource, this.getClass());
JasperCompileManager.compileReportToFile(url.getFile(), url.getFile() + ".jasper");
result.setLocation(resource + ".jasper");
}

private static final List<Map<String, String>> JR_MAP_ARRAY_DATA_SOURCE = Stream.<Map<String, String>>of(
new HashMap<>() {{
put("firstName", "Foo");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-->
<jasperReport name="CsvReport" language="java" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802"
uuid="5a2a5a9e-4c9c-4f3e-9c1c-6a1a7b1f2d30">
<property name="net.sf.jasperreports.csv.column.names" value="firstName,lastName"/>
<query language="csv"><![CDATA[]]></query>
<field name="firstName"/>
<field name="lastName"/>

<detail>
<band height="16">
<element kind="textField" x="0" y="0" width="100" height="16"
uuid="9a7c6d2e-2b3f-4d5e-8f60-1b2c3d4e5f60">
<expression>"Hello " + <![CDATA[$F{firstName}]]> + " " + <![CDATA[$F{lastName}]]> + "!"</expression>
</element>
</band>
</detail>
</jasperReport>
Loading