struts-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Irfan (JIRA)" <j...@apache.org>
Subject [jira] [Comment Edited] (WW-4633) ClassCastException while generating report using Struts 2.3.28 and jasperreports 4.5.1
Date Wed, 11 May 2016 11:54:13 GMT

    [ https://issues.apache.org/jira/browse/WW-4633?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15280005#comment-15280005 ] 

Irfan edited comment on WW-4633 at 5/11/16 11:53 AM:
-----------------------------------------------------

This is my action class where iam fetching result.
@Controller("atk.himma.pulmonary.action.PulmonaryReportAction")
@Scope("atkAction")
public class PulmonaryReportAction extends BaseAction implements ParameterAware {
    
    private static final long serialVersionUID = 1L;

	protected Map<String, Object> parameters = new HashMap<String, Object>(0);
	
	private static final ILogger LOGGER = AppLogFactory.getLog(PulmonaryReportAction.class);

	@Resource
	@Qualifier("mbuSetupClientResource")
	private IMBUSetupResource mbuSetupResource;
    
    @Autowired
    private IPulmonaryService pulmonaryService;
        
    @Autowired
    private IPulmonaryEvaluationService evaluationService;
    
    @Autowired
    private INewAssessmentService newAssessmentService;
    
    @Autowired
    private ICardioPulmonaryService cardioPulmonaryService;
        
    private PulmonaryServiceInfo serviceInfo;
    
    private CardioPulmonary cardioPulmonary;
    
    private PulmonaryNewAssessment pulmonaryNewAssessment;
    
    private List<PulmonaryDiagnosisLog> diagnosisLog;
    
    private PulmonaryDiagnosisLog pulmonaryDiagnosisLog;
    
    private List<PulmonaryAllergyInfo> allergyInfo;
    
    private List<PulmonaryVitalInfo> vitalInfo;
    
    private List<PulmonaryEvaluationDetail> evaluationDetails;
    
    private JRBeanCollectionDataSource beanColDataSource ;
    
    private List<Map<String,?>> formsList;

    private SimpleDateFormat sdf = new SimpleDateFormat(UserContextUtil.getUserDateFormat() + " " + UserContextUtil.getUserTimeFormat());

	@AuthorizationNotRequired
	public String getPulmonaryReport() throws BaseException {
		String pulmonaryServiceIds = getRequestParameter("pulmonaryServiceIds");
		List<Long> pulServiceIds = new ArrayList<Long>(0);
		Map<String, Object> formsMap = new HashMap<String, Object>();
		formsList = new ArrayList<Map<String,?>>();
		if(StringUtils.isNotBlank(pulmonaryServiceIds)){
		    String[] serviceIds =  pulmonaryServiceIds.split(",");
		    for (String serviceId : serviceIds) {
		        pulServiceIds.add(Long.parseLong(serviceId));
            }
		}
		String reportsDirPath = ServletActionContext.getServletContext().getRealPath("/reports/jasper/");
        File reportsDir = new File(reportsDirPath);
        parameters.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
        Integer evaluationCount = null;
        Integer cardioCount = null;
        Integer assessmentCount = null;
        int totalPageCount = 0;
        if(getRequestParameterInt("evaluationCount") != null){
            evaluationCount = Integer.valueOf(getRequestParameterInt("evaluationCount"));
            totalPageCount = totalPageCount + evaluationCount;
        }
        if(getRequestParameterInt("cardioCount") != null){
            cardioCount = Integer.valueOf(getRequestParameter("cardioCount"));
            totalPageCount = totalPageCount + cardioCount;
        }
        if(getRequestParameterInt("assessmentCount") != null){
            assessmentCount = Integer.valueOf(getRequestParameterInt("assessmentCount"));
            totalPageCount = totalPageCount + assessmentCount;
        }
        List<PulmonaryEvalationReport> evalationReportList = new ArrayList<PulmonaryEvalationReport>();
        List<PulmonaryEvalationReport> assMentList = new ArrayList<PulmonaryEvalationReport>();
        List<PulmonaryEvalationReport> cardioList = new ArrayList<PulmonaryEvalationReport>();
        for (Long pulmonaryServiceId : CollectionUtil.emptyIfNull(pulServiceIds)) {
        	 PulmonaryEvalationReport evalationReport = new PulmonaryEvalationReport();
             PulmonaryEvalationReport assMentReport = new PulmonaryEvalationReport();
             PulmonaryEvalationReport cardioReport = new PulmonaryEvalationReport();
             PulmonaryEvaluation  evaluationDetail = evaluationService.getEvaluationByServiceId(pulmonaryServiceId);
            evalationReport = patientVitalDignAndAllergy(evalationReport, pulmonaryServiceId, evaluationDetail);
            if (evaluationCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                for (int i = 0; i < evaluationCount; i++) {
                    evalationReportList.add(evalationReport);
                }
                formsMap.put("evalDs", evalationReportList);
            }

            if (cardioCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                cardioReport = getCardioPulmonaryReport(evalationReport, pulmonaryServiceId);
                for (int i = 0; i < cardioCount; i++) {
                	cardioList.add(cardioReport);
                }
                formsMap.put("cardioDs", cardioList);
            }

            if (assessmentCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                assMentReport = getNewAssessmentReport(evalationReport, pulmonaryServiceId);
                for (int i = 0; i < assessmentCount; i++) {
                	assMentList.add(assMentReport);
                }
                formsMap.put("assmDS", assMentList);
            }
        }
    	try {
	        if(CollectionUtil.isNotNullEmpty(assMentList)){
	        	PulmonaryEvalationReport lastObj = assMentList.get(assMentList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				assMentList.set( assMentList.size() - 1, lastObjClonelastObj);
				 formsMap.put("assmDS", assMentList);
	        } else if(CollectionUtil.isNotNullEmpty(cardioList)){
	        	PulmonaryEvalationReport lastObj = cardioList.get(cardioList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				cardioList.set( cardioList.size() - 1, lastObjClonelastObj);
				 formsMap.put("cardioDs", cardioList);
	        } else if(CollectionUtil.isNotNullEmpty(evalationReportList)){
	        	PulmonaryEvalationReport lastObj = evalationReportList.get(evalationReportList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				evalationReportList.set( evalationReportList.size() - 1, lastObjClonelastObj);
				 formsMap.put("evalDs", evalationReportList);
	        }
		} catch (CloneNotSupportedException e) {
			LOGGER.error(e);
		}
        formsList.add(formsMap);
        parameters.put("totPage", totalPageCount);
        if(UserContextUtil.getUserMBUId()!=null){
        	Long mbuId = UserContextUtil.getUserMBUId();
        	Boolean isMBULogo = mbuSetupResource.isMBULogoConfiguredForReports(mbuId);
    		if(isMBULogo){
    			parameters.put("logoUrl", ReportUtil.getMBULogoURL(mbuId));
    		}else{
    			parameters.put("logoUrl", null);
    		}
        }
		parameters.put("fieldsDisplay", ReportAdressUtil.getMBUAdress(UserContextUtil.getUserMBUId()));
		parameters.put("printedBy", UserContextUtil.getLoggedInEmployeeName());
		parameters.put("printedDate", sdf.format(new Date()));
		parameters.put("slogan", "SERVING YOU BETTER");
        beanColDataSource = new JRBeanCollectionDataSource(formsList);
		return SUCCESS;
	}

    private PulmonaryEvalationReport  patientVitalDignAndAllergy(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId,PulmonaryEvaluation evaluationDetail) throws BaseException{
    	serviceInfo = pulmonaryService.getPulmonaryOrder(pulmonaryServiceId);
    	
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationDiagnosisLog())){
    		diagnosisLog = evaluationDetail.getEvaluationDiagnosisLog();
    	}
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationVitals())){
    		vitalInfo = evaluationDetail.getEvaluationVitals();
    	}
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationAllergyInfos())){
    		allergyInfo = evaluationDetail.getEvaluationAllergyInfos();
    	}
		for(PulmonaryAllergyInfo pAllergyInfo : CollectionUtil.emptyIfNull(allergyInfo)){
			pAllergyInfo.setSeverityName(baseLVService.getDisplayText("ALLERGY_SEVERITY", pAllergyInfo.getSeverityId()));
			pAllergyInfo.setCategoryName(baseLVService.getDisplayText("ALLERGY_CATEGORY", pAllergyInfo.getAllergyCategoryId()));
			pAllergyInfo.setAllergyType(baseLVService.getDisplayText("ALLERGY_TYPE", pAllergyInfo.getAllergyTypeId()));
		}
		
		for(PulmonaryDiagnosisLog pDiagnosisLog :CollectionUtil.emptyIfNull(diagnosisLog)){
			pDiagnosisLog.setDiagnosisType(baseLVService.getDisplayText("DR_DIAGNOSIS_TYPE", pDiagnosisLog.getType()));
		}
		
		for(PulmonaryVitalInfo pvVitalInfo : CollectionUtil.emptyIfNull(vitalInfo)){
			if(pvVitalInfo.getBpLow() != null && pvVitalInfo.getBpLow() != 0 && pvVitalInfo.getBpHigh() != null && pvVitalInfo.getBpHigh() != 0){
				pvVitalInfo.setBp(pvVitalInfo.getBpLow().toString() + " / "+ pvVitalInfo.getBpHigh().toString());
			}
		}
		evalationReport.setServiceInfo(serviceInfo);
		parameters.put("diagnosisDS", diagnosisLog);
	    parameters.put("vitalDS", vitalInfo);
	    parameters.put("allergyDS", allergyInfo);
	    return evalationReport;
    }
    
    private PulmonaryEvalationReport  getEvaluationReport(PulmonaryEvalationReport evalationReport, PulmonaryEvaluation evaluationDetail) throws BaseException{
    	PulmonaryEvaluationDetail pulmonaryEvaluationDetail = null;
		for (PulmonaryEvaluationDetail detail : CollectionUtil.emptyIfNull(evaluationDetail.getEvaluationDetails())) {
			if (detail.isActiveRecord()) {
				pulmonaryEvaluationDetail = detail;
				break;
			}
		}
		evaluationDetails = new ArrayList<PulmonaryEvaluationDetail>();
		evaluationDetail.setEvaluationDetails(evaluationDetails);
		evaluationDetail.getEvaluationDetails().add(pulmonaryEvaluationDetail);
		 parameters.put("evalParam",Boolean.TRUE );
		 return evalationReport;
		
    }
    
    private PulmonaryEvalationReport  getCardioPulmonaryReport(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId) throws BaseException{
    	cardioPulmonary = cardioPulmonaryService.getActiveCardioPulmonary(pulmonaryServiceId);
    	evalationReport.setCardioPulmonary(cardioPulmonary);
    	 parameters.put("cardioParam",Boolean.TRUE );
    	 return evalationReport;
    }
    
    private PulmonaryEvalationReport  getNewAssessmentReport(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId) throws BaseException{
    	pulmonaryNewAssessment= newAssessmentService.getActiveNewAssessment(pulmonaryServiceId);
    	evalationReport.setNewAssessment(pulmonaryNewAssessment);
    	 parameters.put("newAssessParam",Boolean.TRUE );
    	 return evalationReport;
    }

    @AuthorizationNotRequired
    public String getCardioReport(){
		return SUCCESS;
    	
    }
   
    @Override
    public void setParameters(Map<String, String[]> parameters) {
        //Dummy method
    }

    public PulmonaryServiceInfo getServiceInfo() {
        return serviceInfo;
    }
    public void setServiceInfo(PulmonaryServiceInfo serviceInfo) {
        this.serviceInfo = serviceInfo;
    }
  /*  public PulmonaryEvaluation getEvaluationDetail() {
        return evaluationDetail;
    }
    public void setEvaluationDetail(PulmonaryEvaluation evaluationDetail) {
        this.evaluationDetail = evaluationDetail;
    }*/
    

	public Map<String, Object> getParameters() {
		return parameters;
	}


	public CardioPulmonary getCardioPulmonary() {
		return cardioPulmonary;
	}

	public void setCardioPulmonary(CardioPulmonary cardioPulmonary) {
		this.cardioPulmonary = cardioPulmonary;
	}

	public JRBeanCollectionDataSource getBeanColDataSource() {
		return beanColDataSource;
	}

	public void setBeanColDataSource(JRBeanCollectionDataSource beanColDataSource) {
		this.beanColDataSource = beanColDataSource;
	}

	public PulmonaryDiagnosisLog getPulmonaryDiagnosisLog() {
		return pulmonaryDiagnosisLog;
	}

	public void setPulmonaryDiagnosisLog(PulmonaryDiagnosisLog pulmonaryDiagnosisLog) {
		this.pulmonaryDiagnosisLog = pulmonaryDiagnosisLog;
	}

	public List<PulmonaryDiagnosisLog> getDiagnosisLog() {
		return diagnosisLog;
	}

	public void setDiagnosisLog(List<PulmonaryDiagnosisLog> diagnosisLog) {
		this.diagnosisLog = diagnosisLog;
	}

	public PulmonaryNewAssessment getPulmonaryNewAssessment() {
		return pulmonaryNewAssessment;
	}

    public void setPulmonaryNewAssessment(PulmonaryNewAssessment pulmonaryNewAssessment) {
		this.pulmonaryNewAssessment = pulmonaryNewAssessment;
	}

	public List<PulmonaryEvaluationDetail> getEvaluationDetails() {
		return evaluationDetails;
	}

	public void setEvaluationDetails(List<PulmonaryEvaluationDetail> evaluationDetails) {
		this.evaluationDetails = evaluationDetails;
	}


	public List<Map<String,?>> getFormsList() {
		return formsList;
	}


	public void setFormsList(List<Map<String,?>> formsList) {
		this.formsList = formsList;
	}
	
	 
}

