JasperReportUtil 工具类

JasperReportUtil 是一个用于报表处理的工具类,包含获取报表SQL、保存JRXML文件到本地、编译JRXML为JASPER文件等功能。它通过HTTP请求获取远程报表文件,并能根据报表名称解析SQL。此外,类中还提供了处理报表参数、CLOB转换为String等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package org.platform.service.report.oauth;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


import javax.sql.rowset.serial.SerialClob;


import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.json.JSONObject;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.platform.service.report.config.ReportConfig;
import org.platform.service.report.dto.ReportQueryParamsDto;
import org.platform.utils.file.FileUtil;
import org.platform.utils.httpclient.HttpClientHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.alibaba.fastjson.JSON;
/**
 * @ProjectName platform-service-report
 * @PackageName org.platform.service.report.oauth
 * @Description 报表公共方法
 * @ClassName JasperReportUtil
 * @Author L_X
 * @Date 2017年8月11日 下午2:41:24
 */
public class JasperReportUtil {

private static final Logger logger = LoggerFactory.getLogger(JasperReportUtil.class);

/**
* @Description 获取报表SQL
* @MethodName findToSql
* @Author L_X
* @Date 2017年9月8日 上午11:11:13
* @param reportName
* @param reportMD5
* @param subReportMD5
* @return
* @throws Exception String
*/
public static String findReportToSql(String reportName, String reportMD5, String subReportMD5) throws Exception{
String sql = null;
if (ReportConfig.IS_ON_OFF.equals(DefaultConstants.IS_ON)) {
File file = new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jrxml");
String md5Local = FileUtil.getFileMD5(file);
File subfile = new File(ReportConfig.NATIVE_FILE_PATH + reportName + "_subReport.jrxml");
String subMd5Local = FileUtil.getFileMD5(subfile);
if (file.exists() && md5Local.equals(reportMD5)) {
sql = getLocationSql(reportName);
} else {
sql = saveSqlToNative(reportName);
}
StringBuffer sb = new StringBuffer("null");
if (StringUtils.isNotBlank(subReportMD5) && !subReportMD5.contentEquals(sb)) {
if ( !subfile.exists() || !subMd5Local.equals(subReportMD5)) {
saveReportFileToLocal(reportName+ "_subReport",".jrxml");
}
}
}else {
sql = getSql(reportName);
}
return sql;
}

/**
* @Description 根据报表名称获取JRXML文件,解析得到SQL
* @MethodName getSql
* @Author L_X
* @Date 2017年8月11日 下午2:39:56
* @param reportName
* @return String
*/
public static String getSql(String reportName) throws Exception{
String xmlString = HttpClientHelper
.get(ReportConfig.HTTP_GET_REPORT_FILE + reportName + ".jrxml");
String replaceAll2 = xmlString.replaceAll("[\\n\\r\\r\\n]", " ");
String replaceAll = replaceAll2.replaceAll("select", "SELECT");
String string = replaceAll;
if (replaceAll.contains("<![CDATA[SELECT")) {
string = replaceAll.split("\\<\\!\\[CDATA\\[SELECT")[1];
} else {
string = replaceAll.split("\\<\\!\\[CDATA\\[ SELECT")[1];
}
String sql = string.split("\\]\\]\\>")[0];
String sql1 = "SELECT" + sql;
return sql1;
}
/**
* @Description 根据报表名称获取JRXML文件,解析得到SQL
* @MethodName getSql
* @Author L_X
* @Date 2017年8月11日 下午2:39:56
* @param reportName
* @return String
*/
public static String saveSqlToNative(String reportName) throws Exception{
String xmlString = HttpClientHelper
.get(ReportConfig.HTTP_GET_REPORT_FILE + reportName + ".jrxml");

FileUtils.write(new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jrxml"), xmlString,"UTF-8");
File newFile = new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jrxml");//JRXML文件
if (newFile.exists()) {
File newDestFile = new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jasper");//JASPER文件
JasperCompileManager.compileReportToFile(newFile.getPath(), newDestFile.getPath());//编译jrxml文件
}
String replaceAll2 = xmlString.replaceAll("[\\n\\r\\r\\n]", " ");
String replaceAll = replaceAll2.replaceAll("select", "SELECT");
String string = replaceAll;
if (replaceAll.contains("<![CDATA[SELECT")) {
string = replaceAll.split("\\<\\!\\[CDATA\\[SELECT")[1];
} else {
string = replaceAll.split("\\<\\!\\[CDATA\\[ SELECT")[1];
}

String sql = string.split("\\]\\]\\>")[0];
String sql1 = "SELECT" + sql;
return sql1;
}
/**

* @param reportName
* @throws IOException
*/
public static void saveJasperToLocal(String reportName) throws IOException{
String jasperString= HttpClientHelper.get(ReportConfig.HTTP_GET_REPORT_FILE + reportName + ".jasper");
FileUtils.write(new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jasper"), jasperString,"UTF-8");
}
public static InputStream getLocalJasper(String reportName) throws IOException{
String jasperString= HttpClientHelper.get(ReportConfig.HTTP_GET_REPORT_FILE + reportName + ".jasper");
FileUtils.write(new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jasper"), jasperString,"UTF-8");
FileInputStream inputStream = FileUtils.openInputStream(new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jasper"));
return inputStream;
}

/**
* 将远程服务器上的文件保存到本地
* @param reportName 文件名 
* @param fileType 文件类型,例如 : .jrxml
* @throws Exception
*/
public static void saveReportFileToLocal(String reportName,String fileType) throws Exception{
String xmlString = HttpClientHelper
.get(ReportConfig.HTTP_GET_REPORT_FILE + reportName + fileType);
FileUtils.write(new File(ReportConfig.NATIVE_FILE_PATH + reportName + fileType), xmlString,"UTF-8");
}
/**
* @Description 根据文件名称获取本地报表SQL
* @MethodName getLocationSql
* @Author L_X
* @Date 2017年9月7日 下午12:55:07
* @param reportName
* @return
* @throws Exception String
*/
public static String getLocationSql(String reportName) throws Exception{
String xmlString = FileUtils.readFileToString(new File(ReportConfig.NATIVE_FILE_PATH + reportName + ".jrxml"), "UTF-8");
//String xmlString =XmlUtil.getDocStrFromFile(ReportConfig.NATIVE_FILE_PATH + reportName + ".jrxml");
String replaceAll2 = xmlString.replaceAll("[\\n\\r\\r\\n]", " ");
String replaceAll = replaceAll2.replaceAll("select", "SELECT");
String string = replaceAll;
if (replaceAll.contains("<![CDATA[SELECT")) { 
string = replaceAll.split("\\<\\!\\[CDATA\\[SELECT")[1];
} else {
string = replaceAll.split("\\<\\!\\[CDATA\\[ SELECT")[1];
}
String sql = string.split("\\]\\]\\>")[0];
String sql1 = "SELECT" + sql;
return sql1;
}
/**
* @Description 
* @MethodName getSqlParams
* @Author L_X
* @Date 2017年8月11日 下午2:48:43
* @param params 报表参数
* @param sql 原生JRXML SQL
*/
public static String getSqlParams(String params,String sql,String queryParamsStr){
Map<String, String> parameterMap = new HashMap<String, String>();
String sqlStr = null;
try {
if(StringUtils.isNotBlank(params)){
parameterMap = processingParams(params,queryParamsStr);

for(Entry<String, String> en : parameterMap.entrySet()){
String name = en.getKey();
String parameterStr= "$P{" + name + "}";
String parameterSql = "$P!{" + name +"}";
String value = "\\'"+en.getValue().toString()+"\\'";
sql = sql.replace(parameterStr, value);
sql = sql.replace(parameterSql, en.getValue().toString());
}
sqlStr = sql;
}else {
sqlStr = sql.replaceAll(DefaultConstants.PARAMS_REGEXP, "");
sqlStr = sqlStr.replaceAll(DefaultConstants.PARAMS_A_REGEXP, "null");
}
} catch (Exception e) {
logger.error("加载报表参数处理错误,原参数:"+params);
logger.error("加载报表参数处理错误",e);
}
return sqlStr;
}

@SuppressWarnings({ "unchecked"})
public static Map<String, String> processingParams(String params,String queryParamsStr){
Map<String, String> parameterMap = new HashMap<String, String>();
try {
List<ReportQueryParamsDto> queryList = JSON.parseArray(queryParamsStr, ReportQueryParamsDto.class);
if(StringUtils.isNotBlank(params)){

params = StringEscapeUtils.unescapeHtml4(params);
JSONObject jsonMap = JSONObject.fromObject(params);  
Iterator<String> it = jsonMap.keys();  
while(it.hasNext()) {
String key = it.next();  
String u = (String) jsonMap.get(key);  
parameterMap.put(key, u);  
}  

for(int i = 0; i < queryList.size(); i++){
if(parameterMap.containsKey(queryList.get(i).getSqlKey())){
if(StringUtils.isNotBlank(parameterMap.get(queryList.get(i).getSqlKey()))){
String sqlval = queryList.get(i).getSqlVal();
sqlval = sqlval.replaceAll("para_val", parameterMap.get(queryList.get(i).getSqlKey()));
parameterMap.put(queryList.get(i).getSqlKey(), sqlval);
}
}
}
}else {
for(int i = 0; i < queryList.size(); i++){
parameterMap.put(queryList.get(i).getSqlKey(), null);
}
}
} catch (Exception e) {
logger.error("处理查询参数,原参数:"+params);
logger.error("处理查询参数错误",e);
}
return parameterMap;
}

/**
    *Java文件操作获取不带扩展名的文件名
    */
    public static String getFileNameNoEx(String filename){
    if((filename!=null)&&(filename.length()>0)){
    int dot=filename.lastIndexOf('.');
    if((dot>-1)&&(dot<(filename.length()))){
    return filename.substring(0,dot);
    }
    }
    return filename;
    }
    /**
     * @Description 清空文件夹
     * @MethodName delFolder
     * @Author L_X
     * @Date 2017年8月10日 上午9:42:58 void
     */
    public static void delFolder(String imgPath){
    File imgRealDir= new File(imgPath);
    if (imgRealDir.exists() && imgRealDir.isDirectory()) {
String[] files = imgRealDir.list();
File temp = null;
for (int i = 0; i < files.length; i++) {
if (imgPath.endsWith(File.separator)) {
temp = new File(imgPath + files[i]);
}else {
temp = new File(imgPath + File.separator + files[i]);
}
if (temp.isFile()) {
temp.delete();
}
}
}
    }
    /**
     * @Description 将字CLOB转成STRING类型
     * @MethodName ClobToString
     * @Author L_X
     * @Date 2017年9月1日 下午12:12:23
     * @param clob
     * @return String
     */
    public static String clobToString(Clob clob) {
        String reString = "";
        try {
        if (clob == null) {
return "";
}
        // 得到流
        Reader is = clob.getCharacterStream();
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        // 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
        while (s != null) {
        sb.append(s);
        s = br.readLine();
        }
        reString = sb.toString();
        } catch (SQLException | IOException e) {
logger.error("CLOB转换String出错", e);
}
        return reString;
    }
    /**
     * @Description String转换CLOB
     * @MethodName stringToClob
     * @Author L_X
     * @Date 2017年9月1日 下午1:09:25
     * @param str
     * @return Clob
     */
    public static Clob stringToClob(String str){
    Clob clob = null;
    try {
    if (StringUtils.isNotBlank(str)) {
    clob = new SerialClob(str.toCharArray());
}
} catch (SQLException e) {
logger.error("String转换CLOB出错:", e);
}
    return clob;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值