2021-06-07
作者:互联网
代码
package kd.bos.lianmei.plugin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.AppMetadataCache;
import kd.bos.form.control.events.ClickListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.service.DispatchService;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.fi.bcm.business.olap.OlapSaveBuilder;
import kd.fi.bcm.common.Pair;
import kd.fi.bcm.formplugin.report.ReportListPlugin;
import kd.bos.servicehelper.permission.PermissionServiceHelper;
/**
* 0调用api代码中,登录用户写死,值为【kingdee】
* 1对“同步报表”按钮设置权限
* 2通过组织成员基本信息中“报表合并”获取组织
* 3解决跨库查fi库的表数据
* 请求服务节点B,获取B-Olap数据后,新增数据到A-Olap(联美->联美量子)
* @author chens
*
*/
public class LmPlugin extends ReportListPlugin implements ClickListener {
private final static String KEY_BUTTON = "lm_getdata";//联美按钮
//体系编码
private final static String CubeNum = "CUBELM0011094912461905123328";//联美
//第三应用/系统编码
private final static String AppId = "OlapData";//联美量子
//第三应用/系统密码
private final static String AppSecuret = "1234567890qwerty";//联美量子
//管理中心/数据中心ID
private final static String AccountId = "1561691182942805408";//联美量子
//管理中心/租户id
private final static String Tenantid = "luenmeilz";//联美量子
private final static String BaseUrl = "https://luenmeilz.kdcloud.com";//联美量子
private final static String GetAppTokenUrl = BaseUrl+"/api/getAppToken.do";
private final static String GetAccessTokenUrl=BaseUrl+"/api/login.do";
private final static String GetOlapDataUrl=BaseUrl+"/kapi/app/cm/GetOlapData";
/**
* 控件添加监听事件/注册控件事件
* 1.获取控件(控件在View层)
* 2.给控件添加监听
*/
@Override
public void registerListener(EventObject e) {
// TODO Auto-generated method stub
super.registerListener(e);
//按钮点击事件监听
this.addItemClickListeners(KEY_BUTTON);
}
/**
* 用户点击按钮所带的子按钮时,触发此事件
*/
@Override
public void itemClick(ItemClickEvent evt) {
super.itemClick(evt);
String key=evt.getItemKey();
if(StringUtils.equals(key, KEY_BUTTON)) {
//当前用户对按钮是否有权限
long userId = Long.parseLong(RequestContext.get().getUserId()); //用户ID
RequestContext.get().getUserName();
String KEY_APPID = "lm_cm_ext";
String appId = AppMetadataCache.getAppInfo(KEY_APPID).getAppId(); //应用ID
String entityNum = "bcm_report_list"; //实体标识
String permItemId = ""; //权限项ID
String permItemNum = "tbbb";//权限项编码
String permItemEntity = "perm_permitem";//权限项实体名
DynamicObjectCollection dynObjColl = QueryServiceHelper.query(permItemEntity, "id", new QFilter[]{new QFilter("number", QFilter.equals, permItemNum)});
for(DynamicObject dynObj:dynObjColl) {
permItemId = dynObj.getString("id");
}
Boolean hasSpecificPerm = PermissionServiceHelper.hasSpecificPerm(userId, appId, entityNum, permItemId);
if(!hasSpecificPerm) {
this.getView().showErrorNotification("您没有此操作权限!");
return;
}
//获取参数 年、月、组织
DynamicObject yearDynamicObject= (DynamicObject)this.getModel().getValue("year");
DynamicObject periodDynamicObject= (DynamicObject)this.getModel().getValue("period");
if(yearDynamicObject == null || periodDynamicObject == null) {
this.getView().showErrorNotification("请选择财年和期间!");
return;
}
String year =yearDynamicObject.getString("number");
String period = periodDynamicObject.getString("number");
List<String> entityList = new ArrayList();
//获取组织
String entityName = "bcm_entitymembertree";
String selectFields = "number";
QFilter[] filters = {new QFilter("lm_tbbb",QCP.equals,"1"),new QFilter("storagetype",QCP.equals,"2")};
DynamicObject[] rows = BusinessDataServiceHelper.load(entityName, selectFields, filters);
// 递归读取子实体各行的属性值
for (DynamicObject row : rows){
entityList.add(row.getString("number"));
}
if(!(entityList!=null && entityList.size()>0)) {
this.getView().showErrorNotification("没有找到需要同步报表的组织!请检查组织成员基本信息中“同步报表”是否勾选!");
return;
}
//发送请求
Map<String, Object> paramMap = new HashMap<>();
Map<String, Object> resultMap = new HashMap();
List<Map> resultList = new ArrayList();
String result ="";
//获取appToken
String appToken = "";
resultMap = new HashMap();
paramMap = new HashMap<>();
paramMap.put("appId", AppId);
paramMap.put("appSecuret", AppSecuret);
paramMap.put("accountId", AccountId);
try {
result = postData(GetAppTokenUrl, paramMap, "UTF-8");
resultMap = toMap(result);
appToken =( (Map<String, String>) resultMap.get("data")).get("app_token");
} catch (Exception e) {
e.printStackTrace();
}
//获取accessToken
String accessToken = "";
paramMap = new HashMap<>();
String user = RequestContext.get().getUserName();
paramMap.put("user","kingdee");//用户名称/手机号/邮箱
paramMap.put("apptoken", appToken);
paramMap.put("tenantid", Tenantid);//租户id
paramMap.put("accountId", AccountId);
paramMap.put("usertype", "UserName");
try {
result = postData(GetAccessTokenUrl, paramMap, "UTF-8");
resultMap = toMap(result);
accessToken =( (Map<String, String>) resultMap.get("data")).get("access_token");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获取多维数据
paramMap = new HashMap<>();
paramMap.put("year",year );
paramMap.put("period", period);
paramMap.put("entity",entityList);
paramMap.put("accessToken", accessToken);
try {
result = postData(GetOlapDataUrl, paramMap, "UTF-8");
resultList = toList(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resultMap = toMap(result);
if(resultMap.get("success").equals("true")) {
//新增数据到A-Olap
OlapSaveBuilder save = new OlapSaveBuilder(CubeNum);
save.setCrossDimensions(new String[]{"Account","Scenario","Process","AuditTrail","Year","Currency","ChangeType","Entity","Period","InternalCompany","ZH"});
save.setMeasures("FMONEY");
List<Pair<String[], Object>> saveValPairs = new ArrayList<>();
//多个值则for循环加
for(Map<String,String> itemMap:resultList){
saveValPairs.add(Pair.onePair(new String[]{itemMap.get("Account"),itemMap.get("Scenario"),itemMap.get("Process"),itemMap.get("AuditTrail"),itemMap.get("Year"),itemMap.get("Currency"),itemMap.get("ChangeType"),itemMap.get("Entity"),itemMap.get("Period"),itemMap.get("InternalCompany"),itemMap.get("ZH")},itemMap.get("FMONEY") ));
}
save.setCellSet(saveValPairs);
save.doSave();
this.getView().showSuccessNotification("同步成功,数据"+resultList.size()+"条!");
}else {
if(resultMap.get("error_desc")!=null) {
this.getView().showErrorNotification(resultMap.get("error_desc").toString());
}else {
this.getView().showErrorNotification("同步失败");
}
}
}
}
/**
* 发起post请求 有参数的情况
* @param url
* @param params
* @param codePage
* @return
* @throws Exception
*/
private synchronized static String postData(String url, Map<String, Object> params, String codePage) throws Exception {
//创建post请求对象
HttpPost httppost = new HttpPost(url);
// 获取到httpclient客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//创建参数集合
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
//添加请求头参数
if(url.equals(GetOlapDataUrl)) {
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("accessToken",params.get("accessToken").toString());
}
// 设置请求的一些配置设置,主要设置请求超时,连接超时等参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000)
.build();
httppost.setConfig(requestConfig);
//添加参数
httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", codePage)));
// 请求结果
String resultString = "";
//启动执行请求,并获得返回值
CloseableHttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 获取请求响应结果
HttpEntity entity = response.getEntity();
if (entity != null) {
// 将响应内容转换为指定编码的字符串
resultString = EntityUtils.toString(entity, codePage);
System.out.printf("Response content:{}", resultString);
return resultString;
}
} else {
System.out.println("请求失败!");
return resultString;
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
return null;
}
/**
* 将str转化为Map<String, Object>
* @param str
* @return
*/
private static Map<String, Object> toMap(String str) {
Map<String, Object> data = new HashMap();
// 将json字符串转换成jsonObject
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(str);
Iterator json = jsonObject.keys();
// 遍历jsonObject数据,添加到Map对象
while (json.hasNext()) {
String key = json.next().toString();
String value = jsonObject.get(key).toString();
if(value.startsWith("{")) {
net.sf.json.JSONObject itemJsonObject = net.sf.json.JSONObject.fromObject(value);
Iterator itemJson = itemJsonObject.keys();
Map<String, String> itemData = new HashMap<String, String>();
while (itemJson.hasNext()) {
String itemKey = itemJson.next().toString();
String itemValue = itemJsonObject.get(itemKey).toString();
itemData.put(itemKey, itemValue);
}
data.put(key, itemData);
}else {
data.put(key, value);
}
}
return data;
}
/**
* 将str转化为List<Map>
* @param str
* @return
*/
private static List<Map> toList(String str) {
List<Map> resultList = new ArrayList();
// 将json字符串转换成jsonObject
JSONObject jsonObject = JSONObject.parseObject(str);//转换成JSON格式
JSONArray records = JSONObject.parseArray(jsonObject.get("data").toString());
if (!records.isEmpty()) {//如果返回的数据不为空
resultList = JSONArray.parseArray(records.toJSONString(), Map.class);//转换成对象
}
return resultList;
}
}
标签:06,String,get,kd,2021,new,import,paramMap,07 来源: https://blog.csdn.net/CHENCALL111/article/details/117661563