创建接口
在服务管理平台中创建一个接口,接口代码如下:
/*
* resources.getEntityManagerContainer() // 实体管理容器.
* resources.getContext() //上下文根.
* resources.getOrganization() //组织访问接口.
* requestText //请求内容.
* request //请求对象.
*/
/*
传入的参数
假设requestText = {
"title" : "关于某某某的通知公告(标题,必填)", //标题
"from" : "办公室(来文单位,必填)",
"to" : "qhsnynctrsc(OA的部门人事处ID,必填)",
"date" : "2020-05-09(收文日期,选填)",
"no" : "农123(字号,选填)",
"key" : "nmt(文件加密私钥,选填,为空则认为没加密)",
"contents" : [ {
"filepath" : "http://xxxxx.com?file=aaaa.docx",
"filename" : "aaaa.docx"
} ],
"slaves" : [ {
"filepath" : "http://xxxxx.com?file=slaves.docx",
"filename" : "slaves.docx"
} ]
}
*/
try{
var result = {
}
print( "requestText="+requestText );
var requestJson = JSON.parse(requestText);
print( "type of requestJson = " + typeof( requestJson ));
print( "type of requestJson = " + requestJson );
if( typeof(requestJson) === "string" ){
requestJson = JSON.parse(requestJson);
}
var workId = "b4cbb9a4-3410-45a4-9c0e-4dad0dcf94b4"; //流程文档的workId
//上传附件-----------------------------------------------------------begin
var token = getToken();
//print( "contents个数:" + requestJson.contents.length);
//print( "slaves个数:" + requestJson.slaves.length);
var contentsSite = "attachment"; //正文附件放置的附件区域
var slavesSite = "attachment_1"; //普通附件放置的附件区域
//处理contents
var conArr = requestJson.contents;
for(var i=0;i//print( "contents-filepath:" + conArr[i].filepath);
//print( "contents-filename:" + conArr[i].filename);
uploadAtt(workId,conArr[i].filepath,conArr[i].filename,token,contentsSite)
}
//处理slaves
var slavesArr = requestJson.slaves;
for(var j=0;j//print( "slaves-filepath:" + slavesArr[j].filepath);
//print( "slaves-filename:" + slavesArr[j].filename);
uploadAtt(workId,slavesArr[j].filepath,slavesArr[j].filename,token,slavesSite)
}
//上传附件-----------------------------------------------------------end
result.state = "NMT0001";
result.message = "成功";
result.data = workId;
}catch(e){
e.printStackTrace();
result.state = "NMT0002";
result.message = "失败";
result.data = e.name + ": " + e.message
}
this.response.setBody(result,"application/json");
/*
var workid = "b4cbb9a4-3410-45a4-9c0e-4dad0dcf94b4"; //workid:待办id
var fileUrl = "http://127.0.0.1/x_desktop/js/base.js"; //附件下载链接
var fileName = "base.js"; //附件名称
var token = getToken();
site:附件放置区域
*/
function uploadAtt(workid,fileUrl,fileName,token,site){ //上传附件
try {
print("token=============================="+token);
//实例化java类
var LinkedHashMap = Java.type("java.util.LinkedHashMap");
var HttpClientUtilsUpfile = Java.type("com.z.custom.HttpClientUtilsUpfile");
var headMap = new LinkedHashMap();
headMap.put("x-token", token);
headMap.put("accept", "*/*");
headMap.put("connection", "Keep-Alive");
headMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
var uploadParams = new LinkedHashMap();
uploadParams.put("fileName", fileName); //附件名称
uploadParams.put("site", site); //附件区域
uploadParams.put("extraParam","");
//上传附件接口,传入文档的workid
var strurl = "http://127.0.0.1:20020/x_processplatform_assemble_surface/jaxrs/attachment/upload/work/" + workid;
/*
*方法功能:java模拟表单附件上传
*strurl : 上传附件接口地址
*fileUrl : 附件下载地址
*fileName :附件名称
*uploadParams : 上传附件接口参数
*headMap : 表单头参数
*/
HttpClientUtilsUpfile.getInstance().uploadUrlFileImpl(strurl, fileUrl,fileName,"file", uploadParams, headMap);
} catch (e) {
e.printStackTrace();
e.printStackTrace();
result.state = "NMT0002";
result.message = "失败";
result.data = e.name + ": " + e.message
}
}
function getToken(){ //获取token
var HttpClientUtilsUpfile = Java.type("com.z.custom.HttpClientUtilsUpfile");
//使用token进行Sso登陆
var path = "http://127.0.0.1:20020/x_organization_assemble_authentication/jaxrs/sso";
var login_uid = "13379254582"; //用户简称
var client = "wwx" //SSO名称
var sso_key = "987654321"; //SSO密钥
//获取token
var token = HttpClientUtilsUpfile.getInstance().getToken(path,client,login_uid,sso_key);
return token;
}
HttpClientUtilsUpfile类代码
接口中引用了com.z.custom.HttpClientUtilsUpfile中的java代码去实现模拟表单上传附件,HttpClientUtilsUpfile类代码如下:
package com.z.custom;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.x.base.core.project.tools.Crypto;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
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 javax.crypto.CipherInputStream;
public class HttpClientUtilsUpfile {
public static final int THREAD_POOL_SIZE = 5;
public interface HttpClientDownLoadProgress {
public void onProgress(int prgetInstanceogress);
}
private static HttpClientUtilsUpfile httpClientDownload;
private ExecutorService downloadExcutorService;
private HttpClientUtilsUpfile() {
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public static HttpClientUtilsUpfile getInstance() {
if (httpClientDownload == null) {
httpClientDownload = new HttpClientUtilsUpfile();
}
return httpClientDownload;
}
/**
* 下载文件
*
* @param url
* @param filePath
*/
public void download(final String url, final String filePath) { downloadExcutorService.execute(new Runnable() {
public void run() {
httpDownloadFile( url, filePath, null, null);
}
});
}
/**
* 下载文件
*
* @param url
* @param filePath
* @param progress
*
*/
public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) {
downloadExcutorService.execute(new Runnable() {
public void run() {
httpDownloadFile(url, filePath, progress, null);
}
});
}
/**
*下载文件
*
* @param url
* @param filePath
*/
private void httpDownloadFile(String url, String filePath,
HttpClientDownLoadProgress progress, Map headMap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
HttpEntity httpEntity = response1.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream is = httpEntity.getContent();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送Get请求
*
* @param url
* @return
*/
public String httpGet(String url) {
return httpGet(url, null);
}
/**
* 发送Get请求
*
* @param url
* @return
*/
public String httpGet(String url, Map headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
setGetHead(httpGet, headMap);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity = response1.getEntity();
responseContent = getRespString(entity);
System.out.println("debug:" + responseContent);
EntityUtils.consume(entity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
public String httpPost(String url, Map paramsMap) {
return httpPost(url, paramsMap, null);
}
/**
* 发送Post请求
*
* @param url
* @param paramsMap
* @return
*/
public String httpPost(String url, Map paramsMap, Map headMap) {
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
responseContent = getRespString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseContent = " + responseContent);
return responseContent;
}
/**
* 设置Post请求的HttpHeader
*
* @param httpPost
* @param headMap
*/
private void setPostHead(HttpPost httpPost, Map headMap) {
if (headMap != null && headMap.size() > 0) {
Set keySet = headMap.keySet();
for (String key : keySet) {
httpPost.addHeader(key, headMap.get(key));
}
}
}
/**
* 设置Get请求的HttpHeader
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, Map headMap) {
if (headMap != null && headMap.size() > 0) {
Set keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}
/**
* 上传文件的实现方法
*
* @param serverUrl
* @param localFilePath
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,String serverFieldName, Map params, Map paramshead)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
FileBody binFileBody = new FileBody(new File(localFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 上传文件的实现方法
*
* @param serverUrl
* @param urlFilePath
* @param urlFileName
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadUrlFileImpl(String serverUrl, String urlFilePath,String urlFileName,String serverFieldName, Map params, Map paramshead)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
FileBody binFileBody = new FileBody(new File(urlFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
BufferedInputStream in = getFileInputStream(urlFilePath);
InputStreamBody inputStreamBody = new InputStreamBody(in,urlFileName);
multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 上传文件的实现方法
* 上传前 需要解密
* @param serverUrl 上传附件服务
* @param urlFilePath 附件URL
* @param urlFileName 附件名称
* @param serverFieldName
* @param params 附件参数
* @param paramshead 文件头
* @param skey 密钥
* @param siv 向量
* @return
* @throws Exception
*/
public String uploadByteFileImpl(String serverUrl, String urlFilePath,String urlFileName,String serverFieldName, Map params, Map paramshead,String skey,String siv)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
//ileBody binFileBody = new FileBody(new File(urlFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
BufferedInputStream fis = getFileInputStream(URLDecoder.decode(urlFilePath, "UTF-8" ));;
//解密
CipherInputStream cis = AESFile.decryptedFile(fis,skey,siv);
if(cis != null){
//InputStream inputByteFile = new ByteArrayInputStream(byteFile);
//BufferedInputStream in = new BufferedInputStream(inputByteFile);
InputStreamBody inputStreamBody = new InputStreamBody(cis,urlFileName);
multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
}else{
respStr = "解密失败";
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 设置上传时的参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map params) {
if (params != null && params.size() > 0) {
Set keys = params.keySet();
for (String key : keys) {
multipartEntityBuilder.addPart(key, new StringBody(params.get(key),ContentType.APPLICATION_JSON));
}
}
}
/**
* 获取响应内容
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString( HttpEntity entity ) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
/**
* 设置Post请求发送的参数
*
* @param httpPost
* @param paramsMap
* @throws Exception
*/
private void setPostParams(HttpPost httpPost, Map paramsMap)
throws Exception {
if (paramsMap != null && paramsMap.size() > 0) {
List nvps = new ArrayList();
Set keySet = paramsMap.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
}
}
/**
* 发送Post请求
* @param url
* @param param
* @return
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" POST"+e);
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println(result);
return result;
}
/**
* 根据ssoToken获取人员认证后的真实xtoken
* @param url
* @param client
* @param login_uid
* @param sso_key
* @return
*/
public String getToken(String url, String client, String login_uid, String sso_key ) {
long time = new Date().getTime();
String xtoken = null;
try {
xtoken = Crypto.encrypt( login_uid + "#" + time, sso_key );
System.out.println(xtoken);
} catch (Exception e1) {
e1.printStackTrace();
}
String string = "{\"token\": "+xtoken+", \"client\": \""+ client +"\"}";
String str = getInstance().sendPost( url,string );
System.out.println("sso response: " + str );
try {
JsonElement jsonObj = new JsonParser().parse(str);
if( jsonObj != null && jsonObj.getAsJsonObject().get("data") != null ){
JsonObject data = jsonObj.getAsJsonObject().get("data").getAsJsonObject();
System.out.println("getToken: " + data.get("token"));
return data.get("token").getAsString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private BufferedInputStream getFileInputStream(String urlPath) {
BufferedInputStream bin=null;
URL url;
try {
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
bin = new BufferedInputStream(httpURLConnection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return bin;
}
private InputStream getInputStream(String urlPath) {
InputStream bin=null;
URL url;
try {
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
bin = httpURLConnection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return bin;
}
public static void main(String[] args) throws IOException, Exception {
}
}
推荐文章:
业务开发-组织架构-组织职位信息管理
2021-02-26
O2OA提供多级组织架构设置能力,用户可以在系统内设置集团、分公司、部门、小组等多级企业组织结构来满足办公需要,可以为组织设置不同的职务来实现配置和人员的解耦。
门户开发-门户脚本开发
2021-03-01
O2OA提供的门户管理平台可以让用户自由地为企业定制符合企业特色的门户系统,门户页面。可以让页面展现的内容真正满足企业自身的需求。本文主要介绍如何在O2OA中使
流程设计-Excel数据导入数据网格(仅支持IE)
2021-02-26
O2OA提供数据网格组件来简体表单中的可编辑表格或者数据展现表格的设计,如费用报销,差旅报销等业务都可能使用到数据网格。本文主要介绍如何将Excel中的数据导入
系统配置-开机自动启动O2Server
2021-02-19
O2OA开发平台允许将平台启动设置为跟随操作系统自动启动,这样避免服务器重启后,还需要手工启动O2Server的操作。本篇介绍如何在windows和Linux两
服务集成-发送用户名使用SSO进行登录认证
2021-03-02
O2OA提供多种SSO单点认证方式,比如约定密钥,OAuth2,SMAP等等。本文主要演示如何通过登录用户名,和SSO相关的配置,使用单点认证的方式进行O2Se
服务管理-前后端脚本的差异
2021-03-01
O2OA提供的服务管理中心可以让用户使用Javascript语言自由编写脚本的处理逻辑来实现与第三方的数据交互,数据同步以及系统内的数据处理等工作。本文主要介绍
门户开发-HTML模板导入
2021-03-01
O2OA提供的门户管理平台可以让用户自由地为企业定制符合企业特色的门户系统,门户页面。可以让页面展现的内容真正满足企业自身的需求。平台支持将完整的HTML文件导
系统配置-工作日节假日配置
2021-02-25
O2OA服务器提供了配置文件,支持自定义工作日、节假日、工作时间配置。本篇主要介绍如何对工作日,节假日进行相关的配置。
平台服务器下载及安装部署-Windows系统
2021-02-25
O2OA信息化系统开发支持公有云,私有云和混合云部署,也支持复杂的网络结构下的分布式部署。O2OA开发平台安装部署非常方便,只需要简单的三步即可完成安装。平台内
OEM白标-如何修改平台中的Logo图标和文字
2021-02-22
一、修改标签页左上角o2专用图标需修改下图中的图标:修改位置在:o2server\servers\webServer目录下的favicon.ico文件,可以把此