This is my print jasper report result class.


 */
public class JasperReportResult extends JasperReportsResult {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 1L;
	
	private static final ILogger LOG = AppLogFactory.getLog(JasperReportResult.class);
	
	@Autowired
	private IATKPrintService printService;
	
	private String documentShortName;
	
	public String getDocumentShortName() {
		return documentShortName;
	}

	public void setDocumentShortName(String documentShortName) {
		this.documentShortName = documentShortName;
	}

	protected String preview;

	private void initializeProperties(ActionInvocation invocation) throws Exception {
		if (dataSource == null && connection == null) {
			String message = "No dataSource specified...";
			LOG.info(message);
			throw new RuntimeException(message);
		}
		if (dataSource != null) {
			dataSource = conditionalParse(dataSource, invocation);
		}
		
		format = conditionalParse(format, invocation);
		if (StringUtils.isEmpty(format)) {
			format = FORMAT_PDF;
		}

		if (contentDisposition != null) {
			contentDisposition = conditionalParse(contentDisposition, invocation);
		}

		if (documentName != null) {
			documentName = conditionalParse(documentName, invocation);
		}

		reportParameters = conditionalParse(reportParameters, invocation);
		exportParameters = conditionalParse(exportParameters, invocation);
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
	protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
		initializeProperties(invocation);

		if (LOG.isDebugEnabled()) {
			LOG.debug("Creating JasperReport for dataSource = " + dataSource + ", format = " + format);
		}

		HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(
				StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(
				StrutsStatics.HTTP_RESPONSE);

		// Handle IE special case: it sends a "contype" request first.
		if ("contype".equals(request.getHeader("User-Agent"))) {
			try {
				response.setContentType("application/pdf");
				response.setContentLength(0);

				ServletOutputStream outputStream = response.getOutputStream();
				outputStream.close();
			} catch (IOException e) {
				LOG.error("Error writing report output", e);
				throw new ServletException(e);
			}
			return;
		}

		// Construct the data source for the report.
		ValueStack stack = invocation.getStack();
		ValueStackDataSource stackDataSource = null;

		Connection conn = (Connection) stack.findValue(connection);
		if (conn == null)
			stackDataSource = new ValueStackDataSource(stack, dataSource, true);

		// Determine the directory that the report file is in and set the
		// reportDirectory parameter
		// For WW 2.1.7:
		// ServletContext servletContext = ((ServletConfig)
		// invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext();
		ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(
				StrutsStatics.SERVLET_CONTEXT);
		String systemId = servletContext.getRealPath(finalLocation);
		Map<String, Object> parameters = new ValueStackShadowMap(stack);
		File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator)));
		parameters.put("reportDirectory", directory);
		parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale());

		// put timezone in jasper report parameter
		if (timeZone != null) {
			timeZone = conditionalParse(timeZone, invocation);
			final TimeZone tz = TimeZone.getTimeZone(timeZone);
			if (tz != null) {
				// put the report time zone
				parameters.put(JRParameter.REPORT_TIME_ZONE, tz);
			}
		}

		// Add any report parameters from action to param map.
		Map reportParams = (Map) stack.findValue(reportParameters);
		if (reportParams != null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Found report parameters; adding to parameters...");
			}
			parameters.putAll(reportParams);
		}

		byte[] output;
		JasperPrint jasperPrint;

		// Fill the report and produce a print object
		try {
			JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(systemId);
			if (conn == null) {
				jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
			} else {
				jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
			}
			removeBlankPage(jasperPrint.getPages());
		} catch (JRException e) {
			LOG.error("Error building report for uri " + systemId, e);
			throw new ServletException(e);
		}

		// Export the print object to the desired output format
		try {
			if (contentDisposition != null || documentName != null) {
				final StringBuilder tmp = new StringBuilder(128);
				tmp.append((contentDisposition == null) ? "inline" : contentDisposition);

				if (documentName != null) {
					tmp.append("; filename=");
					tmp.append(documentName);
					tmp.append(".");
					tmp.append(format.toLowerCase());
				}

				response.setHeader("Content-disposition", tmp.toString());
			}

			JRExporter exporter;

			if (format.equals(FORMAT_PDF)) {
				response.setContentType("application/pdf");
				exporter = new JRPdfExporter();			
				boolean encryptionReq = Boolean.valueOf(preview);
				if (encryptionReq) {
					exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
					exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY, Boolean.TRUE);
				}
			} else if (format.equals(FORMAT_CSV)) {
				response.setContentType("text/csv");
				exporter = new JRCsvExporter();
			} else if (format.equals(FORMAT_HTML)) {
				response.setContentType("text/html");

				// IMAGES_MAPS seems to be only supported as
				// "backward compatible" from JasperReports 1.1.0

				Map imagesMap = new HashMap();
				request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);

				exporter = new JRHtmlExporter();
				exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
				exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl);

				// Needed to support chart images:
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
				request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
			} else if (format.equals(FORMAT_XLS)) {
				response.setContentType("application/vnd.ms-excel");
				exporter = new JRXlsExporter();
			} else if (format.equals(FORMAT_XML)) {
				response.setContentType("text/xml");
				exporter = new JRXmlExporter();
			} else if (format.equals(FORMAT_RTF)) {
				response.setContentType("application/rtf");
				exporter = new JRRtfExporter();
			} else if ("img".equals(format)) {
				/**
				 * Added By ATK - To support image export 
				 */
				int pageIndex = 0;
				BufferedImage pageImage = new BufferedImage(jasperPrint.getPageWidth() + 1,
						jasperPrint.getPageHeight() + 1, BufferedImage.TYPE_INT_RGB);
				exporter = new JRGraphics2DExporter();
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
				exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
				exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pageIndex));

				ServletOutputStream out = response.getOutputStream();
				exporter.exportReport();
				ImageIO.write(pageImage, "jpeg", out);
				out.close();
			} else {
				throw new ServletException("Unknown report format: " + format);
			}

			Map exportParams = (Map) stack.findValue(exportParameters);
			if (exportParams != null) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Found export parameters; adding to exporter parameters...");
				}
				exporter.getParameters().putAll(exportParams);
			}

			output = exportReportToBytes(jasperPrint, exporter);
		} catch (JRException e) {
			String message = "Error producing " + format + " report for uri " + systemId;
			LOG.error(message, e);
			throw new ServletException(e);
		}
		if (!"img".equals(format)) {
			response.setContentLength(output.length);
			DocumentPrinter documentPrinter = printService.getDocumentPrinter(documentShortName);
			if(documentPrinter!=null){
				documentPrinter.setDocName(documentShortName);
				if(documentPrinter.getPrintOption().equals(DocumentPrinter.CLIENT_OPTION)){
					addFileDownloadCookie(response);
					writeReport(response, output);
				}else if(documentPrinter.getPrintOption().equals(DocumentPrinter.BOTH_OPTION)){
					printService.print(output, documentPrinter);
					addFilePrintedCookie(response);
					addFileDownloadCookie(response);
					writeReport(response, output);
				}else{
					printService.print(output, documentPrinter);
					response.setHeader("Content-disposition", "");		
					response.setContentType("text/html");										
					addFilePrintedCookie(response);
					writeReport(response, new String("").getBytes());
				}	
			}else{
				addFileDownloadCookie(response);
				writeReport(response, output);				
			}
			
		}
	}
	
	private void removeBlankPage(List<JRPrintPage> pages) {
	      for (Iterator<JRPrintPage> i=pages.iterator(); i.hasNext();) {
	          JRPrintPage page = i.next();
	          if (CollectionUtil.isNullOrEmpty(page.getElements())) {
	              i.remove();
	          }
	      }
	  }
	
	private void addFileDownloadCookie(HttpServletResponse response){		
		Cookie fileDownload = new Cookie("fileDownload", "true");
		fileDownload.setPath("/");
		fileDownload.setMaxAge(2*60*60);
		response.addCookie(fileDownload);		
	}
	
	private void addFilePrintedCookie(HttpServletResponse response){		
		Cookie filePrinted = new Cookie("filePrinted", "true");
		filePrinted.setPath("/");
		filePrinted.setMaxAge(2*60*60);
		response.addCookie(filePrinted);		
	}

	/**
	 * Writes report bytes to response output stream.
	 * 
	 * @param response
	 *            Current response.
	 * @param output
	 *            Report bytes to write.
	 * @throws ServletException
	 *             on stream IOException.
	 */
	private void writeReport(HttpServletResponse response, byte[] output) throws ServletException {
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			outputStream.write(output);
			outputStream.flush();
		} catch (IOException e) {
			LOG.error("Error writing report output", e);
			throw new ServletException(e);
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				LOG.error("Error closing report output stream", e);
				throw new ServletException(e);
			}
		}
	}

	private byte[] exportReportToBytes(JasperPrint jasperPrint, JRExporter exporter) throws JRException {
		byte[] output;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
		if (delimiter != null) {
			exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, delimiter);
		}

		exporter.exportReport();

		output = baos.toByteArray();

		return output;
	}

	public String getPreview() {
		return preview;
	}

	public void setPreview(String preview) {
		this.preview = preview;
	}
}



