Jasper Reports:从 post 休息服务获取 JSON 数据

Jasper Reports: getting JSON data from a post rest service

我正在尝试从休息服务中获取 JSON 数据。我知道这对于 GET 服务来说非常简单,您只需提供 URI,Jasper studio 就可以提取数据,但我想为 post 休息服务执行此操作,该服务也会消耗一些 JSON 输入.

工作流程类似于:

  1. 在请求中发送用户 ID header 和请求中的一些 JSON 参数 body.
  2. 获取 JSON 数据作为输出。
  3. 使用 JSON 数据构建报告。

我是 Jasper 的新手,我正在使用 Jasper server 6 和 Japser Studio 6,但我找不到任何文档来做这样的事情。

如果有人能为此指出正确的方向,我将不胜感激。

我能找到的关闭的东西是 this link。从那里我知道我可以创建一个构造函数,该构造函数将从其余服务中获取数据,但是我如何将其提供给报告?另请注意,此处检索的 JSON object 有点复杂,至少有 2 个包含任意数量项目的列表。

编辑:

好的,我的自定义适配器是这样的:

package CustomDataAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;

public class SearchAdapter implements JRDataSource {
/**
 * This will hold the JSON returned by generic search service
 */
private JSONObject json = null;

/**
 * Will create the object with data retrieved from service.
 */
public SearchAdapter() {
    String url = "[URL is here]";
    String request = "{searchType: \"TEST\", searchTxt: \"TEST\"}";

    // Setting up post client and request.
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    HttpResponse response = null;

    post.setHeader("userId", "1000");
    post.setHeader("Content-Type", "application/json");

    // Setting up Request payload
    HttpEntity entity = null;
    try {
        entity = new StringEntity(request);
        post.setEntity(entity);

        // do post
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Reading Server Response
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new Exception("Search Failed");
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String inputLine;
        StringBuffer resp = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            resp.append(inputLine);
        }

        in.close();

        this.json = new JSONObject(resp.toString());
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

/*
 * (non-Javadoc)
 * 
 * @see
 * net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
 * .engine.JRField)
 */
public Object getFieldValue(JRField field) throws JRException {
    // TODO Auto-generated method
    // stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
    return this.json;
}

/*
 * (non-Javadoc)
 * 
 * @see net.sf.jasperreports.engine.JRDataSource#next()
 */
public boolean next() throws JRException {
    return (this.json != null);
}

/**
 * Return an instance of the class that implements the custom data adapter.
 */
public static JRDataSource getDataSource() {
    return new SearchAdapter();
}

}

我能够在 Jasper Studio 中创建一个适配器和测试连接功能 returns 正确,但我无法让它读取 JSON 和 [=41= 中的任何字段] 那个报告。我只得到一份空白文件。仅供参考,JSON 类似于:

{
"key": "value",
"key": "value",
"key": [list],
"key": [list]
}

好吧,我现在觉得自己很蠢,但解决方案很简单。原来你不能只是 return 一个 JSON 对象。您需要 return 字段并在报告中手动添加字段。

出于记录目的,我的最终代码如下所示:

package CustomDataAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;

public class SearchAdapter implements JRDataSource {

    /**
     * This will hold the JSON returned by generic search service
     */
    private JSONObject json = null;

    /**
     * Ensures that we infinitely calling the service.
     */
    private boolean flag = false;
    /**
     * Will create the object with data retrieved from service.
     */
    private void setJson() {
        String url = "[URL is here]";
        String request = "{\"searchType\": \"Test\", \"searchTxt\": \"Test\"}";

        // Setting up post client and request.
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        HttpResponse response = null;

        post.setHeader("userId", "1000");
        post.setHeader("Content-Type", "application/json");

        // Setting up Request payload
        StringEntity entity = null;
        try {
            entity = new StringEntity(request);
            post.setEntity(entity);

            // do post
            response = client.execute(post);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Reading Server Response
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                // Thrown Exception in case things go wrong
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String inputLine;
                StringBuffer resp = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    resp.append(inputLine);
                }

                in.close();

                String ex = "Search Failed. Status Code: " + statusCode;
                ex += "\n Error: " + resp.toString();
                throw new Exception(ex);
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String inputLine;
            StringBuffer resp = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                resp.append(inputLine);
            }

            in.close();

            this.json = new JSONObject(resp.toString());
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
     * .engine.JRField)
     */
    @Override
    public Object getFieldValue(JRField field) throws JRException {
        // TODO Auto-generated method
        // stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
        try {
            return this.json.get(field.getName());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see net.sf.jasperreports.engine.JRDataSource#next()
     */
    @Override
    public boolean next() throws JRException {
        if (this.json != null && !flag) {
            flag = true;
            return true;
        } else {
            return false;
        }
    }

    /**
     * Return an instance of the class that implements the custom data adapter.
     */
    public static JRDataSource getDataSource() {
        SearchAdapter adapter = new SearchAdapter();
        adapter.setJson();
        return adapter;
    }

}