Browse Source

open

master
pioneer 2 years ago
commit
86ca01da27
  1. 6
      README.md
  2. BIN
      bin/main/com/fr/plugin/FunctionRecoder.class
  3. BIN
      bin/main/com/fr/plugin/GUANJIAConfig.class
  4. BIN
      bin/main/com/fr/plugin/GUANJIALifeCycleMonitor.class
  5. 25
      bin/main/com/fr/plugin/demo.js
  6. BIN
      bin/main/com/fr/plugin/http/GUANJIAHttpHandler.class
  7. BIN
      bin/main/com/fr/plugin/http/GUANJIAUrlAliasProvider.class
  8. BIN
      bin/main/com/fr/plugin/http/handler/ALLSapApi1Handler.class
  9. BIN
      bin/main/com/fr/plugin/utils/ConnectSAPServer.class
  10. BIN
      bin/main/com/fr/plugin/utils/DBUtils.class
  11. 128
      build.gradle
  12. 13
      encrypt.xml
  13. BIN
      lib/finekit-10.0-20220427.jar
  14. BIN
      lib/sapjco.jar
  15. BIN
      lib/sapjco3.jar
  16. 24
      plugin.xml
  17. 12
      src/main/java/com/fr/plugin/FunctionRecoder.java
  18. 94
      src/main/java/com/fr/plugin/GUANJIAConfig.java
  19. 18
      src/main/java/com/fr/plugin/GUANJIALifeCycleMonitor.java
  20. 16
      src/main/java/com/fr/plugin/http/GUANJIAHttpHandler.java
  21. 14
      src/main/java/com/fr/plugin/http/GUANJIAUrlAliasProvider.java
  22. 245
      src/main/java/com/fr/plugin/http/handler/ALLSapApi1Handler.java
  23. 68
      src/main/java/com/fr/plugin/utils/ConnectSAPServer.java
  24. 380
      src/main/java/com/fr/plugin/utils/DBUtils.java
  25. 25
      src/main/resources/com/fr/plugin/demo.js

6
README.md

@ -0,0 +1,6 @@
# open-JSD-10757
JSD-10757 对接sap的rfc接口取数\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。

BIN
bin/main/com/fr/plugin/FunctionRecoder.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/GUANJIAConfig.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/GUANJIALifeCycleMonitor.class

Binary file not shown.

25
bin/main/com/fr/plugin/demo.js

@ -0,0 +1,25 @@
var data = []
for (i = 0; i < len; i++) {
var factory = _g().getCellValue(0, 1, i + 4);
//获取B5的扩展值
var wl = _g().getCellValue(0, 2, i + 4);
//获取C5的扩展值
data.push({
"MATNR": wl,
"WERKS": factory
})
}
$.ajax({
url: "/webroot/decision/url/sapApi",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function (e) {
alert("提交响应:" + e)
},
error: function () {
alert("提交失败请联系技术支持查看日志")
}
})

BIN
bin/main/com/fr/plugin/http/GUANJIAHttpHandler.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/http/GUANJIAUrlAliasProvider.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/http/handler/ALLSapApi1Handler.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/utils/ConnectSAPServer.class

Binary file not shown.

BIN
bin/main/com/fr/plugin/utils/DBUtils.class

Binary file not shown.

128
build.gradle