my struts2 file.

<package name="jasper" namespace="/reports" extends="atk-default">
		<default-class-ref class="atk.himma.pulmonary.action.PulmonaryReportAction" />
	 <action name="getPulmonaryReport" method="getPulmonaryReport">
			<interceptor-ref name="himmaLazyStack">
					<param name="atkParams.removeEmptyParams">false</param>
			</interceptor-ref>
			 <result type="jasper">
				<param name="location">/reports/jasper/pulmonaryMainReport.jasper</param>
				<param name="contentDisposition">attachment;fileName="pulmonaryReport.pdf"</param>
				<param name="dataSource">evalationReportList</param>
				<!-- <param name="dataSource">jrDataSource</param>
				<param name="dataSource">mainFormsList</param> -->
				<param name="dataSource">beanColDataSource</param>
				<param name="dataSource">formsList</param>
			  	<param name="format">PDF</param>
				<param name="reportParameters">parameters</param>
			</result> 
		</action> 


was (Author: irfank):
This is my action class where iam fetching result.
@Controller("atk.himma.pulmonary.action.PulmonaryReportAction")
@Scope("atkAction")
public class PulmonaryReportAction extends BaseAction implements ParameterAware {
    
    private static final long serialVersionUID = 1L;

	protected Map<String, Object> parameters = new HashMap<String, Object>(0);
	
	private static final ILogger LOGGER = AppLogFactory.getLog(PulmonaryReportAction.class);

	@Resource
	@Qualifier("mbuSetupClientResource")
	private IMBUSetupResource mbuSetupResource;
    
    @Autowired
    private IPulmonaryService pulmonaryService;
        
    @Autowired
    private IPulmonaryEvaluationService evaluationService;
    
    @Autowired
    private INewAssessmentService newAssessmentService;
    
    @Autowired
    private ICardioPulmonaryService cardioPulmonaryService;
        
    private PulmonaryServiceInfo serviceInfo;
    
    private CardioPulmonary cardioPulmonary;
    
    private PulmonaryNewAssessment pulmonaryNewAssessment;
    
    private List<PulmonaryDiagnosisLog> diagnosisLog;
    
    private PulmonaryDiagnosisLog pulmonaryDiagnosisLog;
    
    private List<PulmonaryAllergyInfo> allergyInfo;
    
    private List<PulmonaryVitalInfo> vitalInfo;
    
    private List<PulmonaryEvaluationDetail> evaluationDetails;
    
    private JRBeanCollectionDataSource beanColDataSource ;
    
    private List<Map<String,?>> formsList;

    private SimpleDateFormat sdf = new SimpleDateFormat(UserContextUtil.getUserDateFormat() + " " + UserContextUtil.getUserTimeFormat());