@ -0,0 +1,128 @@
apply plugin: 'java'
ext {
/**
* jar的路径
* 1.jar需要打包到zip中,lib根目录下
* 2.jar仅仅是编译时需要lib下子目录下即可
*/
libPath = "$projectDir/../../webroot/WEB-INF/lib"
/**
* class进行加密保护
*/
guard = false
def pluginInfo = getPluginInfo()
pluginPre = "fine-plugin"
pluginName = pluginInfo.id
pluginVersion = pluginInfo.version
outputPath = "$projectDir/../../webroot/WEB-INF/plugins/plugin-" + pluginName + "-1.0/classes"
}
group = 'com.fr.plugin'
version = '10.0'
sourceCompatibility = '8'
sourceSets {
main {
java.outputDir = file(outputPath)
output.resourcesDir = file(outputPath)
}
}
ant.importBuild("encrypt.xml")
//ant变量
ant.projectDir = projectDir
ant.references["compile.classpath"] = ant.path {
fileset(dir: libPath, includes: '**/*.jar')
fileset(dir: ".",includes:"**/*.jar" )
}
classes.dependsOn('clean')
task copyFiles(type: Copy,dependsOn: 'classes'){
from outputPath
into "$projectDir/classes"
}
task myCopy(type: Copy){
from ("$projectDir/lib"){include "*.jar"}
from "$projectDir/plugin.xml"
into "$projectDir/../../webroot/WEB-INF/plugins/plugin-" + pluginName + "-1.0/"
}
task preJar(type:Copy,dependsOn: guard ? 'compile_encrypt_javas' : 'compile_plain_javas'){
from "$projectDir/classes"
into "$projectDir/transform-classes"
include "**/*.*"
}
jar.dependsOn("preJar")
classes.dependsOn("myCopy")
task makeJar(type: Jar,dependsOn: preJar){
from fileTree(dir: "$projectDir/transform-classes")
baseName pluginPre
appendix pluginName
version pluginVersion
destinationDir = file("$buildDir/libs")
doLast(){
delete file("$projectDir/classes")
delete file("$projectDir/transform-classes")
}
}
task copyFile(type: Copy,dependsOn: ["makeJar"]){
from "$buildDir/libs"
from("$projectDir/lib") {
include "*.jar"
}
from "$projectDir/plugin.xml"
into file("$buildDir/temp/plugin")
}
task zip(type:Zip,dependsOn:["copyFile"]){
from "$buildDir/temp/plugin"
destinationDir file("$buildDir/install")
baseName pluginPre
appendix pluginName
version pluginVersion
}
//build时包含哪些文件,
processResources {
// exclude everything
// *.css没效果
// exclude '**/*.css'
// except this file
// include 'xx.xml'
}
/*读取plugin.xml中的version*/
def getPluginInfo(){
def xmlFile = file("plugin.xml")
if (!xmlFile.exists()) {
return ["id":"none", "version":"1.0.0"]
}
def plugin = new XmlParser().parse(xmlFile)
def version = plugin.version[0].text()
def id = plugin.id[0].text()
return ["id":id,"version":version]
}
repositories {
mavenLocal()
maven {
url = uri('https://mvn.fanruan.com/repository/maven-public/')
}
}
dependencies {
//使jar
implementation fileTree(dir: 'lib', include: ['**/*.jar'])
implementation fileTree(dir: libPath, include: ['**/*.jar'])
}

13
encrypt.xml

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project>
<target name="compile_encrypt_javas" depends="copyFiles">
<echo message="加密文件"/>
<echo message="${projectDir}"/>
<taskdef name="pretreatment" classname="com.fr.plugin.pack.PluginPretreatmentTask">
<classpath refid="compile.classpath"/>
</taskdef>
<pretreatment baseDir="${projectDir}"/>
</target>
<target name="compile_plain_javas" depends="copyFiles">
</target>
</project>

BIN
lib/finekit-10.0-20220427.jar

Binary file not shown.

BIN
lib/sapjco.jar

Binary file not shown.

BIN
lib/sapjco3.jar

Binary file not shown.

24
plugin.xml

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<plugin>
<id>com.eco.plugin.zzl.sap.guanjia</id>
<name><![CDATA[冠捷_EK]]></name>
<active>yes</active>
<version>0.3.3</version>
<env-version>10.0</env-version>
<jartime>2021-02-10</jartime>
<vendor>fr.open</vendor>
<main-package>com.fr.plugin</main-package>
<!--用来记录这个任务的创建时间-->
<description><![CDATA[
2022-7-28 20:20:02 JSD-10757插件初始化
补增10904
]]></description>
<!--任务ID: 10757-->
<create-day>2022-7-28 20:20:02</create-day>
<extra-decision>
<HttpHandlerProvider class="com.fr.plugin.http.GUANJIAHttpHandler"/>
<URLAliasProvider class="com.fr.plugin.http.GUANJIAUrlAliasProvider"/>
</extra-decision>
<lifecycle-monitor class="com.fr.plugin.GUANJIALifeCycleMonitor"/>
<function-recorder class="com.fr.plugin.FunctionRecoder"/>
</plugin>

12
src/main/java/com/fr/plugin/FunctionRecoder.java

@ -0,0 +1,12 @@
package com.fr.plugin;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
@FunctionRecorder
public class FunctionRecoder {
@ExecuteFunctionRecord
public void exe(){
System.out.println("插件功能埋点,虽然不会执行,除非上架应用");
}
}

94
src/main/java/com/fr/plugin/GUANJIAConfig.java