	@AuthorizationNotRequired
	public String getPulmonaryReport() throws BaseException {
		String pulmonaryServiceIds = getRequestParameter("pulmonaryServiceIds");
		List<Long> pulServiceIds = new ArrayList<Long>(0);
		Map<String, Object> formsMap = new HashMap<String, Object>();
		formsList = new ArrayList<Map<String,?>>();
		if(StringUtils.isNotBlank(pulmonaryServiceIds)){
		    String[] serviceIds =  pulmonaryServiceIds.split(",");
		    for (String serviceId : serviceIds) {
		        pulServiceIds.add(Long.parseLong(serviceId));
            }
		}
		String reportsDirPath = ServletActionContext.getServletContext().getRealPath("/reports/jasper/");
        File reportsDir = new File(reportsDirPath);
        parameters.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
        Integer evaluationCount = null;
        Integer cardioCount = null;
        Integer assessmentCount = null;
        int totalPageCount = 0;
        if(getRequestParameterInt("evaluationCount") != null){
            evaluationCount = Integer.valueOf(getRequestParameterInt("evaluationCount"));
            totalPageCount = totalPageCount + evaluationCount;
        }
        if(getRequestParameterInt("cardioCount") != null){
            cardioCount = Integer.valueOf(getRequestParameter("cardioCount"));
            totalPageCount = totalPageCount + cardioCount;
        }
        if(getRequestParameterInt("assessmentCount") != null){
            assessmentCount = Integer.valueOf(getRequestParameterInt("assessmentCount"));
            totalPageCount = totalPageCount + assessmentCount;
        }
        List<PulmonaryEvalationReport> evalationReportList = new ArrayList<PulmonaryEvalationReport>();
        List<PulmonaryEvalationReport> assMentList = new ArrayList<PulmonaryEvalationReport>();
        List<PulmonaryEvalationReport> cardioList = new ArrayList<PulmonaryEvalationReport>();
        for (Long pulmonaryServiceId : CollectionUtil.emptyIfNull(pulServiceIds)) {
        	 PulmonaryEvalationReport evalationReport = new PulmonaryEvalationReport();
             PulmonaryEvalationReport assMentReport = new PulmonaryEvalationReport();
             PulmonaryEvalationReport cardioReport = new PulmonaryEvalationReport();
             PulmonaryEvaluation  evaluationDetail = evaluationService.getEvaluationByServiceId(pulmonaryServiceId);
            evalationReport = patientVitalDignAndAllergy(evalationReport, pulmonaryServiceId, evaluationDetail);
            if (evaluationCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                for (int i = 0; i < evaluationCount; i++) {
                    evalationReportList.add(evalationReport);
                }
                formsMap.put("evalDs", evalationReportList);
            }

            if (cardioCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                cardioReport = getCardioPulmonaryReport(evalationReport, pulmonaryServiceId);
                for (int i = 0; i < cardioCount; i++) {
                	cardioList.add(cardioReport);
                }
                formsMap.put("cardioDs", cardioList);
            }

            if (assessmentCount != null) {
                evalationReport = getEvaluationReport(evalationReport, evaluationDetail);
                assMentReport = getNewAssessmentReport(evalationReport, pulmonaryServiceId);
                for (int i = 0; i < assessmentCount; i++) {
                	assMentList.add(assMentReport);
                }
                formsMap.put("assmDS", assMentList);
            }
        }
    	try {
	        if(CollectionUtil.isNotNullEmpty(assMentList)){
	        	PulmonaryEvalationReport lastObj = assMentList.get(assMentList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				assMentList.set( assMentList.size() - 1, lastObjClonelastObj);
				 formsMap.put("assmDS", assMentList);
	        } else if(CollectionUtil.isNotNullEmpty(cardioList)){
	        	PulmonaryEvalationReport lastObj = cardioList.get(cardioList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				cardioList.set( cardioList.size() - 1, lastObjClonelastObj);
				 formsMap.put("cardioDs", cardioList);
	        } else if(CollectionUtil.isNotNullEmpty(evalationReportList)){
	        	PulmonaryEvalationReport lastObj = evalationReportList.get(evalationReportList.size() - 1);
				PulmonaryEvalationReport lastObjClonelastObj = (PulmonaryEvalationReport) lastObj.clone();
				lastObjClonelastObj.setIsPageBreak(false);
				evalationReportList.set( evalationReportList.size() - 1, lastObjClonelastObj);
				 formsMap.put("evalDs", evalationReportList);
	        }
		} catch (CloneNotSupportedException e) {
			LOGGER.error(e);
		}
        formsList.add(formsMap);
        parameters.put("totPage", totalPageCount);
        if(UserContextUtil.getUserMBUId()!=null){
        	Long mbuId = UserContextUtil.getUserMBUId();
        	Boolean isMBULogo = mbuSetupResource.isMBULogoConfiguredForReports(mbuId);
    		if(isMBULogo){
    			parameters.put("logoUrl", ReportUtil.getMBULogoURL(mbuId));
    		}else{
    			parameters.put("logoUrl", null);
    		}
        }
		parameters.put("fieldsDisplay", ReportAdressUtil.getMBUAdress(UserContextUtil.getUserMBUId()));
		parameters.put("printedBy", UserContextUtil.getLoggedInEmployeeName());
		parameters.put("printedDate", sdf.format(new Date()));
		parameters.put("slogan", "SERVING YOU BETTER");
        beanColDataSource = new JRBeanCollectionDataSource(formsList);
		return SUCCESS;
	}

    private PulmonaryEvalationReport  patientVitalDignAndAllergy(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId,PulmonaryEvaluation evaluationDetail) throws BaseException{
    	serviceInfo = pulmonaryService.getPulmonaryOrder(pulmonaryServiceId);
    	
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationDiagnosisLog())){
    		diagnosisLog = evaluationDetail.getEvaluationDiagnosisLog();
    	}
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationVitals())){
    		vitalInfo = evaluationDetail.getEvaluationVitals();
    	}
    	if(CollectionUtil.isNotNullEmpty(evaluationDetail.getEvaluationAllergyInfos())){
    		allergyInfo = evaluationDetail.getEvaluationAllergyInfos();
    	}
		for(PulmonaryAllergyInfo pAllergyInfo : CollectionUtil.emptyIfNull(allergyInfo)){
			pAllergyInfo.setSeverityName(baseLVService.getDisplayText("ALLERGY_SEVERITY", pAllergyInfo.getSeverityId()));
			pAllergyInfo.setCategoryName(baseLVService.getDisplayText("ALLERGY_CATEGORY", pAllergyInfo.getAllergyCategoryId()));
			pAllergyInfo.setAllergyType(baseLVService.getDisplayText("ALLERGY_TYPE", pAllergyInfo.getAllergyTypeId()));
		}
		
		for(PulmonaryDiagnosisLog pDiagnosisLog :CollectionUtil.emptyIfNull(diagnosisLog)){
			pDiagnosisLog.setDiagnosisType(baseLVService.getDisplayText("DR_DIAGNOSIS_TYPE", pDiagnosisLog.getType()));
		}
		
		for(PulmonaryVitalInfo pvVitalInfo : CollectionUtil.emptyIfNull(vitalInfo)){
			if(pvVitalInfo.getBpLow() != null && pvVitalInfo.getBpLow() != 0 && pvVitalInfo.getBpHigh() != null && pvVitalInfo.getBpHigh() != 0){
				pvVitalInfo.setBp(pvVitalInfo.getBpLow().toString() + " / "+ pvVitalInfo.getBpHigh().toString());
			}
		}
		evalationReport.setServiceInfo(serviceInfo);
		parameters.put("diagnosisDS", diagnosisLog);
	    parameters.put("vitalDS", vitalInfo);
	    parameters.put("allergyDS", allergyInfo);
	    return evalationReport;
    }
    
    private PulmonaryEvalationReport  getEvaluationReport(PulmonaryEvalationReport evalationReport, PulmonaryEvaluation evaluationDetail) throws BaseException{
    	PulmonaryEvaluationDetail pulmonaryEvaluationDetail = null;
		for (PulmonaryEvaluationDetail detail : CollectionUtil.emptyIfNull(evaluationDetail.getEvaluationDetails())) {
			if (detail.isActiveRecord()) {
				pulmonaryEvaluationDetail = detail;
				break;
			}
		}
		evaluationDetails = new ArrayList<PulmonaryEvaluationDetail>();
		evaluationDetail.setEvaluationDetails(evaluationDetails);
		evaluationDetail.getEvaluationDetails().add(pulmonaryEvaluationDetail);
		 parameters.put("evalParam",Boolean.TRUE );
		 return evalationReport;
		
    }
    
    private PulmonaryEvalationReport  getCardioPulmonaryReport(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId) throws BaseException{
    	cardioPulmonary = cardioPulmonaryService.getActiveCardioPulmonary(pulmonaryServiceId);
    	evalationReport.setCardioPulmonary(cardioPulmonary);
    	 parameters.put("cardioParam",Boolean.TRUE );
    	 return evalationReport;
    }
    
    private PulmonaryEvalationReport  getNewAssessmentReport(PulmonaryEvalationReport evalationReport,Long pulmonaryServiceId) throws BaseException{
    	pulmonaryNewAssessment= newAssessmentService.getActiveNewAssessment(pulmonaryServiceId);
    	evalationReport.setNewAssessment(pulmonaryNewAssessment);
    	 parameters.put("newAssessParam",Boolean.TRUE );
    	 return evalationReport;
    }

    @AuthorizationNotRequired
    public String getCardioReport(){
		return SUCCESS;
    	
    }
   
    @Override
    public void setParameters(Map<String, String[]> parameters) {
        //Dummy method
    }

    public PulmonaryServiceInfo getServiceInfo() {
        return serviceInfo;
    }
    public void setServiceInfo(PulmonaryServiceInfo serviceInfo) {
        this.serviceInfo = serviceInfo;
    }
  /*  public PulmonaryEvaluation getEvaluationDetail() {
        return evaluationDetail;
    }
    public void setEvaluationDetail(PulmonaryEvaluation evaluationDetail) {
        this.evaluationDetail = evaluationDetail;
    }*/
    

	public Map<String, Object> getParameters() {
		return parameters;
	}


	public CardioPulmonary getCardioPulmonary() {
		return cardioPulmonary;
	}

	public void setCardioPulmonary(CardioPulmonary cardioPulmonary) {
		this.cardioPulmonary = cardioPulmonary;
	}

	public JRBeanCollectionDataSource getBeanColDataSource() {
		return beanColDataSource;
	}

	public void setBeanColDataSource(JRBeanCollectionDataSource beanColDataSource) {
		this.beanColDataSource = beanColDataSource;
	}

	public PulmonaryDiagnosisLog getPulmonaryDiagnosisLog() {
		return pulmonaryDiagnosisLog;
	}

	public void setPulmonaryDiagnosisLog(PulmonaryDiagnosisLog pulmonaryDiagnosisLog) {
		this.pulmonaryDiagnosisLog = pulmonaryDiagnosisLog;
	}

	public List<PulmonaryDiagnosisLog> getDiagnosisLog() {
		return diagnosisLog;
	}

	public void setDiagnosisLog(List<PulmonaryDiagnosisLog> diagnosisLog) {
		this.diagnosisLog = diagnosisLog;
	}

	public PulmonaryNewAssessment getPulmonaryNewAssessment() {
		return pulmonaryNewAssessment;
	}

    public void setPulmonaryNewAssessment(PulmonaryNewAssessment pulmonaryNewAssessment) {
		this.pulmonaryNewAssessment = pulmonaryNewAssessment;
	}

	public List<PulmonaryEvaluationDetail> getEvaluationDetails() {
		return evaluationDetails;
	}

	public void setEvaluationDetails(List<PulmonaryEvaluationDetail> evaluationDetails) {
		this.evaluationDetails = evaluationDetails;
	}


	public List<Map<String,?>> getFormsList() {
		return formsList;
	}


	public void setFormsList(List<Map<String,?>> formsList) {
		this.formsList = formsList;
	}
	
	 
}