@ -0,0 +1,94 @@
package com.fr.plugin;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
@Visualization(category = "冠捷_EK配置")
public class GUANJIAConfig extends DefaultConfiguration {
private static volatile GUANJIAConfig config = null;
public static GUANJIAConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(GUANJIAConfig.class);
}
return config;
}
@Identifier(value = "sapIp", name = "sapIp", description = "描述", status = Status.SHOW, restart = true)
private Conf<String> sapIp = Holders.simple("xxx");
@Identifier(value = "sysCode", name = "系统编号", description = "描述", status = Status.SHOW, restart = true)
private Conf<String> sysCode = Holders.simple("xx");
@Identifier(value = "cusCode", name = "客户端编号", description = "描述", status = Status.SHOW, restart = true)
private Conf<String> cusCode = Holders.simple("xx");
@Identifier(value = "userName", name = "用户名", description = "描述", status = Status.SHOW, restart = true)
private Conf<String> userName = Holders.simple("xx");
@Identifier(value = "pwd", name = "密码", description = "描述", status = Status.SHOW, restart = true)
private Conf<String> pwd = Holders.simple("xxx");
public String getSapIp() {
return sapIp.get();
}
public void setSapIp(String sapIp) {
this.sapIp.set(sapIp);
}
public String getSysCode() {
return sysCode.get();
}
public void setSysCode(String sysCode) {
this.sysCode.set(sysCode);
}
public String getCusCode() {
return cusCode.get();
}
public void setCusCode(String cusCode) {
this.cusCode.set(cusCode);
}
public String getUserName() {
return userName.get();
}
public void setUserName(String userName) {
this.userName.set(userName);
}
public String getPwd() {
return pwd.get();
}
public void setPwd(String pwd) {
this.pwd.set(pwd);
}
@Identifier(value = "apiUrl", name = "apiUrl", description = "描述", status = Status.HIDE)
private Conf<String> apiUrl = Holders.simple("http://172.20.0.1:8000/sap/zrestful_test?sap-client=150&RFC=ZRFC_OMP_DATAMASTER");
public String getApiUrl() {
return apiUrl.get();
}
public void setApiUrl(String apiUrl) {
this.apiUrl.set(apiUrl);
}
@Override
public Object clone() throws CloneNotSupportedException {
GUANJIAConfig cloned = (GUANJIAConfig) super.clone();
cloned.apiUrl = (Conf<String>) this.apiUrl.clone();
cloned.pwd = (Conf<String>) this.pwd.clone();
cloned.userName = (Conf<String>) this.userName.clone();
cloned.cusCode = (Conf<String>) this.cusCode.clone();
cloned.sysCode = (Conf<String>) this.sysCode.clone();
cloned.sapIp = (Conf<String>) this.sapIp.clone();
return cloned;
}
}

18
src/main/java/com/fr/plugin/GUANJIALifeCycleMonitor.java

@ -0,0 +1,18 @@
package com.fr.plugin;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
import com.fr.stable.fun.Authorize;
@Authorize
public class GUANJIALifeCycleMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
GUANJIAConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

16
src/main/java/com/fr/plugin/http/GUANJIAHttpHandler.java

@ -0,0 +1,16 @@
package com.fr.plugin.http;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
import com.fr.plugin.http.handler.*;
public class GUANJIAHttpHandler extends AbstractHttpHandlerProvider {
HttpHandler[] actions = new HttpHandler[]{
new ALLSapApi1Handler(),
};
@Override
public HttpHandler[] registerHandlers() {
return actions;
}
}

14
src/main/java/com/fr/plugin/http/GUANJIAUrlAliasProvider.java

@ -0,0 +1,14 @@
package com.fr.plugin.http;
import com.fr.decision.fun.impl.AbstractURLAliasProvider;
import com.fr.decision.webservice.url.alias.URLAlias;
import com.fr.decision.webservice.url.alias.URLAliasFactory;
public class GUANJIAUrlAliasProvider extends AbstractURLAliasProvider {
@Override
public URLAlias[] registerAlias() {
return new URLAlias[]{
URLAliasFactory.createPluginAlias("/sapApi", "/sapApi", true),
};
}
}

245
src/main/java/com/fr/plugin/http/handler/ALLSapApi1Handler.java