This is my print jasper report result class.


 */
public class JasperReportResult extends JasperReportsResult {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 1L;
	
	private static final ILogger LOG = AppLogFactory.getLog(JasperReportResult.class);
	
	@Autowired
	private IATKPrintService printService;
	
	private String documentShortName;
	
	public String getDocumentShortName() {
		return documentShortName;
	}

	public void setDocumentShortName(String documentShortName) {
		this.documentShortName = documentShortName;
	}

	protected String preview;

	private void initializeProperties(ActionInvocation invocation) throws Exception {
		if (dataSource == null && connection == null) {
			String message = "No dataSource specified...";
			LOG.info(message);
			throw new RuntimeException(message);
		}
		if (dataSource != null) {
			dataSource = conditionalParse(dataSource, invocation);
		}
		
		format = conditionalParse(format, invocation);
		if (StringUtils.isEmpty(format)) {
			format = FORMAT_PDF;
		}

		if (contentDisposition != null) {
			contentDisposition = conditionalParse(contentDisposition, invocation);
		}

		if (documentName != null) {
			documentName = conditionalParse(documentName, invocation);
		}

		reportParameters = conditionalParse(reportParameters, invocation);
		exportParameters = conditionalParse(exportParameters, invocation);
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
	protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
		initializeProperties(invocation);

		if (LOG.isDebugEnabled()) {
			LOG.debug("Creating JasperReport for dataSource = " + dataSource + ", format = " + format);
		}

		HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(
				StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(
				StrutsStatics.HTTP_RESPONSE);

		// Handle IE special case: it sends a "contype" request first.
		if ("contype".equals(request.getHeader("User-Agent"))) {
			try {
				response.setContentType("application/pdf");
				response.setContentLength(0);

				ServletOutputStream outputStream = response.getOutputStream();
				outputStream.close();
			} catch (IOException e) {
				LOG.error("Error writing report output", e);
				throw new ServletException(e);
			}
			return;
		}

		// Construct the data source for the report.
		ValueStack stack = invocation.getStack();
		ValueStackDataSource stackDataSource = null;

		Connection conn = (Connection) stack.findValue(connection);
		if (conn == null)
			stackDataSource = new ValueStackDataSource(stack, dataSource, true);

		// Determine the directory that the report file is in and set the
		// reportDirectory parameter
		// For WW 2.1.7:
		// ServletContext servletContext = ((ServletConfig)
		// invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext();
		ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(
				StrutsStatics.SERVLET_CONTEXT);
		String systemId = servletContext.getRealPath(finalLocation);
		Map<String, Object> parameters = new ValueStackShadowMap(stack);
		File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator)));
		parameters.put("reportDirectory", directory);
		parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale());

		// put timezone in jasper report parameter
		if (timeZone != null) {
			timeZone = conditionalParse(timeZone, invocation);
			final TimeZone tz = TimeZone.getTimeZone(timeZone);
			if (tz != null) {
				// put the report time zone
				parameters.put(JRParameter.REPORT_TIME_ZONE, tz);
			}
		}

		// Add any report parameters from action to param map.
		Map reportParams = (Map) stack.findValue(reportParameters);
		if (reportParams != null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Found report parameters; adding to parameters...");
			}
			parameters.putAll(reportParams);
		}

		byte[] output;
		JasperPrint jasperPrint;

		// Fill the report and produce a print object
		try {
			JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(systemId);
			if (conn == null) {
				jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
			} else {
				jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
			}
			removeBlankPage(jasperPrint.getPages());
		} catch (JRException e) {
			LOG.error("Error building report for uri " + systemId, e);
			throw new ServletException(e);
		}

		// Export the print object to the desired output format
		try {
			if (contentDisposition != null || documentName != null) {
				final StringBuilder tmp = new StringBuilder(128);
				tmp.append((contentDisposition == null) ? "inline" : contentDisposition);

				if (documentName != null) {
					tmp.append("; filename=");
					tmp.append(documentName);
					tmp.append(".");
					tmp.append(format.toLowerCase());
				}

				response.setHeader("Content-disposition", tmp.toString());
			}

			JRExporter exporter;

			if (format.equals(FORMAT_PDF)) {
				response.setContentType("application/pdf");
				exporter = new JRPdfExporter();			
				boolean encryptionReq = Boolean.valueOf(preview);
				if (encryptionReq) {
					exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
					exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY, Boolean.TRUE);
				}
			} else if (format.equals(FORMAT_CSV)) {
				response.setContentType("text/csv");
				exporter = new JRCsvExporter();
			} else if (format.equals(FORMAT_HTML)) {
				response.setContentType("text/html");

				// IMAGES_MAPS seems to be only supported as
				// "backward compatible" from JasperReports 1.1.0

				Map imagesMap = new HashMap();
				request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);

				exporter = new JRHtmlExporter();
				exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
				exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl);

				// Needed to support chart images:
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
				request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
			} else if (format.equals(FORMAT_XLS)) {
				response.setContentType("application/vnd.ms-excel");
				exporter = new JRXlsExporter();
			} else if (format.equals(FORMAT_XML)) {
				response.setContentType("text/xml");
				exporter = new JRXmlExporter();
			} else if (format.equals(FORMAT_RTF)) {
				response.setContentType("application/rtf");
				exporter = new JRRtfExporter();
			} else if ("img".equals(format)) {
				/**
				 * Added By ATK - To support image export 
				 */
				int pageIndex = 0;
				BufferedImage pageImage = new BufferedImage(jasperPrint.getPageWidth() + 1,
						jasperPrint.getPageHeight() + 1, BufferedImage.TYPE_INT_RGB);
				exporter = new JRGraphics2DExporter();
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
				exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
				exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pageIndex));

				ServletOutputStream out = response.getOutputStream();
				exporter.exportReport();
				ImageIO.write(pageImage, "jpeg", out);
				out.close();
			} else {
				throw new ServletException("Unknown report format: " + format);
			}

			Map exportParams = (Map) stack.findValue(exportParameters);
			if (exportParams != null) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Found export parameters; adding to exporter parameters...");
				}
				exporter.getParameters().putAll(exportParams);
			}

			output = exportReportToBytes(jasperPrint, exporter);
		} catch (JRException e) {
			String message = "Error producing " + format + " report for uri " + systemId;
			LOG.error(message, e);
			throw new ServletException(e);
		}
		if (!"img".equals(format)) {
			response.setContentLength(output.length);
			DocumentPrinter documentPrinter = printService.getDocumentPrinter(documentShortName);
			if(documentPrinter!=null){
				documentPrinter.setDocName(documentShortName);
				if(documentPrinter.getPrintOption().equals(DocumentPrinter.CLIENT_OPTION)){
					addFileDownloadCookie(response);
					writeReport(response, output);
				}else if(documentPrinter.getPrintOption().equals(DocumentPrinter.BOTH_OPTION)){
					printService.print(output, documentPrinter);
					addFilePrintedCookie(response);
					addFileDownloadCookie(response);
					writeReport(response, output);
				}else{
					printService.print(output, documentPrinter);
					response.setHeader("Content-disposition", "");		
					response.setContentType("text/html");										
					addFilePrintedCookie(response);
					writeReport(response, new String("").getBytes());
				}	
			}else{
				addFileDownloadCookie(response);
				writeReport(response, output);				
			}
			
		}
	}
	
	private void removeBlankPage(List<JRPrintPage> pages) {
	      for (Iterator<JRPrintPage> i=pages.iterator(); i.hasNext();) {
	          JRPrintPage page = i.next();
	          if (CollectionUtil.isNullOrEmpty(page.getElements())) {
	              i.remove();
	          }
	      }
	  }
	
	private void addFileDownloadCookie(HttpServletResponse response){		
		Cookie fileDownload = new Cookie("fileDownload", "true");
		fileDownload.setPath("/");
		fileDownload.setMaxAge(2*60*60);
		response.addCookie(fileDownload);		
	}
	
	private void addFilePrintedCookie(HttpServletResponse response){		
		Cookie filePrinted = new Cookie("filePrinted", "true");
		filePrinted.setPath("/");
		filePrinted.setMaxAge(2*60*60);
		response.addCookie(filePrinted);		
	}

	/**
	 * Writes report bytes to response output stream.
	 * 
	 * @param response
	 *            Current response.
	 * @param output
	 *            Report bytes to write.
	 * @throws ServletException
	 *             on stream IOException.
	 */
	private void writeReport(HttpServletResponse response, byte[] output) throws ServletException {
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			outputStream.write(output);
			outputStream.flush();
		} catch (IOException e) {
			LOG.error("Error writing report output", e);
			throw new ServletException(e);
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				LOG.error("Error closing report output stream", e);
				throw new ServletException(e);
			}
		}
	}

	private byte[] exportReportToBytes(JasperPrint jasperPrint, JRExporter exporter) throws JRException {
		byte[] output;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
		if (delimiter != null) {
			exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, delimiter);
		}

		exporter.exportReport();

		output = baos.toByteArray();

		return output;
	}

	public String getPreview() {
		return preview;
	}

	public void setPreview(String preview) {
		this.preview = preview;
	}
}