@ -0,0 +1,245 @@
package com.fr.plugin.http.handler;
import com.fanruan.api.log.LogKit;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.utils.ConnectSAPServer;
import com.fr.plugin.utils.DBUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import com.sap.conn.jco.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
public class ALLSapApi1Handler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return null;
}
@Override
public String getPath() {
return "/sapApi";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res) throws Exception {
String requestBody = getRequestBody(req);
LogKit.info("收到的JSON:{}", requestBody);
JSONArray array = new JSONArray(requestBody);
DBUtils dbUtils = new DBUtils();
//check exist
int resq = array.size();
// JSONArray reqJSONArr = new JSONArray();
// for (int i = 0; i < resq; i++) {
// JSONObject jsonObject = array.getJSONObject(i);
// String matnr = jsonObject.getString("MATNR");
// boolean exist = dbUtils.checkExist("select count(1) c from TPV_OMP_MATERIAL_DATA where TPV_MODEL=?", matnr);
// if (!exist) {
// reqJSONArr.add(jsonObject);
// }
// }
LogKit.info("发送到接口的JSON为:{}", array);
// GUANJIAConfig config = GUANJIAConfig.getInstance();
// String apiUrl = config.getApiUrl();
// String resp = HttpKit.postJSON(apiUrl, reqJSONArr, new HashMap<>());
// LogKit.info("请求:{},响应:{}", apiUrl, resp);
// JSONArray jsonArray = new JSONArray(resp);
JSONObject retJSON = send2SAP(array);
JSONArray jsonArray = retJSON.getJSONArray("arr1");
LogKit.info("SAP返回的为:{}", jsonArray);
String user ="admin";
try {
User user1 = UserService.getInstance().getUserByRequestCookie(req);
user=user1.getUserName();
}catch (Exception e){
}
//更新TPV_OMP_MATERIAL_DATA表
dbUtils.saveJSONArr(jsonArray, user );
//更新状态表
JSONArray arr2 = retJSON.getJSONArray("arr2");
int size1 = arr2.size();
for (int i = 0; i < size1; i++) {
JSONObject o = arr2.getJSONObject(i);
dbUtils.saveReJSON(o, user );
}
WebUtils.printAsString(res, "入库成功");
}
private JSONObject send2SAP(JSONArray inArr) throws JCoException {
JCoDestination jCoDestination = ConnectSAPServer.Connect();
JCoFunction function = jCoDestination.getRepository().getFunction("ZRFC_OMP_DATAMASTER");
if (function == null)
throw new RuntimeException("Function not found in SAP.");
// JCoParameterList tableParameterList = function.getTableParameterList();
JCoParameterList importParameterList = function.getImportParameterList();
JCoTable input_tab = importParameterList.getTable("IT_INPUT");
// JCoTable input_tab = tableParameterList.getTable("IT_INPUT");
int size = inArr.size();
for (int i = 0; i < size; i++) {
input_tab.appendRow();
JSONObject jsonObject = inArr.getJSONObject(i);
input_tab.setValue("MATNR", jsonObject.getString("MATNR"));
input_tab.setValue("WERKS", jsonObject.getString("WERKS"));
}
function.execute(jCoDestination);
JCoTable returnTable = function.getTableParameterList().getTable("IT_OUTPUT");
int numRows = returnTable.getNumRows();
LogKit.info("接收到条数:{}", numRows);
JSONArray jsonArray = new JSONArray();
if (numRows > 0) {
for (int i = 0; i < numRows; i++) {
JSONObject jsonObject = new JSONObject();
for (JCoField jCoField : returnTable) {
LogKit.info("jcoFile:{} ,value:{}", jCoField.getName(), jCoField.getValue());
}
jsonObject.put("MATNR", toString2(returnTable.getValue("MATNR")));
jsonObject.put("BISMT",toString2( returnTable.getValue("BISMT")));
jsonObject.put("MAKTX", toString2(returnTable.getValue("MAKTX")));
jsonObject.put("BRGEW",toString2( returnTable.getValue("BRGEW")));
jsonObject.put("BTGEW",toString2( returnTable.getValue("NTGEW")));
jsonObject.put("VOLUM",toString2( returnTable.getValue("VOLUM")));
jsonObject.put("SPART",toString2( returnTable.getValue("SPART")));
jsonObject.put("MATKL",toString2( returnTable.getValue("MATKL")));
jsonObject.put("MEINS",toString2( returnTable.getValue("MEINS")));
jsonObject.put("NORMT",toString2( returnTable.getValue("NORMT")));
jsonObject.put("FERTH",toString2( returnTable.getValue("FERTH")));
jsonObject.put("Z_BRDTYPE", toString2(returnTable.getValue("Z_BRDTYPE")));
jsonObject.put("Z_BRDID",toString2( returnTable.getValue("Z_BRDID")));
jsonObject.put("Z_REGION", toString2(returnTable.getValue("Z_REGION")));
jsonObject.put("Z_CMNFTYPE",toString2( returnTable.getValue("Z_CMNFTYPE")));
jsonObject.put("Z_PRDLINE",toString2( returnTable.getValue("Z_PRDLINE")));
jsonObject.put("Z_STYLEID",toString2( returnTable.getValue("Z_STYLEID")));
jsonObject.put("Z_SRCTYPE",toString2( returnTable.getValue("Z_SRCTYPE")));
jsonObject.put("Z_ASSM",toString2( returnTable.getValue("Z_ASSM")));
jsonObject.put("Z_WPNL",toString2( returnTable.getValue("Z_WPNL")));
jsonObject.put("Z_SIZE", toString2(returnTable.getValue("Z_SIZE")));
jsonObject.put("Z_RATIO", toString2(returnTable.getValue("Z_RATIO")));
jsonObject.put("Z_PNLLIGHT",toString2( returnTable.getValue("Z_PNLLIGHT")));
jsonObject.put("Z_PNLSUPTYPE", toString2(returnTable.getValue("Z_PNLSUPTYPE")));
jsonObject.put("Z_PNLBRDID",toString2( returnTable.getValue("Z_PNLBRDID")));
jsonObject.put("Z_FUNTYPE", toString2(returnTable.getValue("Z_FUNTYPE")));
jsonObject.put("Z_SGNTYPE", toString2(returnTable.getValue("Z_SGNTYPE")));
jsonObject.put("Z_CUSTNAME",toString2( returnTable.getValue("Z_CUSTNAME")));
jsonObject.put("Z_PARSE", toString2(returnTable.getValue("Z_PARSE")));
jsonObject.put("Z_BG", toString2(returnTable.getValue("Z_BG")));
jsonObject.put("Z_SMARTTV", toString2(returnTable.getValue("Z_SMARTTV")));
jsonObject.put("Z_DOBLY", toString2(returnTable.getValue("Z_DOBLY")));
jsonObject.put("GEBSQ", toString2(returnTable.getValue("GEBSQ")));
jsonObject.put("HSCODE",toString2( returnTable.getValue("HSCODE")));
jsonObject.put("CMODEL", toString2(returnTable.getValue("CMODEL")));
jsonObject.put("MATNR_LCM", toString2(returnTable.getValue("MATNR_LCM")));
jsonObject.put("MAKTX_LCM", toString2(returnTable.getValue("MAKTX_LCM")));
jsonArray.add(jsonObject);
returnTable.nextRow();
}
}
JCoTable extable = function.getTableParameterList().getTable("ET_RETURN");
int exCount = extable.getNumRows();
LogKit.info("接收到extable 条数:{}", exCount);
JSONArray jsonexArray = new JSONArray();
if (exCount > 0) {
for (int i = 0; i < exCount; i++) {
JSONObject jsonObject = new JSONObject();
for (JCoField jCoField : extable) {
LogKit.info("jcoFile:{} ,value:{}", jCoField.getName(), jCoField.getValue());
// jsonObject.put(jCoField.getName(), jCoField.getString());
}
jsonObject.put("MATNR", toString2(extable.getValue("MATNR")));
jsonObject.put("WERKS", toString2(extable.getValue("WERKS")));
jsonObject.put("RETURN", toString2(extable.getValue("RETURN")));
jsonexArray.add(jsonObject);
extable.nextRow();
}
}
JSONObject returnObj = new JSONObject();
returnObj.put("arr1", jsonArray);
returnObj.put("arr2", jsonexArray);
LogKit.info("两个表数据:{}",returnObj);
return returnObj;
}
private String toString2(Object obj) {
if (obj != null) {
return obj.toString();
}
return "";
}
public static String getRequestBody(HttpServletRequest req) {
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) {
}
return sb.toString();
}
/**
* 根据key获取cookie
*
* @param req
* @return
*/
public static String getCookieByKey(HttpServletRequest req, String key) {
Cookie[] cookies = req.getCookies();
String cookie = "";
if (cookies == null || cookies.length <= 0) {
return "";
}
for (int i = 0; i < cookies.length; i++) {
Cookie item = cookies[i];
if (item.getName().equalsIgnoreCase(key)) {
cookie = item.getValue();
}
}
LogKit.info("cookie:" + cookie);
return cookie;
}
private String deleteCookieByName(HttpServletRequest request, HttpServletResponse response, String name) {
Cookie[] cookies = request.getCookies();
if (null == cookies) {
FineLoggerFactory.getLogger().debug("没有cookie");
} else {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
String cookieValue = cookie.getValue();
//设置值为null
cookie.setValue(null);
//立即销毁cookie
cookie.setMaxAge(0);
cookie.setPath("/");
FineLoggerFactory.getLogger().debug("被删除的cookie名字为:{}", cookie.getName(), cookieValue);
response.addCookie(cookie);
return cookieValue;
}
}
}
return "";
}
}

68
src/main/java/com/fr/plugin/utils/ConnectSAPServer.java

@ -0,0 +1,68 @@
package com.fr.plugin.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;
import com.fanruan.api.log.LogKit;
import com.fr.plugin.GUANJIAConfig;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.ext.DestinationDataProvider;
public class ConnectSAPServer {
static String ABAP_AS_POOLED = "ABAP_AS_WITH_POOL";
static {
Properties connectProperties = new Properties();
GUANJIAConfig config = GUANJIAConfig.getInstance();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST,
config.getSapIp());
LogKit.info("SAP接口地址:{}", config.getSapIp());
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, config.getSysCode());
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "01");
connectProperties
.setProperty(DestinationDataProvider.JCO_CLIENT, config.getCusCode());
LogKit.info("SAPCUSCODE:{}", config.getCusCode());
connectProperties.setProperty(DestinationDataProvider.JCO_USER,
config.getUserName());
LogKit.info("SAP用户名:{}", config.getUserName());
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD,
config.getPwd());
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD,
config.getPwd());
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "EN");
connectProperties.setProperty(
DestinationDataProvider.JCO_POOL_CAPACITY, "10");
connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT,
"10");
createDataFile(ABAP_AS_POOLED, "jcoDestination", connectProperties);
}
static void createDataFile(String name, String suffix, Properties properties) {
File cfg = new File(name + "." + suffix);
try {
FileOutputStream fos = new FileOutputStream(cfg, false);
properties.store(fos, "SAP连接配置文件");
fos.close();
} catch (Exception e) {
throw new RuntimeException(
"Unable to create the destination file "
+ cfg.getName(), e);
}
}
public static JCoDestination Connect() {
JCoDestination destination = null;
try {
destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
} catch (JCoException e) {
LogKit.error("链接数据库:", e);
}
return destination;
}
}