> ClassCastException while generating report using Struts 2.3.28 and jasperreports 4.5.1
> --------------------------------------------------------------------------------------
>
>                 Key: WW-4633
>                 URL: https://issues.apache.org/jira/browse/WW-4633
>             Project: Struts 2
>          Issue Type: Bug
>          Components: Other
>    Affects Versions: 2.3.28
>            Reporter: Irfan
>
> Im getting Exception while generating report im using Struts 2.3.28 and jasperreports 4.5.1,
> 12:42:32,430 ERROR [com.atk.common.struts2.result.JasperReportResult] (http--0.0.0.0-8080-4) Error building report for uri D:\jboss-as-7.1.1.Final-MIG\standalone\tmp\vfs\temp9bbbed31d5b5c7fe\himma-pulmonary.war-d20a7b05840d8b89\reports\jasper\pulmonaryMainReport.jasper: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
>     Source text : $F{evalDs} != null
>     at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:267) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRCalculator.evaluateEstimated(JRCalculator.java:582) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:553) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRFillDataset.evaluateExpression(JRFillDataset.java:1387) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRBaseFiller.evaluateExpression(JRBaseFiller.java:1654) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRFillBand.evaluatePrintWhenExpression(JRFillBand.java:306) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:721) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:265) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:128) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:836) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:765) [jasperreports-4.5.1.jar:4.5.1]
>     at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:84) [jasperreports-4.5.1.jar:4.5.1]
>     at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_80]
> Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to net.sf.jasperreports.engine.JRDataSource
>     at pulmonaryMainReport_subreport1_1462949725806_561776.evaluateEstimated(pulmonaryMainReport_subreport1_1462949725806_561776:530)    at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:254) [jasperreports-4.5.1.jar:4.5.1]



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)

Mime
View raw message