380
src/main/java/com/fr/plugin/utils/DBUtils.java

@ -0,0 +1,380 @@
package com.fr.plugin.utils;
import com.fanruan.api.data.ConnectionKit;
import com.fanruan.api.log.LogKit;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.log.FineLoggerProvider;
import java.sql.Date;
import java.sql.*;
import java.util.*;
public class DBUtils {
String db_name = "";
private static FineLoggerProvider logger = FineLoggerFactory.getLogger();
public DBUtils() {
this.db_name = "finebi";
}
public com.fr.data.impl.Connection getDbConnect() {
return ConnectionKit.getConnection(db_name);
}
public List<Map<String, Object>> select(String sql, Object... params) {
logger.info("query data by sql:" + sql + Arrays.toString(params));
try {
com.fr.data.impl.Connection dbConnect = getDbConnect();
Connection con = dbConnect.createConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
setParams(preparedStatement, params);
ResultSet rs = preparedStatement.executeQuery(sql);
// 获得记录的详细信息,然后获得总列数
ResultSetMetaData resMetaData = rs.getMetaData();
int colNum = resMetaData.getColumnCount();
// 用对象保存数据
String name = "";
String value = "";
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> cells = new HashMap<String, Object>();
for (int i = 0; i < colNum; i++) {
name = resMetaData.getColumnLabel(i);
if (cells.get(name) != null) {
name = resMetaData.getColumnLabel(i);
}
if (rs.getObject(i) != null && resMetaData.getColumnTypeName(i).equals("DATETIME") || resMetaData.getColumnTypeName(i).equals("TIMESTAMP")) {
value = rs.getObject(i).toString();
cells.put(name, value.substring(0, value.length() - 2));
} else {
cells.put(name, rs.getString(i));
}
}
list.add(cells);
}
// 释放数据库资源
rs.close();
preparedStatement.close();
con.close();
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int exec(String sql, String date) throws Exception {
logger.info("query data by sql:{} 时间:{}", sql, date);
Connection con = null;
CallableStatement call = null;
try {
com.fr.data.impl.Connection dbConnect = getDbConnect();
con = dbConnect.createConnection();
call = con.prepareCall(sql);
call.registerOutParameter(1, Types.INTEGER);
call.execute();
Integer ret = call.getInt(1);
return ret;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (call != null) {
call.close();
}
if (con != null) {
con.close();
}
}
}
public Map<String, Object> findOneRow(String sql, Object... params) {
List<Map<String, Object>> select = select(sql, params);
if (select != null) {
if (!select.isEmpty()) {
return select.get(0);
}
}
return null;
}
public boolean checkExist(String sql, Object... params) throws Exception {
Connection connection = getDbConnect().createConnection();
PreparedStatement pstmt = connection.prepareStatement(sql);
setParams(pstmt, params);
try {
ResultSet resultSet = pstmt.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1) > 0;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
return false;
}
private void setParams(PreparedStatement pstmt, Object... params) throws SQLException {
if (params.length > 0) {
int length = params.length;
for (int i = 1; i <= length; i++) {
pstmt.setObject(i, params[i - 1]);
}
}
}
public int exSqlUpdate(String sql, Object... params) throws Exception {
logger.info("update data by sql:" + sql + " params " + Arrays.toString(params));
PreparedStatement pstmt = null;
Connection connection = null;
try {
com.fr.data.impl.Connection dbConnect = getDbConnect();
connection = dbConnect.createConnection();
pstmt = connection.prepareStatement(sql);
setParams(pstmt, params);
int i = pstmt.executeUpdate();
return i;
} catch (Exception e) {
FineLoggerFactory.getLogger().error("执行更新SQL报错: sql:{}", e, sql);
} finally {
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
}
return 0;
}
/**
* 取查询结果集字段
*
* @param sql
* @param params
* @return
* @throws Exception
*/
public List<Map<String, String>> exQuery(String sql, Object... params) throws Exception {
logger.info("query data by sql:" + sql + " params " + Arrays.toString(params));
com.fr.data.impl.Connection dbConnect = getDbConnect();
Connection connection = dbConnect.createConnection();
PreparedStatement pstmt = connection.prepareStatement(sql);
setParams(pstmt, params);
ResultSet resultSet = pstmt.executeQuery();
ResultSetMetaData resMetaData = resultSet.getMetaData();
int columnCount = resMetaData.getColumnCount();
List<Map<String, String>> arrs = new ArrayList<Map<String, String>>();
while (resultSet.next()) {
String name;
String value;
Map<String, String> one = new HashMap<String, String>();
for (int i = 1; i <= columnCount; i++) {
name = resMetaData.getColumnLabel(i);
if (one.get(name) != null) {
name = resMetaData.getColumnLabel(i);
}
if (resultSet.getObject(i) != null && resMetaData.getColumnTypeName(i).equals("DATETIME") || resMetaData.getColumnTypeName(i).equals("TIMESTAMP")) {
value = resultSet.getObject(i).toString();
one.put(name, value.substring(0, value.length() - 2));
} else {
one.put(name, resultSet.getString(i));
}
}
arrs.add(one);
}
pstmt.close();
connection.close();
return arrs;
}
private static final String sqlJSON = "insert into TPV_OMP_MATERIAL_DATA ( " +
"TPV_MODEL, " +
"SAFETY_MODEL,\n" +
"MATERIAL_DESC,\n" +
"GROSS_WEIGHT,\n" +
"NET_WEIGHT,\n" +
"VOLUME,\n" +
"PRODUCT_GROUP,\n" +
"MATERIAL_GROUP,\n" +
"BASE_METER_UNIT,\n" +
"CABINET_QTY,\n" +
"CUSTOMER_MODEL,\n" +
"BG,\n" +
"BRAND,\n" +
"SALES_REGION,\n" +
"OEM_MODE,\n" +
"PRODUCT_SERIES,\n" +
"PRODUCT_SERIES_CODE,\n" +
"GET_MODE,\n" +
"SHIPMENT_CATEGORY,\n" +
"WITHOUT_PANEL,\n" +
"SIZE,\n" +
"APPEARANCE_RATIO,\n" +
"BACKLIGHT_TYPE,\n" +
"PANEL_SUPPLY,\n" +
"PANEL_MAKER,\n" +
"FUNCTION_CATEGORY,\n" +
"SIGNAL_CLASS,\n" +
"CUSTOMER_NAME,\n" +
"RESOLUTION,\n" +
"SUB_BG,\n" +
"SMART_TV,\n" +
"DOBLY,\n" +
"CUSTOMERS_CLASS_CODE,\n" +
"COMMODITY_CODE,\n" +
"DECLARATION_ELEMENT,\n" +
"LCM_MODEL,\n" +
"LCM_MODEL_DESC,\n" +
"USER_NAME,\n" +
"CREATE_TIME) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
public void saveJSONArr(JSONArray jsonArray, String userName) throws SQLException {
com.fr.data.impl.Connection dbConnect = getDbConnect();
Connection con = null;
try {
con = dbConnect.createConnection();
con.setAutoCommit(false);
int size = jsonArray.size();
for (int i = 0; i < size; i++) {
JSONObject o = jsonArray.getJSONObject(i);
deleteByJSON(o,con);
saveJSON(o, userName, con);
}
con.commit();
} catch (Exception e) {
LogKit.error("SQL 异常 :",e);
try {
if (con != null) {
con.rollback();
}
}catch (Exception e12){
}
} finally {
if (con != null) {
try {
con.close();
}catch (Exception e){
}
}
}
}
String deleteJSONSQL = "delete from TPV_OMP_MATERIAL_DATA where TPV_MODEL=?";
private Integer deleteByJSON(JSONObject o, Connection con) throws SQLException {
logger.info("update data by sql:" + deleteJSONSQL + " params " + o);
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement(deleteJSONSQL);
pstmt.setString(1, o.getString("MATNR"));
int i = pstmt.executeUpdate();
return i;
} catch (Exception e) {
FineLoggerFactory.getLogger().error("执行更新SQL报错: sql:{}", e, sqlJSON);
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
}catch (Exception e){
}
}
return 0;
}
public int saveJSON(JSONObject o, String userName, Connection connection) throws SQLException {
logger.info("update data by sql:" + sqlJSON + " params " + o);
PreparedStatement pstmt = null;
try {
pstmt = connection.prepareStatement(sqlJSON);
pstmt.setString(1, o.getString("MATNR"));
pstmt.setString(2, o.getString("BISMT"));
pstmt.setString(3, o.getString("MAKTX"));
pstmt.setString(4, o.getString("BRGEW"));
pstmt.setString(5, o.getString("BTGEW"));
pstmt.setString(6, o.getString("VOLUM"));
pstmt.setString(7, o.getString("SPART"));
pstmt.setString(8, o.getString("MATKL"));
pstmt.setString(9, o.getString("MEINS"));
pstmt.setString(10, o.getString("NORMT"));
pstmt.setString(11, o.getString("FERTH"));
pstmt.setString(12, o.getString("Z_BRDTYPE"));
pstmt.setString(13, o.getString("Z_BRDID"));
pstmt.setString(14, o.getString("Z_REGION"));
pstmt.setString(15, o.getString("Z_CMNFTYPE"));
pstmt.setString(16, o.getString("Z_PRDLINE"));
pstmt.setString(17, o.getString("Z_STYLEID"));
pstmt.setString(18, o.getString("Z_SRCTYPE"));
pstmt.setString(19, o.getString("Z_ASSM"));
pstmt.setString(20, o.getString("Z_WPNL"));
pstmt.setString(21, o.getString("Z_SIZE"));
pstmt.setString(22, o.getString("Z_RATIO"));
pstmt.setString(23, o.getString("Z_PNLLIGHT"));
pstmt.setString(24, o.getString("Z_PNLSUPTYPE"));
pstmt.setString(25, o.getString("Z_PNLBRDID"));
pstmt.setString(26, o.getString("Z_FUNTYPE"));
pstmt.setString(27, o.getString("Z_SGNTYPE"));
pstmt.setString(28, o.getString("Z_CUSTNAME"));
pstmt.setString(29, o.getString("Z_PARSE"));
pstmt.setString(30, o.getString("Z_BG"));
pstmt.setString(31, o.getString("Z_SMARTTV"));
pstmt.setString(32, o.getString("Z_DOBLY"));
pstmt.setString(33, o.getString("GEBSQ"));
pstmt.setString(34, o.getString("HSCODE"));
pstmt.setString(35, o.getString("CMODEL"));
pstmt.setString(36, o.getString("MATNR_LCM"));
pstmt.setString(37, o.getString("MAKTX_LCM"));
pstmt.setString(38, userName);
pstmt.setDate(39, new Date(System.currentTimeMillis()));
int i = pstmt.executeUpdate();
return i;
} catch (Exception e) {
FineLoggerFactory.getLogger().error("执行更新SQL报错: sql:{}", e, sqlJSON);
} finally {
if (pstmt != null) {
pstmt.close();
}
}
return 0;
}
private static final String sqlexJSON = "INSERT INTO TPV_OMP_MATERIAL_DATA_STATUS (FACTORY,TPV_MODEL,STATUS,USER_NAME,CREATE_TIME) VALUES (?,?,?,?,?)";
public int saveReJSON(JSONObject o, String userName) throws SQLException {
logger.info("update data by sql:" + sqlexJSON + " params " + o);
PreparedStatement pstmt = null;
Connection connection = null;
try {
com.fr.data.impl.Connection dbConnect = getDbConnect();
connection = dbConnect.createConnection();
pstmt = connection.prepareStatement(sqlexJSON);
pstmt.setString(1, o.getString("WERKS"));
pstmt.setString(2, o.getString("MATNR"));
pstmt.setString(3, o.getString("RETURN"));
pstmt.setString(4, userName);
pstmt.setDate(5, new Date(System.currentTimeMillis()));
int i = pstmt.executeUpdate();
return i;
} catch (Exception e) {
FineLoggerFactory.getLogger().error("执行更新SQL报错: sql:{}", e, sqlJSON);
} finally {
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
}
return 0;
}
}

25
src/main/resources/com/fr/plugin/demo.js

@ -0,0 +1,25 @@
var data = []
for (i = 0; i < len; i++) {
var factory = _g().getCellValue(0, 1, i + 4);
//获取B5的扩展值
var wl = _g().getCellValue(0, 2, i + 4);
//获取C5的扩展值
data.push({
"MATNR": wl,
"WERKS": factory
})
}
$.ajax({
url: "/webroot/decision/url/sapApi",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function (e) {
alert("提交响应:" + e)
},
error: function () {
alert("提交失败请联系技术支持查看日志")
}
})
Loading…
Cancel
Save